fog-1.19.0/0000755000004100000410000000000012261242552012406 5ustar www-datawww-datafog-1.19.0/Rakefile0000644000004100000410000001247112261242551014057 0ustar www-datawww-datarequire 'bundler/setup' require 'date' require 'rubygems' require 'rubygems/package_task' require 'yard' require File.dirname(__FILE__) + '/lib/fog' ############################################################################# # # Helper functions # ############################################################################# def name @name ||= Dir['*.gemspec'].first.split('.').first end def version Fog::VERSION end def date Date.today.to_s end def rubyforge_project name end def gemspec_file "#{name}.gemspec" end def gem_file "#{name}-#{version}.gem" end def replace_header(head, header_name) head.sub!(/(\.#{header_name}\s*= ').*'/) { "#{$1}#{send(header_name)}'"} end ############################################################################# # # Standard tasks # ############################################################################# GEM_NAME = "#{name}" task :default => :test task :travis => ['test:travis', 'coveralls_push_workaround'] require "tasks/test_task" Fog::Rake::TestTask.new namespace :test do mock = 'true' || ENV['FOG_MOCK'] task :travis do # jruby coveralls causes an OOM in travis ENV['COVERAGE'] = 'false' if RUBY_PLATFORM == 'java' sh("export FOG_MOCK=#{mock} && bundle exec shindont") end task :vsphere do sh("export FOG_MOCK=#{mock} && bundle exec shindont tests/vsphere") end task :openvz do sh("export FOG_MOCK=#{mock} && bundle exec shindont tests/openvz") end end desc 'Run mocked tests for a specific provider' task :mock, :provider do |t, args| if args.to_a.size != 1 fail 'USAGE: rake mock[]' end provider = args[:provider] sh("export FOG_MOCK=true && bundle exec shindont tests/#{provider}") end desc 'Run live tests against a specific provider' task :live, :provider do |t, args| if args.to_a.size != 1 fail 'USAGE: rake live[]' end provider = args[:provider] sh("export FOG_MOCK=false && bundle exec shindont tests/#{provider}") end task :nuke do Fog.providers.each do |provider| next if ['Vmfusion'].include?(provider) begin compute = Fog::Compute.new(:provider => provider) for server in compute.servers Formatador.display_line("[#{provider}] destroying server #{server.identity}") server.destroy rescue nil end rescue end begin dns = Fog::DNS.new(:provider => provider) for zone in dns.zones for record in zone.records record.destroy rescue nil end Formatador.display_line("[#{provider}] destroying zone #{zone.identity}") zone.destroy rescue nil end rescue end end end desc "Open an irb session preloaded with this library" task :console do sh "irb -rubygems -r ./lib/#{name}.rb" end ############################################################################# # # Packaging tasks # ############################################################################# task :release => ["release:prepare", "release:publish"] namespace :release do task :preflight do unless `git branch` =~ /^\* master$/ puts "You must be on the master branch to release!" exit! end if `git tag` =~ /^\* v#{version}$/ puts "Tag v#{version} already exists!" exit! end end task :prepare => :preflight do Rake::Task[:build].invoke sh "gem install pkg/#{name}-#{version}.gem" Rake::Task[:git_mark_release].invoke end task :publish do Rake::Task[:git_push_release].invoke Rake::Task[:gem_push].invoke end end task :git_mark_release do sh "git commit --allow-empty -a -m 'Release #{version}'" sh "git tag v#{version}" end task :git_push_release do sh "git push origin master" sh "git push origin v#{version}" end task :gem_push do sh "gem push pkg/#{name}-#{version}.gem" end desc "Build fog-#{version}.gem" task :build => :gemspec do sh "mkdir -p pkg" sh "gem build #{gemspec_file}" sh "mv #{gem_file} pkg" end task :gem => :build desc "Updates the gemspec and runs 'validate'" task :gemspec => :validate do # read spec file and split out manifest section spec = File.read(gemspec_file) # replace name version and date replace_header(spec, :name) replace_header(spec, :version) replace_header(spec, :date) #comment this out if your rubyforge_project has a different name replace_header(spec, :rubyforge_project) File.open(gemspec_file, 'w') { |io| io.write(spec) } puts "Updated #{gemspec_file}" end desc "Run before pushing out the code" task :validate do libfiles = Dir['lib/*'] - ["lib/#{name}.rb", "lib/#{name}", "lib/tasks"] unless libfiles.empty? puts "Directory `lib` should only contain a `#{name}.rb` file and `#{name}` dir." exit! end unless Dir['VERSION*'].empty? puts "A `VERSION` file at root level violates Gem best practices." exit! end end # Include Yard tasks for rake yard YARDOC_LOCATION = "doc" YARD::Rake::YardocTask.new do |t| t.files = ['lib/**/*.rb', "README"] t.options = ["--output-dir", YARDOC_LOCATION, "--title", "#{name} #{version}"] end require "tasks/changelog_task" Fog::Rake::ChangelogTask.new task :coveralls_push_workaround do use_coveralls = (Gem::Version.new(RUBY_VERSION) > Gem::Version.new('1.9.2')) if (ENV['COVERAGE'] != 'false') && use_coveralls require 'coveralls/rake/task' Coveralls::RakeTask.new Rake::Task["coveralls:push"].invoke end end fog-1.19.0/bin/0000755000004100000410000000000012261242551013155 5ustar www-datawww-datafog-1.19.0/bin/fog0000755000004100000410000000337512261242551013666 0ustar www-datawww-data#!/usr/bin/env ruby require File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'fog')) require 'optparse' require 'irb' require 'yaml' options = OptionParser.new do |opts| opts.banner = 'usage: fog [options] CREDENTIAL' opts.on('-C', '--credentials-path FILE', 'Path to the credentials file') do |file| Fog.credentials_path = file end opts.on_tail('-v', '--version', 'Prints the version') do puts Fog::VERSION exit end opts.on_tail('-h', '--help', 'Prints this message') do puts opts exit end end options.parse! Fog.credential = ARGV.first ? ARGV.first.to_sym : nil Fog.mock! if ENV['FOG_MOCK'] if Fog.credentials.empty? begin Fog::Errors.missing_credentials rescue Fog::Errors::LoadError => error abort error.message end end require 'fog/bin' providers = Fog.available_providers providers = if providers.length > 1 providers[0...-1].join(', ') << ' and ' << providers[-1] else providers.first end if ARGV.length > 1 result = instance_eval(ARGV[1..-1].join(' ')) puts(Fog::JSON.encode(result)) else ARGV.clear # Avoid passing args to IRB IRB.setup(nil) @irb = IRB::Irb.new(nil) IRB.conf[:MAIN_CONTEXT] = @irb.context IRB.conf[:PROMPT][:FOG] = IRB.conf[:PROMPT][:SIMPLE].dup IRB.conf[:PROMPT][:FOG][:RETURN] = "%s\n" @irb.context.prompt_mode = :FOG @irb.context.workspace = IRB::WorkSpace.new(binding) trap 'INT' do @irb.signal_handle end Formatador.display_line('Welcome to fog interactive!') Formatador.display_line(":#{Fog.credential} provides #{providers}") providers = Fog.providers # FIXME: hacks until we can `include Fog` in bin CDN = Fog::CDN Compute = Fog::Compute DNS = Fog::DNS Storage = Fog::Storage catch(:IRB_EXIT) { @irb.eval_input } end fog-1.19.0/Gemfile0000644000004100000410000000025612261242551013703 0ustar www-datawww-datasource "https://rubygems.org" group :development, :test do # This is here because gemspec doesn't support require: false gem 'coveralls', :require => false end gemspec fog-1.19.0/tests/0000755000004100000410000000000012261242552013550 5ustar www-datawww-datafog-1.19.0/tests/digitalocean/0000755000004100000410000000000012261242552016173 5ustar www-datawww-datafog-1.19.0/tests/digitalocean/helper.rb0000644000004100000410000000226012261242552017777 0ustar www-datawww-data # Shortcut for Fog::Compute[:digitalocean] def service Fog::Compute[:digitalocean] end def fog_test_server_attributes image = service.images.find { |i| i.name == 'Ubuntu 12.04 x64' } region = service.regions.find { |r| r.name == 'New York 1' } flavor = service.flavors.find { |r| r.name == '512MB' } { :image_id => image.id, :region_id => region.id, :flavor_id => flavor.id } end def fog_server_name "fog-server-test" end # Create a long lived server for the tests def fog_test_server server = service.servers.find { |s| s.name == fog_server_name } unless server server = service.servers.create({ :name => fog_server_name }.merge(fog_test_server_attributes)) server.wait_for { ready? } end server end # Destroy the long lived server def fog_test_server_destroy server = service.servers.find { |s| s.name == fog_server_name } server.destroy if server end at_exit do unless Fog.mocking? || Fog.credentials[:digitalocean_api_key].nil? server = service.servers.find { |s| s.name == fog_server_name } if server server.wait_for(120) do reload rescue nil; ready? end end fog_test_server_destroy end end fog-1.19.0/tests/digitalocean/requests/0000755000004100000410000000000012261242552020046 5ustar www-datawww-datafog-1.19.0/tests/digitalocean/requests/compute/0000755000004100000410000000000012261242552021522 5ustar www-datawww-datafog-1.19.0/tests/digitalocean/requests/compute/power_state_tests.rb0000644000004100000410000000107112261242552025624 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | power on/off/shutdown requests', ['digitalocean', 'compute']) do service = Fog::Compute[:digitalocean] server = fog_test_server tests('success') do test('#power_off_server') do service.power_off_server(server.id).body['status'] == 'OK' end test('#power_on_server') do service.power_on_server(server.id).body['status'] == 'OK' end test('#shutdown_server') do service.shutdown_server(server.id).body['status'] == 'OK' end server.start end end fog-1.19.0/tests/digitalocean/requests/compute/destroy_ssh_key_tests.rb0000644000004100000410000000117212261242552026510 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | destroy_ssh_key request', ['digitalocean', 'compute']) do service = Fog::Compute[:digitalocean] tests('success') do test('#destroy_ssh_key') do key = service.create_ssh_key 'fookey', 'fookey' service.destroy_ssh_key(key.body['ssh_key']['id']).body['status'] == 'OK' end end tests('failures') do test 'delete invalid key' do # DigitalOcean API returns 500 with this sometimes # so mark it as pending in real mode pending unless Fog.mocking? service.destroy_ssh_key('00000000000').body['status'] == 'ERROR' end end end fog-1.19.0/tests/digitalocean/requests/compute/list_servers_tests.rb0000644000004100000410000000124212261242552026014 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | list_servers request', ['digitalocean', 'compute']) do @server_format = { 'id' => Integer, 'name' => String, 'image_id' => Integer, 'size_id' => Integer, 'region_id' => Integer, 'backups_active' => Fog::Nullable::Boolean, 'ip_address' => Fog::Nullable::String, 'status' => String } tests('success') do tests('#list_servers') do Fog::Compute[:digitalocean].list_servers.body['droplets'].each do |server| tests('format').data_matches_schema(@server_format) do server end end end end end fog-1.19.0/tests/digitalocean/requests/compute/power_cycle_server_tests.rb0000644000004100000410000000067312261242552027200 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | power_cycle_server request', ['digitalocean', 'compute']) do server = fog_test_server tests('success') do tests('#power_cycle_server') do test('returns 200') do service.power_cycle_server(server.id).status == 200 end test('state is off') do server.wait_for { server.state == 'off' } server.state == 'off' end end end end fog-1.19.0/tests/digitalocean/requests/compute/list_flavors_tests.rb0000644000004100000410000000101012261242552025770 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | list_flavors request', ['digitalocean', 'compute']) do # {"id":2,"name":"Amsterdam 1"} @flavor_format = { 'id' => Integer, 'name' => String, } tests('success') do tests('#list_flavor') do flavors = Fog::Compute[:digitalocean].list_flavors.body test 'returns a Hash' do flavors.is_a? Hash end tests('flavor').formats(@flavor_format, false) do flavors['sizes'].first end end end end fog-1.19.0/tests/digitalocean/requests/compute/list_regions_tests.rb0000644000004100000410000000101312261242552025765 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | list_regions request', ['digitalocean', 'compute']) do # {"id":2,"name":"Amsterdam 1"} @region_format = { 'id' => Integer, 'name' => String, } tests('success') do tests('#list_regions') do regions = Fog::Compute[:digitalocean].list_regions.body test 'returns a Hash' do regions.is_a? Hash end tests('region').formats(@region_format, false) do regions['regions'].first end end end end fog-1.19.0/tests/digitalocean/requests/compute/reboot_server_tests.rb0000644000004100000410000000043512261242552026153 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | reboot_server request', ['digitalocean', 'compute']) do server = fog_test_server tests('success') do tests('#reboot_server').succeeds do service.reboot_server(server.id).body['status'] == 'OK' end end end fog-1.19.0/tests/digitalocean/requests/compute/get_ssh_key_tests.rb0000644000004100000410000000112612261242552025575 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | get_ssh_keys request', ['digitalocean', 'compute']) do @ssh_key_format = { 'id' => Integer, 'name' => String, 'ssh_pub_key' => String, } service = Fog::Compute[:digitalocean] tests('success') do tests('#get_ssh_key') do key = service.create_ssh_key 'fookey', 'ssh-dss FOO' tests('format').data_matches_schema(@ssh_key_format) do service.get_ssh_key(key.body['ssh_key']['id']).body['ssh_key'] end service.destroy_ssh_key(key.body['ssh_key']['id']) end end end fog-1.19.0/tests/digitalocean/requests/compute/list_ssh_keys_tests.rb0000644000004100000410000000103712261242552026155 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | list_ssh_keys request', ['digitalocean', 'compute']) do @ssh_key_format = { 'id' => Integer, 'name' => String } tests('success') do ssh_key = service.create_ssh_key 'fookey', 'ssh-dss FOO' tests('#list_ssh_keys') do service.list_ssh_keys.body['ssh_keys'].each do |key| tests('format').data_matches_schema(@ssh_key_format) do key end end end service.destroy_ssh_key(ssh_key.body['ssh_key']['id']) end end fog-1.19.0/tests/digitalocean/requests/compute/destroy_server_tests.rb0000644000004100000410000000053612261242552026354 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | destroy_server request', ['digitalocean', 'compute']) do service = Fog::Compute[:digitalocean] server = fog_test_server tests('success') do test('#destroy_server') do service.destroy_server(server.id).body['status'] == 'OK' service.servers.get(server.id) == nil end end end fog-1.19.0/tests/digitalocean/requests/compute/list_images_tests.rb0000644000004100000410000000110112261242552025562 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | list_images request', ['digitalocean', 'compute']) do # {"id"=>1601, "name"=>"CentOS 5.8 x64", "distribution"=>"CentOS"} @image_format = { 'id' => Integer, 'name' => String, 'distribution' => String } tests('success') do tests('#list_images') do images = Fog::Compute[:digitalocean].list_images.body test 'returns a Hash' do images.is_a? Hash end tests('image').formats(@image_format, false) do images['images'].first end end end end fog-1.19.0/tests/digitalocean/requests/compute/create_server_tests.rb0000644000004100000410000000160012261242552026117 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | create_server request', ['digitalocean', 'compute']) do @server_format = { 'id' => Integer, 'name' => String, 'image_id' => Integer, 'size_id' => Integer, 'event_id' => Integer } service = Fog::Compute[:digitalocean] tests('success') do tests('#create_server').formats({'status' => 'OK', 'droplet' => @server_format}) do image = service.images.find { |img| img.name == 'Ubuntu 12.04 x64' } flavor = service.flavors.find { |f| f.name == '512MB' } data = Fog::Compute[:digitalocean].create_server fog_server_name, flavor.id, image.id, service.regions.first.id data.body end end end fog-1.19.0/tests/digitalocean/requests/compute/get_server_details_tests.rb0000644000004100000410000000052412261242552027144 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | get_server_details request', ['digitalocean', 'compute']) do tests('success') do test('#get_server_details') do server = fog_test_server body = Fog::Compute[:digitalocean].get_server_details(server.id).body body['droplet']['name'] == fog_server_name end end end fog-1.19.0/tests/digitalocean/requests/compute/create_ssh_key_tests.rb0000644000004100000410000000103412261242552026257 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | create_ssh_key request', ['digitalocean', 'compute']) do @key_format = { 'id' => Integer, 'name' => String, 'ssh_pub_key' => String } service = Fog::Compute[:digitalocean] tests('success') do tests('#create_ssh_key').formats({'status' => 'OK', 'ssh_key' => @key_format}) do @key = Fog::Compute[:digitalocean].create_ssh_key 'fookey', 'fookey' @key.body end end service.destroy_ssh_key @key.body['ssh_key']['id'] end fog-1.19.0/tests/digitalocean/models/0000755000004100000410000000000012261242552017456 5ustar www-datawww-datafog-1.19.0/tests/digitalocean/models/compute/0000755000004100000410000000000012261242552021132 5ustar www-datawww-datafog-1.19.0/tests/digitalocean/models/compute/ssh_keys_tests.rb0000644000004100000410000000161612261242552024535 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | ssh_keys collection', ['digitalocean']) do service = Fog::Compute[:digitalocean] tests('The ssh_keys collection') do key = service.ssh_keys.create :name => 'fookey', :ssh_pub_key => 'fookey' [:all, :get].each do |method| test("should respond to #{method}") do service.ssh_keys.respond_to? method end end tests('should have Fog::Compute::DigitalOcean::SshKey inside') do service.ssh_keys.each do |s| test { s.kind_of? Fog::Compute::DigitalOcean::SshKey } end end tests('should be able to get a model') do test('by instance id') do retrieved_key = service.ssh_keys.get(key.id) test { retrieved_key.kind_of? Fog::Compute::DigitalOcean::SshKey } test { retrieved_key.name == key.name } end end key.destroy end end fog-1.19.0/tests/digitalocean/models/compute/flavor_tests.rb0000644000004100000410000000146612261242552024201 0ustar www-datawww-dataShindo.tests("Fog::Compute[:digitalocean] | flavor model", ['digitalocean', 'compute']) do service = Fog::Compute[:digitalocean] flavor = service.flavors.first tests('The flavor model should') do tests('have the action') do test('reload') { flavor.respond_to? 'reload' } end tests('have attributes') do model_attribute_hash = flavor.attributes attributes = [ :id, :name, ] tests("The flavor model should respond to") do attributes.each do |attribute| test("#{attribute}") { flavor.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end end end fog-1.19.0/tests/digitalocean/models/compute/region_tests.rb0000644000004100000410000000146612261242552024173 0ustar www-datawww-dataShindo.tests("Fog::Compute[:digitalocean] | region model", ['digitalocean', 'compute']) do service = Fog::Compute[:digitalocean] region = service.regions.first tests('The region model should') do tests('have the action') do test('reload') { region.respond_to? 'reload' } end tests('have attributes') do model_attribute_hash = region.attributes attributes = [ :id, :name, ] tests("The region model should respond to") do attributes.each do |attribute| test("#{attribute}") { region.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end end end fog-1.19.0/tests/digitalocean/models/compute/image_tests.rb0000644000004100000410000000150412261242552023763 0ustar www-datawww-dataShindo.tests("Fog::Compute[:digitalocean] | image model", ['digitalocean', 'compute']) do service = Fog::Compute[:digitalocean] image = service.images.first tests('The image model should') do tests('have the action') do test('reload') { image.respond_to? 'reload' } end tests('have attributes') do model_attribute_hash = image.attributes attributes = [ :id, :name, :distribution ] tests("The image model should respond to") do attributes.each do |attribute| test("#{attribute}") { image.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end end end fog-1.19.0/tests/digitalocean/models/compute/server_tests.rb0000644000004100000410000000376512261242552024222 0ustar www-datawww-dataShindo.tests("Fog::Compute[:digitalocean] | server model", ['digitalocean', 'compute']) do server = fog_test_server tests('The server model should') do tests('have the action') do test('reload') { server.respond_to? 'reload' } %w{ shutdown reboot power_cycle stop start }.each do |action| test(action) { server.respond_to? action } end end tests('have attributes') do model_attribute_hash = server.attributes attributes = [ :id, :name, :state, :backups_active, :public_ip_address, :private_ip_address, :flavor_id, :region_id, :image_id, :ssh_keys= ] tests("The server model should respond to") do attributes.each do |attribute| test("#{attribute}") { server.respond_to? attribute } end end end test('#reboot') do pending if Fog.mocking? server.reboot server.wait_for { server.state == 'off' } server.state == 'off' end test('#power_cycle') do pending if Fog.mocking? server.wait_for { server.ready? } server.power_cycle server.wait_for { server.state == 'off' } server.state == 'off' end test('#stop') do server.stop server.wait_for { server.state == 'off' } server.state == 'off' end test('#start') do server.start server.wait_for { ready? } server.ready? end # DigitalOcean shutdown is unreliable # so disable it in real mode for now test('#shutdown') do pending unless Fog.mocking? server.start server.wait_for { server.ready? } server.shutdown server.wait_for { server.state == 'off' } server.state == 'off' end test('#update') do begin server.update rescue NotImplementedError => e true end end end # restore server state server.start server.wait_for { ready? } end fog-1.19.0/tests/digitalocean/models/compute/servers_tests.rb0000644000004100000410000000124012261242552024367 0ustar www-datawww-dataShindo.tests('Fog::Compute[:digitalocean] | servers collection', ['digitalocean']) do service = Fog::Compute[:digitalocean] options = { :name => "#{fog_server_name}-#{Time.now.to_i.to_s}" }.merge fog_test_server_attributes collection_tests(service.servers, options, true) do @instance.wait_for { ready? } end tests("#bootstrap").succeeds do pending if Fog.mocking? @server = service.servers.bootstrap({ :public_key_path => File.join(File.dirname(__FILE__), '../../fixtures/id_rsa.pub'), :private_key_path => File.join(File.dirname(__FILE__), '../../fixtures/id_rsa') }.merge(options)) end @server.destroy if @server end fog-1.19.0/tests/digitalocean/models/compute/ssh_key_tests.rb0000644000004100000410000000166212261242552024353 0ustar www-datawww-dataShindo.tests("Fog::Compute[:digitalocean] | ssh_key model", ['digitalocean', 'compute']) do service = Fog::Compute[:digitalocean] tests('The ssh_key model should') do test('#save') do @key = service.ssh_keys.create :name => 'fookey', :ssh_pub_key => 'fookey' @key.is_a? Fog::Compute::DigitalOcean::SshKey end tests('have the action') do test('reload') { @key.respond_to? 'reload' } %w{ save destroy }.each do |action| test(action) { @key.respond_to? action } end end tests('have attributes') do attributes = [ :id, :name, :ssh_pub_key ] tests("The key model should respond to") do attributes.each do |attribute| test("#{attribute}") { @key.respond_to? attribute } end end end test('#destroy') do @key.destroy end end end fog-1.19.0/tests/voxel/0000755000004100000410000000000012261242552014705 5ustar www-datawww-datafog-1.19.0/tests/voxel/requests/0000755000004100000410000000000012261242552016560 5ustar www-datawww-datafog-1.19.0/tests/voxel/requests/compute/0000755000004100000410000000000012261242552020234 5ustar www-datawww-datafog-1.19.0/tests/voxel/requests/compute/image_tests.rb0000644000004100000410000000234712261242552023073 0ustar www-datawww-dataShindo.tests('Fog::Compute[:voxel] | image requests', ['voxel']) do @images_format = { 'images' => [{ 'id' => Integer, 'summary' => String }], 'stat' => String } @image_format = { 'images' => [{ 'description' => String, 'id' => Integer, 'filesystem' => { 'size' => Integer, 'type' => String, 'units' => String, }, 'operating_system' => { 'admin_username' => String, 'architecture' => Integer, 'family' => String, 'product_family' => String, 'product_version' => String, 'version' => String }, 'summary' => String }], 'stat' => String } tests('success') do tests('#images_list').formats(@images_format) do pending if Fog.mocking? Fog::Compute[:voxel].images_list.body end tests('#images_list(1)').formats(@image_format) do pending if Fog.mocking? Fog::Compute[:voxel].images_list(1).body end end tests('failure') do tests('#images_list(0)').raises(Fog::Compute::Voxel::Error) do pending if Fog.mocking? Fog::Compute[:voxel].images_list(0).body end end end fog-1.19.0/tests/voxel/requests/compute/server_tests.rb0000644000004100000410000000644012261242552023315 0ustar www-datawww-dataShindo.tests('Fog::Compute[:voxel] | server requests', ['voxel']) do @server_format = { 'device' => { 'id' => String, 'last_update' => Time }, 'stat' => String } @devices_format = { 'devices' => [{ 'access_methods' => [], 'description' => String, 'drives' => [{ 'position' => Fog::Nullable::String, 'size' => Integer }], 'id' => String, 'ipassignments' => [{ 'description' => String, 'id' => String, 'type' => String, 'value' => String }], 'label' => String, 'location' => { 'cage' => { 'id' => String, 'value' => String }, 'facility' => { 'code' => String, 'id' => String, 'value' => String }, 'position' => Fog::Nullable::String, 'rack' => { 'id' => String, 'value' => String }, 'row' => { 'id' => String, 'value' => String }, 'zone' => { 'id' => String, 'value' => String } }, 'memory' => { 'size' => Integer }, 'model' => { 'id' => String, 'value' => String }, 'operating_system' => { 'architecture' => Integer, 'name' => String }, 'power_consumption' => String, 'processor' => { 'cores' => Integer }, 'status' => String, 'type' => { 'id' => String, 'value' => String }, }], 'stat' => String, } tests('success') do @server_id = nil @name = "fog.#{Time.now.to_i}" tests("#voxcloud_create( :hostname => '#{@name}', :disk_size => 10, :processing_cores => 1, :image_id => 55, :facility => 'LDJ1' )").formats(@server_format) do pending if Fog.mocking? data = Fog::Compute[:voxel].voxcloud_create( :hostname => @name, :disk_size => 10, :processing_cores => 1, :image_id => 55, :facility => "LDJ1" ).body @server_id = data['device']['id'] data end unless Fog.mocking? Fog::Compute[:voxel].servers.get(@server_id).wait_for { ready? } end tests('#devices_list').formats(@devices_format) do pending if Fog.mocking? Fog::Compute[:voxel].devices_list.body end tests('#devices_list(@server_id)').formats(@devices_format) do pending if Fog.mocking? Fog::Compute[:voxel].devices_list(@server_id).body end tests("#voxcloud_delete(#{@server_id})").succeeds do pending if Fog.mocking? Fog::Compute[:voxel].voxcloud_delete(@server_id) end end tests('failure') do tests('#voxcloud_delete(0)').raises(Fog::Compute::Voxel::Error) do pending if Fog.mocking? Fog::Compute[:voxel].voxcloud_delete(0) end tests('#voxcloud_status(0)').raises(Fog::Compute::Voxel::Error) do pending if Fog.mocking? Fog::Compute[:voxel].voxcloud_status(0) end tests('#devices_list(0)').raises(Fog::Compute::Voxel::Error) do pending if Fog.mocking? Fog::Compute[:voxel].devices_list(0) end end end fog-1.19.0/tests/cloudsigma/0000755000004100000410000000000012261242552015677 5ustar www-datawww-datafog-1.19.0/tests/cloudsigma/requests/0000755000004100000410000000000012261242552017552 5ustar www-datawww-datafog-1.19.0/tests/cloudsigma/requests/server_tests.rb0000644000004100000410000000455012261242552022633 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudsigma] | server requests', ['cloudsigma']) do @server_format = { 'uuid' => String, 'status' => String, 'vnc_password' => String, 'name' => String, 'cpus_instead_of_cores' => Fog::Boolean, 'tags' => Array, 'mem' => Integer, 'enable_numa' => Fog::Boolean, 'smp' => Integer, 'hv_relaxed' => Fog::Boolean, 'hv_tsc' => Fog::Boolean, 'meta' => Fog::Nullable::Hash, 'owner' => Fog::Nullable::Hash, 'runtime' => Fog::Nullable::Hash, 'cpu' => Integer, 'resource_uri' => Fog::Nullable::String, 'drives' => Array, 'nics' => Array } @server_create_args = {:name => 'fogtest', :cpu => 2000, :mem => 512*1024**2, :vnc_password => 'myrandompass'} tests('success') do tests("#create_server(#@server_create_args)").formats(@server_format, false) do server_def = Fog::Compute[:cloudsigma].create_server(@server_create_args).body['objects'].first @server_uuid = server_def['uuid'] server_def end tests("#get_server(#@server_uuid)").formats(@server_format, false) do @resp_server = Fog::Compute[:cloudsigma].get_server(@server_uuid).body end tests("#update_server(#@server_uuid)").formats(@server_format, false) do @resp_server['cpu'] = 1000 @resp_server = Fog::Compute[:cloudsigma].update_server(@server_uuid, @resp_server).body @resp_server end tests("#start_server(#@server_uuid)").succeeds do response = Fog::Compute[:cloudsigma].start_server(@server_uuid) response.body['result'] == "success" end server = Fog::Compute[:cloudsigma].servers.get(@server_uuid) server.wait_for { status == 'running' } tests("#stop_server(#@server_uuid)").succeeds do response = Fog::Compute[:cloudsigma].stop_server(@server_uuid) response.body['result'] == "success" end server = Fog::Compute[:cloudsigma].servers.get(@server_uuid) server.wait_for { status == 'stopped' } tests("#delete_server(#@server_uuid)").succeeds do resp = Fog::Compute[:cloudsigma].delete_server(@server_uuid) resp.body.empty? && resp.status == 204 end end tests('failure') do tests("#get_server(#@server_uuid)|deleted|").raises(Fog::CloudSigma::Errors::NotFound) do Fog::Compute[:cloudsigma].get_server(@server_uuid).body end end end fog-1.19.0/tests/cloudsigma/requests/volumes_tests.rb0000644000004100000410000000312112261242552023010 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudsigma] | volume requests', ['cloudsigma']) do @volume_format = { 'uuid' => String, 'size' => Integer, 'status' => String, 'name' => String, 'tags' => Array, 'meta' => Fog::Nullable::Hash, 'owner' => Fog::Nullable::Hash, 'resource_uri' => Fog::Nullable::String, 'licenses' => Array, 'jobs' => Array, 'affinities' => Array, 'mounted_on' => Array, 'media' => String, 'allow_multimount' => Fog::Boolean } @volume_create_args = {:name => 'fogtest', :size => 1024**3, :media => :cdrom} tests('success') do tests("#create_volume(#@volume_create_args)").formats(@volume_format, false) do @resp_volume = Fog::Compute[:cloudsigma].create_volume(@volume_create_args).body['objects'].first @volume_uuid = @resp_volume['uuid'] @resp_volume end volume = Fog::Compute[:cloudsigma].volumes.get(@volume_uuid) volume.wait_for { status == 'unmounted' } tests("#update_volume(#@volume_uuid)").formats(@volume_format, false) do @resp_volume['media'] = 'disk' @resp_volume = Fog::Compute[:cloudsigma].update_volume(@volume_uuid, @resp_volume).body @resp_volume end tests("#delete_volume(#@volume_uuid)").succeeds do resp = Fog::Compute[:cloudsigma].delete_volume(@volume_uuid) resp.body.empty? && resp.status == 204 end end tests('failure') do tests("#get_volume(#@server_uuid)|deleted|").raises(Fog::CloudSigma::Errors::NotFound) do Fog::Compute[:cloudsigma].get_volume(@volume_uuid).body end end endfog-1.19.0/tests/cloudsigma/models/0000755000004100000410000000000012261242552017162 5ustar www-datawww-datafog-1.19.0/tests/cloudsigma/models/server_tests.rb0000644000004100000410000000376212261242552022247 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudsigma] | server model', ['cloudsigma']) do service = Fog::Compute[:cloudsigma] servers = Fog::Compute[:cloudsigma].servers server_create_args = {:name => 'fogtest', :cpu => 2000, :mem => 512*1024**2, :vnc_password => 'myrandompass'} model_tests(servers, server_create_args, true) do tests('start_stop').succeeds do @instance.start @instance.wait_for(timeout=60) { status == 'running' } @instance.stop @instance.wait_for(timeout=60) { status == 'stopped' } end tests('attach_dhcp_nic').succeeds do @instance.add_public_nic() @instance.save @instance.reload returns('dhcp') { @instance.nics.first.ip_v4_conf.conf } succeeds {/^([0-9a-f]{2}[:]){5}([0-9a-f]{2})$/ === @instance.nics.first.mac} end tests('attach_vlan') do if Fog.mocking? # Do not buy subscription with real account service.subscriptions.create({:period=>"1 month", :amount=>1, :resource=>"vlan"}) vlan = service.vlans.first vlan.meta['name'] = 'fog-test' vlan.save end vlan = service.vlans.find {|vlan| vlan.meta['name'] == 'fog-test'} # Skip if there is no vlan marked for fog tests pending unless vlan @instance.add_private_nic(vlan) @instance.save @instance.reload returns(vlan.uuid) { @instance.nics.last.vlan['uuid'] || @instance.nics.last.vlan} succeeds {/^([0-9a-f]{2}[:]){5}([0-9a-f]{2})$/ === @instance.nics.last.mac} end tests('attach_volume') do volume_create_args = {:name => 'fogservermodeltest', :size => 1000**3, :media => :cdrom} v = service.volumes.create(volume_create_args) volume_uuid = v.uuid @instance.mount_volume(v) @instance.save @instance.reload returns(volume_uuid) { @instance.volumes.first.volume } @instance.unmount_volume(v) @instance.save @instance.reload succeeds { @instance.volumes.empty? } v.delete end end endfog-1.19.0/tests/cloudsigma/models/volumes_tests.rb0000644000004100000410000000052112261242552022421 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudsigma] | volumes collection', ['cloudsigma']) do volumes = Fog::Compute[:cloudsigma].volumes volume_create_args = {:name => 'fogtest', :size => 1024**3, :media => :cdrom} collection_tests(volumes, volume_create_args, true) do @instance.wait_for(timeout=60) { status == 'unmounted' } end endfog-1.19.0/tests/cloudsigma/models/servers_tests.rb0000644000004100000410000000045412261242552022425 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudsigma] | servers collection', ['cloudsigma']) do servers = Fog::Compute[:cloudsigma].servers server_create_args = {:name => 'fogtest', :cpu => 2000, :mem => 512*1024**2, :vnc_password => 'myrandompass'} collection_tests(servers, server_create_args, true) endfog-1.19.0/tests/cloudsigma/models/volume_tests.rb0000644000004100000410000000120512261242552022236 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudsigma] | volume model', ['cloudsigma']) do volumes = Fog::Compute[:cloudsigma].volumes volume_create_args = {:name => 'fogmodeltest', :size => 1000**3, :media => :cdrom} model_tests(volumes, volume_create_args, true) do @instance.wait_for(timeout=60) { status == 'unmounted' } tests('#update').succeeds do @instance.media = 'disk' #@instance.size = 1024**3 # resizes disk @instance.save @instance.reload @instance.wait_for(timeout=60) { status == 'unmounted' } #returns(1024**3) { @instance.size } returns('disk') { @instance.media } end end endfog-1.19.0/tests/aws/0000755000004100000410000000000012261242552014342 5ustar www-datawww-datafog-1.19.0/tests/aws/signaturev4_tests.rb0000644000004100000410000000515112261242552020366 0ustar www-datawww-data# encoding: utf-8 Shindo.tests('AWS | signaturev4', ['aws']) do # These testcases are from http://docs.amazonwebservices.com/general/latest/gr/signature-v4-test-suite.html @signer = Fog::AWS::SignatureV4.new('AKIDEXAMPLE', 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', 'us-east-1','host') Fog::Time.now = ::Time.utc(2011,9,9,23,36,0) tests('get-vanilla') do returns(@signer.sign({:headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/'}, Fog::Time.now)) do 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=b27ccfbfa7df52a200ff74193ca6e32d4b48b8856fab7ebf1c595d0670a7e470' end end tests('get-vanilla-query-order-key with symbol keys') do returns(@signer.sign({:query => {:'a' => 'foo', :'b' => 'foo'}, :headers => {:'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/'}, Fog::Time.now)) do 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=0dc122f3b28b831ab48ba65cb47300de53fbe91b577fe113edac383730254a3b' end end tests('get-vanilla-query-order-key') do returns(@signer.sign({:query => {'a' => 'foo', 'b' => 'foo'}, :headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/'}, Fog::Time.now)) do 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=0dc122f3b28b831ab48ba65cb47300de53fbe91b577fe113edac383730254a3b' end end tests('get-unreserved') do returns(@signer.sign({:headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/-._~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'}, Fog::Time.now)) do 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=830cc36d03f0f84e6ee4953fbe701c1c8b71a0372c63af9255aa364dd183281e' end end tests('post-x-www-form-urlencoded-parameter') do returns(@signer.sign({:headers => {'Content-type' => 'application/x-www-form-urlencoded; charset=utf8', 'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :post, :path => '/', :body => 'foo=bar'}, Fog::Time.now)) do 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=content-type;date;host, Signature=b105eb10c6d318d2294de9d49dd8b031b55e3c3fe139f2e637da70511e9e7b71' end end Fog::Time.now = ::Time.now endfog-1.19.0/tests/aws/requests/0000755000004100000410000000000012261242552016215 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/sts/0000755000004100000410000000000012261242552017026 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/sts/get_federation_token_tests.rb0000644000004100000410000000106612261242552024757 0ustar www-datawww-dataShindo.tests('AWS::STS | session tokens', ['aws']) do @policy = {"Statement" => [{"Effect" => "Allow", "Action" => "*", "Resource" => "*"}]} @federation_format = { 'SessionToken' => String, 'SecretAccessKey' => String, 'Expiration' => String, 'AccessKeyId' => String, 'Arn' => String, 'FederatedUserId' => String, 'PackedPolicySize' => String, 'RequestId' => String } tests("#get_federation_token('test@fog.io', #{@policy.inspect})").formats(@federation_format) do Fog::AWS[:sts].get_federation_token("test@fog.io", @policy).body end end fog-1.19.0/tests/aws/requests/sts/assume_role_tests.rb0000644000004100000410000000111012261242552023104 0ustar www-datawww-dataShindo.tests('AWS::STS | assume role', ['aws']) do @policy = {"Statement" => [{"Effect" => "Allow", "Action" => "*", "Resource" => "*"}]} @response_format = { 'SessionToken' => String, 'SecretAccessKey' => String, 'Expiration' => String, 'AccessKeyId' => String, 'Arn' => String, 'RequestId' => String } tests("#assume_role('rolename', 'assumed_role_session', 'external_id', #{@policy.inspect}, 900)").formats(@response_format) do pending if Fog.mocking? Fog::AWS[:sts].assume_role("rolename","assumed_role_session","external_id", @policy, 900).body end end fog-1.19.0/tests/aws/requests/sts/session_token_tests.rb0000644000004100000410000000053612261242552023464 0ustar www-datawww-dataShindo.tests('AWS::STS | session tokens', ['aws']) do @session_format = { 'SessionToken' => String, 'SecretAccessKey' => String, 'Expiration' => String, 'AccessKeyId' => String, 'RequestId' => String } tests("#get_session_token").formats(@session_format) do pending if Fog.mocking? Fog::AWS[:sts].get_session_token.body end end fog-1.19.0/tests/aws/requests/sqs/0000755000004100000410000000000012261242552017023 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/sqs/helper.rb0000644000004100000410000000022012261242552020621 0ustar www-datawww-dataclass AWS module SQS module Formats BASIC = { 'ResponseMetadata' => {'RequestId' => String} } end end end fog-1.19.0/tests/aws/requests/sqs/message_tests.rb0000644000004100000410000000317512261242552022224 0ustar www-datawww-dataShindo.tests('AWS::SQS | message requests', ['aws']) do tests('success') do @queue_url = Fog::AWS[:sqs].create_queue('fog_message_tests').body['QueueUrl'] send_message_format = AWS::SQS::Formats::BASIC.merge({ 'MessageId' => String, 'MD5OfMessageBody' => String }) tests("#send_message('#{@queue_url}', 'message')").formats(send_message_format) do Fog::AWS[:sqs].send_message(@queue_url, 'message').body end receive_message_format = AWS::SQS::Formats::BASIC.merge({ 'Message' => [{ 'Attributes' => { 'ApproximateFirstReceiveTimestamp' => Time, 'ApproximateReceiveCount' => Integer, 'SenderId' => String, 'SentTimestamp' => Time }, 'Body' => String, 'MD5OfBody' => String, 'MessageId' => String, 'ReceiptHandle' => String }] }) tests("#receive_message").formats(receive_message_format) do data = Fog::AWS[:sqs].receive_message(@queue_url).body @receipt_handle = data['Message'].first['ReceiptHandle'] data end tests("#change_message_visibility('#{@queue_url}, '#{@receipt_handle}', 60)").formats(AWS::SQS::Formats::BASIC) do Fog::AWS[:sqs].change_message_visibility(@queue_url, @receipt_handle, 60).body end tests("#delete_message('#{@queue_url}', '#{@receipt_handle}')").formats(AWS::SQS::Formats::BASIC) do Fog::AWS[:sqs].delete_message(@queue_url, @receipt_handle).body end unless Fog.mocking? Fog::AWS[:sqs].delete_queue(@queue_url) end end endfog-1.19.0/tests/aws/requests/sqs/queue_tests.rb0000644000004100000410000000322212261242552021715 0ustar www-datawww-dataShindo.tests('AWS::SQS | queue requests', ['aws']) do tests('success') do create_queue_format = AWS::SQS::Formats::BASIC.merge({ 'QueueUrl' => String }) tests("#create_queue('fog_queue_tests')").formats(create_queue_format) do data = Fog::AWS[:sqs].create_queue('fog_queue_tests').body @queue_url = data['QueueUrl'] data end list_queues_format = AWS::SQS::Formats::BASIC.merge({ 'QueueUrls' => [String] }) tests("#list_queues").formats(list_queues_format) do Fog::AWS[:sqs].list_queues.body end tests("#set_queue_attributes('#{@queue_url}', 'VisibilityTimeout', 60)").formats(AWS::SQS::Formats::BASIC) do Fog::AWS[:sqs].set_queue_attributes(@queue_url, 'VisibilityTimeout', 60).body end get_queue_attributes_format = AWS::SQS::Formats::BASIC.merge({ 'Attributes' => { 'ApproximateNumberOfMessages' => Integer, 'ApproximateNumberOfMessagesNotVisible' => Integer, 'CreatedTimestamp' => Time, 'MaximumMessageSize' => Integer, 'LastModifiedTimestamp' => Time, 'MessageRetentionPeriod' => Integer, 'QueueArn' => String, 'VisibilityTimeout' => Integer } }) tests("#get_queue_attributes('#{@queue_url}', 'All')").formats(get_queue_attributes_format) do Fog::AWS[:sqs].get_queue_attributes(@queue_url, 'All').body end tests("#delete_queue('#{@queue_url}')").formats(AWS::SQS::Formats::BASIC) do Fog::AWS[:sqs].delete_queue(@queue_url).body end end endfog-1.19.0/tests/aws/requests/storage/0000755000004100000410000000000012261242552017661 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/storage/multipart_upload_tests.rb0000644000004100000410000001066612261242552025026 0ustar www-datawww-dataShindo.tests('Fog::Storage[:aws] | multipart upload requests', ["aws"]) do @directory = Fog::Storage[:aws].directories.create(:key => uniq_id('fogmultipartuploadtests')) tests('success') do @initiate_multipart_upload_format = { 'Bucket' => String, 'Key' => String, 'UploadId' => String } tests("#initiate_multipart_upload('#{@directory.identity}')", 'fog_multipart_upload').formats(@initiate_multipart_upload_format) do pending if Fog.mocking? data = Fog::Storage[:aws].initiate_multipart_upload(@directory.identity, 'fog_multipart_upload').body @upload_id = data['UploadId'] data end @list_multipart_uploads_format = { 'Bucket' => String, 'IsTruncated' => Fog::Boolean, 'MaxUploads' => Integer, 'KeyMarker' => NilClass, 'NextKeyMarker' => String, 'NextUploadIdMarker' => Fog::Nullable::String, 'Upload' => [{ 'Initiated' => Time, 'Initiator' => { 'DisplayName' => String, 'ID' => String }, 'Key' => String, 'Owner' => { 'DisplayName' => String, 'ID' => String }, 'StorageClass' => String, 'UploadId' => String }], 'UploadIdMarker' => NilClass, } tests("#list_multipart_uploads('#{@directory.identity})").formats(@list_multipart_uploads_format) do pending if Fog.mocking? Fog::Storage[:aws].list_multipart_uploads(@directory.identity).body end @parts = [] tests("#upload_part('#{@directory.identity}', 'fog_multipart_upload', '#{@upload_id}', 1, ('x' * 6 * 1024 * 1024))").succeeds do pending if Fog.mocking? data = Fog::Storage[:aws].upload_part(@directory.identity, 'fog_multipart_upload', @upload_id, 1, ('x' * 6 * 1024 * 1024)) @parts << data.headers['ETag'] end @list_parts_format = { 'Bucket' => String, 'Initiator' => { 'DisplayName' => String, 'ID' => String }, 'IsTruncated' => Fog::Boolean, 'Key' => String, 'MaxParts' => Integer, 'NextPartNumberMarker' => String, 'Part' => [{ 'ETag' => String, 'LastModified' => Time, 'PartNumber' => Integer, 'Size' => Integer }], 'PartNumberMarker' => String, 'StorageClass' => String, 'UploadId' => String } tests("#list_parts('#{@directory.identity}', 'fog_multipart_upload', '#{@upload_id}')").formats(@list_parts_format) do pending if Fog.mocking? Fog::Storage[:aws].list_parts(@directory.identity, 'fog_multipart_upload', @upload_id).body end if !Fog.mocking? @parts << Fog::Storage[:aws].upload_part(@directory.identity, 'fog_multipart_upload', @upload_id, 2, ('x' * 4 * 1024 * 1024)).headers['ETag'] end @complete_multipart_upload_format = { 'Bucket' => String, 'ETag' => String, 'Key' => String, 'Location' => String } tests("#complete_multipart_upload('#{@directory.identity}', 'fog_multipart_upload', '#{@upload_id}', #{@parts.inspect})").formats(@complete_multipart_upload_format) do pending if Fog.mocking? Fog::Storage[:aws].complete_multipart_upload(@directory.identity, 'fog_multipart_upload', @upload_id, @parts).body end tests("#get_object('#{@directory.identity}', 'fog_multipart_upload').body").succeeds do pending if Fog.mocking? Fog::Storage[:aws].get_object(@directory.identity, 'fog_multipart_upload').body == ('x' * 10 * 1024 * 1024) end if !Fog.mocking? @directory.files.new(:key => 'fog_multipart_upload').destroy end if !Fog.mocking? @upload_id = Fog::Storage[:aws].initiate_multipart_upload(@directory.identity, 'fog_multipart_abort').body['UploadId'] end tests("#abort_multipart_upload('#{@directory.identity}', 'fog_multipart_abort', '#{@upload_id}')").succeeds do pending if Fog.mocking? Fog::Storage[:aws].abort_multipart_upload(@directory.identity, 'fog_multipart_abort', @upload_id) end end tests('failure') do tests("initiate_multipart_upload") tests("list_multipart_uploads") tests("upload_part") tests("list_parts") tests("complete_multipart_upload") tests("abort_multipart_upload") end @directory.destroy end fog-1.19.0/tests/aws/requests/storage/object_tests.rb0000644000004100000410000001650612261242552022706 0ustar www-datawww-dataShindo.tests('AWS::Storage | object requests', ['aws']) do @directory = Fog::Storage[:aws].directories.create(:key => 'fogobjecttests-' + Time.now.to_i.to_s(32)) @aws_owner = Fog::Storage[:aws].get_bucket_acl(@directory.key).body['Owner'] tests('success') do @multiple_delete_format = { 'DeleteResult' => [{ 'Deleted' => { 'Key' => String } }] } tests("#put_object('#{@directory.identity}', 'fog_object', lorem_file)").succeeds do Fog::Storage[:aws].put_object(@directory.identity, 'fog_object', lorem_file) end tests("#copy_object('#{@directory.identity}', 'fog_object', '#{@directory.identity}', 'fog_other_object')").succeeds do Fog::Storage[:aws].copy_object(@directory.identity, 'fog_object', @directory.identity, 'fog_other_object') end @directory.files.get('fog_other_object').destroy tests("#get_object('#{@directory.identity}', 'fog_object')").returns(lorem_file.read) do Fog::Storage[:aws].get_object(@directory.identity, 'fog_object').body end tests("#get_object('#{@directory.identity}', 'fog_object', &block)").returns(lorem_file.read) do data = '' Fog::Storage[:aws].get_object(@directory.identity, 'fog_object') do |chunk, remaining_bytes, total_bytes| data << chunk end data end tests("#get_object('#{@directory.identity}', 'fog_object', {'Range' => 'bytes=0-20'})").returns(lorem_file.read[0..20]) do Fog::Storage[:aws].get_object(@directory.identity, 'fog_object', {'Range' => 'bytes=0-20'}).body end tests("#get_object('#{@directory.identity}', 'fog_object', {'Range' => 'bytes=0-0'})").returns(lorem_file.read[0..0]) do Fog::Storage[:aws].get_object(@directory.identity, 'fog_object', {'Range' => 'bytes=0-0'}).body end tests("#head_object('#{@directory.identity}', 'fog_object')").succeeds do Fog::Storage[:aws].head_object(@directory.identity, 'fog_object') end tests("#post_object_restore('#{@directory.identity}', 'fog_object')").succeeds do pending unless Fog.mocking? Fog::Storage[:aws].post_object_restore(@directory.identity, 'fog_object') end tests("#put_object_acl('#{@directory.identity}', 'fog_object', 'private')").succeeds do Fog::Storage[:aws].put_object_acl(@directory.identity, 'fog_object', 'private') end acl = { 'Owner' => @aws_owner, 'AccessControlList' => [ { 'Grantee' => @aws_owner, 'Permission' => "FULL_CONTROL" } ]} tests("#put_object_acl('#{@directory.identity}', 'fog_object', hash with id)").returns(acl) do Fog::Storage[:aws].put_object_acl(@directory.identity, 'fog_object', acl) Fog::Storage[:aws].get_object_acl(@directory.identity, 'fog_object').body end tests("#put_object_acl('#{@directory.identity}', 'fog_object', hash with email)").returns({ 'Owner' => @aws_owner, 'AccessControlList' => [ { 'Grantee' => { 'ID' => 'f62f0218873cfa5d56ae9429ae75a592fec4fd22a5f24a20b1038a7db9a8f150', 'DisplayName' => 'mtd' }, 'Permission' => "FULL_CONTROL" } ]}) do pending if Fog.mocking? Fog::Storage[:aws].put_object_acl(@directory.identity, 'fog_object', { 'Owner' => @aws_owner, 'AccessControlList' => [ { 'Grantee' => { 'EmailAddress' => 'mtd@amazon.com' }, 'Permission' => "FULL_CONTROL" } ]}) Fog::Storage[:aws].get_object_acl(@directory.identity, 'fog_object').body end acl = { 'Owner' => @aws_owner, 'AccessControlList' => [ { 'Grantee' => { 'URI' => 'http://acs.amazonaws.com/groups/global/AllUsers' }, 'Permission' => "FULL_CONTROL" } ]} tests("#put_object_acl('#{@directory.identity}', 'fog_object', hash with uri)").returns(acl) do Fog::Storage[:aws].put_object_acl(@directory.identity, 'fog_object', acl) Fog::Storage[:aws].get_object_acl(@directory.identity, 'fog_object').body end tests("#delete_object('#{@directory.identity}', 'fog_object')").succeeds do Fog::Storage[:aws].delete_object(@directory.identity, 'fog_object') end tests("#get_object_http_url('#{@directory.identity}', 'fog_object', expiration timestamp)").returns(true) do object_url = Fog::Storage[:aws].get_object_http_url(@directory.identity, 'fog_object', (Time.now + 60)) (object_url =~ /http:\/\/#{Regexp.quote(@directory.identity)}\.s3\.amazonaws\.com\/fog_object/) != nil end tests("delete_multiple_objects('#{@directory.identity}', ['fog_object', 'fog_other_object'])").formats(@multiple_delete_format) do Fog::Storage[:aws].delete_multiple_objects(@directory.identity, ['fog_object', 'fog_other_object']).body end end fognonbucket = uniq_id('fognonbucket') tests('failure') do tests("#put_object('#{fognonbucket}', 'fog_non_object', lorem_file)").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].put_object(fognonbucket, 'fog_non_object', lorem_file) end tests("#copy_object('#{fognonbucket}', 'fog_object', '#{@directory.identity}', 'fog_other_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].copy_object(fognonbucket, 'fog_object', @directory.identity, 'fog_other_object') end tests("#copy_object('#{@directory.identity}', 'fog_non_object', '#{@directory.identity}', 'fog_other_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].copy_object(@directory.identity, 'fog_non_object', @directory.identity, 'fog_other_object') end tests("#copy_object('#{@directory.identity}', 'fog_object', 'fognonbucket', 'fog_other_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].copy_object(@directory.identity, 'fog_object', fognonbucket, 'fog_other_object') end tests("#get_object('#{fognonbucket}', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].get_object(fognonbucket, 'fog_non_object') end tests("#get_object('#{@directory.identity}', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].get_object(@directory.identity, 'fog_non_object') end tests("#head_object(fognonbucket, 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].head_object(fognonbucket, 'fog_non_object') end tests("#head_object('#{@directory.identity}', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].head_object(@directory.identity, 'fog_non_object') end tests("#delete_object('#{fognonbucket}', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].delete_object(fognonbucket, 'fog_non_object') end tests("#delete_multiple_objects('#{fognonbucket}', ['fog_non_object'])").raises(Excon::Errors::NotFound) do pending if Fog.mocking? Fog::Storage[:aws].delete_multiple_objects(fognonbucket, ['fog_non_object']) end tests("#put_object_acl('#{@directory.identity}', 'fog_object', 'invalid')").raises(Excon::Errors::BadRequest) do Fog::Storage[:aws].put_object_acl('#{@directory.identity}', 'fog_object', 'invalid') end tests("#post_object_restore('#{@directory.identity}', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].post_object_restore(@directory.identity, 'fog_non_object') end end @directory.destroy end fog-1.19.0/tests/aws/requests/storage/acl_utils_tests.rb0000644000004100000410000002246212261242552023415 0ustar www-datawww-datarequire 'fog/aws/requests/storage/acl_utils' Shindo.tests('Fog::Storage::AWS | ACL utils', ["aws"]) do tests(".hash_to_acl") do tests(".hash_to_acl({}) at xpath //AccessControlPolicy").returns("", "has an empty AccessControlPolicy") do xml = Fog::Storage::AWS.hash_to_acl({}) Nokogiri::XML(xml).xpath("//AccessControlPolicy").first.content.chomp end tests(".hash_to_acl({}) at xpath //AccessControlPolicy/Owner").returns(nil, "does not have an Owner element") do xml = Fog::Storage::AWS.hash_to_acl({}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner").first end tests(".hash_to_acl('Owner' => {}) at xpath //AccessControlPolicy/Owner").returns(nil, "does not have an Owner element") do xml = Fog::Storage::AWS.hash_to_acl('Owner' => {}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner").first end tests(".hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'}) at xpath //AccessControlPolicy/Owner/ID").returns("abcdef0123456789", "returns the Owner ID") do xml = Fog::Storage::AWS.hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/ID").first.content end tests(".hash_to_acl('Owner' => {'DisplayName' => 'bob'}) at xpath //AccessControlPolicy/Owner/ID").returns(nil, "does not have an Owner ID element") do xml = Fog::Storage::AWS.hash_to_acl('Owner' => {'DisplayName' => 'bob'}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/ID").first end tests(".hash_to_acl('Owner' => {'DisplayName' => 'bob'}) at xpath //AccessControlPolicy/Owner/DisplayName").returns("bob", "returns the Owner DisplayName") do xml = Fog::Storage::AWS.hash_to_acl('Owner' => {'DisplayName' => 'bob'}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/DisplayName").first.content end tests(".hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'}) at xpath //AccessControlPolicy/Owner/DisplayName").returns(nil, "does not have an Owner DisplayName element") do xml = Fog::Storage::AWS.hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/DisplayName").first end tests(".hash_to_acl({}) at xpath //AccessControlPolicy/AccessControlList").returns(nil, "has no AccessControlList") do xml = Fog::Storage::AWS.hash_to_acl({}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlPolicy").first end acl = { 'AccessControlList' => [ { 'Grantee' => { 'ID' => 'abcdef0123456789', 'DisplayName' => 'bob' }, 'Permission' => 'READ' } ] } tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee").returns("CanonicalUser", "has an xsi:type of CanonicalUser") do xml = Fog::Storage::AWS.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee").first.attributes["type"].value end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/ID").returns("abcdef0123456789", "returns the Grantee ID") do xml = Fog::Storage::AWS.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/ID").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/DisplayName").returns("bob", "returns the Grantee DisplayName") do xml = Fog::Storage::AWS.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/DisplayName").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Permission").returns("READ", "returns the Grantee Permission") do xml = Fog::Storage::AWS.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Permission").first.content end acl = { 'AccessControlList' => [ { 'Grantee' => { 'EmailAddress' => 'user@example.com' }, 'Permission' => 'FULL_CONTROL' } ] } tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee").returns("AmazonCustomerByEmail", "has an xsi:type of AmazonCustomerByEmail") do xml = Fog::Storage::AWS.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee").first.attributes["type"].value end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").returns("user@example.com", "returns the Grantee EmailAddress") do xml = Fog::Storage::AWS.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Permission").returns("FULL_CONTROL", "returns the Grantee Permission") do xml = Fog::Storage::AWS.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Permission").first.content end acl = { 'AccessControlList' => [ { 'Grantee' => { 'URI' => 'http://acs.amazonaws.com/groups/global/AllUsers' }, 'Permission' => 'WRITE' } ] } tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee").returns("Group", "has an xsi:type of Group") do xml = Fog::Storage::AWS.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee").first.attributes["type"].value end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/URI").returns("http://acs.amazonaws.com/groups/global/AllUsers", "returns the Grantee URI") do xml = Fog::Storage::AWS.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/URI").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Permission").returns("WRITE", "returns the Grantee Permission") do xml = Fog::Storage::AWS.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Permission").first.content end acl = { 'AccessControlList' => [ { 'Grantee' => { 'ID' => 'abcdef0123456789', 'DisplayName' => 'bob' }, 'Permission' => 'READ' }, { 'Grantee' => { 'EmailAddress' => 'user@example.com' }, 'Permission' => 'FULL_CONTROL' }, { 'Grantee' => { 'URI' => 'http://acs.amazonaws.com/groups/global/AllUsers' }, 'Permission' => 'WRITE' } ] } tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant").returns(3, "has three elements") do xml = Fog::Storage::AWS.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant").size end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/ID").returns("abcdef0123456789", "returns the first Grant's Grantee ID") do xml = Fog::Storage::AWS.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/ID").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").returns("user@example.com", "returns the second Grant's Grantee EmailAddress") do xml = Fog::Storage::AWS.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/URI").returns("http://acs.amazonaws.com/groups/global/AllUsers", "returns the third Grant's Grantee URI") do xml = Fog::Storage::AWS.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/URI").first.content end end tests(".acl_to_hash") do acl_xml = <<-XML 2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0 me 2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0 me FULL_CONTROL XML tests(".acl_to_hash(#{acl_xml.inspect})").returns({ "Owner" => { "DisplayName" => "me", "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0" }, "AccessControlList" => [{ "Grantee" => { "DisplayName" => "me", "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0" }, "Permission" => "FULL_CONTROL" }] }, 'returns hash of ACL XML') do Fog::Storage::AWS.acl_to_hash(acl_xml) end end end fog-1.19.0/tests/aws/requests/storage/delete_multiple_objects_tests.rb0000644000004100000410000000104012261242552026311 0ustar www-datawww-dataShindo.tests('AWS::Storage | delete_multiple_objects', ['aws']) do @directory = Fog::Storage[:aws].directories.create(:key => 'fogobjecttests-' + Time.now.to_i.to_s(32)) tests("doesn't alter options") do version_id = {'fog_object' => ['12345']} options = {:quiet => true, 'versionId' => version_id} Fog::Storage[:aws].delete_multiple_objects(@directory.identity, ['fog_object'], options) test(":quiet is unchanged") { options[:quiet] } test("'versionId' is unchanged") { options['versionId'] == version_id } end end fog-1.19.0/tests/aws/requests/storage/versioning_tests.rb0000644000004100000410000002430712261242552023621 0ustar www-datawww-datadef clear_bucket Fog::Storage[:aws].get_bucket_object_versions(@aws_bucket_name).body['Versions'].each do |version| object = version[version.keys.first] Fog::Storage[:aws].delete_object(@aws_bucket_name, object['Key'], 'versionId' => object['VersionId']) end end def create_versioned_bucket @aws_bucket_name = 'fogbuckettests-' + Fog::Mock.random_hex(16) Fog::Storage[:aws].put_bucket(@aws_bucket_name) Fog::Storage[:aws].put_bucket_versioning(@aws_bucket_name, 'Enabled') end def delete_bucket Fog::Storage[:aws].get_bucket_object_versions(@aws_bucket_name).body['Versions'].each do |version| object = version[version.keys.first] Fog::Storage[:aws].delete_object(@aws_bucket_name, object['Key'], 'versionId' => object['VersionId']) end Fog::Storage[:aws].delete_bucket(@aws_bucket_name) end Shindo.tests('Fog::Storage[:aws] | versioning', ["aws"]) do tests('success') do tests("#put_bucket_versioning") do @aws_bucket_name = 'fogbuckettests-' + Fog::Mock.random_hex(16) Fog::Storage[:aws].put_bucket(@aws_bucket_name) tests("#put_bucket_versioning('#{@aws_bucket_name}', 'Enabled')").succeeds do Fog::Storage[:aws].put_bucket_versioning(@aws_bucket_name, 'Enabled') end tests("#put_bucket_versioning('#{@aws_bucket_name}', 'Suspended')").succeeds do Fog::Storage[:aws].put_bucket_versioning(@aws_bucket_name, 'Suspended') end delete_bucket end tests("#get_bucket_versioning('#{@aws_bucket_name}')") do @aws_bucket_name = 'fogbuckettests-' + Fog::Mock.random_hex(16) Fog::Storage[:aws].put_bucket(@aws_bucket_name) tests("#get_bucket_versioning('#{@aws_bucket_name}') without versioning").returns({}) do Fog::Storage[:aws].get_bucket_versioning(@aws_bucket_name).body['VersioningConfiguration'] end tests("#get_bucket_versioning('#{@aws_bucket_name}') with versioning enabled").returns('Enabled') do Fog::Storage[:aws].put_bucket_versioning(@aws_bucket_name, 'Enabled') Fog::Storage[:aws].get_bucket_versioning(@aws_bucket_name).body['VersioningConfiguration']['Status'] end tests("#get_bucket_versioning('#{@aws_bucket_name}') with versioning suspended").returns('Suspended') do Fog::Storage[:aws].put_bucket_versioning(@aws_bucket_name, 'Suspended') Fog::Storage[:aws].get_bucket_versioning(@aws_bucket_name).body['VersioningConfiguration']['Status'] end delete_bucket end tests("#get_bucket_object_versions('#{@aws_bucket_name}')") do create_versioned_bucket before do @versions = Fog::Storage[:aws].get_bucket_object_versions(@aws_bucket_name) end v1 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'a', :key => 'file') v2 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'ab', :key => v1.key) v3 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'abc', :key => v1.key) v4 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'abcd', :key => v1.key) tests("versions").returns([v4.version, v3.version, v2.version, v1.version]) do @versions.body['Versions'].collect {|v| v['Version']['VersionId']} end tests("version sizes").returns([4, 3, 2, 1]) do @versions.body['Versions'].collect {|v| v['Version']['Size']} end tests("latest version").returns(v4.version) do latest = @versions.body['Versions'].find {|v| v['Version']['IsLatest']} latest['Version']['VersionId'] end end tests("get_object('#{@aws_bucket_name}', 'file')") do clear_bucket v1 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'a', :key => 'file') v2 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'ab', :key => v1.key) tests("get_object('#{@aws_bucket_name}', '#{v2.key}') returns the latest version").returns(v2.version) do res = Fog::Storage[:aws].get_object(@aws_bucket_name, v2.key) res.headers['x-amz-version-id'] end tests("get_object('#{@aws_bucket_name}', '#{v1.key}', 'versionId' => '#{v1.version}') returns the specified version").returns(v1.version) do res = Fog::Storage[:aws].get_object(@aws_bucket_name, v1.key, 'versionId' => v1.version) res.headers['x-amz-version-id'] end v2.destroy tests("get_object('#{@aws_bucket_name}', '#{v2.key}') raises exception if delete marker is latest version").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].get_object(@aws_bucket_name, v2.key) end end tests("delete_object('#{@aws_bucket_name}', 'file')") do clear_bucket file = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'a', :key => 'file') tests("deleting an object just stores a delete marker").returns(true) do file.destroy versions = Fog::Storage[:aws].get_bucket_object_versions(@aws_bucket_name) versions.body['Versions'].first.has_key?('DeleteMarker') end tests("there are two versions: the original and the delete marker").returns(2) do versions = Fog::Storage[:aws].get_bucket_object_versions(@aws_bucket_name) versions.body['Versions'].size end tests("deleting the delete marker makes the object available again").returns(file.version) do versions = Fog::Storage[:aws].get_bucket_object_versions(@aws_bucket_name) delete_marker = versions.body['Versions'].find { |v| v.has_key?('DeleteMarker') } Fog::Storage[:aws].delete_object(@aws_bucket_name, file.key, 'versionId' => delete_marker['DeleteMarker']['VersionId']) res = Fog::Storage[:aws].get_object(@aws_bucket_name, file.key) res.headers['x-amz-version-id'] end end tests("deleting_multiple_objects('#{@aws_bucket_name}", 'file') do clear_bucket bucket = Fog::Storage[:aws].directories.get(@aws_bucket_name) file_count = 5 file_names = [] files = {} file_count.times do |id| file_names << "file_#{id}" files[file_names.last] = bucket.files.create(:body => 'a', :key => file_names.last) end tests("deleting an object just stores a delete marker").returns(true) do Fog::Storage[:aws].delete_multiple_objects(@aws_bucket_name, file_names) versions = Fog::Storage[:aws].get_bucket_object_versions( @aws_bucket_name) all_versions = {} versions.body['Versions'].each do |version| object = version[version.keys.first] next if file_names.index(object['Key']).nil? if !all_versions.has_key?(object['Key']) all_versions[object['Key']] = version.has_key?('DeleteMarker') else all_versions[object['Key']] |= version.has_key?('DeleteMarker') end end all_true = true all_versions.values.each do |marker| all_true = false if !marker end all_true end tests("there are two versions: the original and the delete marker"). returns(file_count*2) do versions = Fog::Storage[:aws].get_bucket_object_versions( @aws_bucket_name) versions.body['Versions'].size end tests("deleting the delete marker makes the object available again"). returns(true) do versions = Fog::Storage[:aws].get_bucket_object_versions( @aws_bucket_name) delete_markers = [] file_versions = {} versions.body['Versions'].each do |version| object = version[version.keys.first] next if object['VersionId'] == files[object['Key']].version file_versions[object['Key']] = object['VersionId'] end Fog::Storage[:aws].delete_multiple_objects(@aws_bucket_name, file_names, 'versionId' => file_versions) all_true = true file_names.each do |file| res = Fog::Storage[:aws].get_object(@aws_bucket_name, file) all_true = false if res.headers['x-amz-version-id'] != files[file].version end all_true end end tests("get_bucket('#{@aws_bucket_name}'") do clear_bucket file = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'a', :key => 'file') tests("includes a non-DeleteMarker object").returns(1) do Fog::Storage[:aws].get_bucket(@aws_bucket_name).body['Contents'].size end file.destroy tests("does not include a DeleteMarker object").returns(0) do Fog::Storage[:aws].get_bucket(@aws_bucket_name).body['Contents'].size end end delete_bucket end tests('failure') do create_versioned_bucket tests("#put_bucket_versioning('#{@aws_bucket_name}', 'bad_value')").raises(Excon::Errors::BadRequest) do Fog::Storage[:aws].put_bucket_versioning(@aws_bucket_name, 'bad_value') end tests("#put_bucket_versioning('fognonbucket', 'Enabled')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].put_bucket_versioning('fognonbucket', 'Enabled') end tests("#get_bucket_versioning('fognonbucket')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].get_bucket_versioning('fognonbucket') end tests("#get_bucket_object_versions('fognonbucket')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].get_bucket_object_versions('fognonbucket') end file = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'y', :key => 'x') tests("#get_object('#{@aws_bucket_name}', '#{file.key}', 'versionId' => 'bad_version'").raises(Excon::Errors::BadRequest) do Fog::Storage[:aws].get_object(@aws_bucket_name, file.key, 'versionId' => '-1') end tests("#delete_object('#{@aws_bucket_name}', '#{file.key}', 'versionId' => 'bad_version'").raises(Excon::Errors::BadRequest) do Fog::Storage[:aws].delete_object(@aws_bucket_name, file.key, 'versionId' => '-1') end end # don't keep the bucket around delete_bucket end fog-1.19.0/tests/aws/requests/storage/cors_utils_tests.rb0000644000004100000410000001164212261242552023622 0ustar www-datawww-datarequire 'fog/aws/requests/storage/cors_utils' Shindo.tests('Fog::Storage::AWS | CORS utils', ["aws"]) do tests(".hash_to_cors") do tests(".hash_to_cors({}) at xpath //CORSConfiguration").returns("", "has an empty CORSConfiguration") do xml = Fog::Storage::AWS.hash_to_cors({}) Nokogiri::XML(xml).xpath("//CORSConfiguration").first.content.chomp end tests(".hash_to_cors({}) at xpath //CORSConfiguration/CORSRule").returns(nil, "has no CORSRules") do xml = Fog::Storage::AWS.hash_to_cors({}) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule").first end cors = { 'CORSConfiguration' => [ { 'AllowedOrigin' => ['origin_123', 'origin_456'], 'AllowedMethod' => ['GET', 'POST'], 'AllowedHeader' => ['Accept', 'Content-Type'], 'ID' => 'blah-888', 'MaxAgeSeconds' => 2500, 'ExposeHeader' => ['x-some-header', 'x-other-header'] } ] } tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedOrigin").returns("origin_123", "returns the CORSRule AllowedOrigin") do xml = Fog::Storage::AWS.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedOrigin")[0].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedOrigin").returns("origin_456", "returns the CORSRule AllowedOrigin") do xml = Fog::Storage::AWS.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedOrigin")[1].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedMethod").returns("GET", "returns the CORSRule AllowedMethod") do xml = Fog::Storage::AWS.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedMethod")[0].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedMethod").returns("POST", "returns the CORSRule AllowedMethod") do xml = Fog::Storage::AWS.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedMethod")[1].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedHeader").returns("Accept", "returns the CORSRule AllowedHeader") do xml = Fog::Storage::AWS.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedHeader")[0].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedHeader").returns("Content-Type", "returns the CORSRule AllowedHeader") do xml = Fog::Storage::AWS.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedHeader")[1].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/ID").returns("blah-888", "returns the CORSRule ID") do xml = Fog::Storage::AWS.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/ID")[0].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/MaxAgeSeconds").returns("2500", "returns the CORSRule MaxAgeSeconds") do xml = Fog::Storage::AWS.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/MaxAgeSeconds")[0].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/ExposeHeader").returns("x-some-header", "returns the CORSRule ExposeHeader") do xml = Fog::Storage::AWS.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/ExposeHeader")[0].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/ExposeHeader").returns("x-other-header", "returns the CORSRule ExposeHeader") do xml = Fog::Storage::AWS.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/ExposeHeader")[1].content end end tests(".cors_to_hash") do cors_xml = <<-XML http://www.example.com http://www.example2.com Content-Length X-Foobar PUT GET 3000 x-amz-server-side-encryption x-amz-balls XML tests(".cors_to_hash(#{cors_xml.inspect})").returns({ "CORSConfiguration" => [{ "AllowedOrigin" => ["http://www.example.com", "http://www.example2.com"], "AllowedHeader" => ["Content-Length", "X-Foobar"], "AllowedMethod" => ["PUT", "GET"], "MaxAgeSeconds" => 3000, "ExposeHeader" => ["x-amz-server-side-encryption", "x-amz-balls"] }] }, 'returns hash of CORS XML') do Fog::Storage::AWS.cors_to_hash(cors_xml) end end end fog-1.19.0/tests/aws/requests/storage/bucket_tests.rb0000644000004100000410000003217612261242552022716 0ustar www-datawww-dataShindo.tests('Fog::Storage[:aws] | bucket requests', ["aws"]) do @aws_bucket_name = 'fogbuckettests-' + Time.now.to_i.to_s(32) tests('success') do @bucket_format = { 'CommonPrefixes' => [], 'IsTruncated' => Fog::Boolean, 'Marker' => NilClass, 'MaxKeys' => Integer, 'Name' => String, 'Prefix' => NilClass, 'Contents' => [{ 'ETag' => String, 'Key' => String, 'LastModified' => Time, 'Owner' => { 'DisplayName' => String, 'ID' => String }, 'Size' => Integer, 'StorageClass' => String }] } @bucket_lifecycle_format = { 'Rules' => [{ 'ID' => String, 'Prefix' => Fog::Nullable::String, 'Enabled' => Fog::Boolean, 'Expiration' => Fog::Nullable::Hash, 'Transition' => Fog::Nullable::Hash }] } @service_format = { 'Buckets' => [{ 'CreationDate' => Time, 'Name' => String, }], 'Owner' => { 'DisplayName' => String, 'ID' => String } } tests("#put_bucket('#{@aws_bucket_name}')").succeeds do Fog::Storage[:aws].put_bucket(@aws_bucket_name) @aws_owner = Fog::Storage[:aws].get_bucket_acl(Fog::Storage[:aws].directories.first.key).body['Owner'] end tests('put existing bucket - default region') do Fog::Storage[:aws].put_bucket(@aws_bucket_name) tests("#put_bucket('#{@aws_bucket_name}') existing").succeeds do Fog::Storage[:aws].put_bucket(@aws_bucket_name) end end tests("#get_service").formats(@service_format) do Fog::Storage[:aws].get_service.body end file = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'y', :key => 'x') tests("#get_bucket('#{@aws_bucket_name}')").formats(@bucket_format) do Fog::Storage[:aws].get_bucket(@aws_bucket_name).body end file.destroy file1 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'a', :key => 'a/a1/file1') file2 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'ab', :key => 'a/file2') file3 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'abc', :key => 'b/file3') file4 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'abcd', :key => 'file4') tests("#get_bucket('#{@aws_bucket_name}')") do before do @bucket = Fog::Storage[:aws].get_bucket(@aws_bucket_name) end tests(".body['Contents'].map{|n| n['Key']}").returns(["a/a1/file1", "a/file2", "b/file3", "file4"]) do @bucket.body['Contents'].map{|n| n['Key']} end tests(".body['Contents'].map{|n| n['Size']}").returns([1, 2, 3, 4]) do @bucket.body['Contents'].map{|n| n['Size']} end tests(".body['CommonPrefixes']").returns([]) do @bucket.body['CommonPrefixes'] end end tests("#get_bucket('#{@aws_bucket_name}', 'delimiter' => '/')") do before do @bucket = Fog::Storage[:aws].get_bucket(@aws_bucket_name, 'delimiter' => '/') end tests(".body['Contents'].map{|n| n['Key']}").returns(['file4']) do @bucket.body['Contents'].map{|n| n['Key']} end tests(".body['CommonPrefixes']").returns(['a/', 'b/']) do @bucket.body['CommonPrefixes'] end end tests("#get_bucket('#{@aws_bucket_name}', 'delimiter' => '/', 'prefix' => 'a/')") do before do @bucket = Fog::Storage[:aws].get_bucket(@aws_bucket_name, 'delimiter' => '/', 'prefix' => 'a/') end tests(".body['Contents'].map{|n| n['Key']}").returns(['a/file2']) do @bucket.body['Contents'].map{|n| n['Key']} end tests(".body['CommonPrefixes']").returns(['a/a1/']) do @bucket.body['CommonPrefixes'] end end file1.destroy; file2.destroy; file3.destroy; file4.destroy tests("#get_bucket_location('#{@aws_bucket_name}')").formats('LocationConstraint' => NilClass) do Fog::Storage[:aws].get_bucket_location(@aws_bucket_name).body end tests("#get_request_payment('#{@aws_bucket_name}')").formats('Payer' => String) do Fog::Storage[:aws].get_request_payment(@aws_bucket_name).body end tests("#put_request_payment('#{@aws_bucket_name}', 'Requester')").succeeds do Fog::Storage[:aws].put_request_payment(@aws_bucket_name, 'Requester') end tests("#put_bucket_website('#{@aws_bucket_name}', 'index.html')").succeeds do Fog::Storage[:aws].put_bucket_website(@aws_bucket_name, 'index.html') end tests("#put_bucket_acl('#{@aws_bucket_name}', 'private')").succeeds do Fog::Storage[:aws].put_bucket_acl(@aws_bucket_name, 'private') end acl = { 'Owner' => @aws_owner, 'AccessControlList' => [ { 'Grantee' => @aws_owner, 'Permission' => "FULL_CONTROL" } ] } tests("#put_bucket_acl('#{@aws_bucket_name}', hash with id)").returns(acl) do Fog::Storage[:aws].put_bucket_acl(@aws_bucket_name, acl) Fog::Storage[:aws].get_bucket_acl(@aws_bucket_name).body end tests("#put_bucket_acl('#{@aws_bucket_name}', hash with email)").returns({ 'Owner' => @aws_owner, 'AccessControlList' => [ { 'Grantee' => { 'ID' => 'f62f0218873cfa5d56ae9429ae75a592fec4fd22a5f24a20b1038a7db9a8f150', 'DisplayName' => 'mtd' }, 'Permission' => "FULL_CONTROL" } ] }) do pending if Fog.mocking? Fog::Storage[:aws].put_bucket_acl(@aws_bucket_name, { 'Owner' => @aws_owner, 'AccessControlList' => [ { 'Grantee' => { 'EmailAddress' => 'mtd@amazon.com' }, 'Permission' => "FULL_CONTROL" } ] }) Fog::Storage[:aws].get_bucket_acl(@aws_bucket_name).body end acl = { 'Owner' => @aws_owner, 'AccessControlList' => [ { 'Grantee' => { 'URI' => 'http://acs.amazonaws.com/groups/global/AllUsers' }, 'Permission' => "FULL_CONTROL" } ] } tests("#put_bucket_acl('#{@aws_bucket_name}', hash with uri)").returns(acl) do Fog::Storage[:aws].put_bucket_acl(@aws_bucket_name, acl) Fog::Storage[:aws].get_bucket_acl(@aws_bucket_name).body end tests("#delete_bucket_website('#{@aws_bucket_name}')").succeeds do pending if Fog.mocking? Fog::Storage[:aws].delete_bucket_website(@aws_bucket_name) end tests('bucket lifecycle') do pending if Fog.mocking? lifecycle = {'Rules' => [{'ID' => 'test rule', 'Prefix' => '/prefix', 'Enabled' => true, 'Days' => 42}]} tests('non-existant bucket') do tests('#put_bucket_lifecycle').returns([404, 'NoSuchBucket']) do begin Fog::Storage[:aws].put_bucket_lifecycle('fognonbucket', lifecycle) rescue Excon::Errors::NotFound => e [e.response.status, e.response.body.match(%r{(.*)})[1]] end end tests('#get_bucket_lifecycle').returns([404, 'NoSuchBucket']) do begin Fog::Storage[:aws].get_bucket_lifecycle('fognonbucket') rescue Excon::Errors::NotFound => e [e.response.status, e.response.body.match(%r{(.*)})[1]] end end tests('#delete_bucket_lifecycle').returns([404, 'NoSuchBucket']) do begin Fog::Storage[:aws].delete_bucket_lifecycle('fognonbucket') rescue Excon::Errors::NotFound => e [e.response.status, e.response.body.match(%r{(.*)})[1]] end end end tests('no lifecycle') do tests('#get_bucket_lifecycle').returns([404, 'NoSuchLifecycleConfiguration']) do begin Fog::Storage[:aws].get_bucket_lifecycle(@aws_bucket_name) rescue Excon::Errors::NotFound => e [e.response.status, e.response.body.match(%r{(.*)})[1]] end end tests('#delete_bucket_lifecycle').succeeds do Fog::Storage[:aws].delete_bucket_lifecycle(@aws_bucket_name) end end tests('create').succeeds do Fog::Storage[:aws].put_bucket_lifecycle(@aws_bucket_name, lifecycle) end tests('read').formats(@bucket_lifecycle_format) do Fog::Storage[:aws].get_bucket_lifecycle(@aws_bucket_name).body end lifecycle = { 'Rules' => 5.upto(6).map { |i| {'ID' => "rule\##{i}", 'Prefix' => i.to_s, 'Enabled' => true, 'Days' => i} } } lifecycle_return = { 'Rules' => 5.upto(6).map { |i| {'ID' => "rule\##{i}", 'Prefix' => i.to_s, 'Enabled' => true, 'Expiration' => {'Days' => i}} } } tests('update').returns(lifecycle_return) do Fog::Storage[:aws].put_bucket_lifecycle(@aws_bucket_name, lifecycle) Fog::Storage[:aws].get_bucket_lifecycle(@aws_bucket_name).body end lifecycle = {'Rules' => [{'ID' => 'test rule', 'Prefix' => '/prefix', 'Enabled' => true, 'Expiration' => {'Days' => 42}, 'Transition' => {'Days' => 6, 'StorageClass'=>'GLACIER'}}]} tests('transition').returns(lifecycle) do Fog::Storage[:aws].put_bucket_lifecycle(@aws_bucket_name, lifecycle) Fog::Storage[:aws].get_bucket_lifecycle(@aws_bucket_name).body end lifecycle = {'Rules' => [{'ID' => 'test rule', 'Prefix' => '/prefix', 'Enabled' => true, 'Expiration' => {'Date' => '2012-12-31T00:00:00.000Z'}}]} tests('date').returns(lifecycle) do Fog::Storage[:aws].put_bucket_lifecycle(@aws_bucket_name, lifecycle) Fog::Storage[:aws].get_bucket_lifecycle(@aws_bucket_name).body end tests('delete').succeeds do Fog::Storage[:aws].delete_bucket_lifecycle(@aws_bucket_name) end tests('read').returns([404, 'NoSuchLifecycleConfiguration']) do begin Fog::Storage[:aws].get_bucket_lifecycle(@aws_bucket_name) rescue Excon::Errors::NotFound => e [e.response.status, e.response.body.match(%r{(.*)})[1]] end end end tests("put_bucket_cors('#{@aws_bucket_name}', cors)").succeeds do cors = {'CORSConfiguration' => [ { 'AllowedOrigin' => 'http://localhost:3000', 'AllowedMethod' => ['POST', 'GET'], 'AllowedHeader' => '*', 'MaxAgeSeconds' => 3000 } ] } Fog::Storage[:aws].put_bucket_cors(@aws_bucket_name, cors) end tests("bucket tagging") do tests("#put_bucket_tagging('#{@aws_bucket_name}')").succeeds do Fog::Storage[:aws].put_bucket_tagging(@aws_bucket_name, {'Key1' => 'Value1', 'Key2' => 'Value2'}) end tests("#get_bucket_tagging('#{@aws_bucket_name}')"). returns('BucketTagging' => {'Key1' => 'Value1', 'Key2' => 'Value2'}) do Fog::Storage[:aws].get_bucket_tagging(@aws_bucket_name).body end tests("#delete_bucket_tagging('#{@aws_bucket_name}')").succeeds do Fog::Storage[:aws].delete_bucket_tagging(@aws_bucket_name) end end tests("#delete_bucket('#{@aws_bucket_name}')").succeeds do Fog::Storage[:aws].delete_bucket(@aws_bucket_name) end end tests('failure') do tests("#delete_bucket('fognonbucket')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].delete_bucket('fognonbucket') end @bucket = Fog::Storage[:aws].directories.create(:key => 'fognonempty') @file = @bucket.files.create(:key => 'foo', :body => 'bar') tests("#delete_bucket('fognonempty')").raises(Excon::Errors::Conflict) do Fog::Storage[:aws].delete_bucket('fognonempty') end @file.destroy @bucket.destroy tests("#get_bucket('fognonbucket')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].get_bucket('fognonbucket') end tests("#get_bucket_location('fognonbucket')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].get_bucket_location('fognonbucket') end tests("#get_request_payment('fognonbucket')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].get_request_payment('fognonbucket') end tests("#put_request_payment('fognonbucket', 'Requester')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].put_request_payment('fognonbucket', 'Requester') end tests("#put_bucket_acl('fognonbucket', 'invalid')").raises(Excon::Errors::BadRequest) do Fog::Storage[:aws].put_bucket_acl('fognonbucket', 'invalid') end tests("#put_bucket_website('fognonbucket', 'index.html')").raises(Excon::Errors::NotFound) do Fog::Storage[:aws].put_bucket_website('fognonbucket', 'index.html') end tests('put existing bucket - non-default region') do storage_eu_endpoint = Fog::Storage[:aws] storage_eu_endpoint.region = "eu-west-1" storage_eu_endpoint.put_bucket(@aws_bucket_name) tests("#put_bucket('#{@aws_bucket_name}') existing").raises(Excon::Errors::Conflict) do storage_eu_endpoint.put_bucket(@aws_bucket_name) end end end # don't keep the bucket around Fog::Storage[:aws].delete_bucket(@aws_bucket_name) rescue nil end fog-1.19.0/tests/aws/requests/emr/0000755000004100000410000000000012261242552017000 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/emr/helper.rb0000644000004100000410000001165212261242552020611 0ustar www-datawww-dataclass AWS module EMR module Formats BASIC = { 'RequestId' => String } RUN_JOB_FLOW = BASIC.merge({ 'JobFlowId' => String }) ADD_INSTANCE_GROUPS = { 'JobFlowId' => String, 'InstanceGroupIds' => Array } SIMPLE_DESCRIBE_JOB_FLOW = { 'JobFlows' => [{ 'Name' => String, 'BootstrapActions' => { 'ScriptBootstrapActionConfig' => { 'Args' => Array } }, 'ExecutionStatusDetail' => { 'CreationDateTime' => String, 'State' => String, 'LastStateChangeReason' => String }, 'Steps' => [{ 'ActionOnFailure' => String, 'Name' => String, 'StepConfig' => { 'HadoopJarStepConfig' => { 'MainClass' => String, 'Jar' => String, 'Args' => Array, 'Properties' => Array } }, 'ExecutionStatusDetail' => { 'CreationDateTime' => String, 'State' => String } }], 'JobFlowId' => String, 'Instances' => { 'InstanceCount' => String, 'NormalizedInstanceHours' => String, 'KeepJobFlowAliveWhenNoSteps' => String, 'Placement' => { 'AvailabilityZone' => String }, 'MasterInstanceType' => String, 'SlaveInstanceType' => String, 'InstanceGroups' => Array, 'TerminationProtected' => String, 'HadoopVersion' => String } }] } JOB_FLOW_WITHOUT_CHANGE = { 'JobFlows' => [{ 'Name' => String, 'BootstrapActions' => { 'ScriptBootstrapActionConfig' => { 'Args' => Array } }, 'ExecutionStatusDetail' => { 'CreationDateTime' => String, 'State' => String, 'LastStateChangeReason' => NilClass }, 'Steps' => [{ 'ActionOnFailure' => String, 'Name' => String, 'StepConfig' => { 'HadoopJarStepConfig' => { 'MainClass' => String, 'Jar' => String, 'Args' => Array, 'Properties' => Array } }, 'ExecutionStatusDetail' => { 'CreationDateTime' => String, 'State' => String } }], 'JobFlowId' => String, 'Instances' => { 'InstanceCount' => String, 'NormalizedInstanceHours' => String, 'KeepJobFlowAliveWhenNoSteps' => String, 'Placement' => { 'AvailabilityZone' => String }, 'MasterInstanceType' => String, 'SlaveInstanceType' => String, 'InstanceGroups' => Array, 'TerminationProtected' => String, 'HadoopVersion' => String } }] } DESCRIBE_JOB_FLOW_WITH_INSTANCE_GROUPS = { 'JobFlows' => [{ 'Name' => String, 'BootstrapActions' => { 'ScriptBootstrapActionConfig' => { 'Args' => Array } }, 'ExecutionStatusDetail' => { 'CreationDateTime' => String, 'State' => String, 'LastStateChangeReason' => NilClass }, 'Steps' => [{ 'ActionOnFailure' => String, 'Name' => String, 'StepConfig' => { 'HadoopJarStepConfig' => { 'MainClass' => String, 'Jar' => String, 'Args' => Array, 'Properties' => Array } }, 'ExecutionStatusDetail' => { 'CreationDateTime' => String, 'State' => String } }], 'JobFlowId' => String, 'Instances' => { 'InstanceCount' => String, 'NormalizedInstanceHours' => String, 'KeepJobFlowAliveWhenNoSteps' => String, 'Placement' => { 'AvailabilityZone' => String }, 'InstanceGroups' => [{ 'Name' => String, 'InstanceRole' => String, 'CreationDateTime' => String, 'LastStateChangeReason' => nil, 'InstanceGroupId' => String, 'Market' => String, 'InstanceType' => String, 'State' => String, 'InstanceRunningCount' => String, 'InstanceRequestCount' => String }], 'MasterInstanceType' => String, 'SlaveInstanceType' => String, 'InstanceGroups' => Array, 'TerminationProtected' => String, 'HadoopVersion' => String } }] } end end end fog-1.19.0/tests/aws/requests/emr/job_flow_tests.rb0000644000004100000410000000433212261242552022352 0ustar www-datawww-dataShindo.tests('AWS::EMR | job flows', ['aws', 'emr']) do pending if Fog.mocking? @job_flow_name = "fog_job_flow_#{Time.now.to_f.to_s.gsub('.','')}" @job_flow_options = { 'Instances' => { 'MasterInstanceType' => 'm1.small', 'SlaveInstanceType' => 'm1.small', 'InstanceCount' => 2, 'Placement' => { 'AvailabilityZone' => 'us-east-1a' }, 'KeepJobFlowAliveWhenNoSteps' => false, 'TerminationProtected' => false, 'HadoopVersion' => '0.20' } } @step_name = "fog_job_flow_step_#{Time.now.to_f.to_s.gsub('.','')}" @job_flow_steps = { 'Steps' => [{ 'Name' => @step_name, 'ActionOnFailure' => 'CONTINUE', 'HadoopJarStep' => { 'Jar' => 'FakeJar', 'MainClass' => 'FakeMainClass', 'Args' => ['arg1', 'arg2'] } }] } @job_flow_id = nil tests('success') do tests("#run_job_flow").formats(AWS::EMR::Formats::RUN_JOB_FLOW) do pending if Fog.mocking? result = AWS[:emr].run_job_flow(@job_flow_name, @job_flow_options).body @job_flow_id = result['JobFlowId'] result end tests("#add_job_flow_steps").formats(AWS::EMR::Formats::BASIC) do pending if Fog.mocking? result = AWS[:emr].add_job_flow_steps(@job_flow_id, @job_flow_steps).body result end tests("#set_termination_protection").formats(AWS::EMR::Formats::BASIC) do result = AWS[:emr].set_termination_protection(true, 'JobFlowIds' => [@job_flow_id]).body test("protected?") do res = AWS[:emr].describe_job_flows('JobFlowIds' => [@job_flow_id]).body jf = res['JobFlows'].first jf['Instances']['TerminationProtected'] == 'true' end result end tests("#terminate_job_flow").formats(AWS::EMR::Formats::BASIC) do pending if Fog.mocking? AWS[:emr].set_termination_protection(false, 'JobFlowIds' => [@job_flow_id]) result = AWS[:emr].terminate_job_flows('JobFlowIds' => [@job_flow_id]).body result end tests("#describe_job_flows").formats(AWS::EMR::Formats::SIMPLE_DESCRIBE_JOB_FLOW) do pending if Fog.mocking? result = AWS[:emr].describe_job_flows('JobFlowIds' => [@job_flow_id]).body result end end end fog-1.19.0/tests/aws/requests/emr/instance_group_tests.rb0000644000004100000410000000631412261242552023573 0ustar www-datawww-dataShindo.tests('AWS::EMR | instance groups', ['aws', 'emr']) do pending if Fog.mocking? @job_flow_name = "fog_job_flow_#{Time.now.to_f.to_s.gsub('.','')}" @job_flow_options = { 'Instances' => { 'MasterInstanceType' => 'm1.small', 'SlaveInstanceType' => 'm1.small', 'InstanceCount' => 2, 'Placement' => { 'AvailabilityZone' => 'us-east-1a' }, 'KeepJobFlowAliveWhenNoSteps' => false, 'TerminationProtected' => false, 'HadoopVersion' => '0.20' } } @job_flow_steps = { 'Steps' => [{ 'Name' => 'Dummy streaming job', 'ActionOnFailure' => 'CONTINUE', 'HadoopJarStep' => { 'Jar' => '/home/hadoop/contrib/streaming/hadoop-streaming.jar', 'MainClass' => nil, 'Args' => %w(-input s3n://elasticmapreduce/samples/wordcount/input -output hdfs:///examples/output/2011-11-03T090856 -mapper s3n://elasticmapreduce/samples/wordcount/wordSplitter.py -reducer aggregate) } }] } @instance_group_name = "fog_instance_group_#{Time.now.to_f.to_s.gsub('.','')}" @instance_groups = { 'InstanceGroups' => [{ 'Name' => @instance_group_name, 'InstanceRole' => 'TASK', 'InstanceType' => 'm1.small', 'InstanceCount' => 2 }] } result = AWS[:emr].run_job_flow(@job_flow_name, @job_flow_options).body @job_flow_id = result['JobFlowId'] tests('success') do tests("#add_instance_groups").formats(AWS::EMR::Formats::ADD_INSTANCE_GROUPS) do pending if Fog.mocking? result = AWS[:emr].add_instance_groups(@job_flow_id, @instance_groups).body @instance_group_id = result['InstanceGroupIds'].first result end tests("#describe_job_flows_with_instance_groups").formats(AWS::EMR::Formats::DESCRIBE_JOB_FLOW_WITH_INSTANCE_GROUPS) do pending if Fog.mocking? result = AWS[:emr].describe_job_flows('JobFlowIds' => [@job_flow_id]).body result end tests("#modify_instance_groups").formats(AWS::EMR::Formats::BASIC) do pending if Fog.mocking? # Add a step so the state doesn't go directly from STARTING to SHUTTING_DOWN AWS[:emr].add_job_flow_steps(@job_flow_id, @job_flow_steps) # Wait until job has started before modifying the instance group begin sleep 10 result = AWS[:emr].describe_job_flows('JobFlowIds' => [@job_flow_id]).body job_flow = result['JobFlows'].first state = job_flow['ExecutionStatusDetail']['State'] print "." end while(state == 'STARTING') # Check results result = AWS[:emr].modify_instance_groups('InstanceGroups' => [{'InstanceGroupId' => @instance_group_id, 'InstanceCount' => 4}]).body # Check the it actually modified the instance count tests("modify worked?") do ig_res = AWS[:emr].describe_job_flows('JobFlowIds' => [@job_flow_id]).body matched = false jf = ig_res['JobFlows'].first jf['Instances']['InstanceGroups'].each do | ig | if ig['InstanceGroupId'] == @instance_group_id matched = true if ig['InstanceRequestCount'].to_i == 4 end end matched end result end end AWS[:emr].terminate_job_flows('JobFlowIds' => [@job_flow_id]) end fog-1.19.0/tests/aws/requests/auto_scaling/0000755000004100000410000000000012261242552020665 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/auto_scaling/helper.rb0000644000004100000410000001475412261242552022504 0ustar www-datawww-dataclass AWS module AutoScaling module Formats BASIC = { 'ResponseMetadata' => {'RequestId' => String} } PAGINATED = { 'NextToken' => Fog::Nullable::String } ACTIVITY = { 'ActivityId' => String, 'AutoScalingGroupName' => String, 'Cause' => Fog::Nullable::String, 'Description' => String, 'EndTime' => Time, 'Progress' => Integer, 'StartTime' => Time, 'StatusCode' => String, 'StatusMessage' => Fog::Nullable::String } ALARM = { 'AlarmARN' => String, 'AlarmName' => String } BLOCK_DEVICE_MAPPING = { 'DeviceName' => String, 'Ebs' => {'SnapshotId' => String, 'VolumeSize' => Integer}, 'VirtualName' => String } ENABLED_METRIC = { 'Granularity' => Array, 'Metric' => Array } INSTANCE = { 'AvailabilityZone' => String, 'HealthStatus' => String, 'InstanceId' => String, 'LaunchConfigurationName' => String, 'LifecycleState' => String } NOTIFICATION_CONFIGURATION = { 'AutoScalingGroupName' => String, 'NotificationType' => String, 'TopicARN' => String } SCHEDULED_UPDATE_GROUP_ACTION = { 'AutoScalingGroupName' => String, 'DesiredCapacity' => Integer, 'EndTime' => Time, 'MaxSize' => Integer, 'MinSize' => Integer, 'Recurrence' => String, 'ScheduledActionARN' => String, 'ScheduledActionName' => String, 'StartTime' => Time, } PROCESS_TYPE = { 'ProcessName' => String } SUSPENDED_PROCESS = PROCESS_TYPE.merge({ 'SuspensionReason' => String }) TAG_DESCRIPTION = { 'Key' => String, 'PropagateAtLaunch' => Fog::Boolean, 'ResourceId' => String, 'ResourceType' => String, 'Value' => Fog::Nullable::String } AUTO_SCALING_GROUP = { 'AutoScalingGroupARN' => String, 'AutoScalingGroupName' => String, 'AvailabilityZones' => Array, 'CreatedTime' => Time, 'DefaultCooldown' => Integer, 'DesiredCapacity' => Integer, 'EnabledMetrics' => [ENABLED_METRIC], 'HealthCheckGracePeriod' => Integer, 'HealthCheckType' => String, 'Instances' => [INSTANCE], 'LaunchConfigurationName' => String, 'LoadBalancerNames' => Array, 'MaxSize' => Integer, 'MinSize' => Integer, 'PlacementGroup' => Fog::Nullable::String, 'Status' => Fog::Nullable::String, 'SuspendedProcesses' => [SUSPENDED_PROCESS], 'Tags' => [TAG_DESCRIPTION], 'TerminationPolicies' => [String], 'VPCZoneIdentifier' => Fog::Nullable::String } AUTO_SCALING_INSTANCE_DETAILS = INSTANCE.merge({ 'AutoScalingGroupName' => String }) LAUNCH_CONFIGURATION = { 'BlockDeviceMappings' => [BLOCK_DEVICE_MAPPING], 'CreatedTime' => Time, 'ImageId' => String, 'InstanceMonitoring' => {'Enabled' => Fog::Boolean}, 'InstanceType' => String, 'KernelId' => Fog::Nullable::String, 'KeyName' => Fog::Nullable::String, 'LaunchConfigurationARN' => String, 'LaunchConfigurationName' => String, 'RamdiskId' => Fog::Nullable::String, 'SpotPrice' => Fog::Nullable::String, 'SecurityGroups' => Array, 'UserData' => Fog::Nullable::String } SCALING_POLICY = { 'AdjustmentType' => String, 'Alarms' => [ALARM], 'AutoScalingGroupName' => String, 'Cooldown' => Integer, 'MinAdjustmentStep' => Integer, 'PolicyARN' => String, 'PolicyName' => String, 'ScalingAdjustment' => Integer } DESCRIBE_ADJUSTMENT_TYPES = BASIC.merge({ 'DescribeAdjustmentTypesResult' => { 'AdjustmentTypes' => [{'AdjustmentType' => String}] } }) DESCRIBE_AUTO_SCALING_GROUPS = BASIC.merge({ 'DescribeAutoScalingGroupsResult' => PAGINATED.merge({ 'AutoScalingGroups' => [AUTO_SCALING_GROUP], }) }) DESCRIBE_AUTO_SCALING_INSTANCES = BASIC.merge({ 'DescribeAutoScalingInstancesResult' => PAGINATED.merge({ 'AutoScalingInstances' => [AUTO_SCALING_INSTANCE_DETAILS], }) }) DESCRIBE_AUTO_SCALING_NOTIFICATION_TYPES = BASIC.merge({ 'DescribeAutoScalingNotificationTypesResult' => { 'AutoScalingNotificationTypes' => [String] } }) DESCRIBE_LAUNCH_CONFIGURATIONS = BASIC.merge({ 'DescribeLaunchConfigurationsResult' => PAGINATED.merge({ 'LaunchConfigurations' => [LAUNCH_CONFIGURATION], }) }) DESCRIBE_METRIC_COLLECTION_TYPES = BASIC.merge({ 'DescribeMetricCollectionTypesResult' => { 'Granularities' => [{'Granularity' => String}], 'Metrics' => [{'Metric' => String}] } }) DESCRIBE_NOTIFICATION_CONFIGURATIONS = BASIC.merge({ 'DescribeNotificationConfigurationsResult' => PAGINATED.merge({ 'NotificationConfigurations' => [NOTIFICATION_CONFIGURATION] }) }) DESCRIBE_POLICIES = BASIC.merge({ 'DescribePoliciesResult' => PAGINATED.merge({ 'ScalingPolicies' => [SCALING_POLICY] }) }) DESCRIBE_SCALING_ACTIVITIES = BASIC.merge({ 'DescribeScalingActivitiesResult' => PAGINATED.merge({ 'Activities' => [ACTIVITY], }) }) DESCRIBE_SCALING_PROCESS_TYPES = BASIC.merge({ 'DescribeScalingProcessTypesResult' => { 'Processes' => [PROCESS_TYPE] } }) DESCRIBE_SCHEDULED_ACTIONS = BASIC.merge({ 'DescribeScheduledActionsResult' => PAGINATED.merge({ 'ScheduledUpdateGroupActions' => [SCHEDULED_UPDATE_GROUP_ACTION] }) }) DESCRIBE_TAGS = BASIC.merge({ 'DescribeTagsResult' => PAGINATED.merge({ 'Tags' => [TAG_DESCRIPTION] }) }) DESCRIBE_TERMINATION_POLICY_TYPES = BASIC.merge({ 'DescribeTerminationPolicyTypesResult' => { 'TerminationPolicyTypes' => [String] } }) PUT_SCALING_POLICY = BASIC.merge({ 'PutScalingPolicyResult' => { 'PolicyARN' => String } }) TERMINATE_INSTANCE_IN_AUTO_SCALING_GROUP = BASIC.merge({ 'TerminateInstanceInAutoScalingGroupResult' => { 'Activity' => [ACTIVITY] } }) end end end fog-1.19.0/tests/aws/requests/auto_scaling/auto_scaling_tests.rb0000644000004100000410000000757212261242552025117 0ustar www-datawww-dataShindo.tests('AWS::AutoScaling | auto_scaling_tests', ['aws', 'auto_scaling']) do @asg_name = 'fog-test-asg' @lc_name = 'fog-test-lc' tests('success') do tests("#create_launch_configuration").formats(AWS::AutoScaling::Formats::BASIC) do image_id = 'ami-8c1fece5' instance_type = 't1.micro' #listeners = [{'LoadBalancerPort' => 80, 'InstancePort' => 80, 'Protocol' => 'http'}] Fog::AWS[:auto_scaling].create_launch_configuration(image_id, instance_type, @lc_name).body end tests("#describe_launch_configurations").formats(AWS::AutoScaling::Formats::DESCRIBE_LAUNCH_CONFIGURATIONS) do Fog::AWS[:auto_scaling].describe_launch_configurations().body end tests("#describe_launch_configurations").formats(AWS::AutoScaling::Formats::DESCRIBE_LAUNCH_CONFIGURATIONS) do Fog::AWS[:auto_scaling].describe_launch_configurations('LaunchConfigurationNames' => @lc_name).body end tests("#describe_launch_configurations").formats(AWS::AutoScaling::Formats::DESCRIBE_LAUNCH_CONFIGURATIONS) do Fog::AWS[:auto_scaling].describe_launch_configurations('LaunchConfigurationNames' => [@lc_name]).body end tests("#create_auto_scaling_group").formats(AWS::AutoScaling::Formats::BASIC) do zones = ['us-east-1d'] max_size = 0 min_size = 0 Fog::AWS[:auto_scaling].create_auto_scaling_group(@asg_name, zones, @lc_name, max_size, min_size).body end tests("#describe_auto_scaling_groups").formats(AWS::AutoScaling::Formats::DESCRIBE_AUTO_SCALING_GROUPS) do Fog::AWS[:auto_scaling].describe_auto_scaling_groups().body end tests("#describe_auto_scaling_groups").formats(AWS::AutoScaling::Formats::DESCRIBE_AUTO_SCALING_GROUPS) do Fog::AWS[:auto_scaling].describe_auto_scaling_groups('AutoScalingGroupNames' => @asg_name).body end tests("#describe_auto_scaling_groups").formats(AWS::AutoScaling::Formats::DESCRIBE_AUTO_SCALING_GROUPS) do Fog::AWS[:auto_scaling].describe_auto_scaling_groups('AutoScalingGroupNames' => [@asg_name]).body end tests("#describe_auto_scaling_instances").formats(AWS::AutoScaling::Formats::DESCRIBE_AUTO_SCALING_INSTANCES) do Fog::AWS[:auto_scaling].describe_auto_scaling_instances().body end tests("#describe_scaling_activities").formats(AWS::AutoScaling::Formats::DESCRIBE_SCALING_ACTIVITIES) do pending if Fog.mocking? Fog::AWS[:auto_scaling].describe_scaling_activities().body end tests("#describe_scaling_activities").formats(AWS::AutoScaling::Formats::DESCRIBE_SCALING_ACTIVITIES) do pending if Fog.mocking? Fog::AWS[:auto_scaling].describe_scaling_activities('ActivityIds' => '1').body end tests("#describe_scaling_activities").formats(AWS::AutoScaling::Formats::DESCRIBE_SCALING_ACTIVITIES) do pending if Fog.mocking? Fog::AWS[:auto_scaling].describe_scaling_activities('ActivityIds' => ['1', '2']).body end tests("#describe_scaling_activities").formats(AWS::AutoScaling::Formats::DESCRIBE_SCALING_ACTIVITIES) do pending if Fog.mocking? Fog::AWS[:auto_scaling].describe_scaling_activities('AutoScalingGroupName' => @asg_name).body end tests("#set_desired_capacity").formats(AWS::AutoScaling::Formats::BASIC) do desired_capacity = 0 Fog::AWS[:auto_scaling].set_desired_capacity(@asg_name, desired_capacity).body end tests("#delete_auto_scaling_group").formats(AWS::AutoScaling::Formats::BASIC) do Fog::AWS[:auto_scaling].delete_auto_scaling_group(@asg_name, 'ForceDelete' => true).body end tests("#delete_auto_scaling_group that does not exists").raises(Fog::AWS::AutoScaling::ValidationError) do Fog::AWS[:auto_scaling].delete_auto_scaling_group("group that does not exist") end tests("#delete_launch_configuration").formats(AWS::AutoScaling::Formats::BASIC) do Fog::AWS[:auto_scaling].delete_launch_configuration(@lc_name).body end end end fog-1.19.0/tests/aws/requests/auto_scaling/describe_types_tests.rb0000644000004100000410000000633712261242552025451 0ustar www-datawww-dataShindo.tests('AWS::AutoScaling | describe types requests', ['aws', 'auto_scaling']) do tests('success') do tests("#describe_adjustment_types").formats(AWS::AutoScaling::Formats::DESCRIBE_ADJUSTMENT_TYPES) do body = Fog::AWS[:auto_scaling].describe_adjustment_types.body [ 'ChangeInCapacity', 'ExactCapacity', 'PercentChangeInCapacity' ].each do |v| returns(true, "AdjustmentTypes contains #{v}") do body['DescribeAdjustmentTypesResult']['AdjustmentTypes'].any? {|t| t['AdjustmentType'] == v} end end body end tests("#describe_auto_scaling_notification_types").formats(AWS::AutoScaling::Formats::DESCRIBE_AUTO_SCALING_NOTIFICATION_TYPES) do body = Fog::AWS[:auto_scaling].describe_auto_scaling_notification_types.body [ 'autoscaling:EC2_INSTANCE_LAUNCH', 'autoscaling:EC2_INSTANCE_LAUNCH_ERROR', 'autoscaling:EC2_INSTANCE_TERMINATE', 'autoscaling:EC2_INSTANCE_TERMINATE_ERROR', 'autoscaling:TEST_NOTIFICATION' ].each do |v| returns(true, "AutoScalingNotificationTypes contains #{v}") do body['DescribeAutoScalingNotificationTypesResult']['AutoScalingNotificationTypes'].include?(v) end end body end tests("#describe_metric_collection_types").formats(AWS::AutoScaling::Formats::DESCRIBE_METRIC_COLLECTION_TYPES) do body = Fog::AWS[:auto_scaling].describe_metric_collection_types.body [ 'GroupDesiredCapacity', 'GroupInServiceInstances', 'GroupMaxSize', 'GroupMinSize', 'GroupPendingInstances', 'GroupTerminatingInstances', 'GroupTotalInstances' ].each do |v| returns(true, "Metrics contains #{v}") do body['DescribeMetricCollectionTypesResult']['Metrics'].any? {|t| t['Metric'] == v} end end [ '1Minute' ].each do |v| returns(true, "Granularities contains #{v}") do body['DescribeMetricCollectionTypesResult']['Granularities'].any? {|t| t['Granularity'] == v} end end body end tests("#describe_scaling_process_types").formats(AWS::AutoScaling::Formats::DESCRIBE_SCALING_PROCESS_TYPES) do body = Fog::AWS[:auto_scaling].describe_scaling_process_types.body [ 'AZRebalance', 'AddToLoadBalancer', 'AlarmNotification', 'HealthCheck', 'Launch', 'ReplaceUnhealthy', 'ScheduledActions', 'Terminate' ].each do |v| returns(true, "Processes contains #{v}") do body['DescribeScalingProcessTypesResult']['Processes'].any? {|t| t['ProcessName'] == v} end end body end tests("#describe_termination_policy_types").formats(AWS::AutoScaling::Formats::DESCRIBE_TERMINATION_POLICY_TYPES) do body = Fog::AWS[:auto_scaling].describe_termination_policy_types.body [ 'ClosestToNextInstanceHour', 'Default', 'NewestInstance', 'OldestInstance', 'OldestLaunchConfiguration' ].each do |v| returns(true, "TerminationPolicyTypes contains #{v}") do body['DescribeTerminationPolicyTypesResult']['TerminationPolicyTypes'].include?(v) end end body end end end fog-1.19.0/tests/aws/requests/auto_scaling/notification_configuration_tests.rb0000644000004100000410000001261212261242552030053 0ustar www-datawww-dataShindo.tests('AWS::AutoScaling | notification configuration requests', ['aws', 'auto_scaling']) do image_id = { # Ubuntu 12.04 LTS 64-bit EBS 'ap-northeast-1' => 'ami-60c77761', 'ap-southeast-1' => 'ami-a4ca8df6', 'ap-southeast-2' => 'ami-fb8611c1', 'eu-west-1' => 'ami-e1e8d395', 'sa-east-1' => 'ami-8cd80691', 'us-east-1' => 'ami-a29943cb', 'us-west-1' => 'ami-87712ac2', 'us-west-2' => 'ami-20800c10' } now = Time.now.utc.to_i lc_name = "fog-test-#{now}" asg_name = "fog-test-#{now}" topic_name = "fog-test-#{now}" begin topic = Fog::AWS[:sns].create_topic(topic_name).body topic_arn = topic['TopicArn'] rescue Fog::Errors::MockNotImplemented topic_arn = Fog::AWS::Mock.arn('sns', Fog::AWS[:auto_scaling].data[:owner_id], "fog-test-#{now}", Fog::AWS[:auto_scaling].region) end lc = Fog::AWS[:auto_scaling].create_launch_configuration(image_id[Fog::AWS[:auto_scaling].region], 't1.micro', lc_name) asg = Fog::AWS[:auto_scaling].create_auto_scaling_group(asg_name, "#{Fog::AWS[:auto_scaling].region}a", lc_name, 0, 0) tests('raises') do tests("#put_notification_configuration(non-existent-group)").raises(Fog::AWS::AutoScaling::ValidationError) do Fog::AWS[:auto_scaling].put_notification_configuration('fog-test-nonexistent-group', 'autoscaling:TEST_NOTIFICATION', topic_arn) end tests("#put_notification_configuration(null-types)").raises(Fog::AWS::AutoScaling::ValidationError) do Fog::AWS[:auto_scaling].put_notification_configuration(asg_name, [], topic_arn) end end tests('success') do tests("#put_notification_configuration(string)").formats(AWS::AutoScaling::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:auto_scaling].put_notification_configuration(asg_name, 'autoscaling:TEST_NOTIFICATION', topic_arn).body end tests("#describe_notification_configurations").formats(AWS::AutoScaling::Formats::DESCRIBE_NOTIFICATION_CONFIGURATIONS) do pending if Fog.mocking? body = Fog::AWS[:auto_scaling].describe_notification_configurations('AutoScalingGroupNames' => asg_name).body notification_configurations = body['DescribeNotificationConfigurationsResult']['NotificationConfigurations'] returns(true, 'exactly 1 configurations') do notification_configurations.size == 1 end returns(true) do config = notification_configurations.first config['AutoScalingGroupName'] == asg_name && config['TopicARN'] == topic_arn && config['NotificationType'] == 'autoscaling:TEST_NOTIFICATION' end body end tests("#put_notification_configuration(array)").formats(AWS::AutoScaling::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:auto_scaling].put_notification_configuration(asg_name, ['autoscaling:EC2_INSTANCE_LAUNCH', 'autoscaling:EC2_INSTANCE_TERMINATE'], topic_arn).body end tests("#describe_notification_configurations").formats(AWS::AutoScaling::Formats::DESCRIBE_NOTIFICATION_CONFIGURATIONS) do pending if Fog.mocking? body = Fog::AWS[:auto_scaling].describe_notification_configurations('AutoScalingGroupName' => asg_name).body notification_configurations = body['DescribeNotificationConfigurationsResult']['NotificationConfigurations'] returns(true, 'exactly 2 configurations') do notification_configurations.size == 2 end [ 'autoscaling:EC2_INSTANCE_LAUNCH', 'autoscaling:EC2_INSTANCE_TERMINATE'].each do |type| returns(true) do notification_configurations.any? do |config| config['AutoScalingGroupName'] == asg_name && config['TopicARN'] == topic_arn && config['NotificationType'] == type end end end body end tests("#describe_notification_configurations(all)").formats(AWS::AutoScaling::Formats::DESCRIBE_NOTIFICATION_CONFIGURATIONS) do pending if Fog.mocking? body = Fog::AWS[:auto_scaling].describe_notification_configurations().body notification_configurations = body['DescribeNotificationConfigurationsResult']['NotificationConfigurations'] returns(true, 'at least 2 configurations') do notification_configurations.size >= 2 end [ 'autoscaling:EC2_INSTANCE_LAUNCH', 'autoscaling:EC2_INSTANCE_TERMINATE'].each do |type| returns(true) do notification_configurations.any? do |config| config['AutoScalingGroupName'] == asg_name && config['TopicARN'] == topic_arn && config['NotificationType'] == type end end end body end tests("#delete_notification_configuration").formats(AWS::AutoScaling::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:auto_scaling].delete_notification_configuration(asg_name, topic_arn).body end tests("#describe_notification_configurations").formats(AWS::AutoScaling::Formats::DESCRIBE_NOTIFICATION_CONFIGURATIONS) do pending if Fog.mocking? body = Fog::AWS[:auto_scaling].describe_notification_configurations('AutoScalingGroupNames' => asg_name).body returns(true) do body['DescribeNotificationConfigurationsResult']['NotificationConfigurations'].empty? end body end end Fog::AWS[:auto_scaling].delete_auto_scaling_group(asg_name) Fog::AWS[:auto_scaling].delete_launch_configuration(lc_name) if topic begin Fog::AWS[:sns].delete_topic(topic_arn) rescue Fog::Errors::MockNotImplemented end end end fog-1.19.0/tests/aws/requests/auto_scaling/model_tests.rb0000644000004100000410000001713312261242552023541 0ustar www-datawww-dataShindo.tests('AWS::AutoScaling | model_tests', ['aws', 'auto_scaling']) do tests('success') do lc = nil lc_id = 'fog-model-lc' tests('configurations') do tests('getting a missing configuration') do returns(nil) { Fog::AWS[:auto_scaling].configurations.get('fog-no-such-lc') } end tests('create configuration') do lc = Fog::AWS[:auto_scaling].configurations.create(:id => lc_id, :image_id => 'ami-8c1fece5', :instance_type => 't1.micro') #tests("dns names is set").returns(true) { lc.dns_name.is_a?(String) } tests("created_at is set").returns(true) { Time === lc.created_at } #tests("policies is empty").returns([]) { lc.policies } end tests('all configurations') do lc_ids = Fog::AWS[:auto_scaling].configurations.all.map{|e| e.id} tests("contains lc").returns(true) { lc_ids.include? lc_id } end tests('get configuration') do lc2 = Fog::AWS[:auto_scaling].configurations.get(lc_id) tests('ids match').returns(lc_id) { lc2.id } end tests('creating a duplicate configuration') do raises(Fog::AWS::AutoScaling::IdentifierTaken) do Fog::AWS[:auto_scaling].configurations.create(:id => lc_id, :image_id => 'ami-8c1fece5', :instance_type => 't1.micro') end end end tests('groups') do tests('getting a missing group') do returns(nil) { Fog::AWS[:auto_scaling].groups.get('fog-no-such-asg') } end asg = nil asg_id = 'fog-model-asg' tests('create') do asg = Fog::AWS[:auto_scaling].groups.create(:id => asg_id, :availability_zones => ['us-east-1d'], :launch_configuration_name => lc_id) #tests("dns names is set").returns(true) { asg.dns_name.is_a?(String) } tests("created_at is set").returns(true) { Time === asg.created_at } #tests("policies is empty").returns([]) { asg.policies } end tests('all') do asg_ids = Fog::AWS[:auto_scaling].groups.all.map{|e| e.id} tests("contains asg").returns(true) { asg_ids.include? asg_id } end tests('get') do asg2 = Fog::AWS[:auto_scaling].groups.get(asg_id) tests('ids match').returns(asg_id) { asg2.id } end tests('suspend processes') do asg.suspend_processes() tests('processes suspended').returns([]) { asg.suspended_processes } end tests('resume processes') do asg.resume_processes() tests('no processes suspended').returns([]) { asg.suspended_processes } end tests('creating a duplicate group') do raises(Fog::AWS::AutoScaling::IdentifierTaken) do Fog::AWS[:auto_scaling].groups.create(:id => asg_id, :availability_zones => ['us-east-1d'], :launch_configuration_name => lc_id) end end tests('destroy group') do asg.destroy asg = nil end #tests('registering an invalid instance') do # raises(Fog::AWS::AutoScaling::InvalidInstance) { asg.register_instances('i-00000000') } #end #tests('deregistering an invalid instance') do # raises(Fog::AWS::AutoScaling::InvalidInstance) { asg.deregister_instances('i-00000000') } #end end tests('configurations') do tests('destroy configuration') do lc.destroy lc = nil end end #server = Fog::AWS[:compute].servers.create #tests('register instance') do # begin # elb.register_instances(server.id) # rescue Fog::AWS::ELB::InvalidInstance # # It may take a moment for a newly created instances to be visible to ELB requests # raise if @retried_registered_instance # @retried_registered_instance = true # sleep 1 # retry # end # # returns([server.id]) { elb.instances } #end #tests('instance_health') do # returns('OutOfService') do # elb.instance_health.detect{|hash| hash['InstanceId'] == server.id}['State'] # end # # returns([server.id]) { elb.instances_out_of_service } #end #tests('deregister instance') do # elb.deregister_instances(server.id) # returns([]) { elb.instances } #end #server.destroy #tests('disable_availability_zones') do # elb.disable_availability_zones(%w{us-east-1c us-east-1d}) # returns(%w{us-east-1a us-east-1b}) { elb.availability_zones.sort } #end #tests('enable_availability_zones') do # elb.enable_availability_zones(%w{us-east-1c us-east-1d}) # returns(%w{us-east-1a us-east-1b us-east-1c us-east-1d}) { elb.availability_zones.sort } #end #tests('default health check') do # default_health_check = { # "HealthyThreshold"=>10, # "Timeout"=>5, # "UnhealthyThreshold"=>2, # "Interval"=>30, # "Target"=>"TCP:80" # } # returns(default_health_check) { elb.health_check } #end #tests('configure_health_check') do # new_health_check = { # "HealthyThreshold"=>5, # "Timeout"=>10, # "UnhealthyThreshold"=>3, # "Interval"=>15, # "Target"=>"HTTP:80/index.html" # } # elb.configure_health_check(new_health_check) # returns(new_health_check) { elb.health_check } #end #tests('listeners') do # default_listener_description = [{"Listener"=>{"InstancePort"=>80, "Protocol"=>"HTTP", "LoadBalancerPort"=>80}, "PolicyNames"=>[]}] # tests('default') do # returns(1) { elb.listeners.size } # # listener = elb.listeners.first # returns([80,80,'HTTP', []]) { [listener.instance_port, listener.lb_port, listener.protocol, listener.policy_names] } # # end # # tests('#get') do # returns(80) { elb.listeners.get(80).lb_port } # end # # tests('create') do # new_listener = { 'InstancePort' => 443, 'LoadBalancerPort' => 443, 'Protocol' => 'TCP'} # elb.listeners.create(:instance_port => 443, :lb_port => 443, :protocol => 'TCP') # returns(2) { elb.listeners.size } # returns(443) { elb.listeners.get(443).lb_port } # end # # tests('destroy') do # elb.listeners.get(443).destroy # returns(nil) { elb.listeners.get(443) } # end #end #tests('policies') do # app_policy_id = 'my-app-policy' # # tests 'are empty' do # returns([]) { elb.policies.to_a } # end # # tests('#all') do # returns([]) { elb.policies.all.to_a } # end # # tests('create app policy') do # elb.policies.create(:id => app_policy_id, :cookie => 'my-app-cookie', :cookie_stickiness => :app) # returns(app_policy_id) { elb.policies.first.id } # end # # tests('get policy') do # returns(app_policy_id) { elb.policies.get(app_policy_id).id } # end # # tests('destroy app policy') do # elb.policies.first.destroy # returns([]) { elb.policies.to_a } # end # # lb_policy_id = 'my-lb-policy' # tests('create lb policy') do # elb.policies.create(:id => lb_policy_id, :expiration => 600, :cookie_stickiness => :lb) # returns(lb_policy_id) { elb.policies.first.id } # end # # tests('setting a listener policy') do # elb.set_listener_policy(80, lb_policy_id) # returns([lb_policy_id]) { elb.listeners.get(80).policy_names } # end # # tests('unsetting a listener policy') do # elb.unset_listener_policy(80) # returns([]) { elb.listeners.get(80).policy_names } # end # # tests('a malformed policy') do # raises(ArgumentError) { elb.policies.create(:id => 'foo', :cookie_stickiness => 'invalid stickiness') } # end #end end end fog-1.19.0/tests/aws/requests/auto_scaling/tag_tests.rb0000644000004100000410000000444512261242552023216 0ustar www-datawww-dataShindo.tests('AWS::AutoScaling | tag requests', ['aws', 'auto_scaling']) do image_id = { # Ubuntu 12.04 LTS 64-bit EBS 'ap-northeast-1' => 'ami-60c77761', 'ap-southeast-1' => 'ami-a4ca8df6', 'ap-southeast-2' => 'ami-fb8611c1', 'eu-west-1' => 'ami-e1e8d395', 'sa-east-1' => 'ami-8cd80691', 'us-east-1' => 'ami-a29943cb', 'us-west-1' => 'ami-87712ac2', 'us-west-2' => 'ami-20800c10' } now = Time.now.utc.to_i lc_name = "fog-test-#{now}" asg_name = "fog-test-#{now}" asg_tag = { 'Key' => 'Name', 'PropagateAtLaunch' => true, 'ResourceId' => asg_name, 'ResourceType' => 'auto-scaling-group', 'Value' => asg_name } lc = Fog::AWS[:auto_scaling].create_launch_configuration(image_id[Fog::AWS[:auto_scaling].region], 't1.micro', lc_name) asg = Fog::AWS[:auto_scaling].create_auto_scaling_group(asg_name, "#{Fog::AWS[:auto_scaling].region}a", lc_name, 0, 0, 'Tags' => [asg_tag]) tests('raises') do tests("#create_or_update_tags(empty)").raises(Fog::AWS::AutoScaling::ValidationError) do Fog::AWS[:auto_scaling].create_or_update_tags([]) end tests("#delete_tags(empty)").raises(Fog::AWS::AutoScaling::ValidationError) do Fog::AWS[:auto_scaling].delete_tags([]) end end tests('success') do tests("#describe_auto_scaling_groups(#{asg_name}").formats(AWS::AutoScaling::Formats::DESCRIBE_AUTO_SCALING_GROUPS) do body = Fog::AWS[:auto_scaling].describe_auto_scaling_groups('AutoScalingGroupNames' => asg_name).body auto_scaling_group = body['DescribeAutoScalingGroupsResult']['AutoScalingGroups'].first returns(true) { auto_scaling_group.has_key?('Tags') } returns(true) { auto_scaling_group['Tags'].size == 1 } returns(true) { auto_scaling_group['Tags'].first == asg_tag } body end tests("#describe_tags").formats(AWS::AutoScaling::Formats::DESCRIBE_TAGS) do pending if Fog.mocking? body = Fog::AWS[:auto_scaling].describe_tags.body tags = body['DescribeTagsResult']['Tags'] returns(true) { tags.any? {|tag| tag == asg_tag} } body end # TODO: more tests! end Fog::AWS[:auto_scaling].delete_auto_scaling_group(asg_name) Fog::AWS[:auto_scaling].delete_launch_configuration(lc_name) end fog-1.19.0/tests/aws/requests/redshift/0000755000004100000410000000000012261242552020025 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/redshift/cluster_parameter_group_tests.rb0000644000004100000410000000553112261242552026535 0ustar www-datawww-dataShindo.tests('Fog::Redshift[:aws] | cluster parameter group requests', ['aws']) do pending if Fog.mocking? suffix = rand(65536).to_s(16) parameter_group = "test-cluster-parameter-group-#{suffix}" @cluster_parameter_format = { 'Parameter' => { "ParameterValue" => String, "DataType" => String, "Source" => String, "IsModifiable" => Fog::Boolean, "Description" => String, "ParameterName" => String } } @cluster_parameters_format = { "Parameters"=> [@cluster_parameter_format] } @cluster_parameter_group_format = { 'ClusterParameterGroup' => { "ParameterGroupFamily" => String, "Description" => String, "ParameterGroupName" => String } } @cluster_parameter_groups_format = { "ParameterGroups"=> [@cluster_parameter_group_format] } @modify_cluster_parameter_group_format = { "ParameterGroupStatus" => String, "ParameterGroupName" => String } tests('success') do tests("create_cluster_parameter_group").formats(@cluster_parameter_group_format) do body = Fog::AWS[:redshift].create_cluster_parameter_group(:parameter_group_name=> parameter_group, :parameter_group_family=>"redshift-1.0", :description=>'testing').body body end tests("describe_cluster_parameter_groups").formats(@cluster_parameter_groups_format) do body = Fog::AWS[:redshift].describe_cluster_parameter_groups.body body end tests("describe_cluster_parameters").formats(@cluster_parameters_format) do body = Fog::AWS[:redshift].describe_cluster_parameters(:parameter_group_name=>parameter_group).body body end tests("modify_cluster_parameter_groups").formats(@modify_cluster_parameter_group_format) do body = Fog::AWS[:redshift].modify_cluster_parameter_group(:parameter_group_name=>parameter_group, :parameters=>{ :parameter_name=>'extra_float_digits', :parameter_value=>2}).body body end tests("delete_cluster_parameter_group") do present = !Fog::AWS[:redshift].describe_cluster_parameter_groups(:parameter_group_name=>parameter_group).body['ParameterGroups'].empty? tests("verify presence before deletion").returns(true) { present } Fog::AWS[:redshift].delete_cluster_parameter_group(:parameter_group_name=>parameter_group) not_present = Fog::AWS[:redshift].describe_cluster_parameter_groups(:parameter_group_name=>parameter_group).body['ParameterGroups'].empty? tests("verify deletion").returns(true) { not_present } end end end fog-1.19.0/tests/aws/requests/redshift/cluster_tests.rb0000644000004100000410000000626612261242552023267 0ustar www-datawww-dataShindo.tests('Fog::Redshift[:aws] | cluster requests', ['aws']) do pending if Fog.mocking? identifier = "test-cluster-#{rand(65536).to_s(16)}" @cluster_format = { 'Cluster' => { "ClusterParameterGroups" => [{ "ClusterParameterGroup" => { "ParameterApplyStatus" => String, "ParameterGroupName" => String } }], "ClusterSecurityGroups" => [{ 'ClusterSecurityGroup' => { "Status" => String, "ClusterSecurityGroupName" => String } }], "VpcSecurityGroups" => Fog::Nullable::Array, "EndPoint" => Fog::Nullable::Hash, "PendingModifiedValues" => Fog::Nullable::Hash, "RestoreStatus" => Fog::Nullable::Hash, "ClusterVersion" => String, "ClusterStatus" => String, "Encrypted" => Fog::Boolean, "NumberOfNodes" => Integer, "PubliclyAccessible" => Fog::Boolean, "AutomatedSnapshotRetentionPeriod" => Integer, "DBName" => String, "PreferredMaintenanceWindow" => String, "NodeType" => String, "ClusterIdentifier" => String, "AllowVersionUpgrade" => Fog::Boolean, "MasterUsername" => String } } @describe_clusters_format = { "ClusterSet" => [{ 'Cluster' => @cluster_format['Cluster'].merge({"ClusterCreateTime"=>Time, "AvailabilityZone"=>String, "EndPoint"=>{"Port"=>Integer, "Address"=>String}}) }] } tests('success') do tests('create_cluster').formats(@cluster_format) do body = Fog::AWS[:redshift].create_cluster(:cluster_identifier => identifier, :master_user_password => 'Password1234', :master_username => 'testuser', :node_type => 'dw.hs1.xlarge', :cluster_type => 'single-node').body Fog.wait_for do "available" == Fog::AWS[:redshift].describe_clusters(:cluster_identifier=>identifier).body['ClusterSet'].first['Cluster']['ClusterStatus'] end body end tests('describe_clusters').formats(@describe_clusters_format["ClusterSet"]) do sleep 30 unless Fog.mocking? body = Fog::AWS[:redshift].describe_clusters(:cluster_identifier=>identifier).body["ClusterSet"] body end tests('reboot_cluster') do sleep 30 unless Fog.mocking? body = Fog::AWS[:redshift].reboot_cluster(:cluster_identifier=>identifier).body tests("verify reboot").returns("rebooting") { body['Cluster']['ClusterStatus']} body end tests('delete_cluster') do Fog.wait_for do "available" == Fog::AWS[:redshift].describe_clusters(:cluster_identifier=>identifier).body['ClusterSet'].first['Cluster']['ClusterStatus'] end sleep 30 unless Fog.mocking? body = Fog::AWS[:redshift].delete_cluster(:cluster_identifier=>identifier, :skip_final_cluster_snapshot=>true).body tests("verify delete").returns("deleting") { body['Cluster']['ClusterStatus']} body end end end fog-1.19.0/tests/aws/requests/redshift/cluster_security_group_tests.rb0000644000004100000410000000323612261242552026424 0ustar www-datawww-dataShindo.tests('Fog::Redshift[:aws] | cluster security group requests', ['aws']) do pending if Fog.mocking? suffix = rand(65536).to_s(16) identifier = "test-cluster-security-group-#{suffix}" @cluster_security_group_format = { "ClusterSecurityGroup" => { "EC2SecurityGroups" => Fog::Nullable::Array, "IPRanges" => Fog::Nullable::Array, "Description" => String, "ClusterSecurityGroupName" => String } } @describe_cluster_security_groups_format = { "ClusterSecurityGroups" => [@cluster_security_group_format] } tests('success') do tests("create_cluster_security_group").formats(@cluster_security_group_format) do body = Fog::AWS[:redshift].create_cluster_security_group(:cluster_security_group_name => identifier, :description => 'testing').body body end tests("describe_cluster_security_groups").formats(@describe_cluster_security_groups_format) do body = Fog::AWS[:redshift].describe_cluster_security_groups.body body end tests("delete_cluster_security_group") do present = !Fog::AWS[:redshift].describe_cluster_security_groups(:cluster_security_group_name => identifier).body['ClusterSecurityGroups'].empty? tests("verify presence before deletion").returns(true) { present } Fog::AWS[:redshift].delete_cluster_security_group(:cluster_security_group_name => identifier) not_present = Fog::AWS[:redshift].describe_cluster_security_groups(:cluster_security_group_name => identifier).body['ClusterSecurityGroups'].empty? tests("verify deletion").returns(true) { not_present } end end end fog-1.19.0/tests/aws/requests/redshift/cluster_snapshot_tests.rb0000644000004100000410000000652412261242552025203 0ustar www-datawww-dataShindo.tests('Fog::Redshift[:aws] | cluster snapshot requests', ['aws']) do pending if Fog.mocking? suffix = rand(65536).to_s(16) identifier = "test-snapshot-#{suffix}" cluster = "test-cluster-#{suffix}" start_time = Fog::Time.now.to_iso8601_basic @cluster_snapshot_format = { 'Snapshot' => { "AccountsWithRestoreAccess" => Fog::Nullable::Array, "Port" => Integer, "SnapshotIdentifier" => String, "OwnerAccount" => String, "Status" => String, "SnapshotType" => String, "ClusterVersion" => String, "EstimatedSecondsToCompletion" => Integer, "SnapshotCreateTime" => Time, "Encrypted" => Fog::Boolean, "NumberOfNodes" => Integer, "DBName" => String, "CurrentBackupRateInMegaBytesPerSecond" => Float, "ClusterCreateTime" => Time, "AvailabilityZone" => String, "ActualIncrementalBackupSizeInMegaBytes" => Float, "TotalBackupSizeInMegaBytes" => Float, "ElapsedTimeInSeconds" => Integer, "BackupProgressInMegaBytes" => Float, "NodeType" => String, "ClusterIdentifier" => String, "MasterUsername" => String } } @describe_cluster_snapshots_format = { "Snapshots" => [@cluster_snapshot_format] } tests('success') do tests("create_cluster_snapshot").formats(@cluster_snapshot_format) do Fog::AWS[:redshift].create_cluster(:cluster_identifier => cluster, :master_user_password => 'Pass1234', :master_username => 'testuser', :node_type => 'dw.hs1.xlarge', :cluster_type => 'single-node') Fog.wait_for do "available" == Fog::AWS[:redshift].describe_clusters(:cluster_identifier=>cluster).body['ClusterSet'].first['Cluster']['ClusterStatus'] end body = Fog::AWS[:redshift].create_cluster_snapshot(:snapshot_identifier => identifier, :cluster_identifier => cluster).body body end tests('describe_cluster_snaphots').formats(@describe_cluster_snapshots_format) do sleep 30 unless Fog.mocking? body = Fog::AWS[:redshift].describe_cluster_snapshots(:start_time=>start_time).body body end tests('delete_cluster_snapshot').formats(@cluster_snapshot_format) do Fog.wait_for do "available" == Fog::AWS[:redshift].describe_cluster_snapshots(:snapshot_identifier=>identifier).body['Snapshots'].first['Snapshot']['Status'] end sleep 30 unless Fog.mocking? body = Fog::AWS[:redshift].delete_cluster_snapshot(:snapshot_identifier=>identifier).body body end Fog::AWS[:redshift].delete_cluster(:cluster_identifier => cluster, :skip_final_cluster_snapshot => true) end end fog-1.19.0/tests/aws/requests/beanstalk/0000755000004100000410000000000012261242552020161 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/beanstalk/application_tests.rb0000644000004100000410000001014712261242552024236 0ustar www-datawww-dataShindo.tests('AWS::ElasticBeanstalk | application_tests', ['aws', 'beanstalk']) do def unique_name(prefix) #get time (with 1/100th of sec accuracy) #want unique domain name and if provider is fast, this can be called more than once per second time = Time.now.to_i.to_s prefix + time end unless Fog.mocking? @beanstalk = Fog::AWS[:beanstalk] end @test_description = "A unique description." @test_app_name = unique_name("fog-test-app-") tests('success') do pending if Fog.mocking? @describe_applications_format = { 'DescribeApplicationsResult' => { 'Applications' => [ 'ApplicationName' => String, 'ConfigurationTemplates' => [String], 'Description' => Fog::Nullable::String, 'DateCreated' => Time, 'DateUpdated' => Time, 'Versions' => [String] ]}, 'ResponseMetadata' => {'RequestId'=> String}, } tests("#describe_applications format").formats(@describe_applications_format) do result = @beanstalk.describe_applications.body end test("#create_application") { response = @beanstalk.create_application({ 'ApplicationName' => @test_app_name, 'Description' => @test_description }) result = false if response.status == 200 app_info = response.body['CreateApplicationResult']['Application'] if app_info if app_info['ApplicationName'] == @test_app_name && app_info['Description'] == @test_description && app_info['ConfigurationTemplates'].empty? && app_info['Versions'].empty? result = true end end end result } test("#describe_applications all") { response = @beanstalk.describe_applications result = false if response.status == 200 apps = response.body['DescribeApplicationsResult']['Applications'] apps.each { |app_info| if app_info if app_info['ApplicationName'] == @test_app_name && app_info['Description'] == @test_description && app_info['ConfigurationTemplates'].empty? && app_info['Versions'].empty? result = true end end } end result } test("#create_application filter") { # Test for a specific app response = @beanstalk.describe_applications([@test_app_name]) result = false if response.status == 200 apps = response.body['DescribeApplicationsResult']['Applications'] if apps && apps.length == 1 app_info = apps.first if app_info['ApplicationName'] == @test_app_name && app_info['Description'] == @test_description && app_info['ConfigurationTemplates'].empty? && app_info['Versions'].empty? result = true end end end result } test("#update_application description") { @test_description = "A completely new description." response = @beanstalk.update_application({ 'ApplicationName' => @test_app_name, 'Description' => @test_description }) result = false if response.status == 200 app_info = response.body['UpdateApplicationResult']['Application'] if app_info if app_info['ApplicationName'] == @test_app_name && app_info['Description'] == @test_description && app_info['ConfigurationTemplates'].empty? && app_info['Versions'].empty? result = true end end end result } test("#delete_application") { response = @beanstalk.delete_application(@test_app_name) result = false if response.status == 200 result = true end result } end end fog-1.19.0/tests/aws/requests/beanstalk/solution_stack_tests.rb0000644000004100000410000000121712261242552024772 0ustar www-datawww-dataShindo.tests('AWS::ElasticBeanstalk | solution_stack_tests', ['aws', 'beanstalk']) do tests('success') do pending if Fog.mocking? @solution_stack_result_format = { 'ListAvailableSolutionStacksResult' => { 'SolutionStackDetails' => [ 'SolutionStackName' => String, 'PermittedFileTypes' => [String] ], 'SolutionStacks' => [String] }, 'ResponseMetadata' => {'RequestId'=> String}, } tests("#list_available_solution_stacks").formats(@solution_stack_result_format) do Fog::AWS[:beanstalk].list_available_solution_stacks.body end end end fog-1.19.0/tests/aws/requests/cloud_watch/0000755000004100000410000000000012261242552020511 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/cloud_watch/put_metric_data_tests.rb0000644000004100000410000000260112261242552025423 0ustar www-datawww-dataShindo.tests('AWS::CloudWatch | metric requests', ['aws', 'cloudwatch']) do tests('success') do namespace = 'Custom/Test' @puts_format = {'ResponseMetadata' => {'RequestId' => String}} tests('#puts_value').formats(@puts_format) do pending if Fog.mocking? Fog::AWS[:cloud_watch].put_metric_data(namespace, [{'MetricName' => 'RequestTest', 'Unit' => 'None', 'Value' => 1}]).body end tests('#puts_statistics_set').succeeds do pending if Fog.mocking? Fog::AWS[:cloud_watch].put_metric_data(namespace, [{'MetricName' => 'RequestTest', 'Unit' => 'None', 'StatisticValues' => {'Minimum' => 0, 'Maximum' => 9, 'Sum' => 45, 'SampleCount' => 10, 'Average' => 4.5}}]).body end tests('#puts with dimensions').succeeds do pending if Fog.mocking? dimensions = [{}] Fog::AWS[:cloud_watch].put_metric_data(namespace, [{'MetricName' => 'RequestTest', 'Unit' => 'None', 'Value' => 1, 'Dimensions' => dimensions}]).body end tests('#puts more than one').succeeds do pending if Fog.mocking? datapoints = (0...3).collect do |i| dp = {'MetricName' => "#{i}RequestTest", 'Unit' => 'None', 'Value' => i} if i%2==0 dp['Dimensions'] = [{'Name' => 'Ruler', 'Value' => "measurement_#{i}"}] end dp end Fog::AWS[:cloud_watch].put_metric_data(namespace, datapoints).body end end end fog-1.19.0/tests/aws/requests/cloud_watch/list_metrics_test.rb0000644000004100000410000000374012261242552024602 0ustar www-datawww-dataShindo.tests('AWS::CloudWatch | metric requests', ['aws', 'cloudwatch']) do tests('success') do @metrics_list_format = { 'ListMetricsResult' => { 'Metrics' => [{ 'Dimensions' => [{ 'Name' => String, 'Value' => String }], "MetricName" => String, "Namespace" => String }], 'NextToken' => Fog::Nullable::String, }, 'ResponseMetadata' => {"RequestId"=> String}, } @instanceId = 'i-2f3eab59' @dimension_filtered_metrics_list_format = { 'ListMetricsResult' => { 'Metrics' => [{ 'Dimensions' => [{ 'Name' => 'InstanceId', 'Value' => @instanceId }], "MetricName" => String, "Namespace" => String }], 'NextToken' => Fog::Nullable::String, }, 'ResponseMetadata' => {"RequestId"=> String}, } tests("#list_metrics").formats(@metrics_list_format) do pending if Fog.mocking? Fog::AWS[:cloud_watch].list_metrics.body end tests("#dimension_filtered_list_metrics").formats(@dimension_filtered_metrics_list_format) do pending if Fog.mocking? Fog::AWS[:cloud_watch].list_metrics('Dimensions' => [{'Name' => 'InstanceId', 'Value' => @instanceId}]).body end tests("#metric_name_filtered_list_metrics").returns(true) do pending if Fog.mocking? metricName = "CPUUtilization" Fog::AWS[:cloud_watch].list_metrics('MetricName' => metricName).body['ListMetricsResult']['Metrics'].all? do |metric| metric['MetricName'] == metricName end end tests("#namespace_filtered_list_metrics").returns(true) do pending if Fog.mocking? namespace = "AWS/EC2" Fog::AWS[:cloud_watch].list_metrics('Namespace' => namespace).body['ListMetricsResult']['Metrics'].all? do |metric| metric['Namespace'] == namespace end end end end fog-1.19.0/tests/aws/requests/cloud_watch/get_metric_statistics_tests.rb0000644000004100000410000000200312261242552026647 0ustar www-datawww-dataShindo.tests('AWS::CloudWatch | metric requests', ['aws', 'cloudwatch']) do tests('success') do @metrics_statistic_format = { 'GetMetricStatisticsResult' => { 'Label' => String, 'Datapoints' => [{ "Timestamp" => Time, 'Unit' => String, 'Minimum' => Float, 'Maximum' => Float, 'Average' => Float, 'Sum' => Float, 'SampleCount' => Float }], }, 'ResponseMetadata' => { 'RequestId' => String } } tests("#get_metric_statistics").formats(@metrics_statistic_format) do pending if Fog.mocking? instanceId = 'i-420c352f' Fog::AWS[:cloud_watch].get_metric_statistics({'Statistics' => ['Minimum','Maximum','Sum','SampleCount','Average'], 'StartTime' => (Time.now-600).iso8601, 'EndTime' => Time.now.iso8601, 'Period' => 60, 'MetricName' => 'DiskReadBytes', 'Namespace' => 'AWS/EC2', 'Dimensions' => [{'Name' => 'InstanceId', 'Value' => instanceId}]}).body end end end fog-1.19.0/tests/aws/requests/glacier/0000755000004100000410000000000012261242552017623 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/glacier/multipart_upload_tests.rb0000644000004100000410000000304212261242552024756 0ustar www-datawww-dataShindo.tests('AWS::Glacier | glacier archive tests', ['aws']) do pending if Fog.mocking? Fog::AWS[:glacier].create_vault('Fog-Test-Vault-upload') tests('initiate and abort') do id = Fog::AWS[:glacier].initiate_multipart_upload('Fog-Test-Vault-upload', 1024*1024).headers['x-amz-multipart-upload-id'] returns(true){ Fog::AWS[:glacier].list_multipart_uploads('Fog-Test-Vault-upload').body['UploadsList'].collect {|item| item['MultipartUploadId']}.include?(id)} Fog::AWS[:glacier].abort_multipart_upload('Fog-Test-Vault-upload', id) returns(false){ Fog::AWS[:glacier].list_multipart_uploads('Fog-Test-Vault-upload').body['UploadsList'].collect {|item| item['MultipartUploadId']}.include?(id)} end tests('do multipart upload') do hash = Fog::AWS::Glacier::TreeHash.new id = Fog::AWS[:glacier].initiate_multipart_upload('Fog-Test-Vault-upload', 1024*1024).headers['x-amz-multipart-upload-id'] part = 't'*1024*1024 hash_for_part = hash.add_part(part) Fog::AWS[:glacier].upload_part('Fog-Test-Vault-upload', id, part, 0, hash_for_part) part_2 = 'u'*1024*1024 hash_for_part_2 = hash.add_part(part_2) Fog::AWS[:glacier].upload_part('Fog-Test-Vault-upload', id, part_2, 1024*1024, hash_for_part_2) archive = Fog::AWS[:glacier].complete_multipart_upload('Fog-Test-Vault-upload', id, 2*1024*1024, hash.hexdigest).headers['x-amz-archive-id'] Fog::AWS[:glacier].delete_archive('Fog-Test-Vault-upload', archive) #amazon won't let us delete the vault because it has been written to in the past day end endfog-1.19.0/tests/aws/requests/glacier/tree_hash_tests.rb0000644000004100000410000000444312261242552023341 0ustar www-datawww-dataShindo.tests('AWS::Glacier | glacier tree hash calcuation', ['aws']) do tests('tree_hash(single part < 1MB)') do returns(Digest::SHA256.hexdigest('')) { Fog::AWS::Glacier::TreeHash.digest('')} end tests('tree_hash(multibyte characters)') do body = ("\xC2\xA1" * 1024*1024) body.force_encoding('UTF-8') if body.respond_to? :encoding expected = Digest::SHA256.hexdigest( Digest::SHA256.digest("\xC2\xA1" * 1024*512) + Digest::SHA256.digest("\xC2\xA1" * 1024*512) ) returns(expected) { Fog::AWS::Glacier::TreeHash.digest(body)} end tests('tree_hash(power of 2 number of parts)') do body = ('x' * 1024*1024) + ('y'*1024*1024) + ('z'*1024*1024) + ('t'*1024*1024) expected = Digest::SHA256.hexdigest( Digest::SHA256.digest( Digest::SHA256.digest('x' * 1024*1024) + Digest::SHA256.digest('y' * 1024*1024) ) + Digest::SHA256.digest( Digest::SHA256.digest('z' * 1024*1024) + Digest::SHA256.digest('t' * 1024*1024) ) ) returns(expected) { Fog::AWS::Glacier::TreeHash.digest(body)} end tests('tree_hash(non power of 2 number of parts)') do body = ('x' * 1024*1024) + ('y'*1024*1024) + ('z'*1024*1024) expected = Digest::SHA256.hexdigest( Digest::SHA256.digest( Digest::SHA256.digest('x' * 1024*1024) + Digest::SHA256.digest('y' * 1024*1024) ) + Digest::SHA256.digest('z' * 1024*1024) ) returns(expected) { Fog::AWS::Glacier::TreeHash.digest(body)} end tests('multipart') do tree_hash = Fog::AWS::Glacier::TreeHash.new part = ('x' * 1024*1024) + ('y'*1024*1024) returns(Fog::AWS::Glacier::TreeHash.digest(part)) { tree_hash.add_part part } tree_hash.add_part('z'* 1024*1024 + 't'*1024*1024) expected = Digest::SHA256.hexdigest( Digest::SHA256.digest( Digest::SHA256.digest('x' * 1024*1024) + Digest::SHA256.digest('y' * 1024*1024) ) + Digest::SHA256.digest( Digest::SHA256.digest('z' * 1024*1024) + Digest::SHA256.digest('t' * 1024*1024) ) ) returns(expected) { tree_hash.hexdigest} end endfog-1.19.0/tests/aws/requests/glacier/vault_tests.rb0000644000004100000410000000260012261242552022523 0ustar www-datawww-dataShindo.tests('AWS::Glacier | glacier vault requests', ['aws']) do pending if Fog.mocking? topic_arn = Fog::AWS[:sns].create_topic( 'fog_test_glacier_topic').body['TopicArn'] Fog::AWS[:glacier].create_vault('Fog-Test-Vault') tests('list_vaults') do returns(true){Fog::AWS[:glacier].list_vaults.body['VaultList'].collect {|data| data['VaultName']}.include?('Fog-Test-Vault')} end tests('describe_vault') do returns('Fog-Test-Vault'){Fog::AWS[:glacier].describe_vault('Fog-Test-Vault').body['VaultName']} end tests('set_vault_notification_configuration') do Fog::AWS[:glacier].set_vault_notification_configuration 'Fog-Test-Vault', topic_arn, ['ArchiveRetrievalCompleted'] end tests('get_vault_notification_configuration') do returns('SNSTopic' => topic_arn, 'Events' => ['ArchiveRetrievalCompleted']){ Fog::AWS[:glacier].get_vault_notification_configuration( 'Fog-Test-Vault').body} end tests('delete_vault_notification_configuration') do Fog::AWS[:glacier].delete_vault_notification_configuration( 'Fog-Test-Vault') raises(Excon::Errors::NotFound){Fog::AWS[:glacier].get_vault_notification_configuration( 'Fog-Test-Vault')} end tests('delete_vault') do Fog::AWS[:glacier].delete_vault( 'Fog-Test-Vault') raises(Excon::Errors::NotFound){Fog::AWS[:glacier].describe_vault( 'Fog-Test-Vault')} end Fog::AWS[:sns].delete_topic topic_arn end fog-1.19.0/tests/aws/requests/glacier/archive_tests.rb0000644000004100000410000000071312261242552023014 0ustar www-datawww-dataShindo.tests('AWS::Glacier | glacier archive tests', ['aws']) do pending if Fog.mocking? Fog::AWS[:glacier].create_vault('Fog-Test-Vault-upload') tests('single part upload') do id = Fog::AWS[:glacier].create_archive('Fog-Test-Vault-upload', 'data body').headers['x-amz-archive-id'] Fog::AWS[:glacier].delete_archive('Fog-Test-Vault-upload', id) end #amazon won't let us delete the vault because it has been written to in the past day endfog-1.19.0/tests/aws/requests/ses/0000755000004100000410000000000012261242552017007 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/ses/helper.rb0000644000004100000410000000022012261242552020605 0ustar www-datawww-dataclass AWS module SES module Formats BASIC = { 'ResponseMetadata' => {'RequestId' => String} } end end end fog-1.19.0/tests/aws/requests/ses/verified_email_address_tests.rb0000644000004100000410000000151612261242552025232 0ustar www-datawww-dataShindo.tests('AWS::SES | verified email address requests', ['aws', 'ses']) do tests('success') do tests("#verify_email_address('test@example.com')").formats(AWS::SES::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:ses].verify_email_address('test@example.com').body end tests("#list_verified_email_addresses").formats(AWS::SES::Formats::BASIC.merge('VerifiedEmailAddresses' => [String])) do pending if Fog.mocking? Fog::AWS[:ses].list_verified_email_addresses.body end # email won't be there to delete, but succeeds regardless tests("#delete_verified_email_address('test@example.com')").formats(AWS::SES::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:ses].delete_verified_email_address('notaanemail@example.com').body end end tests('failure') do end end fog-1.19.0/tests/aws/requests/ses/verified_domain_identity_tests.rb0000644000004100000410000000052112261242552025611 0ustar www-datawww-dataShindo.tests('AWS::SES | verified domain identity requests', ['aws', 'ses']) do tests('success') do tests("#verify_domain_identity('example.com')").formats(AWS::SES::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:ses].verify_domain_identity('example.com').body end end tests('failure') do end end fog-1.19.0/tests/aws/requests/dns/0000755000004100000410000000000012261242552017001 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/dns/helper.rb0000644000004100000410000000103512261242552020604 0ustar www-datawww-dataclass AWS module DNS module Formats RESOURCE_RECORD_SET = { "ResourceRecords" => Array, "Name" => String, "Type" => String, "AliasTarget"=> Fog::Nullable::Hash, "TTL" => Fog::Nullable::String } LIST_RESOURCE_RECORD_SETS = { "ResourceRecordSets" => [RESOURCE_RECORD_SET], "IsTruncated" => Fog::Boolean, "MaxItems" => Integer, "NextRecordName" => Fog::Nullable::String, "NextRecordType" => Fog::Nullable::String } end end end fog-1.19.0/tests/aws/requests/dns/dns_tests.rb0000644000004100000410000001742012261242552021340 0ustar www-datawww-dataShindo.tests('Fog::DNS[:aws] | DNS requests', ['aws', 'dns']) do @org_zone_count = 0 @zone_id = '' @change_id = '' @new_records = [] @domain_name = generate_unique_domain @elb_connection = Fog::AWS::ELB.new @r53_connection = Fog::DNS[:aws] tests('success') do test('get current zone count') do @org_zone_count= 0 response = @r53_connection.list_hosted_zones if response.status == 200 @hosted_zones = response.body['HostedZones'] @org_zone_count = @hosted_zones.count end response.status == 200 end test('create simple zone') { result = false response = @r53_connection.create_hosted_zone(@domain_name) if response.status == 201 zone = response.body['HostedZone'] change_info = response.body['ChangeInfo'] ns_servers = response.body['NameServers'] if (zone and change_info and ns_servers) @zone_id = zone['Id'] caller_ref = zone['CallerReference'] @change_id = change_info['Id'] status = change_info['Status'] ns_srv_count = ns_servers.count if (@zone_id.length > 0) and (caller_ref.length > 0) and (@change_id.length > 0) and (status.length > 0) and (ns_srv_count > 0) result = true end end end result } test("get status of change #{@change_id}") { result = false response = @r53_connection.get_change(@change_id) if response.status == 200 status = response.body['Status'] if (status == 'PENDING') or (status == 'INSYNC') result = true end end result } test("get info on hosted zone #{@zone_id}") { result = false response = @r53_connection.get_hosted_zone(@zone_id) if response.status == 200 zone = response.body['HostedZone'] zone_id = zone['Id'] name = zone['Name'] caller_ref = zone['CallerReference'] ns_servers = response.body['NameServers'] # AWS returns domain with a dot at end - so when compare, remove dot if (zone_id == @zone_id) and (name.chop == @domain_name) and (caller_ref.length > 0) and (ns_servers.count > 0) result = true end end result } test('list zones') do result = false response = @r53_connection.list_hosted_zones if response.status == 200 zones= response.body['HostedZones'] if (zones.count > 0) zone = zones[0] zone_id = zone['Id'] zone_name= zone['Name'] caller_ref = zone['CallerReference'] end max_items = response.body['MaxItems'] if (zone_id.length > 0) and (zone_name.length > 0) and (caller_ref.length > 0) and (max_items > 0) result = true end end result end test("add a A resource record") { # create an A resource record host = 'www.' + @domain_name ip_addrs = ['1.2.3.4'] resource_record = { :name => host, :type => 'A', :ttl => 3600, :resource_records => ip_addrs } resource_record_set = resource_record.merge(:action => 'CREATE') change_batch = [] change_batch << resource_record_set options = { :comment => 'add A record to domain'} response = @r53_connection.change_resource_record_sets(@zone_id, change_batch, options) if response.status == 200 change_id = response.body['Id'] status = response.body['Status'] @new_records << resource_record end response.status == 200 } test("add a CNAME resource record") { # create a CNAME resource record host = 'mail.' + @domain_name value = ['www.' + @domain_name] resource_record = { :name => host, :type => 'CNAME', :ttl => 3600, :resource_records => value } resource_record_set = resource_record.merge(:action => 'CREATE') change_batch = [] change_batch << resource_record_set options = { :comment => 'add CNAME record to domain'} response = @r53_connection.change_resource_record_sets( @zone_id, change_batch, options) if response.status == 200 change_id = response.body['Id'] status = response.body['Status'] @new_records << resource_record end response.status == 200 } test("add a MX resource record") { # create a MX resource record host = @domain_name value = ['7 mail.' + @domain_name] resource_record = { :name => host, :type => 'MX', :ttl => 3600, :resource_records => value } resource_record_set = resource_record.merge( :action => 'CREATE') change_batch = [] change_batch << resource_record_set options = { :comment => 'add MX record to domain'} response = @r53_connection.change_resource_record_sets( @zone_id, change_batch, options) if response.status == 200 change_id = response.body['Id'] status = response.body['Status'] @new_records << resource_record end response.status == 200 } test("add an ALIAS resource record") { # create a load balancer @elb_connection.create_load_balancer(["us-east-1a"], "fog", [{"Protocol" => "HTTP", "LoadBalancerPort" => "80", "InstancePort" => "80"}]) elb_response = @elb_connection.describe_load_balancers("LoadBalancerNames" => "fog") elb = elb_response.body["DescribeLoadBalancersResult"]["LoadBalancerDescriptions"].first hosted_zone_id = elb["CanonicalHostedZoneNameID"] dns_name = elb["DNSName"] # create an ALIAS record host = @domain_name alias_target = { :hosted_zone_id => hosted_zone_id, :dns_name => dns_name } resource_record = { :name => host, :type => 'A', :alias_target => alias_target } resource_record_set = resource_record.merge(:action => 'CREATE') change_batch = [] change_batch << resource_record_set options = { :comment => 'add ALIAS record to domain'} puts "Hosted Zone ID (ELB): #{hosted_zone_id}" puts "DNS Name (ELB): #{dns_name}" puts "Zone ID for Route 53: #{@zone_id}" sleep 120 unless Fog.mocking? response = @r53_connection.change_resource_record_sets(@zone_id, change_batch, options) if response.status == 200 change_id = response.body['Id'] status = response.body['Status'] @new_records << resource_record end response.status == 200 } tests("list resource records").formats(AWS::DNS::Formats::LIST_RESOURCE_RECORD_SETS) { # get resource records for zone @r53_connection.list_resource_record_sets(@zone_id).body } test("delete #{@new_records.count} resource records") { result = true change_batch = [] @new_records.each { |record| resource_record_set = record.merge( :action => 'DELETE') change_batch << resource_record_set } options = { :comment => 'remove records from domain'} response = @r53_connection.change_resource_record_sets(@zone_id, change_batch, options) if response.status != 200 result = false break end result } test("delete hosted zone #{@zone_id}") { # cleanup the ELB as well @elb_connection.delete_load_balancer("fog") response = @r53_connection.delete_hosted_zone(@zone_id) response.status == 200 } end tests('failure') do tests('create hosted zone using invalid domain name').raises(Excon::Errors::BadRequest) do pending if Fog.mocking? response = @r53_connection.create_hosted_zone('invalid-domain') end tests('get hosted zone using invalid ID').raises(Excon::Errors::Forbidden) do pending if Fog.mocking? zone_id = 'dummy-id' response = @r53_connection.get_hosted_zone(zone_id) end end end fog-1.19.0/tests/aws/requests/elb/0000755000004100000410000000000012261242552016757 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/elb/helper.rb0000644000004100000410000000566512261242552020577 0ustar www-datawww-dataclass AWS module ELB module Formats BASIC = { 'ResponseMetadata' => {'RequestId' => String} } LOAD_BALANCER = { "AvailabilityZones" => Array, "BackendServerDescriptions" => Array, "CanonicalHostedZoneName" => String, "CanonicalHostedZoneNameID" => String, "CreatedTime" => Time, "DNSName" => String, "HealthCheck" => {"HealthyThreshold" => Integer, "Timeout" => Integer, "UnhealthyThreshold" => Integer, "Interval" => Integer, "Target" => String}, "Instances" => Array, "ListenerDescriptions" => [{ 'PolicyNames' => Array, 'Listener' => { 'InstancePort' => Integer, 'InstanceProtocol' => String, 'LoadBalancerPort' => Integer, 'Protocol' => String, 'SSLCertificateId' => Fog::Nullable::String } }], "LoadBalancerName" => String, "Policies" => {"LBCookieStickinessPolicies" => Array, "AppCookieStickinessPolicies" => Array, "OtherPolicies" => Array}, "Scheme" => String, "SecurityGroups" => [Fog::Nullable::String], "SourceSecurityGroup" => {"GroupName" => String, "OwnerAlias" => String}, "Subnets" => [Fog::Nullable::String] } CREATE_LOAD_BALANCER = BASIC.merge({ 'CreateLoadBalancerResult' => { 'DNSName' => String } }) DESCRIBE_LOAD_BALANCERS = BASIC.merge({ 'DescribeLoadBalancersResult' => {'LoadBalancerDescriptions' => [LOAD_BALANCER], 'NextMarker' => Fog::Nullable::String} }) POLICY_ATTRIBUTE_DESCRIPTION = { "AttributeName" => String, "AttributeValue" => String } POLICY = { "PolicyAttributeDescriptions" => [POLICY_ATTRIBUTE_DESCRIPTION], "PolicyName" => String, "PolicyTypeName" => String } DESCRIBE_LOAD_BALANCER_POLICIES = BASIC.merge({ 'DescribeLoadBalancerPoliciesResult' => { 'PolicyDescriptions' => [POLICY] } }) POLICY_ATTRIBUTE_TYPE_DESCRIPTION = { "AttributeName" => String, "AttributeType" => String, "Cardinality" => String, "DefaultValue" => String, "Description" => String } POLICY_TYPE = { "Description" => String, "PolicyAttributeTypeDescriptions" => [POLICY_ATTRIBUTE_TYPE_DESCRIPTION], "PolicyTypeName" => String } DESCRIBE_LOAD_BALANCER_POLICY_TYPES = BASIC.merge({ 'DescribeLoadBalancerPolicyTypesResult' => {'PolicyTypeDescriptions' => [POLICY_TYPE] } }) CONFIGURE_HEALTH_CHECK = BASIC.merge({ 'ConfigureHealthCheckResult' => {'HealthCheck' => { 'Target' => String, 'Interval' => Integer, 'Timeout' => Integer, 'UnhealthyThreshold' => Integer, 'HealthyThreshold' => Integer }} }) DELETE_LOAD_BALANCER = BASIC.merge({ 'DeleteLoadBalancerResult' => NilClass }) end end end fog-1.19.0/tests/aws/requests/elb/listener_tests.rb0000644000004100000410000000673112261242552022362 0ustar www-datawww-dataShindo.tests('AWS::ELB | listener_tests', ['aws', 'elb']) do @load_balancer_id = 'fog-test-listener' @key_name = 'fog-test' tests('success') do Fog::AWS[:elb].create_load_balancer(['us-east-1a'], @load_balancer_id, [{'LoadBalancerPort' => 80, 'InstancePort' => 80, 'Protocol' => 'HTTP'}]) @certificate = Fog::AWS[:iam].upload_server_certificate(AWS::IAM::SERVER_CERT, AWS::IAM::SERVER_CERT_PRIVATE_KEY, @key_name).body['Certificate'] tests("#create_load_balancer_listeners").formats(AWS::ELB::Formats::BASIC) do listeners = [ {'Protocol' => 'TCP', 'InstanceProtocol' => 'TCP', 'LoadBalancerPort' => 443, 'InstancePort' => 443, 'SSLCertificateId' => @certificate['Arn']}, {'Protocol' => 'HTTP', 'InstanceProtocol' => 'HTTP', 'LoadBalancerPort' => 80, 'InstancePort' => 80} ] response = Fog::AWS[:elb].create_load_balancer_listeners(@load_balancer_id, listeners).body response end tests("#delete_load_balancer_listeners").formats(AWS::ELB::Formats::BASIC) do ports = [80, 443] Fog::AWS[:elb].delete_load_balancer_listeners(@load_balancer_id, ports).body end tests("#create_load_balancer_listeners with non-existant SSL certificate") do listeners = [ {'Protocol' => 'HTTPS', 'InstanceProtocol' => 'HTTPS', 'LoadBalancerPort' => 443, 'InstancePort' => 443, 'SSLCertificateId' => 'non-existant'}, ] raises(Fog::AWS::IAM::NotFound) { Fog::AWS[:elb].create_load_balancer_listeners(@load_balancer_id, listeners) } end tests("#create_load_balancer_listeners with invalid SSL certificate").raises(Fog::AWS::IAM::NotFound) do sleep 8 unless Fog.mocking? listeners = [ {'Protocol' => 'HTTPS', 'InstanceProtocol' => 'HTTPS', 'LoadBalancerPort' => 443, 'InstancePort' => 443, 'SSLCertificateId' => "#{@certificate['Arn']}fake"}, ] Fog::AWS[:elb].create_load_balancer_listeners(@load_balancer_id, listeners).body end # This is sort of fucked up, but it may or may not fail, thanks AWS tests("#create_load_balancer_listeners with SSL certificate").formats(AWS::ELB::Formats::BASIC) do sleep 8 unless Fog.mocking? listeners = [ {'Protocol' => 'HTTPS', 'InstanceProtocol' => 'HTTPS', 'LoadBalancerPort' => 443, 'InstancePort' => 443, 'SSLCertificateId' => @certificate['Arn']}, ] Fog::AWS[:elb].create_load_balancer_listeners(@load_balancer_id, listeners).body end tests("#set_load_balancer_listener_ssl_certificate").formats(AWS::ELB::Formats::BASIC) do Fog::AWS[:elb].set_load_balancer_listener_ssl_certificate(@load_balancer_id, 443, @certificate['Arn']).body end tests("#create_load_balancer_listeners with invalid Protocol and InstanceProtocol configuration").raises(Fog::AWS::ELB::ValidationError) do listeners = [ {'Protocol' => 'HTTP', 'InstanceProtocol' => 'TCP', 'LoadBalancerPort' => 80, 'InstancePort' => 80}, ] Fog::AWS[:elb].create_load_balancer_listeners(@load_balancer_id, listeners).body end tests("#create_load_balancer_listeners with valid Protocol and InstanceProtocol configuration").formats(AWS::ELB::Formats::BASIC) do listeners = [ {'Protocol' => 'HTTP', 'InstanceProtocol' => 'HTTPS', 'LoadBalancerPort' => 80, 'InstancePort' => 80}, ] Fog::AWS[:elb].create_load_balancer_listeners(@load_balancer_id, listeners).body end Fog::AWS[:iam].delete_server_certificate(@key_name) Fog::AWS[:elb].delete_load_balancer(@load_balancer_id) end end fog-1.19.0/tests/aws/requests/elb/policy_tests.rb0000644000004100000410000001452712261242552022036 0ustar www-datawww-dataShindo.tests('AWS::ELB | policy_tests', ['aws', 'elb']) do @load_balancer_id = 'fog-test-policies' tests('success') do listeners = [{'LoadBalancerPort' => 80, 'InstancePort' => 80, 'Protocol' => 'HTTP'}] Fog::AWS[:elb].create_load_balancer(['us-east-1a'], @load_balancer_id, listeners) tests("#describe_load_balancer_policy_types").formats(AWS::ELB::Formats::DESCRIBE_LOAD_BALANCER_POLICY_TYPES) do @policy_types = Fog::AWS[:elb].describe_load_balancer_policy_types.body end tests("#create_app_cookie_stickiness_policy").formats(AWS::ELB::Formats::BASIC) do cookie, policy = 'fog-app-cookie', 'fog-app-policy' Fog::AWS[:elb].create_app_cookie_stickiness_policy(@load_balancer_id, policy, cookie).body end tests("#create_lb_cookie_stickiness_policy with expiry").formats(AWS::ELB::Formats::BASIC) do policy = 'fog-lb-expiry' expiry = 300 Fog::AWS[:elb].create_lb_cookie_stickiness_policy(@load_balancer_id, policy, expiry).body end tests("#create_lb_cookie_stickiness_policy without expiry").formats(AWS::ELB::Formats::BASIC) do policy = 'fog-lb-no-expiry' Fog::AWS[:elb].create_lb_cookie_stickiness_policy(@load_balancer_id, policy).body end tests("#create_load_balancer_policy").formats(AWS::ELB::Formats::BASIC) do policy = 'fog-policy' Fog::AWS[:elb].create_load_balancer_policy(@load_balancer_id, policy, 'PublicKeyPolicyType', {'PublicKey' => AWS::IAM::SERVER_CERT_PUBLIC_KEY}).body end tests("#describe_load_balancer_policies") do body = Fog::AWS[:elb].describe_load_balancer_policies(@load_balancer_id).body formats(AWS::ELB::Formats::DESCRIBE_LOAD_BALANCER_POLICIES) { body } # Check the result of each policy by name returns({ "PolicyAttributeDescriptions"=>[{ "AttributeName"=>"CookieName", "AttributeValue"=>"fog-app-cookie" }], "PolicyName"=>"fog-app-policy", "PolicyTypeName"=>"AppCookieStickinessPolicyType" }) do body["DescribeLoadBalancerPoliciesResult"]["PolicyDescriptions"].detect{|e| e['PolicyName'] == 'fog-app-policy' } end returns({ "PolicyAttributeDescriptions"=>[{ "AttributeName"=>"CookieExpirationPeriod", "AttributeValue"=>"300" }], "PolicyName"=>"fog-lb-expiry", "PolicyTypeName"=>"LBCookieStickinessPolicyType" }) do body["DescribeLoadBalancerPoliciesResult"]["PolicyDescriptions"].detect{|e| e['PolicyName'] == 'fog-lb-expiry' } end returns({ "PolicyAttributeDescriptions"=>[{ "AttributeName"=>"CookieExpirationPeriod", "AttributeValue"=>"0" }], "PolicyName"=>"fog-lb-no-expiry", "PolicyTypeName"=>"LBCookieStickinessPolicyType" }) do body["DescribeLoadBalancerPoliciesResult"]["PolicyDescriptions"].detect{|e| e['PolicyName'] == 'fog-lb-no-expiry' } end returns({ "PolicyAttributeDescriptions"=>[{ "AttributeName"=>"PublicKey", "AttributeValue"=> AWS::IAM::SERVER_CERT_PUBLIC_KEY }], "PolicyName"=>"fog-policy", "PolicyTypeName"=>"PublicKeyPolicyType" }) do body["DescribeLoadBalancerPoliciesResult"]["PolicyDescriptions"].detect{|e| e['PolicyName'] == 'fog-policy' } end end tests("#describe_load_balancer includes all policies") do lb = Fog::AWS[:elb].describe_load_balancers("LoadBalancerNames" => [@load_balancer_id]).body["DescribeLoadBalancersResult"]["LoadBalancerDescriptions"].first returns([ {"PolicyName"=>"fog-app-policy", "CookieName"=>"fog-app-cookie"} ]) { lb["Policies"]["AppCookieStickinessPolicies"] } returns([ {"PolicyName"=>"fog-lb-expiry", "CookieExpirationPeriod"=> 300} ]) { lb["Policies"]["LBCookieStickinessPolicies"].select{|e| e["PolicyName"] == "fog-lb-expiry"} } returns([ {"PolicyName" => "fog-lb-no-expiry"} ]) { lb["Policies"]["LBCookieStickinessPolicies"].select{|e| e["PolicyName"] == "fog-lb-no-expiry"} } returns([ "fog-policy" ]) { lb["Policies"]["OtherPolicies"] } end tests("#delete_load_balancer_policy").formats(AWS::ELB::Formats::BASIC) do policy = 'fog-lb-no-expiry' Fog::AWS[:elb].delete_load_balancer_policy(@load_balancer_id, policy).body end tests("#set_load_balancer_policies_of_listener adds policy").formats(AWS::ELB::Formats::BASIC) do port, policies = 80, ['fog-lb-expiry'] Fog::AWS[:elb].set_load_balancer_policies_of_listener(@load_balancer_id, port, policies).body end tests("#set_load_balancer_policies_of_listener removes policy").formats(AWS::ELB::Formats::BASIC) do port = 80 Fog::AWS[:elb].set_load_balancer_policies_of_listener(@load_balancer_id, port, []).body end proxy_policy = "EnableProxyProtocol" Fog::AWS[:elb].create_load_balancer_policy(@load_balancer_id, proxy_policy, 'ProxyProtocolPolicyType', { "ProxyProtocol" => true }) tests("#set_load_balancer_policies_for_backend_server replaces policies on port").formats(AWS::ELB::Formats::BASIC) do Fog::AWS[:elb].set_load_balancer_policies_for_backend_server(@load_balancer_id, 80, [proxy_policy]).body end tests("#describe_load_balancers has other policies") do Fog::AWS[:elb].set_load_balancer_policies_for_backend_server(@load_balancer_id, 80, [proxy_policy]).body description = Fog::AWS[:elb].describe_load_balancers("LoadBalancerNames" => [@load_balancer_id]).body["DescribeLoadBalancersResult"]["LoadBalancerDescriptions"].first returns(true) { description["Policies"]["OtherPolicies"].include?(proxy_policy) } end Fog::AWS[:elb].delete_load_balancer(@load_balancer_id) end end fog-1.19.0/tests/aws/requests/elb/load_balancer_tests.rb0000644000004100000410000000620012261242552023272 0ustar www-datawww-dataShindo.tests('AWS::ELB | load_balancer_tests', ['aws', 'elb']) do @load_balancer_id = 'fog-test-elb' @key_name = 'fog-test' tests('success') do if (Fog::AWS[:iam].get_server_certificate(@key_name) rescue nil) Fog::AWS[:iam].delete_server_certificate(@key_name) end @certificate = Fog::AWS[:iam].upload_server_certificate(AWS::IAM::SERVER_CERT, AWS::IAM::SERVER_CERT_PRIVATE_KEY, @key_name).body['Certificate'] tests("#create_load_balancer").formats(AWS::ELB::Formats::CREATE_LOAD_BALANCER) do zones = ['us-east-1a'] listeners = [{'LoadBalancerPort' => 80, 'InstancePort' => 80, 'InstanceProtocol' => 'HTTP', 'Protocol' => 'HTTP'}] Fog::AWS[:elb].create_load_balancer(zones, @load_balancer_id, listeners).body end tests("#describe_load_balancers").formats(AWS::ELB::Formats::DESCRIBE_LOAD_BALANCERS) do Fog::AWS[:elb].describe_load_balancers.body end tests('#describe_load_balancers with bad lb') do raises(Fog::AWS::ELB::NotFound) { Fog::AWS[:elb].describe_load_balancers('LoadBalancerNames' => 'none-such-lb') } end tests("#describe_load_balancers with SSL listener") do sleep 5 unless Fog.mocking? listeners = [ {'Protocol' => 'HTTPS', 'LoadBalancerPort' => 443, 'InstancePort' => 443, 'SSLCertificateId' => @certificate['Arn']}, ] Fog::AWS[:elb].create_load_balancer_listeners(@load_balancer_id, listeners) response = Fog::AWS[:elb].describe_load_balancers('LoadBalancerNames' => @load_balancer_id).body tests("SSLCertificateId is set").returns(@certificate['Arn']) do listeners = response["DescribeLoadBalancersResult"]["LoadBalancerDescriptions"].first["ListenerDescriptions"] listeners.find {|l| l["Listener"]["Protocol"] == 'HTTPS' }["Listener"]["SSLCertificateId"] end end tests("modify_load_balancer_attributes") do Fog::AWS[:elb].modify_load_balancer_attributes(@load_balancer_id, 'CrossZoneLoadBalancing' => {'Enabled' => true}).body response = Fog::AWS[:elb].describe_load_balancer_attributes(@load_balancer_id).body response['DescribeLoadBalancerAttributesResult']['LoadBalancerAttributes']['CrossZoneLoadBalancing']['Enabled'] == true end tests("#configure_health_check").formats(AWS::ELB::Formats::CONFIGURE_HEALTH_CHECK) do health_check = { 'Target' => 'HTTP:80/index.html', 'Interval' => 10, 'Timeout' => 5, 'UnhealthyThreshold' => 2, 'HealthyThreshold' => 3 } Fog::AWS[:elb].configure_health_check(@load_balancer_id, health_check).body end tests("#delete_load_balancer").formats(AWS::ELB::Formats::DELETE_LOAD_BALANCER) do Fog::AWS[:elb].delete_load_balancer(@load_balancer_id).body end tests("#delete_load_balancer when non existant").formats(AWS::ELB::Formats::DELETE_LOAD_BALANCER) do Fog::AWS[:elb].delete_load_balancer('non-existant').body end tests("#delete_load_balancer when already deleted").formats(AWS::ELB::Formats::DELETE_LOAD_BALANCER) do Fog::AWS[:elb].delete_load_balancer(@load_balancer_id).body end Fog::AWS[:iam].delete_server_certificate(@key_name) end end fog-1.19.0/tests/aws/requests/data_pipeline/0000755000004100000410000000000012261242552021013 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/data_pipeline/helper.rb0000644000004100000410000000306612261242552022624 0ustar www-datawww-dataclass AWS module DataPipeline module Formats BASIC = { 'pipelineId' => String, } FIELDS = [ { "key" => String, "refValue" => Fog::Nullable::String, "stringValue" => Fog::Nullable::String, } ] LIST_PIPELINES = { "hasMoreResults" => Fog::Nullable::Boolean, "marker" => Fog::Nullable::String, "pipelineIdList" => [ { "id" => String, "name" => String, } ] } QUERY_OBJECTS = { "hasMoreResults" => Fog::Nullable::Boolean, "marker" => Fog::Nullable::String, "ids" => Fog::Nullable::Array, } DESCRIBE_OBJECTS = { "hasMoreResults" => Fog::Nullable::Boolean, "marker" => Fog::Nullable::String, "pipelineObjects" => [ { 'id' => String, 'name' => String, 'fields' => FIELDS, } ] } DESCRIBE_PIPELINES = { "pipelineDescriptionList" => [ { "description" => Fog::Nullable::String, "name" => String, "pipelineId" => String, "fields" => FIELDS, } ] } PUT_PIPELINE_DEFINITION = { "errored" => Fog::Boolean, "validationErrors" => Fog::Nullable::Array, } GET_PIPELINE_DEFINITION = { "pipelineObjects" => [ { "id" => String, "name" => String, "fields" => FIELDS, } ] } end end end fog-1.19.0/tests/aws/requests/data_pipeline/pipeline_tests.rb0000644000004100000410000000513712261242552024375 0ustar www-datawww-dataShindo.tests('AWS::DataPipeline | pipeline_tests', ['aws', 'data_pipeline']) do pending if Fog.mocking? @pipeline_id = nil tests('success') do tests("#create_pipeline").formats(AWS::DataPipeline::Formats::BASIC) do unique_id = 'fog-test-pipeline-unique-id' name = 'fog-test-pipeline-name' description = 'Fog test pipeline' result = Fog::AWS[:data_pipeline].create_pipeline(unique_id, name, description) @pipeline_id = result['pipelineId'] result end tests("#list_pipelines").formats(AWS::DataPipeline::Formats::LIST_PIPELINES) do Fog::AWS[:data_pipeline].list_pipelines() end tests("#describe_pipelines").formats(AWS::DataPipeline::Formats::DESCRIBE_PIPELINES) do ids = [@pipeline_id] Fog::AWS[:data_pipeline].describe_pipelines(ids) end tests("#put_pipeline_definition").formats(AWS::DataPipeline::Formats::PUT_PIPELINE_DEFINITION) do objects = [ { "id" => "Nightly", "type" => "Schedule", "startDateTime" => Time.now.strftime("%Y-%m-%dT%H:%M:%S"), "period" => "24 hours", }, { "id" => "Default", "role" => "role-dumps", "resourceRole" => "role-dumps-inst", "schedule" => { "ref" => "Nightly" }, }, ] Fog::AWS[:data_pipeline].put_pipeline_definition(@pipeline_id, objects) end tests("#activate_pipeline") do Fog::AWS[:data_pipeline].activate_pipeline(@pipeline_id) end tests("#get_pipeline_definition").formats(AWS::DataPipeline::Formats::GET_PIPELINE_DEFINITION) do Fog::AWS[:data_pipeline].get_pipeline_definition(@pipeline_id) end tests("#query_objects") do tests("for COMPONENTs").formats(AWS::DataPipeline::Formats::QUERY_OBJECTS) do Fog::AWS[:data_pipeline].query_objects(@pipeline_id, 'COMPONENT') end tests("for INSTANCEs").formats(AWS::DataPipeline::Formats::QUERY_OBJECTS) do Fog::AWS[:data_pipeline].query_objects(@pipeline_id, 'INSTANCE') end tests("for ATTEMPTs").formats(AWS::DataPipeline::Formats::QUERY_OBJECTS) do Fog::AWS[:data_pipeline].query_objects(@pipeline_id, 'ATTEMPT') end end tests('#describe_objects').formats(AWS::DataPipeline::Formats::DESCRIBE_OBJECTS) do attempts = Fog::AWS[:data_pipeline].query_objects(@pipeline_id, 'ATTEMPT') object_ids = attempts['ids'][0..5] Fog::AWS[:data_pipeline].describe_objects(@pipeline_id, object_ids) end tests("#delete_pipeline").returns(true) do Fog::AWS[:data_pipeline].delete_pipeline(@pipeline_id) end end end fog-1.19.0/tests/aws/requests/cdn/0000755000004100000410000000000012261242552016761 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/cdn/cdn_tests.rb0000644000004100000410000001470012261242552021276 0ustar www-datawww-dataShindo.tests('Fog::CDN[:aws] | CDN requests', ['aws', 'cdn']) do @cf_connection = Fog::CDN[:aws] tests('distributions success') do test('get current ditribution list count') do @count= 0 response = @cf_connection.get_distribution_list if response.status == 200 @distributions = response.body['DistributionSummary'] @count = @distributions.count end response.status == 200 end test('create distribution') { result = false response = @cf_connection.post_distribution('S3Origin' => { 'DNSName' => 'test_cdn.s3.amazonaws.com'}, 'Enabled' => true) if response.status == 201 @dist_id = response.body['Id'] @etag = response.headers['ETag'] @caller_reference = response.body['DistributionConfig']['CallerReference'] if (@dist_id.length > 0) result = true end end result } test("get info on distribution #{@dist_id}") { result = false response = @cf_connection.get_distribution(@dist_id) if response.status == 200 @etag = response.headers['ETag'] status = response.body['Status'] if ((status == 'Deployed') or (status == 'InProgress')) and not @etag.nil? result = true end end result } test('list distributions') do result = false response = @cf_connection.get_distribution_list if response.status == 200 distributions = response.body['DistributionSummary'] if (distributions.count > 0) dist = distributions[0] dist_id = dist['Id'] end max_items = response.body['MaxItems'] if (dist_id.length > 0) and (max_items > 0) result = true end end result end test("invalidate paths") { response = @cf_connection.post_invalidation(@dist_id, ["/test.html", "/path/to/file.html"]) if response.status == 201 @invalidation_id = response.body['Id'] end response.status == 201 } test("list invalidations") { result = false response = @cf_connection.get_invalidation_list(@dist_id) if response.status == 200 if response.body['InvalidationSummary'].find { |f| f['Id'] == @invalidation_id } result = true end end result } test("get invalidation information") { result = false response = @cf_connection.get_invalidation(@dist_id, @invalidation_id) if response.status == 200 paths = response.body['InvalidationBatch']['Path'].sort status = response.body['Status'] if status.length > 0 and paths == [ '/test.html', '/path/to/file.html' ].sort result = true end end result } test("disable distribution #{@dist_id} - can take 15 minutes to complete...") { result = false response = @cf_connection.put_distribution_config(@dist_id, @etag, 'S3Origin' => { 'DNSName' => 'test_cdn.s3.amazonaws.com'}, 'Enabled' => false, 'CallerReference' => @caller_reference) if response.status == 200 @etag = response.headers['ETag'] unless @etag.nil? result = true end end result } test("remove distribution #{@dist_id}") { result = true # unfortunately you can delete only after a distribution becomes Deployed Fog.wait_for { response = @cf_connection.get_distribution(@dist_id) @etag = response.headers['ETag'] response.status == 200 and response.body['Status'] == 'Deployed' } response = @cf_connection.delete_distribution(@dist_id, @etag) if response.status != 204 result = false end result } end tests('streaming distributions success') do test('get current streaming ditribution list count') do @count= 0 response = @cf_connection.get_streaming_distribution_list if response.status == 200 @distributions = response.body['StreamingDistributionSummary'] @count = @distributions.count end response.status == 200 end test('create distribution') { result = false response = @cf_connection.post_streaming_distribution('S3Origin' => { 'DNSName' => 'test_cdn.s3.amazonaws.com'}, 'Enabled' => true) if response.status == 201 @dist_id = response.body['Id'] @etag = response.headers['ETag'] @caller_reference = response.body['StreamingDistributionConfig']['CallerReference'] if (@dist_id.length > 0) result = true end end result } test("get info on distribution #{@dist_id}") { result = false response = @cf_connection.get_streaming_distribution(@dist_id) if response.status == 200 @etag = response.headers['ETag'] status = response.body['Status'] if ((status == 'Deployed') or (status == 'InProgress')) and not @etag.nil? result = true end end result } test('list streaming distributions') do result = false response = @cf_connection.get_streaming_distribution_list if response.status == 200 distributions = response.body['StreamingDistributionSummary'] if (distributions.count > 0) dist = distributions[0] dist_id = dist['Id'] end max_items = response.body['MaxItems'] if (dist_id.length > 0) and (max_items > 0) result = true end end result end test("disable distribution #{@dist_id} - can take 15 minutes to complete...") { result = false response = @cf_connection.put_streaming_distribution_config(@dist_id, @etag, 'S3Origin' => { 'DNSName' => 'test_cdn.s3.amazonaws.com'}, 'Enabled' => false, 'CallerReference' => @caller_reference) if response.status == 200 @etag = response.headers['ETag'] unless @etag.nil? result = true end end result } test("remove distribution #{@dist_id}") { result = true # unfortunately you can delete only after a distribution becomes Deployed Fog.wait_for { response = @cf_connection.get_streaming_distribution(@dist_id) @etag = response.headers['ETag'] response.status == 200 and response.body['Status'] == 'Deployed' } response = @cf_connection.delete_streaming_distribution(@dist_id, @etag) if response.status != 204 result = false end result } end end fog-1.19.0/tests/aws/requests/dynamodb/0000755000004100000410000000000012261242552020012 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/dynamodb/table_tests.rb0000644000004100000410000000655012261242552022656 0ustar www-datawww-dataShindo.tests('Fog::AWS[:dynamodb] | table requests', ['aws']) do @table_format = { 'CreationDateTime' => Float, 'KeySchema' => { 'HashKeyElement' => { 'AttributeName' => String, 'AttributeType' => String } }, 'ProvisionedThroughput' => { 'ReadCapacityUnits' => Integer, 'WriteCapacityUnits' => Integer }, 'TableName' => String, 'TableStatus' => String } @table_name = "fog_table_#{Time.now.to_f.to_s.gsub('.','')}" tests('success') do tests("#create_table(#{@table_name}, {'HashKeyElement' => {'AttributeName' => 'id', 'AttributeType' => 'S'}, {'ReadCapacityUnits' => 5, 'WriteCapacityUnits' => 5})").formats('TableDescription' => @table_format) do pending if Fog.mocking? Fog::AWS[:dynamodb].create_table(@table_name, {'HashKeyElement' => {'AttributeName' => 'id', 'AttributeType' => 'S'}}, {'ReadCapacityUnits' => 5, 'WriteCapacityUnits' => 5}).body end tests("#describe_table(#{@table_name})").formats('Table' => @table_format) do pending if Fog.mocking? Fog::AWS[:dynamodb].describe_table(@table_name).body end tests("#list_tables").formats({'LastEvaluatedTableName' => Fog::Nullable::String, 'TableNames' => [String]}) do pending if Fog.mocking? Fog::AWS[:dynamodb].list_tables.body end unless Fog.mocking? Fog.wait_for { Fog::AWS[:dynamodb].describe_table(@table_name).body['Table']['TableStatus'] == 'ACTIVE' } end @update_table_format = { 'TableDescription' => @table_format.merge({ 'ItemCount' => Integer, 'ProvisionedThroughput' => { 'LastIncreaseDateTime' => Float, 'ReadCapacityUnits' => Integer, 'WriteCapacityUnits' => Integer }, 'TableSizeBytes' => Integer }) } tests("#update_table(#{@table_name}, {'ReadCapacityUnits' => 10, 'WriteCapacityUnits' => 10})").formats(@update_table_format) do pending if Fog.mocking? Fog::AWS[:dynamodb].update_table(@table_name, {'ReadCapacityUnits' => 10, 'WriteCapacityUnits' => 10}).body end unless Fog.mocking? Fog.wait_for { Fog::AWS[:dynamodb].describe_table(@table_name).body['Table']['TableStatus'] == 'ACTIVE' } end @delete_table_format = { 'TableDescription' => { 'ProvisionedThroughput' => { 'ReadCapacityUnits' => Integer, 'WriteCapacityUnits' => Integer }, 'TableName' => String, 'TableStatus' => String } } tests("#delete_table(#{@table_name}").formats(@delete_table_format) do pending if Fog.mocking? Fog::AWS[:dynamodb].delete_table(@table_name).body end end tests('failure') do tests("#delete_table('notatable')").raises(Excon::Errors::BadRequest) do pending if Fog.mocking? Fog::AWS[:dynamodb].delete_table('notatable') end tests("#describe_table('notatable')").raises(Excon::Errors::BadRequest) do pending if Fog.mocking? Fog::AWS[:dynamodb].describe_table('notatable') end tests("#update_table('notatable', {'ReadCapacityUnits' => 10, 'WriteCapacityUnits' => 10})").raises(Excon::Errors::BadRequest) do pending if Fog.mocking? Fog::AWS[:dynamodb].update_table('notatable', {'ReadCapacityUnits' => 10, 'WriteCapacityUnits' => 10}).body end end end fog-1.19.0/tests/aws/requests/dynamodb/item_tests.rb0000644000004100000410000001173212261242552022523 0ustar www-datawww-dataShindo.tests('Fog::AWS[:dynamodb] | item requests', ['aws']) do @table_name = "fog_table_#{Time.now.to_f.to_s.gsub('.','')}" unless Fog.mocking? Fog::AWS[:dynamodb].create_table( @table_name, {'HashKeyElement' => {'AttributeName' => 'key', 'AttributeType' => 'S'}}, {'ReadCapacityUnits' => 5, 'WriteCapacityUnits' => 5} ) Fog.wait_for { Fog::AWS[:dynamodb].describe_table(@table_name).body['Table']['TableStatus'] == 'ACTIVE' } end tests('success') do tests("#put_item('#{@table_name}', {'key' => {'S' => 'key'}}, {'value' => {'S' => 'value'}})").formats('ConsumedCapacityUnits' => Float) do pending if Fog.mocking? Fog::AWS[:dynamodb].put_item(@table_name, {'key' => {'S' => 'key'}}, {'value' => {'S' => 'value'}}).body end tests("#update_item('#{@table_name}', {'HashKeyElement' => {'S' => 'key'}}, {'value' => {'Value' => {'S' => 'value'}}})").formats('ConsumedCapacityUnits' => Float) do pending if Fog.mocking? Fog::AWS[:dynamodb].update_item(@table_name, {'HashKeyElement' => {'S' => 'key'}}, {'value' => {'Value' => {'S' => 'value'}}}).body end @batch_get_item_format = { 'Responses' => { @table_name => { 'ConsumedCapacityUnits' => Float, 'Items' => [{ 'key' => { 'S' => String }, 'value' => { 'S' => String } }] } }, 'UnprocessedKeys' => {} } tests("#batch_get_item({'#{@table_name}' => {'Keys' => [{'HashKeyElement' => {'S' => 'key'}}]}})").formats(@batch_get_item_format) do pending if Fog.mocking? Fog::AWS[:dynamodb].batch_get_item( {@table_name => {'Keys' => [{'HashKeyElement' => {'S' => 'key'}}]}} ).body end @batch_put_item_format = { 'Responses'=> { @table_name => { 'ConsumedCapacityUnits' => Float} }, 'UnprocessedItems'=> {} } tests("#batch_put_item({ '#{@table_name}' => [{ 'PutRequest' => { 'Item' => { 'HashKeyElement' => { 'S' => 'key' }, 'RangeKeyElement' => { 'S' => 'key' }}}}]})" ).formats(@batch_put_item_format) do pending if Fog.mocking? Fog::AWS[:dynamodb].batch_put_item( {@table_name => [{'PutRequest'=> {'Item'=> {'HashKeyElement' => { 'S' => 'key' }, 'RangeKeyElement' => { 'S' => 'key' } }}}]} ).body end @get_item_format = { 'ConsumedCapacityUnits' => Float, 'Item' => { 'key' => { 'S' => String }, 'value' => { 'S' => String } } } tests("#get_item('#{@table_name}', {'HashKeyElement' => {'S' => 'key'}})").formats(@get_item_format) do pending if Fog.mocking? Fog::AWS[:dynamodb].get_item(@table_name, {'HashKeyElement' => {'S' => 'key'}}).body end tests("#get_item('#{@table_name}', {'HashKeyElement' => {'S' => 'notakey'}})").formats('ConsumedCapacityUnits' => Float) do pending if Fog.mocking? Fog::AWS[:dynamodb].get_item(@table_name, {'HashKeyElement' => {'S' => 'notakey'}}).body end @query_format = { 'ConsumedCapacityUnits' => Float, 'Count' => Integer, 'Items' => [{ 'key' => { 'S' => String }, 'value' => { 'S' => String } }], 'LastEvaluatedKey' => NilClass } tests("#query('#{@table_name}', {'S' => 'key'}").formats(@query_format) do pending if Fog.mocking? pending # requires a table with range key Fog::AWS[:dynamodb].query(@table_name, {'S' => 'key'}).body end @scan_format = @query_format.merge('ScannedCount' => Integer) tests("scan('#{@table_name}')").formats(@scan_format) do pending if Fog.mocking? Fog::AWS[:dynamodb].scan(@table_name).body end tests("#delete_item('#{@table_name}', {'HashKeyElement' => {'S' => 'key'}})").formats('ConsumedCapacityUnits' => Float) do pending if Fog.mocking? Fog::AWS[:dynamodb].delete_item(@table_name, {'HashKeyElement' => {'S' => 'key'}}).body end tests("#delete_item('#{@table_name}, {'HashKeyElement' => {'S' => 'key'}})").formats('ConsumedCapacityUnits' => Float) do pending if Fog.mocking? Fog::AWS[:dynamodb].delete_item(@table_name, {'HashKeyElement' => {'S' => 'key'}}).body end end tests('failure') do tests("#put_item('notatable', {'key' => {'S' => 'key'}}, {'value' => {'S' => 'value'}})").raises(Excon::Errors::BadRequest) do pending if Fog.mocking? Fog::AWS[:dynamodb].put_item('notatable', {'key' => {'S' => 'key'}}, {'value' => {'S' => 'value'}}) end tests("#update_item('notatable', {'HashKeyElement' => {'S' => 'key'}}, {'value' => {'Value' => {'S' => 'value'}}})").raises(Excon::Errors::BadRequest) do pending if Fog.mocking? Fog::AWS[:dynamodb].update_item('notatable', {'HashKeyElement' => {'S' => 'key'}}, {'value' => {'Value' => {'S' => 'value'}}}) end end unless Fog.mocking? Fog::AWS[:dynamodb].delete_table(@table_name) end end fog-1.19.0/tests/aws/requests/rds/0000755000004100000410000000000012261242552017005 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/rds/security_group_tests.rb0000644000004100000410000001145012261242552023640 0ustar www-datawww-dataShindo.tests('AWS::RDS | security group requests', ['aws', 'rds']) do suffix = rand(65536).to_s(16) @sec_group_name = "fog-sec-group-#{suffix}" if Fog.mocking? @owner_id = '123456780' else @owner_id = Fog::AWS[:rds].security_groups.get('default').owner_id end tests('success') do tests("#create_db_security_group").formats(AWS::RDS::Formats::CREATE_DB_SECURITY_GROUP) do body = Fog::AWS[:rds].create_db_security_group(@sec_group_name, 'Some description').body returns( @sec_group_name) { body['CreateDBSecurityGroupResult']['DBSecurityGroup']['DBSecurityGroupName']} returns( 'Some description') { body['CreateDBSecurityGroupResult']['DBSecurityGroup']['DBSecurityGroupDescription']} returns( []) { body['CreateDBSecurityGroupResult']['DBSecurityGroup']['EC2SecurityGroups']} returns( []) { body['CreateDBSecurityGroupResult']['DBSecurityGroup']['IPRanges']} body end tests("#describe_db_security_groups").formats(AWS::RDS::Formats::DESCRIBE_DB_SECURITY_GROUP) do Fog::AWS[:rds].describe_db_security_groups.body end tests("#authorize_db_security_group_ingress CIDR").formats(AWS::RDS::Formats::AUTHORIZE_DB_SECURITY_GROUP) do @cidr = '0.0.0.0/0' body = Fog::AWS[:rds].authorize_db_security_group_ingress(@sec_group_name,{'CIDRIP'=>@cidr}).body returns("authorizing") { body['AuthorizeDBSecurityGroupIngressResult']['DBSecurityGroup']['IPRanges'].detect{|h| h['CIDRIP'] == @cidr}['Status']} body end sec_group = Fog::AWS[:rds].security_groups.get(@sec_group_name) sec_group.wait_for {ready?} tests("#authorize_db_security_group_ingress another CIDR").formats(AWS::RDS::Formats::AUTHORIZE_DB_SECURITY_GROUP) do @cidr = "10.0.0.0/24" body = Fog::AWS[:rds].authorize_db_security_group_ingress(@sec_group_name,{'CIDRIP'=>@cidr}).body returns("authorizing") { body['AuthorizeDBSecurityGroupIngressResult']['DBSecurityGroup']['IPRanges'].detect{|h| h['CIDRIP'] == @cidr}['Status']} body end sec_group = Fog::AWS[:rds].security_groups.get(@sec_group_name) sec_group.wait_for {ready?} tests("#count CIDRIP").formats(AWS::RDS::Formats::DESCRIBE_DB_SECURITY_GROUP) do body = Fog::AWS[:rds].describe_db_security_groups(@sec_group_name).body returns(2) { body['DescribeDBSecurityGroupsResult']['DBSecurityGroups'][0]['IPRanges'].size } body end tests("#revoke_db_security_group_ingress CIDR").formats(AWS::RDS::Formats::REVOKE_DB_SECURITY_GROUP) do @cidr = '0.0.0.0/0' body = Fog::AWS[:rds].revoke_db_security_group_ingress(@sec_group_name,{'CIDRIP'=> @cidr}).body returns("revoking") { body['RevokeDBSecurityGroupIngressResult']['DBSecurityGroup']['IPRanges'].detect{|h| h['CIDRIP'] == @cidr}['Status']} body end tests("#authorize_db_security_group_ingress EC2").formats(AWS::RDS::Formats::AUTHORIZE_DB_SECURITY_GROUP) do @ec2_sec_group = 'default' body = Fog::AWS[:rds].authorize_db_security_group_ingress(@sec_group_name,{'EC2SecurityGroupName' => @ec2_sec_group, 'EC2SecurityGroupOwnerId' => @owner_id}).body returns("authorizing") { body['AuthorizeDBSecurityGroupIngressResult']['DBSecurityGroup']['EC2SecurityGroups'].detect{|h| h['EC2SecurityGroupName'] == @ec2_sec_group}['Status']} returns(@owner_id) { body['AuthorizeDBSecurityGroupIngressResult']['DBSecurityGroup']['EC2SecurityGroups'].detect{|h| h['EC2SecurityGroupName'] == @ec2_sec_group}['EC2SecurityGroupOwnerId']} body end tests("duplicate #authorize_db_security_group_ingress EC2").raises(Fog::AWS::RDS::AuthorizationAlreadyExists) do @ec2_sec_group = 'default' Fog::AWS[:rds].authorize_db_security_group_ingress(@sec_group_name,{'EC2SecurityGroupName' => @ec2_sec_group, 'EC2SecurityGroupOwnerId' => @owner_id}) end sec_group = Fog::AWS[:rds].security_groups.get(@sec_group_name) sec_group.wait_for {ready?} tests("#revoke_db_security_group_ingress EC2").formats(AWS::RDS::Formats::REVOKE_DB_SECURITY_GROUP) do @ec2_sec_group = 'default' body = Fog::AWS[:rds].revoke_db_security_group_ingress(@sec_group_name,{'EC2SecurityGroupName' => @ec2_sec_group, 'EC2SecurityGroupOwnerId' => @owner_id}).body returns("revoking") { body['RevokeDBSecurityGroupIngressResult']['DBSecurityGroup']['EC2SecurityGroups'].detect{|h| h['EC2SecurityGroupName'] == @ec2_sec_group}['Status']} body end #TODO, authorize ec2 security groups tests("#delete_db_security_group").formats(AWS::RDS::Formats::BASIC) do body = Fog::AWS[:rds].delete_db_security_group(@sec_group_name).body raises(Fog::AWS::RDS::NotFound) {Fog::AWS[:rds].describe_db_security_groups(@sec_group_name)} body end end endfog-1.19.0/tests/aws/requests/rds/subnet_groups_tests.rb0000644000004100000410000000360012261242552023452 0ustar www-datawww-dataShindo.tests('AWS::RDS | subnet group requests', ['aws', 'rds']) do # random_differentiator # Useful when rapidly re-running tests, so we don't have to wait # serveral minutes for deleted VPCs/subnets to disappear suffix = rand(65536).to_s(16) @subnet_group_name = "fog-test-#{suffix}" vpc_range = rand(245) + 10 @vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => "10.#{vpc_range}.0.0/16") # Create 4 subnets in this VPC, each one in a different AZ subnet_az = 'us-east-1a' subnet_range = 8 @subnets = (1..4).map do subnet = Fog::Compute[:aws].create_subnet(@vpc.id, "10.#{vpc_range}.#{subnet_range}.0/24", 'AvailabilityZone' => subnet_az).body['subnetSet'].first subnet_az = subnet_az.succ subnet_range *= 2 subnet end tests('success') do subnet_ids = @subnets.map { |sn| sn['subnetId'] }.to_a tests("#create_db_subnet_group").formats(AWS::RDS::Formats::CREATE_DB_SUBNET_GROUP) do result = Fog::AWS[:rds].create_db_subnet_group(@subnet_group_name, subnet_ids, 'A subnet group').body returns(@subnet_group_name) { result['CreateDBSubnetGroupResult']['DBSubnetGroup']['DBSubnetGroupName'] } returns('A subnet group') { result['CreateDBSubnetGroupResult']['DBSubnetGroup']['DBSubnetGroupDescription'] } returns(@vpc.id) { result['CreateDBSubnetGroupResult']['DBSubnetGroup']['VpcId'] } returns(subnet_ids.sort) { result['CreateDBSubnetGroupResult']['DBSubnetGroup']['Subnets'].sort } result end tests("#describe_db_subnet_groups").formats(AWS::RDS::Formats::DESCRIBE_DB_SUBNET_GROUPS) do Fog::AWS[:rds].describe_db_subnet_groups.body end tests("#delete_db_subnet_group").formats(AWS::RDS::Formats::BASIC) do Fog::AWS[:rds].delete_db_subnet_group(@subnet_group_name).body end end @subnets.each do |sn| Fog::Compute[:aws].delete_subnet(sn['subnetId']) end @vpc.destroy end fog-1.19.0/tests/aws/requests/rds/helper.rb0000644000004100000410000001717712261242552020626 0ustar www-datawww-dataclass AWS module RDS module Formats BASIC = { 'ResponseMetadata' => {'RequestId' => String} } DB_AVAILABILITY_ZONE_OPTION = { 'Name' => String, 'ProvisionedIopsCapable' => Fog::Boolean } DB_PARAMETER_GROUP = { 'DBParameterGroupFamily' => String, 'DBParameterGroupName'=> String, 'Description'=> String } CREATE_DB_PARAMETER_GROUP = { 'ResponseMetadata' => {'RequestId' => String}, 'CreateDBParameterGroupResult' => { 'DBParameterGroup' => DB_PARAMETER_GROUP } } DB_SECURITY_GROUP = { 'DBSecurityGroupDescription' => String, 'DBSecurityGroupName' => String, 'EC2SecurityGroups' => [Fog::Nullable::Hash], 'IPRanges' => [Fog::Nullable::Hash], 'OwnerId' => Fog::Nullable::String } CREATE_DB_SECURITY_GROUP = BASIC.merge({ 'CreateDBSecurityGroupResult' => { 'DBSecurityGroup' => DB_SECURITY_GROUP } }) AUTHORIZE_DB_SECURITY_GROUP = BASIC.merge({ 'AuthorizeDBSecurityGroupIngressResult' => { 'DBSecurityGroup' => DB_SECURITY_GROUP } }) REVOKE_DB_SECURITY_GROUP = BASIC.merge({ 'RevokeDBSecurityGroupIngressResult' => { 'DBSecurityGroup' => DB_SECURITY_GROUP } }) DESCRIBE_DB_SECURITY_GROUP = BASIC.merge({ 'DescribeDBSecurityGroupsResult' => { 'DBSecurityGroups' => [DB_SECURITY_GROUP] } }) DB_SUBNET_GROUP = { 'DBSubnetGroupName' => String, 'DBSubnetGroupDescription' => String, 'SubnetGroupStatus' => String, 'VpcId' => String, 'Subnets' => [String] } CREATE_DB_SUBNET_GROUP = BASIC.merge({ 'CreateDBSubnetGroupResult' => { 'DBSubnetGroup' => DB_SUBNET_GROUP } }) DESCRIBE_DB_SUBNET_GROUPS = BASIC.merge({ 'DescribeDBSubnetGroupsResult' => { 'DBSubnetGroups' => [DB_SUBNET_GROUP] } }) DESCRIBE_DB_PARAMETER_GROUP = { 'ResponseMetadata' => {'RequestId' => String}, 'DescribeDBParameterGroupsResult' =>{ 'DBParameterGroups' => [DB_PARAMETER_GROUP] } } ORDERABLE_DB_INSTANCE_OPTION = { 'MultiAZCapable' => Fog::Boolean, 'Engine' => String, 'LicenseModel' => String, 'ReadReplicaCapable' => Fog::Boolean, 'EngineVersion' => String, 'AvailabilityZones' => [DB_AVAILABILITY_ZONE_OPTION], 'DBInstanceClass' => String, 'Vpc' => Fog::Boolean } DESCRIBE_ORDERABLE_DB_INSTANCE_OPTION = BASIC.merge({ 'DescribeOrderableDBInstanceOptionsResult' =>{ 'OrderableDBInstanceOptions' => [ORDERABLE_DB_INSTANCE_OPTION] } }) MODIFY_PARAMETER_GROUP = BASIC.merge({ 'ModifyDBParameterGroupResult' => { 'DBParameterGroupName' => String } }) DB_PARAMETER = { 'ParameterValue' => Fog::Nullable::String, 'DataType' => String, 'AllowedValues' => Fog::Nullable::String, 'Source' => String, 'IsModifiable' => Fog::Boolean, 'Description' => String, 'ParameterName' => String, 'ApplyType' => String } DESCRIBE_DB_PARAMETERS = BASIC.merge({ 'DescribeDBParametersResult' => { 'Marker' => Fog::Nullable::String, 'Parameters' => [DB_PARAMETER] } }) DB_LOG_FILE = { 'LastWritten' => Time, 'Size' => Integer, 'LogFileName' => String } DESCRIBE_DB_LOG_FILES = BASIC.merge({ 'DescribeDBLogFilesResult' => { 'Marker' => Fog::Nullable::String, 'DBLogFiles' => [DB_LOG_FILE] } }) SNAPSHOT={ 'AllocatedStorage' => Integer, 'AvailabilityZone' => String, 'DBInstanceIdentifier' => String, 'DBSnapshotIdentifier' => String, 'EngineVersion' => String, 'Engine' => String, 'InstanceCreateTime' => Time, 'MasterUsername' => String, 'Port' => Integer, 'SnapshotCreateTime' => Fog::Nullable::Time, 'Status' => String, 'SnapshotType' => String } INSTANCE = { 'AllocatedStorage' => Integer, 'AutoMinorVersionUpgrade' => Fog::Boolean, 'AvailabilityZone' => Fog::Nullable::String, 'BackupRetentionPeriod' => Integer, 'DBInstanceClass' => String, 'DBInstanceIdentifier' => String, 'DBInstanceStatus' => String, 'DBName' => Fog::Nullable::String, 'DBParameterGroups' => [{ 'ParameterApplyStatus' => String, 'DBParameterGroupName' => String }], 'DBSecurityGroups' => [{ 'Status' => String, 'DBSecurityGroupName' => String }], 'DBSubnetGroupName' => Fog::Nullable::String, 'PubliclyAccessible' => Fog::Boolean, 'Endpoint' => { 'Address' => Fog::Nullable::String, 'Port' => Fog::Nullable::Integer }, 'Engine' => String, 'EngineVersion' => String, 'InstanceCreateTime' => Fog::Nullable::Time, 'LatestRestorableTime' => Fog::Nullable::Time, 'LicenseModel' => String, 'MasterUsername' => String, 'MultiAZ' => Fog::Boolean, 'PendingModifiedValues' => { 'BackupRetentionPeriod' => Fog::Nullable::Integer, 'DBInstanceClass' => Fog::Nullable::String, 'EngineVersion' => Fog::Nullable::String, 'MasterUserPassword' => Fog::Nullable::String, 'MultiAZ' => Fog::Nullable::String, 'AllocatedStorage' => Fog::Nullable::Integer, 'Port' => Fog::Nullable::Integer }, 'PreferredBackupWindow'=> String, 'PreferredMaintenanceWindow'=> String, 'ReadReplicaDBInstanceIdentifiers'=> [Fog::Nullable::String] } REPLICA_INSTANCE = INSTANCE.merge({ 'BackupRetentionPeriod' => Fog::Nullable::String, 'PreferredBackupWindow' => Fog::Nullable::String, 'ReadReplicaSourceDBInstanceIdentifier'=> String }) CREATE_DB_INSTANCE = BASIC.merge({ 'CreateDBInstanceResult' => { 'DBInstance' => INSTANCE } }) DESCRIBE_DB_INSTANCES = BASIC.merge({ 'DescribeDBInstancesResult' => { 'Marker' => Fog::Nullable::String, 'DBInstances' => [INSTANCE] } }) MODIFY_DB_INSTANCE = BASIC.merge({ 'ModifyDBInstanceResult' => { 'DBInstance' => INSTANCE } }) DELETE_DB_INSTANCE = BASIC.merge({ 'DeleteDBInstanceResult' => { 'DBInstance' => INSTANCE } }) REBOOT_DB_INSTANCE = BASIC.merge({ 'RebootDBInstanceResult' => { 'DBInstance' => INSTANCE } }) CREATE_READ_REPLICA = BASIC.merge({ 'CreateDBInstanceReadReplicaResult' => { 'DBInstance' => REPLICA_INSTANCE } }) CREATE_DB_SNAPSHOT = BASIC.merge({ 'CreateDBSnapshotResult' => { 'DBSnapshot' => SNAPSHOT } }) DESCRIBE_DB_SNAPSHOTS = BASIC.merge({ 'DescribeDBSnapshotsResult' => { 'Marker' => Fog::Nullable::String, 'DBSnapshots' => [SNAPSHOT] } }) DELETE_DB_SNAPSHOT = BASIC.merge({ 'DeleteDBSnapshotResult' => { 'DBSnapshot' => SNAPSHOT } }) LIST_TAGS_FOR_RESOURCE = { 'ListTagsForResourceResult' => { 'TagList' => Fog::Nullable::Hash } } end end end fog-1.19.0/tests/aws/requests/rds/tagging_tests.rb0000644000004100000410000000513512261242552022200 0ustar www-datawww-dataShindo.tests('AWS::RDS | tagging requests', ['aws', 'rds']) do @rds = Fog::AWS[:rds] @db_instance_id = "fog-test-#{rand(65536).to_s(16)}" Formatador.display_line "Creating RDS instance #{@db_instance_id}" @rds.create_db_instance(@db_instance_id, 'AllocatedStorage' => 5, 'DBInstanceClass' => 'db.t1.micro', 'Engine' => 'mysql', 'MasterUsername' => 'foguser', 'MasterUserPassword' => 'fogpassword') Formatador.display_line "Waiting for instance #{@db_instance_id} to be ready" @db = @rds.servers.get(@db_instance_id) @db.wait_for { ready? } tests('success') do single_tag = {'key1' => 'value1'} two_tags = {'key2' => 'value2', 'key3' => 'value3'} tests("#add_tags_to_resource with a single tag"). formats(AWS::RDS::Formats::BASIC) do result = @rds.add_tags_to_resource(@db_instance_id, single_tag).body returns(single_tag) do @rds.list_tags_for_resource(@db_instance_id). body['ListTagsForResourceResult']['TagList'] end result end tests("#add_tags_to_resource with a multiple tags"). formats(AWS::RDS::Formats::BASIC) do result = @rds.add_tags_to_resource(@db_instance_id, two_tags).body returns(single_tag.merge(two_tags)) do @rds.list_tags_for_resource(@db_instance_id). body['ListTagsForResourceResult']['TagList'] end result end tests("#remove_tags_from_resource").formats(AWS::RDS::Formats::BASIC) do result = @rds.remove_tags_from_resource( @db_instance_id, single_tag.keys).body returns(two_tags) do @rds.list_tags_for_resource(@db_instance_id). body['ListTagsForResourceResult']['TagList'] end result end tests("#list_tags_for_resource"). formats(AWS::RDS::Formats::LIST_TAGS_FOR_RESOURCE) do result = @rds.list_tags_for_resource(@db_instance_id).body returns(two_tags) do result['ListTagsForResourceResult']['TagList'] end result end end tests('failure') do tests "tagging a nonexisting instance" do raises(Fog::AWS::RDS::NotFound) do @rds.add_tags_to_resource('doesnexist', {'key1' => 'value1'}) end end tests "listing tags for a nonexisting instance" do raises(Fog::AWS::RDS::NotFound) do @rds.list_tags_for_resource('doesnexist') end end tests "removing tags for a nonexisting instance" do raises(Fog::AWS::RDS::NotFound) do @rds.remove_tags_from_resource('doesnexist', ['key1']) end end end Formatador.display_line "Destroying DB instance #{@db_instance_id}" @db.destroy end fog-1.19.0/tests/aws/requests/rds/describe_events.rb0000644000004100000410000000053412261242552022500 0ustar www-datawww-dataShindo.tests('AWS::RDS | describe DB events requests',['aws', 'rds']) do tests('success') do pending if Fog.mocking? tests( '#describe_events' ).formats(AWS::RDS::Formats::EVENT_LIST) do AWS[:rds].describe_events().body['Events'] end end tests('failure') do #TODO: What constitutes a failure here? end end fog-1.19.0/tests/aws/requests/rds/parameter_request_tests.rb0000644000004100000410000000244112261242552024305 0ustar www-datawww-dataShindo.tests('AWS::RDS | parameter requests', ['aws', 'rds']) do tests('success') do pending if Fog.mocking? Fog::AWS[:rds].create_db_parameter_group('fog-group', 'MySQL5.1', 'Some description') tests('#modify_db_parameter_group').formats(AWS::RDS::Formats::MODIFY_PARAMETER_GROUP) do body = Fog::AWS[:rds].modify_db_parameter_group('fog-group',[ {'ParameterName' => 'query_cache_size', 'ParameterValue' => '12345', 'ApplyMethod' => 'immediate'} ]).body body end tests('#describe_db_parameters').formats(AWS::RDS::Formats::DESCRIBE_DB_PARAMETERS) do Fog::AWS[:rds].describe_db_parameters('fog-group', :max_records => 20).body end tests("#describe_db_parameters :source => 'user'")do body = Fog::AWS[:rds].describe_db_parameters('fog-group', :source => 'user').body returns(1){ body['DescribeDBParametersResult']['Parameters'].length} param = body['DescribeDBParametersResult']['Parameters'].first returns('query_cache_size'){param['ParameterName']} returns('12345'){param['ParameterValue']} returns(true){param['IsModifiable']} returns('query_cache_size'){param['ParameterName']} end Fog::AWS[:rds].delete_db_parameter_group('fog-group') end end fog-1.19.0/tests/aws/requests/rds/parameter_group_tests.rb0000644000004100000410000000477012261242552023760 0ustar www-datawww-dataShindo.tests('AWS::RDS | parameter group requests', ['aws', 'rds']) do tests('success') do tests("#create_db_parameter_groups").formats(AWS::RDS::Formats::CREATE_DB_PARAMETER_GROUP) do body = Fog::AWS[:rds].create_db_parameter_group('fog-group', 'MySQL5.1', 'Some description').body returns( 'mysql5.1') { body['CreateDBParameterGroupResult']['DBParameterGroup']['DBParameterGroupFamily']} returns( 'fog-group') { body['CreateDBParameterGroupResult']['DBParameterGroup']['DBParameterGroupName']} returns( 'Some description') { body['CreateDBParameterGroupResult']['DBParameterGroup']['Description']} body end Fog::AWS[:rds].create_db_parameter_group('other-fog-group', 'MySQL5.1', 'Some description') tests("#describe_db_parameter_groups").formats(AWS::RDS::Formats::DESCRIBE_DB_PARAMETER_GROUP) do body = Fog::AWS[:rds].describe_db_parameter_groups().body returns(4) {body['DescribeDBParameterGroupsResult']['DBParameterGroups'].length} body end tests("#describe_db_parameter_groups('fog-group)").formats(AWS::RDS::Formats::DESCRIBE_DB_PARAMETER_GROUP) do body = Fog::AWS[:rds].describe_db_parameter_groups('fog-group').body returns(1) {body['DescribeDBParameterGroupsResult']['DBParameterGroups'].length} group = body['DescribeDBParameterGroupsResult']['DBParameterGroups'].first returns( 'mysql5.1') { group['DBParameterGroupFamily']} returns( 'fog-group') { group['DBParameterGroupName']} returns( 'Some description') { group['Description']} body end tests("delete_db_parameter_group").formats(AWS::RDS::Formats::BASIC) do body = Fog::AWS[:rds].delete_db_parameter_group('fog-group').body raises(Fog::AWS::RDS::NotFound) {Fog::AWS[:rds].describe_db_parameter_groups('fog-group')} body end Fog::AWS[:rds].delete_db_parameter_group('other-fog-group') end tests("failures") do raises(Fog::AWS::RDS::NotFound) {Fog::AWS[:rds].describe_db_parameter_groups('doesntexist')} raises(Fog::AWS::RDS::NotFound) {Fog::AWS[:rds].delete_db_parameter_group('doesntexist')} tests "creating second group with same id" do Fog::AWS[:rds].create_db_parameter_group('fog-group', 'MySQL5.1', 'Some description') raises(Fog::AWS::RDS::IdentifierTaken) {Fog::AWS[:rds].create_db_parameter_group('fog-group', 'MySQL5.1', 'Some description')} end Fog::AWS[:rds].delete_db_parameter_group('fog-group') end endfog-1.19.0/tests/aws/requests/rds/log_file_tests.rb0000644000004100000410000000111312261242552022330 0ustar www-datawww-dataShindo.tests('AWS::RDS | log file requests', %w[aws rds]) do tests('success') do pending if Fog.mocking? suffix = rand(65536).to_s(16) @db_instance_id = "fog-test-#{suffix}" tests('#describe_db_log_files').formats(AWS::RDS::Formats::DESCRIBE_DB_LOG_FILES) do result = Fog::AWS[:rds].describe_db_log_files(@db_instance_id).body['DescribeDBLogFilesResult'] returns(true) { result['DBLogFiles'].size > 0 } result end end tests('failures') do raises(Fog::AWS::RDS::NotFound) {Fog::AWS[:rds].describe_db_log_files('doesntexist')} end end fog-1.19.0/tests/aws/requests/rds/instance_option_tests.rb0000644000004100000410000000137112261242552023752 0ustar www-datawww-dataShindo.tests('AWS::RDS | db instance option requests', ['aws', 'rds']) do tests('success') do tests("#describe_orderable_db_instance_options('mysql)").formats(AWS::RDS::Formats::DESCRIBE_ORDERABLE_DB_INSTANCE_OPTION) do body = Fog::AWS[:rds].describe_orderable_db_instance_options('mysql').body returns(2) {body['DescribeOrderableDBInstanceOptionsResult']['OrderableDBInstanceOptions'].length} group = body['DescribeOrderableDBInstanceOptionsResult']['OrderableDBInstanceOptions'].first returns( true ) { group['MultiAZCapable'] } returns( 'mysql' ) { group['Engine'] } returns( true ) { group['ReadReplicaCapable'] } returns( true ) { group['AvailabilityZones'].length >= 1 } body end end end fog-1.19.0/tests/aws/requests/rds/instance_tests.rb0000644000004100000410000001145012261242552022361 0ustar www-datawww-dataShindo.tests('AWS::RDS | instance requests', ['aws', 'rds']) do # Disabled due to https://github.com/fog/fog/1546 pending # random_differentiator # Useful when rapidly re-running tests, so we don't have to wait # serveral minutes for deleted servers to disappear suffix = rand(65536).to_s(16) @db_instance_id = "fog-test-#{suffix}" @db_replica_id = "fog-replica-#{suffix}" @db_snapshot_id = "fog-snapshot" @db_final_snapshot_id = "fog-final-snapshot" tests('success') do tests("#create_db_instance").formats(AWS::RDS::Formats::CREATE_DB_INSTANCE) do result = Fog::AWS[:rds].create_db_instance(@db_instance_id, 'AllocatedStorage' => 5, 'DBInstanceClass' => 'db.m1.small', 'Engine' => 'mysql', 'EngineVersion' => '5.1.50', 'MasterUsername' => 'foguser', 'BackupRetentionPeriod' => 1, 'MasterUserPassword' => 'fogpassword').body instance = result['CreateDBInstanceResult']['DBInstance'] returns('creating'){ instance['DBInstanceStatus']} result end tests("#describe_db_instances").formats(AWS::RDS::Formats::DESCRIBE_DB_INSTANCES) do Fog::AWS[:rds].describe_db_instances.body end server = Fog::AWS[:rds].servers.get(@db_instance_id) server.wait_for {ready?} new_storage = 6 tests("#modify_db_instance with immediate apply").formats(AWS::RDS::Formats::MODIFY_DB_INSTANCE) do body = Fog::AWS[:rds].modify_db_instance(@db_instance_id, true, 'AllocatedStorage'=> new_storage).body tests 'pending storage' do instance = body['ModifyDBInstanceResult']['DBInstance'] returns(new_storage){instance['PendingModifiedValues']['AllocatedStorage']} end body end server.wait_for { state == 'modifying' } server.wait_for { state == 'available' } tests 'new storage' do returns(new_storage){ server.allocated_storage} end tests("reboot db instance") do tests("#reboot").formats(AWS::RDS::Formats::REBOOT_DB_INSTANCE) do Fog::AWS[:rds].reboot_db_instance(@db_instance_id).body end end server.wait_for { state == 'rebooting' } server.wait_for { state == 'available'} tests("#create_db_snapshot").formats(AWS::RDS::Formats::CREATE_DB_SNAPSHOT) do body = Fog::AWS[:rds].create_db_snapshot(@db_instance_id, @db_snapshot_id).body returns('creating'){ body['CreateDBSnapshotResult']['DBSnapshot']['Status']} body end tests("#describe_db_snapshots").formats(AWS::RDS::Formats::DESCRIBE_DB_SNAPSHOTS) do body = Fog::AWS[:rds].describe_db_snapshots.body end server.wait_for { state == 'available' } tests( "#create read replica").formats(AWS::RDS::Formats::CREATE_READ_REPLICA) do Fog::AWS[:rds].create_db_instance_read_replica(@db_replica_id, @db_instance_id).body end replica = Fog::AWS[:rds].servers.get(@db_replica_id) replica.wait_for {ready?} tests("replica source") do returns(@db_instance_id){replica.read_replica_source} end server.reload tests("replica identifiers") do returns([@db_replica_id]){server.read_replica_identifiers} end tests("#delete_db_instance").formats(AWS::RDS::Formats::DELETE_DB_INSTANCE) do #server.wait_for { state == 'available'} Fog::AWS[:rds].delete_db_instance(@db_replica_id, nil, true) body = Fog::AWS[:rds].delete_db_instance(@db_instance_id, @db_final_snapshot_id).body tests "final snapshot" do returns('creating'){Fog::AWS[:rds].describe_db_snapshots(:snapshot_id => @db_final_snapshot_id).body['DescribeDBSnapshotsResult']['DBSnapshots'].first['Status']} end body end tests("#delete_db_snapshot").formats(AWS::RDS::Formats::DELETE_DB_SNAPSHOT) do Fog::AWS[:rds].snapshots.get(@db_snapshot_id).wait_for { ready? } Fog::AWS[:rds].delete_db_snapshot(@db_snapshot_id).body end tests("snapshot.destroy") do snapshot = Fog::AWS[:rds].snapshots.get(@db_final_snapshot_id) snapshot.wait_for { ready? } snapshot.destroy returns(nil) { Fog::AWS[:rds].snapshots.get(@db_final_snapshot_id) } end end tests('failure') do tests "deleting nonexisting instance" do raises(Fog::AWS::RDS::NotFound) {Fog::AWS[:rds].delete_db_instance('doesnexist', 'irrelevant')} end tests "deleting non existing snapshot" do raises(Fog::AWS::RDS::NotFound) {Fog::AWS[:rds].delete_db_snapshot('doesntexist')} end tests "modifying non existing instance" do raises(Fog::AWS::RDS::NotFound) { Fog::AWS[:rds].modify_db_instance 'doesntexit', true, 'AllocatedStorage'=> 10} end end end fog-1.19.0/tests/aws/requests/compute/0000755000004100000410000000000012261242552017671 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/compute/spot_price_history_tests.rb0000644000004100000410000000116012261242552025366 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | spot price history requests', ['aws']) do @spot_price_history_format = { 'spotPriceHistorySet' => [{ 'availabilityZone' => String, 'instanceType' => String, 'spotPrice' => Float, 'productDescription' => String, 'timestamp' => Time }], 'requestId' => String } tests('success') do pending # Some history data doesn't have an availability zone tests("#describe_spot_price_history").formats(@spot_price_history_format) do Fog::Compute[:aws].describe_spot_price_history.body end end end fog-1.19.0/tests/aws/requests/compute/availability_zone_tests.rb0000644000004100000410000000127612261242552025153 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | availability zone requests', ['aws']) do @availability_zones_format = { 'availabilityZoneInfo' => [{ 'messageSet' => [], 'regionName' => String, 'zoneName' => String, 'zoneState' => String }], 'requestId' => String } tests('success') do tests('#describe_availability_zones').formats(@availability_zones_format) do Fog::Compute[:aws].describe_availability_zones.body end tests("#describe_availability_zones('zone-name' => 'us-east-1a')").formats(@availability_zones_format) do Fog::Compute[:aws].describe_availability_zones('zone-name' => 'us-east-1a').body end end end fog-1.19.0/tests/aws/requests/compute/security_group_tests.rb0000644000004100000410000004662112261242552024534 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | security group requests', ['aws']) do @create_security_group_format = { 'requestId' => String, 'groupId' => String, 'return' => Fog::Boolean } @security_groups_format = { 'requestId' => String, 'securityGroupInfo' => [{ 'groupDescription' => String, 'groupId' => Fog::Nullable::String, 'groupName' => String, 'ipPermissions' => [{ 'fromPort' => Fog::Nullable::Integer, 'groups' => [{ 'groupName' => Fog::Nullable::String, 'userId' => String, 'groupId' => String }], 'ipProtocol' => String, 'ipRanges' => [Fog::Nullable::Hash], 'toPort' => Fog::Nullable::Integer, }], 'ipPermissionsEgress' => [], 'ownerId' => String, 'vpcId' => Fog::Nullable::String }] } @owner_id = Fog::Compute[:aws].describe_security_groups('group-name' => 'default').body['securityGroupInfo'].first['ownerId'] @group_id_default = Fog::Compute[:aws].describe_security_groups('group-name' => 'default').body['securityGroupInfo'].first['groupId'] tests('success') do tests("#create_security_group('fog_security_group', 'tests group')").formats(@create_security_group_format) do Fog::Compute[:aws].create_security_group('fog_security_group', 'tests group').body end tests("#create_security_group('fog_security_group_two', 'tests group')").formats(@create_security_group_format) do Fog::Compute[:aws].create_security_group('fog_security_group_two', 'tests group').body end @group_id_two = Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group_two').body['securityGroupInfo'].first['groupId'] group_id = Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['groupId'] to_be_revoked = [] expected_permissions = [] permission = { 'SourceSecurityGroupName' => 'default' } tests("#authorize_security_group_ingress('fog_security_group', #{permission.inspect})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permission).body end to_be_revoked.push([permission, expected_permissions.dup]) expected_permissions = [ {"groups"=>[{"groupName"=>"default", "userId"=>@owner_id, "groupId"=>@group_id_default}], "fromPort"=>1, "ipRanges"=>[], "ipProtocol"=>"tcp", "toPort"=>65535}, {"groups"=>[{"groupName"=>"default", "userId"=>@owner_id, "groupId"=>@group_id_default}], "fromPort"=>1, "ipRanges"=>[], "ipProtocol"=>"udp", "toPort"=>65535}, {"groups"=>[{"groupName"=>"default", "userId"=>@owner_id, "groupId"=>@group_id_default}], "fromPort"=>-1, "ipRanges"=>[], "ipProtocol"=>"icmp", "toPort"=>-1} ] tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions']) end tests("#describe_security_groups('group-id' => '#{group_id}')").returns([]) do array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-id' => group_id).body['securityGroupInfo'].first['ipPermissions']) end permission = { 'SourceSecurityGroupName' => 'fog_security_group_two', 'SourceSecurityGroupOwnerId' => @owner_id } tests("#authorize_security_group_ingress('fog_security_group', #{permission.inspect})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permission).body end to_be_revoked.push([permission, expected_permissions.dup]) expected_permissions = [ {"groups"=> [{"userId"=>@owner_id, "groupName"=>"default", "groupId"=>@group_id_default}, {"userId"=>@owner_id, "groupName"=>"fog_security_group_two", "groupId"=>@group_id_two}], "ipRanges"=>[], "ipProtocol"=>"tcp", "fromPort"=>1, "toPort"=>65535}, {"groups"=> [{"userId"=>@owner_id, "groupName"=>"default", "groupId"=>@group_id_default}, {"userId"=>@owner_id, "groupName"=>"fog_security_group_two", "groupId"=>@group_id_two}], "ipRanges"=>[], "ipProtocol"=>"udp", "fromPort"=>1, "toPort"=>65535}, {"groups"=> [{"userId"=>@owner_id, "groupName"=>"default", "groupId"=>@group_id_default}, {"userId"=>@owner_id, "groupName"=>"fog_security_group_two", "groupId"=>@group_id_two}], "ipRanges"=>[], "ipProtocol"=>"icmp", "fromPort"=>-1, "toPort"=>-1} ] tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions']) end permission = { 'IpProtocol' => 'tcp', 'FromPort' => '22', 'ToPort' => '22' } tests("#authorize_security_group_ingress('fog_security_group', #{permission.inspect})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permission).body end to_be_revoked.push([permission, expected_permissions.dup]) # previous did nothing tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions']) end permission = { 'IpProtocol' => 'tcp', 'FromPort' => '22', 'ToPort' => '22', 'CidrIp' => '10.0.0.0/8' } tests("#authorize_security_group_ingress('fog_security_group', #{permission.inspect})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permission).body end to_be_revoked.push([permission, expected_permissions.dup]) expected_permissions += [ {"groups"=>[], "ipRanges"=>[{"cidrIp"=>"10.0.0.0/8"}], "ipProtocol"=>"tcp", "fromPort"=>22, "toPort"=>22} ] tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions']) end # authorize with nested IpProtocol without IpRanges or Groups does nothing permissions = { 'IpPermissions' => [ { 'IpProtocol' => 'tcp', 'FromPort' => '22', 'ToPort' => '22' } ] } tests("#authorize_security_group_ingress('fog_security_group', #{permissions.inspect})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permissions).body end to_be_revoked.push([permissions, expected_permissions.dup]) # previous did nothing tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions']) end # authorize with nested IpProtocol with IpRanges permissions = { 'IpPermissions' => [ { 'IpProtocol' => 'tcp', 'FromPort' => '80', 'ToPort' => '80', 'IpRanges' => [{ 'CidrIp' => '192.168.0.0/24' }] } ] } tests("#authorize_security_group_ingress('fog_security_group', #{permissions.inspect})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permissions).body end to_be_revoked.push([permissions, expected_permissions.dup]) expected_permissions += [ {"groups"=>[], "ipRanges"=>[{"cidrIp"=>"192.168.0.0/24"}], "ipProtocol"=>"tcp", "fromPort"=>80, "toPort"=>80} ] tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions']) end # authorize with nested IpProtocol with Groups permissions = { 'IpPermissions' => [ { 'IpProtocol' => 'tcp', 'FromPort' => '8000', 'ToPort' => '8000', 'Groups' => [{ 'GroupName' => 'fog_security_group_two' }] } ] } tests("#authorize_security_group_ingress('fog_security_group', #{permissions.inspect})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permissions).body end to_be_revoked.push([permissions, expected_permissions.dup]) expected_permissions += [ {"groups"=>[{"userId"=>@owner_id, "groupName"=>"fog_security_group_two", "groupId"=>@group_id_two}], "ipRanges"=>[], "ipProtocol"=>"tcp", "fromPort"=>8000, "toPort"=>8000} ] tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions']) end # authorize with nested IpProtocol with IpRanges and Groups # try integers on this one instead of strings permissions = { 'IpPermissions' => [ { 'IpProtocol' => 'tcp', 'FromPort' => 9000, 'ToPort' => 9000, 'IpRanges' => [{ 'CidrIp' => '172.16.0.0/24' }], 'Groups' => [{ 'GroupName' => 'fog_security_group_two' }] } ] } tests("#authorize_security_group_ingress('fog_security_group', #{permissions.inspect})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permissions).body end to_be_revoked.push([permissions, expected_permissions.dup]) expected_permissions += [ {"groups"=> [{"userId"=>@owner_id, "groupName"=>"fog_security_group_two", "groupId"=>@group_id_two}], "ipRanges"=>[{"cidrIp"=>"172.16.0.0/24"}], "ipProtocol"=>"tcp", "fromPort"=>9000, "toPort"=>9000} ] tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions']) end tests("#describe_security_groups").formats(@security_groups_format) do Fog::Compute[:aws].describe_security_groups.body end tests("#describe_security_groups('group-name' => 'fog_security_group')").formats(@security_groups_format) do Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body end to_be_revoked.reverse.each do |permission, expected_permissions_after| tests("#revoke_security_group_ingress('fog_security_group', #{permission.inspect})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].revoke_security_group_ingress('fog_security_group', permission).body end tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do array_differences(expected_permissions_after, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions']) end end tests("#delete_security_group('fog_security_group')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_security_group('fog_security_group').body end tests("#delete_security_group('fog_security_group_two')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_security_group('fog_security_group_two').body end vpc_id = Fog::Compute[:aws].create_vpc('10.255.254.64/28').body['vpcSet'].first['vpcId'] # Create security group in VPC tests("#create_security_group('vpc_security_group', 'tests group')").formats(@create_security_group_format) do Fog::Compute[:aws].create_security_group('vpc_security_group', 'tests group', vpc_id).body end group_id = Fog::Compute[:aws].describe_security_groups('group-name' => 'vpc_security_group').body['securityGroupInfo'].first['groupId'] permissions = { 'IpPermissions' => [ { 'IpProtocol' => '42', 'IpRanges' => [{ 'CidrIp' => '10.0.0.0/8' }], } ] } expected_permissions = [ {"groups"=>[], "ipRanges"=>[{"cidrIp"=>"10.0.0.0/8"}], "ipProtocol"=>"42"} ] options = permissions.clone options['GroupId'] = group_id tests("#authorize_security_group_ingress(#{options.inspect})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].authorize_security_group_ingress(options).body end tests("#describe_security_groups('group-name' => 'vpc_security_group')").returns([]) do array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'vpc_security_group').body['securityGroupInfo'].first['ipPermissions']) end tests("#revoke_security_group_ingress(#{options.inspect})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].revoke_security_group_ingress(options).body end vpc_group=Fog::Compute[:aws].security_groups.get_by_id(group_id) vpc_group.destroy Fog::Compute[:aws].delete_vpc(vpc_id) end ## Rate limiting seems to want us to take a break otherwise it will throw errors tests('failure') do @security_group = Fog::Compute[:aws].security_groups.create(:description => 'tests group', :name => 'fog_security_group') @other_security_group = Fog::Compute[:aws].security_groups.create(:description => 'tests group', :name => 'fog_other_security_group') tests("duplicate #create_security_group(#{@security_group.name}, #{@security_group.description})").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].create_security_group(@security_group.name, @security_group.description) end tests("#authorize_security_group_ingress('not_a_group_name', {'FromPort' => 80, 'IpProtocol' => 'tcp', 'toPort' => 80})").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].authorize_security_group_ingress( 'not_a_group_name', { 'FromPort' => 80, 'IpProtocol' => 'tcp', 'ToPort' => 80, } ) end tests("#authorize_security_group_ingress('not_a_group_name', {'SourceSecurityGroupName' => 'not_a_group_name', 'SourceSecurityGroupOwnerId' => '#{@owner_id}'})").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].authorize_security_group_ingress( 'not_a_group_name', { 'SourceSecurityGroupName' => 'not_a_group_name', 'SourceSecurityGroupOwnerId' => @owner_id } ) end tests("#authorize_security_group_ingress('fog_security_group', {'IpPermissions' => [{'IpProtocol' => 'tcp', 'FromPort' => 80, 'ToPort' => 80, 'IpRanges' => [{'CidrIp' => '10.0.0.0/8'}]}]})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', {'IpPermissions' => [{'IpProtocol' => 'tcp', 'FromPort' => 80, 'ToPort' => 80, 'IpRanges' => [{'CidrIp' => '10.0.0.0/8'}]}]}).body end tests("#authorize_security_group_ingress('fog_security_group', {'IpPermissions' => [{'IpProtocol' => 'tcp', 'FromPort' => 80, 'ToPort' => 80, 'IpRanges' => [{'CidrIp' => '10.0.0.0/8'}]}]})").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', {'IpPermissions' => [{'IpProtocol' => 'tcp', 'FromPort' => 80, 'ToPort' => 80, 'IpRanges' => [{'CidrIp' => '10.0.0.0/8'}]}]}) end tests("#authorize_security_group_ingress('fog_security_group', {'IpPermissions' => [{'Groups' => [{'GroupName' => '#{@other_security_group.name}'}], 'FromPort' => 80, 'ToPort' => 80, 'IpProtocol' => 'tcp'}]})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', {'IpPermissions' => [{'Groups' => [{'GroupName' => @other_security_group.name}], 'FromPort' => 80, 'ToPort' => 80, 'IpProtocol' => 'tcp'}]}).body end tests("#delete_security_group('#{@other_security_group.name}')").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].delete_security_group(@other_security_group.name) end broken_params = [ {}, { "IpProtocol" => "what" }, { "IpProtocol" => "tcp" }, { "IpProtocol" => "what", "FromPort" => 1, "ToPort" => 1 }, ] broken_params += broken_params.map do |broken_params_item| { "IpPermissions" => [broken_params_item] } end broken_params += [ { "IpPermissions" => [] }, { "IpPermissions" => nil } ] broken_params.each do |broken_params_item| tests("#authorize_security_group_ingress('fog_security_group', #{broken_params_item.inspect})").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', broken_params_item) end tests("#revoke_security_group_ingress('fog_security_group', #{broken_params_item.inspect})").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].revoke_security_group_ingress('fog_security_group', broken_params_item) end end tests("#revoke_security_group_ingress('not_a_group_name', {'FromPort' => 80, 'IpProtocol' => 'tcp', 'toPort' => 80})").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].revoke_security_group_ingress( 'not_a_group_name', { 'FromPort' => 80, 'IpProtocol' => 'tcp', 'ToPort' => 80, } ) end tests("#revoke_security_group_ingress('not_a_group_name', {'SourceSecurityGroupName' => 'not_a_group_name', 'SourceSecurityGroupOwnerId' => '#{@owner_id}'})").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].revoke_security_group_ingress( 'not_a_group_name', { 'SourceSecurityGroupName' => 'not_a_group_name', 'SourceSecurityGroupOwnerId' => @owner_id } ) end tests("#delete_security_group('not_a_group_name')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].delete_security_group('not_a_group_name') end @security_group.destroy @other_security_group.destroy tests("#delete_security_group('default')").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].delete_security_group('default') end broken_params = [ ['fog_security_group', { 'GroupName' => 'fog_security_group' }], [nil, nil], [nil, { 'GroupId' => nil }], [nil, { 'GroupName' => nil, 'GroupId' => nil }] ] broken_params.each do |list_elem| tests("#authorize_security_group_ingress(#{list_elem[0].inspect}, #{list_elem[1].inspect})").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].authorize_security_group_ingress(list_elem[0], list_elem[1]) end tests("#revoke_security_group_ingress(#{list_elem[0].inspect}, #{list_elem[1].inspect})").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].revoke_security_group_ingress(list_elem[0], list_elem[1]) end end end end fog-1.19.0/tests/aws/requests/compute/helper.rb0000644000004100000410000000024312261242552021474 0ustar www-datawww-dataclass AWS module Compute module Formats BASIC = { 'requestId' => String, 'return' => ::Fog::Boolean } end end end fog-1.19.0/tests/aws/requests/compute/region_tests.rb0000644000004100000410000000104212261242552022720 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | region requests', ['aws']) do @regions_format = { 'regionInfo' => [{ 'regionEndpoint' => String, 'regionName' => String }], 'requestId' => String } tests('success') do tests("#describe_regions").formats(@regions_format) do Fog::Compute[:aws].describe_regions.body end tests("#describe_regions('region-name' => 'us-east-1')").formats(@regions_format) do Fog::Compute[:aws].describe_regions('region-name' => 'us-east-1').body end end end fog-1.19.0/tests/aws/requests/compute/image_tests.rb0000644000004100000410000001536412261242552022533 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | image requests', ['aws']) do @describe_images_format = { 'imagesSet' => [{ 'architecture' => String, 'blockDeviceMapping' => [Fog::Nullable::Hash], 'description' => Fog::Nullable::String, 'hypervisor' => String, 'imageId' => String, 'imageLocation' => String, 'imageOwnerAlias' => Fog::Nullable::String, 'imageOwnerId' => String, 'imageState' => String, 'imageType' => String, 'isPublic' => Fog::Boolean, 'kernelId' => String, 'name' => String, 'platform' => Fog::Nullable::String, 'productCodes' => [], 'ramdiskId' => Fog::Nullable::String, 'rootDeviceName' => String, 'rootDeviceType' => String, 'stateReason' => {}, 'tagSet' => {}, 'virtualizationType' => String }], 'requestId' => String, } @register_image_format = { 'imageId' => String, 'requestId' => String } @modify_image_attribute_format = { 'return' => Fog::Boolean, 'requestId' => String } @create_image_format = { 'requestId' => String, 'imageId' => String } @image_copy_result = { 'requestId' => String, 'imageId' => String } tests('success') do # the result for this is HUGE and relatively uninteresting... # tests("#describe_images").formats(@images_format) do # Fog::Compute[:aws].describe_images.body # end @image_id = 'ami-1aad5273' if Fog.mocking? @other_account = Fog::Compute::AWS.new(:aws_access_key_id => 'other', :aws_secret_access_key => 'account') @server = Fog::Compute[:aws].servers.create @server.wait_for{state == 'running'} @created_image tests("#create_image").formats(@create_image_format) do result = Fog::Compute[:aws].create_image(@server.id, 'Fog-Test-Image', 'Fog Test Image', false).body @created_image = Fog::Compute[:aws].images.get(result['imageId']) result end tests("#create_image - no reboot").formats(@create_image_format) do result = Fog::Compute[:aws].create_image(@server.id, 'Fog-Test-Image', 'Fog Test Image', true).body @created_image = Fog::Compute[:aws].images.get(result['imageId']) result end tests("#create_image - automatic ebs image registration").returns(true) do create_image_response = Fog::Compute[:aws].create_image(@server.id, 'Fog-Test-Image', 'Fog Test Image') Fog::Compute[:aws].images.get(create_image_response.body['imageId']) != nil end @server.destroy tests("#copy_image (#{@image_id}, 'eu-west-1')").formats(@image_copy_result) do data = Fog::Compute.new(:provider => :aws, :region => "us-west-1", :version => "2013-02-01").copy_image(@image_id, "eu-east-1").body @eu_image_id = data['imageId'] data end tests("#register_image").formats(@register_image_format) do @image = Fog::Compute[:aws].register_image('image', 'image', '/dev/sda1').body end tests("#register_image - with ebs block device mapping").formats(@register_image_format) do @ebs_image = Fog::Compute[:aws].register_image('image', 'image', '/dev/sda1', [ { 'DeviceName' => '/dev/sdh', "SnapshotId" => "snap-123456789", "VolumeSize" => "10G", "DeleteOnTermination" => true}]).body end tests("#register_image - with ephemeral block device mapping").formats(@register_image_format) do @ephemeral_image = Fog::Compute[:aws].register_image('image', 'image', '/dev/sda1', [ { 'VirtualName' => 'ephemeral0', "DeviceName" => "/dev/sdb"} ]).body end @image_id = @image['imageId'] sleep 1 tests("#describe_images('Owner' => 'self')").formats(@describe_images_format) do Fog::Compute[:aws].describe_images('Owner' => 'self').body end tests("#describe_images('state' => 'available')").formats(@describe_images_format) do Fog::Compute[:aws].describe_images('state' => 'available').body end tests("other_account#describe_images('image-id' => '#{@image_id}')").returns([]) do @other_account.describe_images('image-id' => @image_id).body['imagesSet'] end tests("#modify_image_attribute('#{@image_id}', 'Add.UserId' => ['#{@other_account.data[:owner_id]}'])").formats(@modify_image_attribute_format) do Fog::Compute[:aws].modify_image_attribute(@image_id, { 'Add.UserId' => [@other_account.data[:owner_id]] }).body end tests("other_account#describe_images('image-id' => '#{@image_id}')").returns([@image_id]) do @other_account.describe_images('image-id' => @image_id).body['imagesSet'].map {|i| i['imageId'] } end tests("#modify_image_attribute('#{@image_id}', 'Remove.UserId' => ['#{@other_account.data[:owner_id]}'])").formats(@modify_image_attribute_format) do Fog::Compute[:aws].modify_image_attribute(@image_id, { 'Remove.UserId' => [@other_account.data[:owner_id]] }).body end tests("other_account#describe_images('image-id' => '#{@image_id}')").returns([]) do @other_account.describe_images('image-id' => @image_id).body['imagesSet'] end end tests("#describe_images('image-id' => '#{@image_id}')").formats(@describe_images_format) do @other_image = Fog::Compute[:aws].describe_images('image-id' => @image_id).body end unless Fog.mocking? tests("#describe_images('Owner' => '#{@other_image['imageOwnerAlias']}', 'image-id' => '#{@image_id}')").formats(@describe_images_format) do Fog::Compute[:aws].describe_images('Owner' => @other_image['imageOwnerAlias'], 'image-id' => @image_id).body end end #NOTE: waiting for the image to complete can sometimes take up to 1 hour # for quicker tests: uncomment the rest of this block #Fog.wait_for { Fog::Compute.new(:provider => :aws, :region => "us-west-1").snapshots.get(@eu_image_id) } #tests("#delete_snapshots(#{@eu_image_id})").formats(AWS::Compute::Formats::BASIC) do # Fog::Compute.new(:provider => :aws, :region => "us-west-1").delete_snapshot(@eu_image_id).body #end end tests('failure') do tests("#modify_image_attribute(nil, { 'Add.Group' => ['all'] })").raises(ArgumentError) do Fog::Compute[:aws].modify_image_attribute(nil, { 'Add.Group' => ['all'] }).body end tests("#modify_image_attribute('ami-00000000', { 'Add.UserId' => ['123456789012'] })").raises(Fog::Compute::AWS::NotFound) do pending unless Fog.mocking? Fog::Compute[:aws].modify_image_attribute('ami-00000000', { 'Add.UserId' => ['123456789012'] }).body end end end fog-1.19.0/tests/aws/requests/compute/subnet_tests.rb0000644000004100000410000000210512261242552022736 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | subnet requests', ['aws']) do @subnets_format = { 'subnetSet' => [{ 'subnetId' => String, 'state' => String, 'vpcId' => String, 'cidrBlock' => String, 'availableIpAddressCount' => String, 'availabilityZone' => String, 'tagSet' => Hash, }], 'requestId' => String } tests('success') do @vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24') @vpc_id = @vpc.id @subnet_id = nil tests('#create_subnet').formats(@subnets_format) do data = Fog::Compute[:aws].create_subnet(@vpc_id, '10.0.10.16/28').body @subnet_id = data['subnetSet'].first['subnetId'] data end tests('#describe_subnets').formats(@subnets_format) do Fog::Compute[:aws].describe_subnets.body end tests("#delete_subnet('#{@subnet_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_subnet(@subnet_id).body end @vpc.destroy end end fog-1.19.0/tests/aws/requests/compute/snapshot_tests.rb0000644000004100000410000000476612261242552023314 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | snapshot requests', ['aws']) do @snapshot_format = { 'description' => Fog::Nullable::String, 'ownerId' => String, 'progress' => String, 'snapshotId' => String, 'startTime' => Time, 'status' => String, 'volumeId' => String, 'volumeSize' => Integer } @snapshots_format = { 'requestId' => String, 'snapshotSet' => [@snapshot_format.merge('tagSet' => {})] } @snapshot_copy_result = { 'requestId' => String, 'snapshotId' => String } @volume = Fog::Compute[:aws].volumes.create(:availability_zone => 'us-east-1a', :size => 1) tests('success') do @snapshot_id = nil tests("#create_snapshot(#{@volume.identity})").formats(@snapshot_format.merge('progress' => NilClass, 'requestId' => String)) do data = Fog::Compute[:aws].create_snapshot(@volume.identity).body @snapshot_id = data['snapshotId'] data end Fog.wait_for { Fog::Compute[:aws].snapshots.get(@snapshot_id) } Fog::Compute[:aws].snapshots.get(@snapshot_id).wait_for { ready? } tests("#describe_snapshots").formats(@snapshots_format) do Fog::Compute[:aws].describe_snapshots.body end tests("#describe_snapshots('snapshot-id' => '#{@snapshot_id}')").formats(@snapshots_format) do Fog::Compute[:aws].describe_snapshots('snapshot-id' => @snapshot_id).body end tests("#copy_snapshot (#{@snapshot_id}, 'us-east-1')").formats(@snapshot_copy_result) do data = Fog::Compute.new(:provider => :aws, :region => "us-west-1").copy_snapshot(@snapshot_id, "us-east-1").body @west_snapshot_id = data['snapshotId'] data end tests("#delete_snapshots(#{@snapshot_id})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_snapshot(@snapshot_id).body end #NOTE: waiting for the copy to complete can sometimes take up to 5 minutes (but sometimes it's nearly instant) #for faster tests: comment out the rest of this block Fog.wait_for { Fog::Compute.new(:provider => :aws, :region => "us-west-1").snapshots.get(@west_snapshot_id) } tests("#delete_snapshots(#{@west_snapshot_id})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute.new(:provider => :aws, :region => "us-west-1").delete_snapshot(@west_snapshot_id).body end end tests('failure') do tests("#delete_snapshot('snap-00000000')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].delete_snapshot('snap-00000000') end end @volume.destroy end fog-1.19.0/tests/aws/requests/compute/spot_datafeed_subscription_tests.rb0000644000004100000410000000333112261242552027046 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | spot datafeed subscription requests', ['aws']) do @spot_datafeed_subscription_format = { 'spotDatafeedSubscription' => { 'bucket' => String, 'ownerId' => String, 'prefix' => String, 'state' => String }, 'requestId' => String } @directory = Fog::Storage[:aws].directories.create(:key => 'fogspotdatafeedsubscriptiontests') tests('success') do pending if Fog.mocking? tests("#create_spot_datafeed_subscription('fogspotdatafeedsubscriptiontests', 'fogspotdatafeedsubscription/')").formats(@spot_datafeed_subscription_format) do Fog::Compute[:aws].create_spot_datafeed_subscription('fogspotdatafeedsubscriptiontests', 'fogspotdatafeedsubscription/').body end tests("duplicate #create_spot_datafeed_subscription('fogspotdatafeedsubscriptiontests', 'fogspotdatafeedsubscription/')").succeeds do Fog::Compute[:aws].create_spot_datafeed_subscription('fogspotdatafeedsubscriptiontests', 'fogspotdatafeedsubscription/') end tests("#describe_spot_datafeed_subscription").formats(@spot_datafeed_subscription_format) do Fog::Compute[:aws].describe_spot_datafeed_subscription.body end tests("#delete_spot_datafeed_subscription").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_spot_datafeed_subscription.body end tests("duplicate #delete_spot_datafeed_subscription").succeeds do Fog::Compute[:aws].delete_spot_datafeed_subscription end end tests('failure') do pending if Fog.mocking? tests("#describe_spot_datafeed_subscription").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].describe_spot_datafeed_subscription end end @directory.destroy end fog-1.19.0/tests/aws/requests/compute/internet_gateway_tests.rb0000644000004100000410000000337112261242552025015 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | internet_gateway requests', ['aws']) do @internet_gateways_format = { 'internetGatewaySet' => [{ 'internetGatewayId' => String, 'attachmentSet' => Hash, 'tagSet' => Fog::Nullable::Hash, }], 'requestId' => String } tests('success') do @vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24') @vpc_id = @vpc.id @subnet=Fog::Compute[:aws].subnets.create('vpc_id' => @vpc_id, 'cidr_block' => '10.0.10.0/24') @subnet_id = @subnet.subnet_id @igw_id = nil tests('#create_internet_gateway').formats(@internet_gateways_format) do data = Fog::Compute[:aws].create_internet_gateway().body @igw_id = data['internetGatewaySet'].first['internetGatewayId'] data end tests('#describe_internet_gateways').formats(@internet_gateways_format) do Fog::Compute[:aws].describe_internet_gateways.body end tests('#describe_internet_gateways with tags').formats(@internet_gateways_format) do Fog::Compute[:aws].create_tags @igw_id, {"environment" => "production"} Fog::Compute[:aws].describe_internet_gateways.body end tests("#attach_internet_gateway('#{@igw_id}, #{@vpc_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].attach_internet_gateway(@igw_id, @vpc_id).body end tests("#detach_internet_gateway('#{@igw_id}, #{@vpc_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].detach_internet_gateway(@igw_id, @vpc_id).body end tests("#delete_internet_gateway('#{@igw_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_internet_gateway(@igw_id).body end @subnet.destroy @vpc.destroy end end fog-1.19.0/tests/aws/requests/compute/network_interface_tests.rb0000644000004100000410000002025012261242552025150 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | network interface requests', ['aws']) do @network_interface_format = { 'networkInterfaceId' => String, 'subnetId' => String, 'vpcId' => String, 'availabilityZone' => String, 'description' => Fog::Nullable::String, 'ownerId' => String, 'requesterId' => Fog::Nullable::String, 'requesterManaged' => String, 'status' => String, 'macAddress' => String, 'privateIpAddress' => String, 'privateDnsName' => Fog::Nullable::String, 'sourceDestCheck' => Fog::Boolean, 'groupSet' => Fog::Nullable::Hash, 'attachment' => Hash, 'association' => Hash, 'tagSet' => Hash } @network_interface_create_format = { 'networkInterface' => @network_interface_format, 'requestId' => String } @network_interfaces_format = { 'requestId' => String, 'networkInterfaceSet' => [ @network_interface_format ] } @attach_network_interface_format = { 'requestId' => String, 'attachmentId' => String } tests('success') do # Create environment @vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24') @subnet = Fog::Compute[:aws].subnets.create('vpc_id' => @vpc.id, 'cidr_block' => '10.0.10.16/28') @security_group = Fog::Compute[:aws].security_groups.create('name' => 'sg_name', 'description' => 'sg_desc', 'vpc_id' => @vpc.id) @subnet_id = @subnet.subnet_id @security_group_id = @security_group.group_id DESCRIPTION = "Small and green" tests("#create_network_interface(#{@subnet_id})").formats(@network_interface_create_format) do data = Fog::Compute[:aws].create_network_interface(@subnet_id, {"PrivateIpAddress" => "10.0.10.23"}).body @nic_id = data['networkInterface']['networkInterfaceId'] data end # Describe network interfaces tests('#describe_network_interfaces').formats(@network_interfaces_format) do Fog::Compute[:aws].describe_network_interfaces.body end # Describe network interface attribute tests("#describe_network_interface_attribute(#{@nic_id}, 'description')").returns(nil) do Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'description').body['description'] end # test describe of all supported attributes [ 'description', 'groupSet', 'sourceDestCheck', 'attachment'].each do |attrib| tests("#describe_network_interface_attribute(#{@nic_id}, #{attrib})").returns(@nic_id) do Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, attrib).body['networkInterfaceId'] end end # Modify network interface description attribute tests("#modify_network_interface_attribute(#{@nic_id}, 'description', '#{DESCRIPTION}')").returns(true) do Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'description', DESCRIPTION).body["return"] end # Describe network interface attribute again tests("#describe_network_interface_attribute(#{@nic_id}, 'description')").returns(DESCRIPTION) do Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'description').body["description"] end # Restore network interface description attribute tests("#modify_network_interface_attribute(#{@nic_id}, 'description', '')").returns(true) do Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'description', '').body["return"] end # Check modifying the group set tests("#modify_network_interface_attribute(#{@nic_id}, 'groupSet', [#{@security_group_id}])").returns(true) do Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'groupSet', [@security_group_id]).body["return"] end tests("#describe_network_interface_attribute(#{@nic_id}, 'groupSet')").returns({ @security_group_id => "sg_name" }) do Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'groupSet').body["groupSet"] end # Check modifying the source dest check (and reset) tests("#modify_network_interface_attribute(#{@nic_id}, 'sourceDestCheck', false)").returns(true) do Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'sourceDestCheck', false).body["return"] end tests("#describe_network_interface_attribute(#{@nic_id}, 'sourceDestCheck')").returns(false) do Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'sourceDestCheck').body["sourceDestCheck"] end tests("#reset_network_interface_attribute(#{@nic_id}, 'sourceDestCheck')").returns(true) do Fog::Compute[:aws].reset_network_interface_attribute(@nic_id, 'sourceDestCheck').body["return"] end tests("#describe_network_interface_attribute(#{@nic_id}, 'sourceDestCheck')").returns(true) do Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'sourceDestCheck').body["sourceDestCheck"] end @server = Fog::Compute[:aws].servers.create({:flavor_id => 'm1.small', :subnet_id => @subnet_id }) @server.wait_for { ready? } @instance_id=@server.id # attach tests('#attach_network_interface').formats(@attach_network_interface_format) do data = Fog::Compute[:aws].attach_network_interface(@nic_id, @instance_id, 1).body @attachment_id = data['attachmentId'] data end # Check modifying the attachment attach_attr = { 'attachmentId' => @attachment_id, 'deleteOnTermination' => true } tests("#modify_network_interface_attribute(#{@nic_id}, 'attachment', #{attach_attr.inspect})").returns(true) do Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'attachment', attach_attr).body["return"] end # detach tests('#detach_network_interface').returns(true) do Fog::Compute[:aws].detach_network_interface(@attachment_id,true).body["return"] end if !Fog.mocking? Fog::Compute[:aws].network_interfaces.get(@nic_id).wait_for { status == 'available'} end # Create network interface with arguments options = { "PrivateIpAddress" => "10.0.10.24", "Description" => DESCRIPTION, "GroupSet" => [@security_group_id] } tests("#create_network_interface(#{@subnet_id}), #{options.inspect}").returns("10.0.10.24") do data = Fog::Compute[:aws].create_network_interface(@subnet_id, options).body @nic2_id = data['networkInterface']['networkInterfaceId'] data['networkInterface']['privateIpAddress'] end # Check assigned values tests("#describe_network_interface_attribute(#{@nic2_id}, 'description')").returns(DESCRIPTION) do Fog::Compute[:aws].describe_network_interface_attribute(@nic2_id, 'description').body["description"] end tests("#describe_network_interface_attribute(#{@nic2_id}, 'groupSet'')").returns({ @security_group_id => "sg_name"}) do Fog::Compute[:aws].describe_network_interface_attribute(@nic2_id, 'groupSet').body["groupSet"] end # Delete network interfaces tests("#delete_network_interface('#{@nic2_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_network_interface(@nic2_id).body end tests("#delete_network_interface('#{@nic_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_network_interface(@nic_id).body end @server.destroy if !Fog.mocking? @server.wait_for { state == 'terminated' } # despite the fact that the state goes to 'terminated' we need a little delay for aws to do its thing sleep 5 end # Bring up another server to test vpc public IP association @server = Fog::Compute[:aws].servers.create(:flavor_id => 'm1.small', :subnet_id => @subnet_id, :associate_public_ip => true) @server.wait_for { ready? } @instance_id = @server.id test("#associate_public_ip") do server = Fog::Compute[:aws].servers.get(@instance_id) server.public_ip_address.nil? == false end # Clean up resources @server.destroy if !Fog.mocking? @server.wait_for { state == 'terminated' } # despite the fact that the state goes to 'terminated' we need a little delay for aws to do its thing sleep 5 end @security_group.destroy @subnet.destroy @vpc.destroy end end fog-1.19.0/tests/aws/requests/compute/route_tests.rb0000644000004100000410000003051312261242552022600 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | route table requests', ['aws']) do @route_table_format = { 'routeTable' => [{ 'routeSet' => [{ 'destinationCidrBlock' => String, 'gatewayId' => String, 'state' => String, }], 'tagSet' => Hash, 'associationSet' => Array, 'routeTableId' => String, 'vpcId' => String, }], 'requestId' => String } @route_tables_format = { 'routeTableSet' => [{ 'associationSet' => [{ 'routeTableAssociationId' => Fog::Nullable::String, 'routeTableId' => String, 'subnetId' => Fog::Nullable::String, 'main' => Fog::Boolean }], 'tagSet' => Hash, 'routeSet' => [{ 'destinationCidrBlock' => String, 'gatewayId' => Fog::Nullable::String, 'instanceId' => Fog::Nullable::String, 'instanceOwnerId' => Fog::Nullable::String, 'networkInterfaceId' => Fog::Nullable::String, 'state' => String, 'origin' => String }], 'routeTableId' => String, 'vpcId' => String, }], 'requestId' => String } vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24') if !Fog.mocking? vpc.wait_for { state.eql? "available" } end @subnet_id = Fog::Compute[:aws].create_subnet(vpc.id, '10.0.10.0/24').body['subnetSet'].first['subnetId'] @network_interface = Fog::Compute[:aws].create_network_interface(@subnet_id, {"PrivateIpAddress" => "10.0.10.23"}).body @internet_gateway_id = Fog::Compute[:aws].create_internet_gateway.body['internetGatewaySet'].first['internetGatewayId'] @network_interface_id = @network_interface['networkInterface']['networkInterfaceId'] key_name = 'fog-test-key' key = Fog::Compute[:aws].key_pairs.create(:name => key_name) @cidr_block = '10.0.10.0/24' @destination_cidr_block = '10.0.10.0/23' @ami = 'ami-79c0ae10' # ubuntu 12.04 daily build 20120728 tests('success') do # Test create_route_table # tests("#create_route_table('#{vpc.id}')").formats(@route_table_format) do data = Fog::Compute[:aws].create_route_table(vpc.id).body @route_table_id = data['routeTable'].first['routeTableId'] data end # Test associate_route_table # tests("#associate_route_table('#{@route_table_id}', '#{@subnet_id}')").formats({'requestId'=>String, 'associationId'=>String}) do data = Fog::Compute[:aws].associate_route_table(@route_table_id, @subnet_id).body @association_id = data['associationId'] data end # Tests create_route # - using internet gateway # - using instance id # - using network interface # Fog::Compute[:aws].attach_internet_gateway(@internet_gateway_id, vpc.id).body tests("#create_route('#{@route_table_id}', '#{@destination_cidr_block}', '#{@internet_gateway_id}', 'nil')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].create_route(@route_table_id, @destination_cidr_block, @internet_gateway_id, nil).body end instance = Fog::Compute[:aws].servers.create(:image_id => @ami, :flavor_id => 't1.micro', :key_name => 'fog-test-key', :subnet_id => @subnet_id) instance.wait_for { state.eql? "running" } tests("#create_route('#{@route_table_id}', '10.0.10.0/22', 'nil', '#{instance.id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].create_route(@route_table_id, '10.0.10.0/22', nil, instance.id).body end tests("#create_route('#{@route_table_id}', '10.0.10.0/21', 'nil', 'nil', '#{@network_interface_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].create_route(@route_table_id, '10.0.10.0/21', nil, nil, @network_interface_id).body end # Tests describe_route_tables # - no parameters # - filter: vpc-id => vpc_id # - filter: vpc-id => ['all'] # tests('#describe_route_tables').formats(@route_tables_format) do Fog::Compute[:aws].describe_route_tables.body end tests("#describe_route_tables('vpc-id' => #{vpc.id})").formats(@route_tables_format) do Fog::Compute[:aws].describe_route_tables('vpc-id' => vpc.id).body end tests("#describe_route_tables('vpc-id' => ['all'])").formats(@route_tables_format) do Fog::Compute[:aws].describe_route_tables('vpc-id' => ['all']).body end # Test delete_route(route_table_id, cidr_block) # tests("#delete_route('#{@route_table_id}', '10.0.10.0/21')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_route(@route_table_id, '10.0.10.0/21').body end tests("#delete_route('#{@route_table_id}', '10.0.10.0/22')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_route(@route_table_id, '10.0.10.0/22').body end Fog::Compute[:aws].servers.all('instance-id'=>instance.id).first.destroy if !Fog.mocking? instance.wait_for { state.eql? "terminated" } end tests("#delete_route('#{@route_table_id}', '#{@destination_cidr_block}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_route(@route_table_id, @destination_cidr_block).body end # Test disassociate_route_table(association_id) # tests("#disassociate_route_table('#{@association_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].disassociate_route_table(@association_id).body end # Test delete_route_table(route_table_id) # tests("#delete_route_table('#{@route_table_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_route_table(@route_table_id).body end end tests('failure') do @route_table_id = Fog::Compute[:aws].create_route_table(vpc.id).body['routeTable'].first['routeTableId'] @association_id = Fog::Compute[:aws].associate_route_table(@route_table_id, @subnet_id).body['associationId'] Fog::Compute[:aws].create_route(@route_table_id, @destination_cidr_block, @internet_gateway_id, nil) instance = Fog::Compute[:aws].servers.create(:image_id => @ami, :flavor_id => 't1.micro', :key_name => 'fog-test-key', :subnet_id => @subnet_id) instance.wait_for { state.eql? "running" } # Tests create_route_table # - no parameters # - passing a nonexisting vpc # tests('#create_route_table').raises(ArgumentError) do Fog::Compute[:aws].create_route_table end tests("#create_route_table('vpc-00000000')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].create_route_table('vpc-00000000') end # Tests associate_route_table # - no parameters # - passing a nonexisiting route table # - passing a nonexisiting subnet # tests('#associate_route_table').raises(ArgumentError) do Fog::Compute[:aws].associate_route_table end tests("#associate_route_table('rtb-00000000', '#{@subnet_id}')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].associate_route_table('rtb-00000000', @subnet_id) end tests("#associate_route_table('#{@route_table_id}', 'subnet-00000000')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].associate_route_table(@route_table_id, 'subnet-00000000') end # Tests create_route # - no parameters # - passing a nonexisiting route table and an exisiting internet gateway # - passing a nonexisiting internet gateway # - passing a nonexisting route table and an exisiting instance # - passing a nonexisiting instance # - passing a nonexsiting route table and an exisiting network interface # - passing a nonexisiting network interface # - attempting to add a route at the same destination cidr block as another # - attempting to add a route at a less specific destination cidr block # tests('#create_route').raises(ArgumentError) do Fog::Compute[:aws].create_route end tests("#create_route('rtb-00000000', '#{@destination_cidr_block}', '#{@internet_gateway_id}')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].create_route('rtb-00000000', @destination_cidr_block, @internet_gateway_id) end tests("#create_route('#{@route_table_id}', '#{@destination_cidr_block}', 'igw-00000000')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].create_route(@route_table_id, @destination_cidr_block, 'igw-00000000') end tests("#create_route('rtb-00000000', '#{@destination_cidr_block}', 'nil', '#{instance.id}')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].create_route('rtb-00000000', @destination_cidr_block, instance.id) end tests("#create_route('#{@route_table_id}', '#{@destination_cidr_block}', 'nil', 'i-00000000')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].create_route(@route_table_id, @destination_cidr_block, nil, 'i-00000000') end tests("#create_route('#{@route_table_id}', '#{@destinationCidrBlock}', 'nil', 'nil', 'eni-00000000')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].create_route(@route_table_id, @destination_cidr_block, nil, nil, 'eni-00000000') end tests("#create_route('#rtb-00000000', '#{@destination_cidr_block}', 'nil, 'nil', '#{@network_interface_id}')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].create_route('rtb-00000000', @destination_cidr_block, nil, nil, @network_interface_id) end tests("#create_route same destination_cidr_block").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].create_route(@route_table_id, @destination_cidr_block, @internet_gateway_id) Fog::Compute[:aws].create_route(@route_table_id, @destination_cidr_block, nil, nil, @network_interface_id).body end if !Fog.mocking? tests("#create_route less specific destination_cidr_block").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].create_route(@route_table_id, '10.0.10.0/25', @internet_gateway_id) Fog::Compute[:aws].delete_route(@route_table_id, @destination_cidr_block).body end end # Test describe_route_tables # - passing a nonexisiting vpc # tests("#describe_route_tables('vpc-id' => 'vpc-00000000").formats({'routeTableSet'=>Array, 'requestId'=>String}) do Fog::Compute[:aws].describe_route_tables('vpc-id' => 'vpc-00000000').body end # Tests delete_route # - no parameters # - passing a nonexisiting route table # tests('#delete_route').raises(ArgumentError) do Fog::Compute[:aws].delete_route end tests("#delete_route('rtb-00000000', '#{@destination_cidr_block}')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].delete_route('rtb-00000000', @destination_cidr_block) end # Tests disassociate_route_table # - no parameters # - passing a nonexisiting route table association id # tests('#disassociate_route_table').raises(ArgumentError) do Fog::Compute[:aws].disassociate_route_table end tests("#disassociate_route_table('rtbassoc-00000000')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].disassociate_route_table('rtbassoc-00000000') end # Tests delete_route_table # - no parameters # - passing a nonexisiting route table # tests('#delete_route_table').raises(ArgumentError) do Fog::Compute[:aws].delete_route_table end tests("#delete_route_table('rtb-00000000')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].delete_route_table('rtb-00000000') end # Dependency Tests # - route is depending on route_table, so route_table cannot be deleted # tests("#delete_route_table('#{@route_table_id}')").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].delete_route_table(@route_table_id) end Fog::Compute[:aws].servers.all('instance-id'=>instance.id).first.destroy if !Fog.mocking? instance.wait_for { state.eql? "terminated" } end Fog::Compute[:aws].delete_route(@route_table_id, @destination_cidr_block) Fog::Compute[:aws].disassociate_route_table(@association_id) Fog::Compute[:aws].delete_route_table(@route_table_id) end Fog::Compute[:aws].delete_network_interface(@network_interface_id) Fog::Compute[:aws].detach_internet_gateway(@internet_gateway_id, vpc.id) Fog::Compute[:aws].delete_internet_gateway(@internet_gateway_id) Fog::Compute[:aws].delete_subnet(@subnet_id) vpc.destroy key.destroy end fog-1.19.0/tests/aws/requests/compute/key_pair_tests.rb0000644000004100000410000000460612261242552023251 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | key pair requests', ['aws']) do tests('success') do @keypair_format = { 'keyFingerprint' => String, 'keyName' => String, 'requestId' => String } @keypairs_format = { 'keySet' => [{ 'keyFingerprint' => String, 'keyName' => String }], 'requestId' => String } @key_pair_name = 'fog_create_key_pair' @public_key_material = 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA1SL+kgze8tvSFW6Tyj3RyZc9iFVQDiCKzjgwn2tS7hyWxaiDhjfY2mBYSZwFdKN+ZdsXDJL4CPutUg4DKoQneVgIC1zuXrlpPbaT0Btu2aFd4qNfJ85PBrOtw2GrWZ1kcIgzZ1mMbQt6i1vhsySD2FEj+5kGHouNxQpI5dFR5K+nGgcTLFGnzb/MPRBk136GVnuuYfJ2I4va/chstThoP8UwnoapRHcBpwTIfbmmL91BsRVqjXZEUT73nxpxFeXXidYwhHio+5dXwE0aM/783B/3cPG6FVoxrBvjoNpQpAcEyjtRh9lpwHZtSEW47WNzpIW3PhbQ8j4MryznqF1Rhw==' tests("#create_key_pair('#{@key_pair_name}')").formats(@keypair_format.merge({'keyMaterial' => String})) do body = Fog::Compute[:aws].create_key_pair(@key_pair_name).body tests("key material").returns(OpenSSL::PKey::RSA, "is a valid private RSA key") do OpenSSL::PKey::RSA.new(body['keyMaterial']).class end body end tests('#describe_key_pairs').formats(@keypairs_format) do Fog::Compute[:aws].describe_key_pairs.body end tests("#describe_key_pairs('key-name' => '#{@key_pair_name}')").formats(@keypairs_format) do Fog::Compute[:aws].describe_key_pairs('key-name' => @key_pair_name).body end tests("#delete_key_pair('#{@key_pair_name}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_key_pair(@key_pair_name).body end tests("#import_key_pair('fog_import_key_pair', '#{@public_key_material}')").formats(@keypair_format) do Fog::Compute[:aws].import_key_pair('fog_import_key_pair', @public_key_material).body end tests("#delete_key_pair('fog_import_key_pair)").succeeds do Fog::Compute[:aws].delete_key_pair('fog_import_key_pair') end tests("#delete_key_pair('not_a_key_name')").succeeds do Fog::Compute[:aws].delete_key_pair('not_a_key_name') end end tests('failure') do @key_pair = Fog::Compute[:aws].key_pairs.create(:name => 'fog_key_pair') tests("duplicate #create_key_pair('#{@key_pair.name}')").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].create_key_pair(@key_pair.name) end @key_pair.destroy end end fog-1.19.0/tests/aws/requests/compute/dhcp_options_tests.rb0000644000004100000410000000257012261242552024135 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | dhcp_options requests', ['aws']) do @dhcp_options_format = { 'dhcpOptionsSet' => [{ 'dhcpOptionsId' => String, 'dhcpConfigurationSet' => Hash, 'tagSet' => Fog::Nullable::Hash, }], 'requestId' => String } tests('success') do @vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24') @vpc_id = @vpc.id tests('#create_dhcp_options').formats(@dhcp_options_format) do data = Fog::Compute[:aws].create_dhcp_options({'domain-name' => 'example.com', 'domain-name-servers' => '10.10.10.10'}).body @dopt_id = data['dhcpOptionsSet'].first['dhcpOptionsId'] data end tests('#describe_dhcp_options').formats(@dhcp_options_format) do Fog::Compute[:aws].describe_dhcp_options.body end tests("#associate_dhcp_options('#{@dopt_id}, #{@vpc_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].associate_dhcp_options(@dopt_id, @vpc_id).body end tests("#associate_default_dhcp_options('default', #{@vpc_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].associate_dhcp_options('default', @vpc_id).body end tests("#delete_dhcp_options('#{@dopt_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_dhcp_options(@dopt_id).body end @vpc.destroy end end fog-1.19.0/tests/aws/requests/compute/vpc_tests.rb0000644000004100000410000000334112261242552022231 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | vpc requests', ['aws']) do @vpcs_format = { 'vpcSet' => [{ 'vpcId' => String, 'state' => String, 'cidrBlock' => String, 'dhcpOptionsId' => String, 'tagSet' => Hash, 'instanceTenancy' => Fog::Nullable::String, }], 'requestId' => String } tests('success') do @vpc_id = nil tests('#create_vpc').formats(@vpcs_format) do data = Fog::Compute[:aws].create_vpc('10.255.254.0/28').body @vpc_id = data['vpcSet'].first['vpcId'] data end tests('#describe_vpcs').formats(@vpcs_format) do Fog::Compute[:aws].describe_vpcs.body end tests("#modify_vpc_attribute('#{@vpc_id}', {'EnableDnsSupport.Value' => true})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].modify_vpc_attribute(@vpc_id, {'EnableDnsSupport.Value' => true}).body end tests("#modify_vpc_attribute('#{@vpc_id}', {'EnableDnsHostnames.Value' => true})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].modify_vpc_attribute(@vpc_id, {'EnableDnsHostnames.Value' => true}).body end tests("#modify_vpc_attribute('#{@vpc_id}')").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].modify_vpc_attribute(@vpc_id).body end tests("#modify_vpc_attribute('#{@vpc_id}', {'EnableDnsSupport.Value' => true, 'EnableDnsHostnames.Value' => true})").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].modify_vpc_attribute(@vpc_id, {'EnableDnsSupport.Value' => true, 'EnableDnsHostnames.Value' => true}).body end tests("#delete_vpc('#{@vpc_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_vpc(@vpc_id).body end end end fog-1.19.0/tests/aws/requests/compute/volume_tests.rb0000644000004100000410000001705712261242552022761 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | volume requests', ['aws']) do @volume_format = { 'availabilityZone' => String, 'createTime' => Time, 'iops' => Fog::Nullable::Integer, 'requestId' => String, 'size' => Integer, 'snapshotId' => Fog::Nullable::String, 'status' => String, 'volumeId' => String, 'volumeType' => String } @volume_attachment_format = { 'attachTime' => Time, 'device' => String, 'instanceId' => String, 'requestId' => String, 'status' => String, 'volumeId' => String } @volume_status_format = { 'volumeStatusSet' => [{ 'availabilityZone' => String, 'volumeId' => String, 'volumeStatus' => { 'status' => String, 'details' => [{ 'name' => String, 'status' => String }] }, 'actionsSet' => [{ 'code' => String, 'description' => String, 'eventId' => String, 'eventType' => String }], 'eventsSet' => [{ 'description' => String, 'eventId' => String, 'eventType' => String, 'notBefore' => Time, 'notAfter' => Time }] }], 'requestId' => String } @volumes_format = { 'volumeSet' => [{ 'availabilityZone' => String, 'attachmentSet' => Array, 'createTime' => Time, 'iops' => Fog::Nullable::Integer, 'size' => Integer, 'snapshotId' => Fog::Nullable::String, 'status' => String, 'tagSet' => Hash, 'volumeId' => String, 'volumeType' => String }], 'requestId' => String } @server = Fog::Compute[:aws].servers.create @server.wait_for { ready? } tests('success') do @volume_id = nil tests('#create_volume').formats(@volume_format) do data = Fog::Compute[:aws].create_volume(@server.availability_zone, 1).body @volume_id = data['volumeId'] data end Fog::Compute[:aws].delete_volume(@volume_id) tests('#create_volume from snapshot').formats(@volume_format) do volume = Fog::Compute[:aws].volumes.create(:availability_zone => 'us-east-1d', :size => 1) snapshot = Fog::Compute[:aws].create_snapshot(volume.identity).body data = Fog::Compute[:aws].create_volume(@server.availability_zone, nil, 'SnapshotId' => snapshot['snapshotId']).body @volume_id = data['volumeId'] data end Fog::Compute[:aws].delete_volume(@volume_id) tests('#create_volume with type and iops').formats(@volume_format) do data = Fog::Compute[:aws].create_volume(@server.availability_zone, 10, 'VolumeType' => 'io1', 'Iops' => 100).body @volume_id = data['volumeId'] data end Fog::Compute[:aws].delete_volume(@volume_id) tests('#create_volume from snapshot with size').formats(@volume_format) do volume = Fog::Compute[:aws].volumes.create(:availability_zone => 'us-east-1d', :size => 1) snapshot = Fog::Compute[:aws].create_snapshot(volume.identity).body data = Fog::Compute[:aws].create_volume(@server.availability_zone, 1, 'SnapshotId' => snapshot['snapshotId']).body @volume_id = data['volumeId'] data end Fog::Compute[:aws].volumes.get(@volume_id).wait_for { ready? } tests('#describe_volumes').formats(@volumes_format) do Fog::Compute[:aws].describe_volumes.body end tests("#describe_volumes('volume-id' => #{@volume_id})").formats(@volumes_format) do Fog::Compute[:aws].describe_volumes('volume-id' => @volume_id).body end tests("#attach_volume(#{@server.identity}, #{@volume_id}, '/dev/sdh')").formats(@volume_attachment_format) do Fog::Compute[:aws].attach_volume(@server.identity, @volume_id, '/dev/sdh').body end Fog::Compute[:aws].volumes.get(@volume_id).wait_for { state == 'in-use' } tests("#describe_volume('attachment.device' => '/dev/sdh')").formats(@volumes_format) do Fog::Compute[:aws].describe_volumes('attachment.device' => '/dev/sdh').body end tests("#describe_volume_status('volume-id' => #{@volume_id})").formats(@volume_status_format) do pending if Fog.mocking? Fog::Compute[:aws].describe_volume_status('volume-id' => @volume_id).body end tests("#detach_volume('#{@volume_id}')").formats(@volume_attachment_format) do Fog::Compute[:aws].detach_volume(@volume_id).body end Fog::Compute[:aws].volumes.get(@volume_id).wait_for { ready? } tests("#modify_volume_attribute('#{@volume_id}', true)").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].modify_volume_attribute(@volume_id, true).body end tests("#delete_volume('#{@volume_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_volume(@volume_id).body end end tests('failure') do @volume = Fog::Compute[:aws].volumes.create(:availability_zone => @server.availability_zone, :size => 1) tests("#attach_volume('i-00000000', '#{@volume.identity}', '/dev/sdh')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].attach_volume('i-00000000', @volume.identity, '/dev/sdh') end tests("#attach_volume('#{@server.identity}', 'vol-00000000', '/dev/sdh')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].attach_volume(@server.identity, 'vol-00000000', '/dev/sdh') end tests("#detach_volume('vol-00000000')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].detach_volume('vol-00000000') end tests("#modify_volume_attribute('vol-00000000', true)").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].modify_volume_attribute('vol-00000000', true) end tests("#detach_volume('#{@volume.identity}')").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].detach_volume(@volume.identity) end tests("#delete_volume('vol-00000000')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].delete_volume('vol-00000000') end # Iops required tests("#create_volume('#{@server.availability_zone}', 10, 'VolumeType' => 'io1')").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].create_volume(@server.availability_zone, 10, 'VolumeType' => 'io1') end # size too small for iops tests("#create_volume('#{@server.availability_zone}', 9, 'VolumeType' => 'io1', 'Iops' => 100)").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].create_volume(@server.availability_zone, 9, 'VolumeType' => 'io1', 'Iops' => 100) end # iops:size ratio too big tests("#create_volume('#{@server.availability_zone}', 10, 'VolumeType' => 'io1', 'Iops' => 101)").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].create_volume(@server.availability_zone, 10, 'VolumeType' => 'io1', 'Iops' => 101) end # iops invalid value (lower than 100) tests("#create_volume('#{@server.availability_zone}', 10, 'VolumeType' => 'io1', 'Iops' => 99)").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].create_volume(@server.availability_zone, 10, 'VolumeType' => 'io1', 'Iops' => 99) end # iops invalid value (greater than 4000) tests("#create_volume('#{@server.availability_zone}', 1024, 'VolumeType' => 'io1', 'Iops' => 4001)").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].create_volume(@server.availability_zone, 1024, 'VolumeType' => 'io1', 'Iops' => 4001) end @volume.destroy end @server.destroy end fog-1.19.0/tests/aws/requests/compute/tag_tests.rb0000644000004100000410000000604512261242552022220 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | tag requests', ['aws']) do @tags_format = { 'tagSet' => [{ 'key' => String, 'resourceId' => String, 'resourceType' => String, 'value' => Fog::Nullable::String }], 'requestId' => String } @volume = Fog::Compute[:aws].volumes.create(:availability_zone => 'us-east-1a', :size => 1) @volume.wait_for { ready? } tests('success') do if Fog.mocking? @other_account = Fog::Compute::AWS.new(:aws_access_key_id => 'other', :aws_secret_access_key => 'account') @image_id = Fog::Compute[:aws].register_image('image', 'image', '/dev/sda1').body['imageId'] end tests("#create_tags('#{@volume.identity}', 'foo' => 'bar')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].create_tags(@volume.identity, 'foo' => 'bar').body end if Fog.mocking? tests("#create_tags('#{@image_id}', 'foo' => 'baz')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].create_tags(@image_id, 'foo' => 'baz').body end end tests('#describe_tags').formats(@tags_format) do Fog::Compute[:aws].describe_tags.body end expected_identities = Fog.mocking? ? [@volume.identity, @image_id] : [@volume.identity] tests('#describe_tags').succeeds do (expected_identities - Fog::Compute[:aws].describe_tags.body['tagSet'].map {|t| t['resourceId'] }).empty? end tests("#describe_tags('key' => 'foo', 'value' => 'bar')").returns([@volume.identity]) do Fog::Compute[:aws].describe_tags('key' => 'foo', 'value' => 'bar').body['tagSet'].map {|t| t['resourceId'] } end if Fog.mocking? tests("#describe_tags('key' => 'foo', 'value' => 'baz')").returns([@image_id]) do Fog::Compute[:aws].describe_tags('key' => 'foo', 'value' => 'baz').body['tagSet'].map {|t| t['resourceId'] } end Fog::Compute[:aws].modify_image_attribute(@image_id, 'Add.UserId' => [@other_account.data[:owner_id]]) tests("other_account#describe_tags('key' => 'foo', 'value' => 'baz')").returns([]) do @other_account.describe_tags('key' => 'foo', 'value' => 'baz').body['tagSet'].map {|t| t['resourceId'] } end tests("other_account#create_tags('#{@image_id}', 'foo' => 'quux')").formats(AWS::Compute::Formats::BASIC) do @other_account.create_tags(@image_id, 'foo' => 'quux').body end tests("other_account#describe_tags('key' => 'foo', 'value' => 'quux')").returns([@image_id]) do @other_account.describe_tags('key' => 'foo', 'value' => 'quux').body['tagSet'].map {|t| t['resourceId'] } end end @volume.destroy tests("#delete_tags('#{@volume.identity}', 'foo' => 'bar')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].delete_tags(@volume.identity, 'foo' => 'bar').body end end tests('failure') do tests("#create_tags('vol-00000000', 'baz' => 'qux')").raises(Fog::Service::NotFound) do Fog::Compute[:aws].create_tags('vol-00000000', 'baz' => 'qux') end end Fog::Compute::AWS::Mock.reset if Fog.mocking? end fog-1.19.0/tests/aws/requests/compute/address_tests.rb0000644000004100000410000000703412261242552023071 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | address requests', ['aws']) do @addresses_format = { 'addressesSet' => [{ 'allocationId' => Fog::Nullable::String, 'associationId' => Fog::Nullable::String, 'domain' => String, 'instanceId' => Fog::Nullable::String, 'publicIp' => String }], 'requestId' => String } @server = Fog::Compute[:aws].servers.create @server.wait_for { ready? } @ip_address = @server.public_ip_address tests('success') do @public_ip = nil @vpc_public_ip = nil @vpc_allocation_id = nil tests('#allocate_address').formats({'domain' => String, 'publicIp' => String, 'requestId' => String}) do data = Fog::Compute[:aws].allocate_address.body @public_ip = data['publicIp'] data end tests("#allocate_address('vpc')").formats({'domain' => String, 'publicIp' => String, 'allocationId' => String, 'requestId' => String}) do data = Fog::Compute[:aws].allocate_address('vpc').body @vpc_public_ip = data['publicIp'] @vpc_allocation_id = data['allocationId'] data end tests('#describe_addresses').formats(@addresses_format) do Fog::Compute[:aws].describe_addresses.body end tests("#describe_addresses('public-ip' => #{@public_ip}')").formats(@addresses_format) do Fog::Compute[:aws].describe_addresses('public-ip' => @public_ip).body end tests("#associate_addresses('#{@server.identity}', '#{@public_ip}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].associate_address(@server.identity, @public_ip).body end tests("#dissassociate_address('#{@public_ip}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].disassociate_address(@public_ip).body end tests("#associate_addresses('#{@server.id}', nil, nil, '#{@vpc_allocation_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].associate_address(@server.id, nil, nil, @vpc_allocation_id).body end tests("#release_address('#{@public_ip}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].release_address(@public_ip).body end tests("#release_address('#{@vpc_allocation_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].release_address(@vpc_allocation_id).body end end tests('failure') do @address = Fog::Compute[:aws].addresses.create @vpc_address = Fog::Compute[:aws].addresses.create(:domain => 'vpc') tests("#associate_addresses('i-00000000', '#{@address.identity}')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].associate_address('i-00000000', @address.identity) end tests("#associate_addresses('#{@server.identity}', '127.0.0.1')").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].associate_address(@server.identity, '127.0.0.1') end tests("#associate_addresses('i-00000000', '127.0.0.1')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].associate_address('i-00000000', '127.0.0.1') end tests("#disassociate_addresses('127.0.0.1') raises BadRequest error").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].disassociate_address('127.0.0.1') end tests("#release_address('127.0.0.1')").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].release_address('127.0.0.1') end tests("#release_address('#{@vpc_address.identity}')").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].release_address(@vpc_address.identity) end @address.destroy @vpc_address.destroy end @server.destroy end fog-1.19.0/tests/aws/requests/compute/instance_tests.rb0000644000004100000410000002274112261242552023252 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | instance requests', ['aws']) do @instance_format = { 'architecture' => String, 'amiLaunchIndex' => Integer, 'associatePublicIP' => Fog::Nullable::Boolean, 'attachmentId' => Fog::Nullable::String, 'blockDeviceMapping' => [Fog::Nullable::Hash], 'clientToken' => Fog::Nullable::String, 'dnsName' => NilClass, 'ebsOptimized' => Fog::Boolean, 'imageId' => String, 'instanceId' => String, 'instanceState' => {'code' => Integer, 'name' => String}, 'instanceType' => String, 'kernelId' => Fog::Nullable::String, 'keyName' => Fog::Nullable::String, 'launchTime' => Time, 'monitoring' => {'state' => Fog::Boolean}, 'networkInterfaceId' => Fog::Nullable::String, 'placement' => { 'availabilityZone' => String, 'groupName' => Fog::Nullable::String, 'tenancy' => String }, 'platform' => Fog::Nullable::String, 'privateDnsName' => NilClass, 'productCodes' => Array, 'reason' => Fog::Nullable::String, 'rootDeviceType' => String, 'sourceDestCheck' => Fog::Nullable::Boolean, 'subnetId' => Fog::Nullable::String, 'vpcId' => Fog::Nullable::String } @run_instances_format = { 'groupSet' => [String], 'instancesSet' => [@instance_format], 'ownerId' => Fog::Nullable::String, 'requestId' => String, 'reservationId' => String } @describe_instances_format = { 'reservationSet' => [{ 'groupSet' => [String], 'groupIds' => [String], 'instancesSet' => [@instance_format.merge( 'architecture' => String, 'dnsName' => Fog::Nullable::String, 'hypervisor' => String, 'iamInstanceProfile' => Hash, 'ipAddress' => Fog::Nullable::String, 'networkInterfaces' => Array, 'ownerId' => String, 'privateDnsName' => Fog::Nullable::String, 'privateIpAddress' => Fog::Nullable::String, 'stateReason' => Hash, 'tagSet' => Hash, 'virtualizationType' => String )], 'ownerId' => Fog::Nullable::String, 'reservationId' => String }], 'requestId' => String } @get_console_output_format = { 'instanceId' => String, 'output' => Fog::Nullable::String, 'requestId' => String, 'timestamp' => Time } @get_password_data_format = { 'instanceId' => String, 'passwordData' => Fog::Nullable::String, 'requestId' => String, 'timestamp' => Time } @terminate_instances_format = { 'instancesSet' => [{ 'currentState' => {'code' => Integer, 'name' => String}, 'instanceId' => String, 'previousState' => {'code' => Integer, 'name' => String}, }], 'requestId' => String } @describe_reserved_instances_offerings_format = { 'reservedInstancesOfferingsSet' => [{ 'reservedInstancesOfferingId' => String, 'instanceType' => String, 'availabilityZone' => String, 'duration' => Integer, 'fixedPrice' => Float, 'offeringType' => String, 'usagePrice' => Float, 'productDescription' => String, 'instanceTenancy' => String, 'currencyCode' => String }], 'requestId' => String } @purchase_reserved_instances_offering_format = { 'reservedInstancesId' => String, 'requestId' => String } @describe_reserved_instances_format = { 'reservedInstancesSet' => [{ 'reservedInstancesId' => String, 'instanceType' => String, 'availabilityZone' => String, 'start' => Time, 'end' => Time, 'duration' => Integer, 'fixedPrice' => Float, 'usagePrice' => Float, 'instanceCount' => Integer, 'offeringType' => String, 'productDescription' => String, 'state' => String, 'tagSet' => [{ 'key' => String, 'value' => String }], 'instanceTenancy' => String, 'currencyCode' => String }], 'requestId' => String } @describe_instance_status_format = { 'requestId' => String, 'instanceStatusSet' => [{ 'instanceId' => String, 'availabilityZone' => String, 'instanceState' => { 'code' => Integer, 'name' => String }, 'systemStatus' => { 'status' => String, 'details' => [{ 'name' => String, 'status' => String }] }, 'instanceStatus' => { 'status' => String, 'details' => [{ 'name' => String, 'status' => String }] }, 'eventsSet' => [Fog::Nullable::Hash], }] } tests('success') do @instance_id = nil @ami = if ENV['FASTER_TEST_PLEASE'] 'ami-79c0ae10' # ubuntu 12.04 daily build 20120728 else # Use a MS Windows AMI to test #get_password_data 'ami-71b50018' # Amazon Public Images - Windows_Server-2008-SP2-English-64Bit-Base-2012.07.11 end # Create a keypair for decrypting the password key_name = 'fog-test-key' key = Fog::Compute[:aws].key_pairs.create(:name => key_name) tests("#run_instances").formats(@run_instances_format) do data = Fog::Compute[:aws].run_instances(@ami, 1, 1, 'InstanceType' => 't1.micro', 'KeyName' => key_name).body @instance_id = data['instancesSet'].first['instanceId'] data end server = Fog::Compute[:aws].servers.get(@instance_id) while server.nil? do # It may take a moment to get the server after launching it sleep 0.1 server = Fog::Compute[:aws].servers.get(@instance_id) end server.wait_for { ready? } tests("#describe_instances").formats(@describe_instances_format) do Fog::Compute[:aws].describe_instances('instance-state-name' => 'running').body end # Launch another instance to test filters another_server = Fog::Compute[:aws].servers.create tests("#describe_instances('instance-id' => '#{@instance_id}'").formats(@describe_instances_format) do body = Fog::Compute[:aws].describe_instances('instance-id' => "#{@instance_id}").body tests("returns 1 instance").returns(1) { body['reservationSet'].size } body end another_server.destroy tests("#get_console_output('#{@instance_id}')").formats(@get_console_output_format) do Fog::Compute[:aws].get_console_output(@instance_id).body end tests("#get_password_data('#{@instance_id}')").formats(@get_password_data_format) do result = Fog::Compute[:aws].get_password_data(@instance_id).body tests("key can decrypt passwordData").returns(true) do pending if Fog.mocking? password_data = result['passwordData'] Fog.wait_for do password_data ||= Fog::Compute[:aws].get_password_data(@instance_id).body['passwordData'] end decoded_password = Base64.decode64(password_data) pkey = OpenSSL::PKey::RSA.new(key.private_key) String === pkey.private_decrypt(decoded_password) end result end unless ENV['FASTER_TEST_PLEASE'] key.destroy tests("#reboot_instances('#{@instance_id}')").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].reboot_instances(@instance_id).body end tests("#terminate_instances('#{@instance_id}')").formats(@terminate_instances_format) do Fog::Compute[:aws].terminate_instances(@instance_id).body end tests("#describe_reserved_instances_offerings").formats(@describe_reserved_instances_offerings_format) do @reserved_instances = Fog::Compute[:aws].describe_reserved_instances_offerings.body @reserved_instances end tests('#describe_instance_status').formats(@describe_instance_status_format) do Fog::Compute[:aws].describe_instance_status.body end if Fog.mocking? @reserved_instance_offering_id = @reserved_instances["reservedInstancesOfferingsSet"].first["reservedInstancesOfferingId"] tests("#purchase_reserved_instances_offering('#{@reserved_instance_offering_id}')").formats(@purchase_reserved_instances_offering_format) do Fog::Compute[:aws].purchase_reserved_instances_offering(@reserved_instance_offering_id, 1).body end tests("#describe_reserved_instances").formats(@describe_reserved_instances_format) do Fog::Compute[:aws].describe_reserved_instances.body end end end tests('failure') do tests("#get_console_output('i-00000000')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].get_console_output('i-00000000') end tests("#get_password_data('i-00000000')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].get_password_data('i-00000000') end tests("#reboot_instances('i-00000000')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].reboot_instances('i-00000000') end tests("#terminate_instances('i-00000000')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].terminate_instances('i-00000000') end end end fog-1.19.0/tests/aws/requests/compute/assign_private_ip_tests.rb0000644000004100000410000000433212261242552025150 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | internet_gateway requests', ['aws']) do tests('success') do @vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24') @vpc_id = @vpc.id @subnet=Fog::Compute[:aws].subnets.create('vpc_id' => @vpc_id, 'cidr_block' => '10.0.10.0/24') @subnet_id = @subnet.subnet_id @network_interface = Fog::Compute[:aws].network_interfaces.new(:subnet_id => @subnet_id) @network_interface.save @network_interface_id = @network_interface.network_interface_id @ip_address = Fog::AWS::Mock.ip_address @second_ip_address = Fog::AWS::Mock.ip_address tests("#assign_private_ip_addresses('#{@network_interface_id}', {'PrivateIpAddresses'=>['#{@ip_address}','#{@second_ip_address}']})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].assign_private_ip_addresses(@network_interface_id, { 'PrivateIpAddresses' =>[@ip_address, @second_ip_address]}).body end tests("#assign_private_ip_addresses('#{@network_interface_id}', {'SecondaryPrivateIpAddressCount'=>4})").formats(AWS::Compute::Formats::BASIC) do Fog::Compute[:aws].assign_private_ip_addresses(@network_interface_id, {'SecondaryPrivateIpAddressCount'=>4}).body end @network_interface.destroy @subnet.destroy @vpc.destroy end tests('failure') do @vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24') @vpc_id = @vpc.id @subnet=Fog::Compute[:aws].subnets.create('vpc_id' => @vpc_id, 'cidr_block' => '10.0.10.0/24') @subnet_id = @subnet.subnet_id @network_interface = Fog::Compute[:aws].network_interfaces.new(:subnet_id => @subnet_id) @network_interface.save @network_interface_id = @network_interface.network_interface_id @ip_address = Fog::AWS::Mock.ip_address tests("#assign_private_ip_addresses('#{@network_interface_id}', {'PrivateIpAddresses'=>['#{@ip_address}','#{@second_ip_address}'], 'SecondaryPrivateIpAddressCount'=>4 })").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].assign_private_ip_addresses(@network_interface_id, { 'PrivateIpAddresses' =>[@ip_address, @second_ip_address], 'SecondaryPrivateIpAddressCount'=>4 }).body end @network_interface.destroy @subnet.destroy @vpc.destroy end endfog-1.19.0/tests/aws/requests/compute/placement_group_tests.rb0000644000004100000410000000333712261242552024632 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | placement group requests', ['aws']) do @placement_group_format = { 'requestId' => String, 'placementGroupSet' => [{ 'groupName' => String, 'state' => String, 'strategy' => String }] } tests('success') do tests("#create_placement_group('fog_placement_group', 'cluster')").formats(AWS::Compute::Formats::BASIC) do pending if Fog.mocking? Fog::Compute[:aws].create_placement_group('fog_placement_group', 'cluster').body end tests("#describe_placement_groups").formats(@placement_group_format) do pending if Fog.mocking? Fog::Compute[:aws].describe_placement_groups.body end tests("#describe_placement_groups('group-name' => 'fog_placement_group)").formats(@placement_group_format) do pending if Fog.mocking? Fog::Compute[:aws].describe_placement_groups('group-name' => 'fog_security_group').body end tests("#delete_placement_group('fog_placement_group')").formats(AWS::Compute::Formats::BASIC) do pending if Fog.mocking? Fog::Compute[:aws].delete_placement_group('fog_placement_group').body end end tests('failure') do pending if Fog.mocking? Fog::Compute[:aws].create_placement_group('fog_placement_group', 'cluster') tests("duplicate #create_placement_group('fog_placement_group', 'cluster')").raises(Fog::Compute::AWS::Error) do Fog::Compute[:aws].create_placement_group('fog_placement_group', 'cluster') end tests("#delete_placement_group('not_a_group_name')").raises(Fog::Compute::AWS::NotFound) do Fog::Compute[:aws].delete_placement_group('not_a_group_name') end Fog::Compute[:aws].delete_placement_group('fog_placement_group') end end fog-1.19.0/tests/aws/requests/compute/client_tests.rb0000644000004100000410000000212212261242552022713 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | account tests', ['aws']) do if Fog.mocking? tests('check for vpc') do tests('supports both vpc and ec2 in compatibility mode').succeeds do client = Fog::Compute[:aws] client.ec2_compatibility_mode(true) data = Fog::Compute[:aws].describe_account_attributes.body data['accountAttributeSet'].any? { |s| [*s["values"]].include?("VPC") && [*s["values"]].include?("EC2") } end tests('supports VPC in vpc mode').succeeds do client = Fog::Compute[:aws] client.ec2_compatibility_mode(true) data = Fog::Compute[:aws].describe_account_attributes.body data['accountAttributeSet'].any? { |s| [*s["values"]].include?("VPC") } end tests('does not support VPC and EC2 in vpc mode').succeeds do client = Fog::Compute[:aws] client.ec2_compatibility_mode(false) data = Fog::Compute[:aws].describe_account_attributes.body !data['accountAttributeSet'].any? { |s| [*s["values"]].include?("VPC") && [*s["values"]].include?("EC2") } end end end end fog-1.19.0/tests/aws/requests/compute/spot_instance_tests.rb0000644000004100000410000000420012261242552024305 0ustar www-datawww-dataShindo.tests('Fog::Compute[:aws] | spot instance requests', ['aws']) do @spot_instance_requests_format = { 'spotInstanceRequestSet' => [{ 'createTime' => Time, 'instanceId' => Fog::Nullable::String, 'launchedAvailabilityZone' => Fog::Nullable::String, 'launchSpecification' => { 'blockDeviceMapping' => [], 'groupSet' => [String], 'keyName' => Fog::Nullable::String, 'imageId' => String, 'instanceType' => String, 'monitoring' => Fog::Boolean, 'ebsOptimized' => Fog::Boolean, 'subnetId' => Fog::Nullable::String, 'iamInstanceProfile' => Fog::Nullable::Hash, }, 'productDescription' => String, 'spotInstanceRequestId' => String, 'spotPrice' => Float, 'state' => String, 'type' => String, 'fault' => Fog::Nullable::Hash, }], 'requestId' => String } @cancel_spot_instance_request_format = { 'spotInstanceRequestSet' => [{ 'spotInstanceRequestId' => String, 'state' => String }], 'requestId' => String } tests('success') do pending if Fog.mocking? tests("#request_spot_instances('ami-3202f25b', 't1.micro', '0.001')").formats(@spot_instance_requests_format) do data = Fog::Compute[:aws].request_spot_instances('ami-3202f25b', 't1.micro', '0.001',{'LaunchSpecification.EbsOptimized' => false}).body @spot_instance_request_id = data['spotInstanceRequestSet'].first['spotInstanceRequestId'] data end tests("#describe_spot_instance_requests").formats(@spot_instance_requests_format) do Fog::Compute[:aws].describe_spot_instance_requests('spot-instance-request-id' => [@spot_instance_request_id]).body end tests("#cancel_spot_instance_requests('#{@spot_instance_request_id}')").formats(@cancel_spot_instance_request_format) do Fog::Compute[:aws].cancel_spot_instance_requests(@spot_instance_request_id).body end end end fog-1.19.0/tests/aws/requests/elasticache/0000755000004100000410000000000012261242552020462 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/elasticache/security_group_tests.rb0000644000004100000410000000704412261242552025321 0ustar www-datawww-dataShindo.tests('AWS::Elasticache | security group requests', ['aws', 'elasticache']) do tests('success') do name = 'fog-test' description = 'Fog Test Security Group' tests( '#create_cache_security_group' ).formats(AWS::Elasticache::Formats::SINGLE_SECURITY_GROUP) do body = AWS[:elasticache].create_cache_security_group(name, description).body group = body['CacheSecurityGroup'] returns(name) { group['CacheSecurityGroupName'] } returns(description) { group['Description'] } returns([], "no authorized security group") { group['EC2SecurityGroups'] } body end tests( '#describe_cache_security_groups without options' ).formats(AWS::Elasticache::Formats::DESCRIBE_SECURITY_GROUPS) do body = AWS[:elasticache].describe_cache_security_groups.body returns(true, "has #{name}") do body['CacheSecurityGroups'].any? do |group| group['CacheSecurityGroupName'] == name end end body end tests( '#describe_cache_security_groups with name' ).formats(AWS::Elasticache::Formats::DESCRIBE_SECURITY_GROUPS) do body = AWS[:elasticache].describe_cache_security_groups(name).body returns(1, "size of 1") { body['CacheSecurityGroups'].size } returns(name, "has #{name}") do body['CacheSecurityGroups'].first['CacheSecurityGroupName'] end body end tests('authorization') do ec2_group = Fog::Compute.new(:provider => 'AWS').security_groups.create( :name => 'fog-test-elasticache', :description => 'Fog Test Elasticache' ) # Reload to get the owner_id ec2_group.reload tests( '#authorize_cache_security_group_ingress' ).formats(AWS::Elasticache::Formats::SINGLE_SECURITY_GROUP) do body = AWS[:elasticache].authorize_cache_security_group_ingress( name, ec2_group.name, ec2_group.owner_id ).body group = body['CacheSecurityGroup'] expected_ec2_groups = [{ 'Status' => 'authorizing', 'EC2SecurityGroupName' => ec2_group.name, 'EC2SecurityGroupOwnerId' => ec2_group.owner_id }] returns(expected_ec2_groups, 'has correct EC2 groups') do group['EC2SecurityGroups'] end body end # Wait for the state to be active Fog.wait_for do response = AWS[:elasticache].describe_cache_security_groups(name) group = response.body['CacheSecurityGroups'].first group['EC2SecurityGroups'].all? {|ec2| ec2['Status'] == 'authorized'} end tests( '#revoke_cache_security_group_ingress' ).formats(AWS::Elasticache::Formats::SINGLE_SECURITY_GROUP) do pending if Fog.mocking? body = AWS[:elasticache].revoke_cache_security_group_ingress( name, ec2_group.name, ec2_group.owner_id ).body group = body['CacheSecurityGroup'] expected_ec2_groups = [{ 'Status' => 'revoking', 'EC2SecurityGroupName' => ec2_group.name, 'EC2SecurityGroupOwnerId' => ec2_group.owner_id }] returns(expected_ec2_groups, 'has correct EC2 groups') do group['EC2SecurityGroups'] end body end ec2_group.destroy end tests( '#delete_cache_security_group' ).formats(AWS::Elasticache::Formats::BASIC) do body = AWS[:elasticache].delete_cache_security_group(name).body end end tests('failure') do # TODO: # Create a duplicate security group # List a missing security group # Delete a missing security group end end fog-1.19.0/tests/aws/requests/elasticache/helper.rb0000644000004100000410000000652612261242552022277 0ustar www-datawww-dataclass AWS module Elasticache module Formats BASIC = { 'ResponseMetadata' => {'RequestId' => String} } # Cache Security Groups SECURITY_GROUP = { 'EC2SecurityGroups' => Array, 'CacheSecurityGroupName' => String, 'Description' => String, 'OwnerId' => String, } SINGLE_SECURITY_GROUP = BASIC.merge('CacheSecurityGroup' => SECURITY_GROUP) DESCRIBE_SECURITY_GROUPS = {'CacheSecurityGroups' => [SECURITY_GROUP]} # Cache Parameter Groups PARAMETER_GROUP = { 'CacheParameterGroupFamily' => String, 'CacheParameterGroupName' => String, 'Description' => String, } SINGLE_PARAMETER_GROUP = BASIC.merge('CacheParameterGroup' => PARAMETER_GROUP) DESCRIBE_PARAMETER_GROUPS = BASIC.merge('CacheParameterGroups' => [PARAMETER_GROUP]) MODIFY_PARAMETER_GROUP = {'CacheParameterGroupName' => String } PARAMETER_SET = { 'Parameters' => Array, 'CacheNodeTypeSpecificParameters' => Array, } ENGINE_DEFAULTS = PARAMETER_SET.merge('CacheParameterGroupFamily' => String) # Cache Clusters - more parameters get added as the lifecycle progresses CACHE_CLUSTER = { 'AutoMinorVersionUpgrade' => String, # actually TrueClass or FalseClass 'CacheSecurityGroups' => Array, 'CacheClusterId' => String, 'CacheClusterStatus' => String, 'CacheNodeType' => String, 'Engine' => String, 'EngineVersion' => String, 'CacheParameterGroup' => Hash, 'NumCacheNodes' => Integer, 'PreferredMaintenanceWindow' => String, 'CacheNodes' => Array, 'PendingModifiedValues' => Hash, } CACHE_CLUSTER_RUNNING = CACHE_CLUSTER.merge({ 'CacheClusterCreateTime' => DateTime, 'PreferredAvailabilityZone' => String, }) CACHE_CLUSTER_MODIFIED = CACHE_CLUSTER_RUNNING.merge({ 'NotificationConfiguration' => Hash, 'PendingModifiedValues' => Hash, }) SINGLE_CACHE_CLUSTER = BASIC.merge('CacheCluster' => CACHE_CLUSTER) DESCRIBE_CACHE_CLUSTERS = BASIC.merge('CacheClusters' => [CACHE_CLUSTER]) EVENT = { 'Date' => DateTime, 'Message' => String, 'SourceIdentifier' => String, 'SourceType' => String, } EVENT_LIST = [EVENT] RESERVED_CACHE_CLUSTER = { 'CacheNodeCount' => Integer, 'CacheNodeType' => String, 'Duration' => Integer, 'FixedPrice' => Float, 'OfferingType' => String, 'ProductDescription' => String, 'RecurringCharges' => Array, 'ReservedCacheNodeId' => String, 'ReservedCacheNodesOfferingId' => String, 'StartTime' => DateTime, 'State' => String, 'UsagePrice' => Float } RESERVED_CACHE_CLUSTER_LIST = [RESERVED_CACHE_CLUSTER] end end end fog-1.19.0/tests/aws/requests/elasticache/describe_reserved_cache_nodes.rb0000644000004100000410000000062212261242552027001 0ustar www-datawww-dataShindo.tests('AWS::Elasticache | describe reserved cache nodes', ['aws', 'elasticache']) do tests('success') do pending if Fog.mocking? tests( '#describe_reserved_cache_nodes' ).formats(AWS::Elasticache::Formats::RESERVED_CACHE_NODES) do AWS[:elasticache].describe_reserved_cache_nodes().body['ReservedCacheNodes'] end end tests('failure') do # TODO: end end fog-1.19.0/tests/aws/requests/elasticache/describe_events.rb0000644000004100000410000000054012261242552024152 0ustar www-datawww-dataShindo.tests('AWS::Elasticache | describe cache cluster events', ['aws', 'elasticache']) do tests('success') do pending if Fog.mocking? tests( '#describe_events' ).formats(AWS::Elasticache::Formats::EVENT_LIST) do AWS[:elasticache].describe_events().body['Events'] end end tests('failure') do # TODO: end end fog-1.19.0/tests/aws/requests/elasticache/parameter_group_tests.rb0000644000004100000410000000663412261242552025436 0ustar www-datawww-dataShindo.tests('AWS::Elasticache | parameter group requests', ['aws', 'elasticache']) do tests('success') do pending if Fog.mocking? name = 'fog-test' description = 'Fog Test Parameter Group' tests( '#describe_engine_default_parameters' ).formats(AWS::Elasticache::Formats::ENGINE_DEFAULTS) do response = AWS[:elasticache].describe_engine_default_parameters engine_defaults = response.body['EngineDefaults'] returns('memcached1.4') { engine_defaults['CacheParameterGroupFamily'] } engine_defaults end tests( '#create_cache_parameter_group' ).formats(AWS::Elasticache::Formats::SINGLE_PARAMETER_GROUP) do body = AWS[:elasticache].create_cache_parameter_group(name, description).body group = body['CacheParameterGroup'] returns(name) { group['CacheParameterGroupName'] } returns(description) { group['Description'] } returns('memcached1.4') { group['CacheParameterGroupFamily'] } body end tests( '#describe_cache_parameters' ).formats(AWS::Elasticache::Formats::PARAMETER_SET) do response = AWS[:elasticache].describe_cache_parameters(name) parameter_set = response.body['DescribeCacheParametersResult'] parameter_set end tests( '#describe_cache_parameter_groups without options' ).formats(AWS::Elasticache::Formats::DESCRIBE_PARAMETER_GROUPS) do body = AWS[:elasticache].describe_cache_parameter_groups.body returns(true, "has #{name}") do body['CacheParameterGroups'].any? do |group| group['CacheParameterGroupName'] == name end end body end tests( '#reset_cache_parameter_group completely' ).formats('CacheParameterGroupName' => String) do result = AWS[:elasticache].reset_cache_parameter_group( name ).body['ResetCacheParameterGroupResult'] returns(name) {result['CacheParameterGroupName']} result end tests( '#modify_cache_parameter_group' ).formats('CacheParameterGroupName' => String) do result = AWS[:elasticache].modify_cache_parameter_group( name, {"chunk_size" => 32} ).body['ModifyCacheParameterGroupResult'] returns(name) {result['CacheParameterGroupName']} result end # BUG: returns "MalformedInput - Unexpected complex element termination" tests( '#reset_cache_parameter_group with one parameter' ).formats('CacheParameterGroupName' => String) do pending result = AWS[:elasticache].reset_cache_parameter_group( name, ["chunk_size"] ).body['ResetCacheParameterGroupResult'] returns(name) {result['CacheParameterGroupName']} result end tests( '#describe_cache_parameter_groups with name' ).formats(AWS::Elasticache::Formats::DESCRIBE_PARAMETER_GROUPS) do body = AWS[:elasticache].describe_cache_parameter_groups(name).body returns(1, "size of 1") { body['CacheParameterGroups'].size } returns(name, "has #{name}") do body['CacheParameterGroups'].first['CacheParameterGroupName'] end body end tests( '#delete_cache_parameter_group' ).formats(AWS::Elasticache::Formats::BASIC) do body = AWS[:elasticache].delete_cache_parameter_group(name).body end end tests('failure') do # TODO: # Create a duplicate parameter group # List a missing parameter group # Delete a missing parameter group end end fog-1.19.0/tests/aws/requests/elasticache/cache_cluster_tests.rb0000644000004100000410000001144212261242552025037 0ustar www-datawww-dataShindo.tests('AWS::Elasticache | cache cluster requests', ['aws', 'elasticache']) do tests('success') do # Randomize the cluster ID so tests can be fequently re-run CLUSTER_ID = "fog-test-cluster-#{rand(999).to_s}" # 20 chars max! NUM_NODES = 2 # Must be > 1, because one of the tests reomves a node! tests( '#create_cache_cluster' ).formats(AWS::Elasticache::Formats::SINGLE_CACHE_CLUSTER) do body = AWS[:elasticache].create_cache_cluster(CLUSTER_ID, :num_nodes => NUM_NODES ).body cluster = body['CacheCluster'] returns(CLUSTER_ID) { cluster['CacheClusterId'] } returns('creating') { cluster['CacheClusterStatus'] } body end tests( '#describe_cache_clusters without options' ).formats(AWS::Elasticache::Formats::DESCRIBE_CACHE_CLUSTERS) do body = AWS[:elasticache].describe_cache_clusters.body returns(true, "has #{CLUSTER_ID}") do body['CacheClusters'].any? do |cluster| cluster['CacheClusterId'] == CLUSTER_ID end end # The DESCRIBE_CACHE_CLUSTERS format must include only one cluster # So remove all but the relevant cluster from the response body test_cluster = body['CacheClusters'].delete_if do |cluster| cluster['CacheClusterId'] != CLUSTER_ID end body end tests( '#describe_cache_clusters with cluster ID' ).formats(AWS::Elasticache::Formats::DESCRIBE_CACHE_CLUSTERS) do body = AWS[:elasticache].describe_cache_clusters(CLUSTER_ID).body returns(1, "size of 1") { body['CacheClusters'].size } returns(CLUSTER_ID, "has #{CLUSTER_ID}") do body['CacheClusters'].first['CacheClusterId'] end body end Formatador.display_line "Waiting for cluster #{CLUSTER_ID}..." AWS[:elasticache].clusters.get(CLUSTER_ID).wait_for {ready?} tests( '#describe_cache_clusters with node info' ).formats(AWS::Elasticache::Formats::CACHE_CLUSTER_RUNNING) do cluster = AWS[:elasticache].describe_cache_clusters(CLUSTER_ID, :show_node_info => true ).body['CacheClusters'].first returns(NUM_NODES, "has #{NUM_NODES} nodes") do cluster['CacheNodes'].count end cluster end tests( '#modify_cache_cluster - change a non-pending cluster attribute' ).formats(AWS::Elasticache::Formats::CACHE_CLUSTER_RUNNING) do body = AWS[:elasticache].modify_cache_cluster(CLUSTER_ID, :auto_minor_version_upgrade => false ).body # now check that parameter change is in place returns('false') { body['CacheCluster']['AutoMinorVersionUpgrade'] } body['CacheCluster'] end tests( '#reboot_cache_cluster - reboot a node' ).formats(AWS::Elasticache::Formats::CACHE_CLUSTER_RUNNING) do c = AWS[:elasticache].clusters.get(CLUSTER_ID) node_id = c.nodes.last['CacheNodeId'] Formatador.display_line "Rebooting node #{node_id}..." body = AWS[:elasticache].reboot_cache_cluster(c.id, [ node_id ]).body returns('rebooting cache cluster nodes') do body['CacheCluster']['CacheClusterStatus'] end body['CacheCluster'] end Formatador.display_line "Waiting for cluster #{CLUSTER_ID}..." AWS[:elasticache].clusters.get(CLUSTER_ID).wait_for {ready?} tests( '#modify_cache_cluster - remove a node' ).formats(AWS::Elasticache::Formats::CACHE_CLUSTER_RUNNING) do c = AWS[:elasticache].clusters.get(CLUSTER_ID) node_id = c.nodes.last['CacheNodeId'] Formatador.display_line "Removing node #{node_id}..." body = AWS[:elasticache].modify_cache_cluster(c.id, { :num_nodes => NUM_NODES - 1, :nodes_to_remove => [node_id], :apply_immediately => true, }).body returns(node_id) { body['CacheCluster']['PendingModifiedValues']['CacheNodeId'] } body['CacheCluster'] end Formatador.display_line "Waiting for cluster #{CLUSTER_ID}..." AWS[:elasticache].clusters.get(CLUSTER_ID).wait_for {ready?} tests( '#delete_cache_clusters' ).formats(AWS::Elasticache::Formats::CACHE_CLUSTER_RUNNING) do body = AWS[:elasticache].delete_cache_cluster(CLUSTER_ID).body # make sure this particular cluster is in the returned list returns(true, "has #{CLUSTER_ID}") do body['CacheClusters'].any? do |cluster| cluster['CacheClusterId'] == CLUSTER_ID end end # now check that it reports itself as 'deleting' cluster = body['CacheClusters'].find do |cluster| cluster['CacheClusterId'] == CLUSTER_ID end returns('deleting') { cluster['CacheClusterStatus'] } cluster end end tests('failure') do # TODO: # Create a duplicate cluster ID # List a missing cache cluster # Delete a missing cache cluster end end fog-1.19.0/tests/aws/requests/cloud_formation/0000755000004100000410000000000012261242552021401 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/cloud_formation/stack_tests.rb0000644000004100000410000001141312261242552024255 0ustar www-datawww-dataShindo.tests('AWS::CloudFormation | stack requests', ['aws', 'cloudformation']) do @validate_template_format = { 'Description' => String, 'Parameters' => [ { 'DefaultValue' => Fog::Nullable::String, 'Description' => String, 'NoEcho' => Fog::Boolean, 'ParameterKey' => String, } ], 'RequestId' => String } @create_stack_format = { 'RequestId' => String, 'StackId' => String } @update_stack_format = { 'RequestId' => String, 'StackId' => String } @get_template_format = { 'RequestId' => String, 'TemplateBody' => String } @describe_stacks_format = { 'RequestId' => String, 'Stacks' => [ { 'CreationTime' => Time, 'DisableRollback' => Fog::Boolean, 'Outputs' => [ { 'OutputKey' => String, 'OutputValue' => String } ], 'Parameters' => [ { 'ParameterKey' => String, 'ParameterValue' => String, } ], 'StackId' => String, 'StackName' => String, 'StackStatus' => String, } ] } @describe_stack_events_format = { 'RequestId' => String, 'StackEvents' => [ { 'EventId' => String, 'LogicalResourceId' => String, 'PhysicalResourceId' => String, 'ResourceProperties' => String, 'ResourceStatus' => String, 'ResourceStatusReason' => Fog::Nullable::String, 'ResourceType' => String, 'StackId' => String, 'StackName' => String, 'Timestamp' => Time } ] } @describe_stack_resources_format = { 'RequestId' => String, 'StackResources' => [ { 'LogicalResourceId' => String, 'PhysicalResourceId' => String, 'ResourceStatus' => String, 'ResourceType' => String, 'StackId' => String, 'StackName' => String, 'Timestamp' => Time } ] } tests('success') do unless Fog.mocking? @stack_name = 'fogstack' << Time.now.to_i.to_s @keypair = Fog::Compute[:aws].key_pairs.create(:name => 'cloudformation') @template_url = 'https://s3.amazonaws.com/cloudformation-templates-us-east-1/EC2InstanceSample-1.0.0.template' end tests("validate_template('TemplateURL' => '#{@template_url}')").formats(@validate_template_format) do pending if Fog.mocking? Fog::AWS[:cloud_formation].validate_template('TemplateURL' => @template_url).body end tests("create_stack('#{@stack_name}', 'TemplateURL' => '#{@template_url}', Parameters => {'KeyName' => 'cloudformation'})").formats(@create_stack_format) do pending if Fog.mocking? Fog::AWS[:cloud_formation].create_stack( @stack_name, 'TemplateURL' => @template_url, 'Parameters' => {'KeyName' => 'cloudformation'} ).body end tests("update_stack('#{@stack_name}', 'TemplateURL' => '#{@template_url}', Parameters => {'KeyName' => 'cloudformation'})").formats(@update_stack_format) do pending if Fog.mocking? Fog::AWS[:cloud_formation].update_stack( @stack_name, 'TemplateURL' => @template_url, 'Parameters' => {'KeyName' => 'cloudformation'} ).body end tests("get_template('#{@stack_name})").formats(@get_template_format) do pending if Fog.mocking? Fog::AWS[:cloud_formation].get_template(@stack_name).body end tests("describe_stacks").formats(@describe_stacks_format) do pending if Fog.mocking? Fog::AWS[:cloud_formation].describe_stacks.body end sleep(1) # avoid throttling tests("describe_stack_events('#{@stack_name}')").formats(@describe_stack_events_format) do pending if Fog.mocking? Fog::AWS[:cloud_formation].describe_stack_events(@stack_name).body end tests("describe_stack_resources('StackName' => '#{@stack_name}')").formats(@describe_stack_resources_format) do pending if Fog.mocking? Fog::AWS[:cloud_formation].describe_stack_resources('StackName' => @stack_name).body end tests("delete_stack('#{@stack_name}')").succeeds do pending if Fog.mocking? Fog::AWS[:cloud_formation].delete_stack(@stack_name) end tests("list_stacks").succeeds do pending if Fog.mocking? Fog::AWS[:cloud_formation].list_stacks.body end tests("list_stack_resources").succeeds do pending if Fog.mocking? Fog::AWS[:cloud_formation].list_stack_resources("StackName"=>@stack_name).body end unless Fog.mocking? @keypair.destroy end end tests('failure') do end end fog-1.19.0/tests/aws/requests/sns/0000755000004100000410000000000012261242552017020 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/sns/helper.rb0000644000004100000410000000016212261242552020623 0ustar www-datawww-dataclass AWS module SNS module Formats BASIC = { 'RequestId' => String } end end end fog-1.19.0/tests/aws/requests/sns/topic_tests.rb0000644000004100000410000000311612261242552021706 0ustar www-datawww-dataShindo.tests('AWS::SES | topic lifecycle tests', ['aws', 'sns']) do tests('success') do tests("#create_topic('fog_topic_tests')").formats(AWS::SNS::Formats::BASIC.merge('TopicArn' => String)) do pending if Fog.mocking? body = Fog::AWS[:sns].create_topic('fog_topic_tests').body @topic_arn = body["TopicArn"] body end tests("#list_topics").formats(AWS::SNS::Formats::BASIC.merge('Topics' => [String])) do pending if Fog.mocking? Fog::AWS[:sns].list_topics.body end tests("#set_topic_attributes('#{@topic_arn}', 'DisplayName', 'other-fog_topic_tests')").formats(AWS::SNS::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:sns].set_topic_attributes(@topic_arn, 'DisplayName', 'other-fog_topic_tests').body end get_topic_attributes_format = AWS::SNS::Formats::BASIC.merge({ 'Attributes' => { 'DisplayName' => String, 'Owner' => String, 'Policy' => String, 'SubscriptionsConfirmed' => Integer, 'SubscriptionsDeleted' => Integer, 'SubscriptionsPending' => Integer, 'TopicArn' => String } }) tests("#get_topic_attributes('#{@topic_arn})").formats(get_topic_attributes_format) do pending if Fog.mocking? Fog::AWS[:sns].get_topic_attributes(@topic_arn).body end tests("#delete_topic('#{@topic_arn}')").formats(AWS::SNS::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:sns].delete_topic(@topic_arn).body end end tests('failure') do end end fog-1.19.0/tests/aws/requests/sns/subscription_tests.rb0000644000004100000410000000531312261242552023315 0ustar www-datawww-dataShindo.tests('AWS::SES | topic lifecycle tests', ['aws', 'sns']) do unless Fog.mocking? @topic_arn = Fog::AWS[:sns].create_topic('fog_subscription_tests').body['TopicArn'] @queue_url = Fog::AWS[:sqs].create_queue('fog_subscription_tests').body['QueueUrl'] @queue_arn = Fog::AWS[:sqs].get_queue_attributes(@queue_url, 'QueueArn').body['Attributes']['QueueArn'] Fog::AWS[:sqs].set_queue_attributes( @queue_url, 'Policy', Fog::JSON.encode({ 'Id' => @topic_arn, 'Statement' => { 'Action' => 'sqs:SendMessage', 'Condition' => { 'StringEquals' => { 'aws:SourceArn' => @topic_arn } }, 'Effect' => 'Allow', 'Principal' => { 'AWS' => '*' }, 'Resource' => @queue_arn, 'Sid' => "#{@topic_arn}+sqs:SendMessage" }, 'Version' => '2008-10-17' }) ) end tests('success') do tests("#subscribe('#{@topic_arn}', '#{@queue_arn}', 'sqs')").formats(AWS::SNS::Formats::BASIC.merge('SubscriptionArn' => String)) do pending if Fog.mocking? body = Fog::AWS[:sns].subscribe(@topic_arn, @queue_arn, 'sqs').body @subscription_arn = body['SubscriptionArn'] body end list_subscriptions_format = AWS::SNS::Formats::BASIC.merge({ 'Subscriptions' => [{ 'Endpoint' => String, 'Owner' => String, 'Protocol' => String, 'SubscriptionArn' => String, 'TopicArn' => String }] }) tests("#list_subscriptions").formats(list_subscriptions_format) do pending if Fog.mocking? Fog::AWS[:sns].list_subscriptions.body end tests("#list_subscriptions_by_topic('#{@topic_arn}')").formats(list_subscriptions_format) do pending if Fog.mocking? body = Fog::AWS[:sns].list_subscriptions_by_topic(@topic_arn).body end tests("#publish('#{@topic_arn}', 'message')").formats(AWS::SNS::Formats::BASIC.merge('MessageId' => String)) do pending if Fog.mocking? body = Fog::AWS[:sns].publish(@topic_arn, 'message').body end tests("#receive_message('#{@queue_url}')...").returns('message') do pending if Fog.mocking? message = nil Fog.wait_for do message = Fog::AWS[:sqs].receive_message(@queue_url).body['Message'].first end Fog::JSON.decode(message['Body'])['Message'] end tests("#unsubscribe('#{@subscription_arn}')").formats(AWS::SNS::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:sns].unsubscribe(@subscription_arn).body end end tests('failure') do end unless Fog.mocking? Fog::AWS[:sns].delete_topic(@topic_arn) Fog::AWS[:sqs].delete_queue(@queue_url) end end fog-1.19.0/tests/aws/requests/iam/0000755000004100000410000000000012261242552016763 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/iam/helper.rb0000644000004100000410000001302212261242552020565 0ustar www-datawww-dataclass AWS module IAM # A self-signed test keypair. Generated using the command: # openssl req -new -newkey rsa:1024 -days 3650 -nodes -x509 -keyout server-private.key -out server-public.crt # NB: Amazon returns an error on extraneous linebreaks SERVER_CERT = %{-----BEGIN CERTIFICATE----- MIIDQzCCAqygAwIBAgIJAJaZ8wH+19AtMA0GCSqGSIb3DQEBBQUAMHUxCzAJBgNV BAYTAlVTMREwDwYDVQQIEwhOZXcgWW9yazERMA8GA1UEBxMITmV3IFlvcmsxHzAd BgNVBAoTFkZvZyBUZXN0IFNuYWtlb2lsIENlcnQxHzAdBgNVBAsTFkZvZyBUZXN0 IFNuYWtlb2lsIENlcnQwHhcNMTEwNTA3MTc0MDU5WhcNMjEwNTA0MTc0MDU5WjB1 MQswCQYDVQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxETAPBgNVBAcTCE5ldyBZ b3JrMR8wHQYDVQQKExZGb2cgVGVzdCBTbmFrZW9pbCBDZXJ0MR8wHQYDVQQLExZG b2cgVGVzdCBTbmFrZW9pbCBDZXJ0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB gQC0CR76sovjdmpWRmEaf8XaG+nGe7czhpdLKkau2b16VtSjkPctxPL5U4vaMxQU boLPr+9oL+9fSYN31VzDD4hyaeGoeI5fhnGeqk71kq5uHONBOQUMbZbBQ8PVd9Sd k+y9JJ6E5fC+GhLL5I+y2DK7syBzyymq1Wi6rPp1XXF7AQIDAQABo4HaMIHXMB0G A1UdDgQWBBRfqBkpU/jEV324748fq6GJM80iVTCBpwYDVR0jBIGfMIGcgBRfqBkp U/jEV324748fq6GJM80iVaF5pHcwdTELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5l dyBZb3JrMREwDwYDVQQHEwhOZXcgWW9yazEfMB0GA1UEChMWRm9nIFRlc3QgU25h a2VvaWwgQ2VydDEfMB0GA1UECxMWRm9nIFRlc3QgU25ha2VvaWwgQ2VydIIJAJaZ 8wH+19AtMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAUV6NDdLHKNhl ACtzLycIhlMTmDr0xBeIBx3lpgw2K0+4oefMS8Z17eeZPeNodxnz56juJm81BZwt DF3qnnPyArLFx0HLB7wQdm9xYVIqQuLO+V6GRuOd+uSX//aDLDZhwbERf35hoyto Jfk4gX/qwuRFNy0vjQeTzdvhB1igG/w= -----END CERTIFICATE----- } # The public key for SERVER_CERT. Generated using the command: # openssl x509 -inform pem -in server-public.crt -pubkey -noout > server.pubkey SERVER_CERT_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0CR76sovjdmpWRmEaf8XaG+nGe7czhpdLKkau2b16VtSjkPctxPL5U4vaMxQUboLPr+9oL+9fSYN31VzDD4hyaeGoeI5fhnGeqk71kq5uHONBOQUMbZbBQ8PVd9Sdk+y9JJ6E5fC+GhLL5I+y2DK7syBzyymq1Wi6rPp1XXF7AQIDAQAB" SERVER_CERT_PRIVATE_KEY = %{-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQC0CR76sovjdmpWRmEaf8XaG+nGe7czhpdLKkau2b16VtSjkPct xPL5U4vaMxQUboLPr+9oL+9fSYN31VzDD4hyaeGoeI5fhnGeqk71kq5uHONBOQUM bZbBQ8PVd9Sdk+y9JJ6E5fC+GhLL5I+y2DK7syBzyymq1Wi6rPp1XXF7AQIDAQAB AoGANjjRBbwkeXs+h4Fm2W5GDmx9ufOkt3X/tvmilCKr+F6SaDjO2RAKBaFt62ea 0pR9/UMFnaFiPJaNa9fsuirBcwId+RizruEp+7FGziM9mC5kcE7WKZrXgGGnLtqg 4x5twVLArgp0ji7TA18q/74uTrI4az8H5iTY4n29ORlLmmkCQQDsGMuLEgGHgN5Y 1c9ax1DT/rUXKxnqsIrijRkgbiTncHAArFJ88c3yykWqGvYnSFwMS8DSWiPyPaAI nNNlb/fPAkEAwzZ4CfvJ+OlE++rTPH9jemC89dnxC7EFGuWJmwdadnev8EYguvve cdGdGttD7QsZKpcz5mDngOUghbVm8vBELwJAMHfOoVgq9DRicP5DuTEdyMeLSZxR j7p6aJPqypuR++k7NQgrTvcc/nDD6G3shpf2PZf3l7dllb9M8TewtixMRQJBAIdX c0AQtoYBTJePxiYyd8i32ypkkK83ar+sFoxKO9jYwD1IkZax2xZ0aoTdMindQPR7 Yjs+QiLmOHcbPqX+GHcCQERsSn0RjzKmKirDntseMB59BB/cEN32+gMDVsZuCfb+ fOy2ZavFl13afnhbh2/AjKeDhnb19x/uXjF7JCUtwpA= -----END RSA PRIVATE KEY----- } # openssl pkcs8 -nocrypt -topk8 -in SERVER_CERT_PRIVATE_KEY.key -outform pem SERVER_CERT_PRIVATE_KEY_PKCS8 = %{-----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALQJHvqyi+N2alZG YRp/xdob6cZ7tzOGl0sqRq7ZvXpW1KOQ9y3E8vlTi9ozFBRugs+v72gv719Jg3fV XMMPiHJp4ah4jl+GcZ6qTvWSrm4c40E5BQxtlsFDw9V31J2T7L0knoTl8L4aEsvk j7LYMruzIHPLKarVaLqs+nVdcXsBAgMBAAECgYA2ONEFvCR5ez6HgWbZbkYObH25 86S3df+2+aKUIqv4XpJoOM7ZEAoFoW3rZ5rSlH39QwWdoWI8lo1r1+y6KsFzAh35 GLOu4Sn7sUbOIz2YLmRwTtYpmteAYacu2qDjHm3BUsCuCnSOLtMDXyr/vi5Osjhr PwfmJNjifb05GUuaaQJBAOwYy4sSAYeA3ljVz1rHUNP+tRcrGeqwiuKNGSBuJOdw cACsUnzxzfLKRaoa9idIXAxLwNJaI/I9oAic02Vv988CQQDDNngJ+8n46UT76tM8 f2N6YLz12fELsQUa5YmbB1p2d6/wRiC6+95x0Z0a20PtCxkqlzPmYOeA5SCFtWby 8EQvAkAwd86hWCr0NGJw/kO5MR3Ix4tJnFGPunpok+rKm5H76Ts1CCtO9xz+cMPo beyGl/Y9l/eXt2WVv0zxN7C2LExFAkEAh1dzQBC2hgFMl4/GJjJ3yLfbKmSQrzdq v6wWjEo72NjAPUiRlrHbFnRqhN0yKd1A9HtiOz5CIuY4dxs+pf4YdwJARGxKfRGP MqYqKsOe2x4wHn0EH9wQ3fb6AwNWxm4J9v587LZlq8WXXdp+eFuHb8CMp4OGdvX3 H+5eMXskJS3CkA== -----END PRIVATE KEY----- } SERVER_CERT_PRIVATE_KEY_MISMATCHED = %{-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAyITMqYJMzkPMcaC+x0W2hnZVW99RXzLR8RYyD3xo2AotdJKx 1DXR4ryegAjsnAhJVwVtxqzPcBMq/XS0hNtWFfKzf+vMZl7uAqotGjURUV8SRQPA 8tT07MemD929xRSV2vTnVATiPn87vcu5igsZ01+Ewd6rGythmvcZD13vtZ4rx0c8 kQJV3ok/CkFaIgDR6Or1NZBCtcIVK9nvqAmYMp6S5mWUMIsl/1qYPerpefrSJjlk J2+jyLp0LHarbzjkzzAdOkBRX1hPkk6cisBeQIpx35shLzfCe8U25XNqquP+ftcu JZ0Wjw+C4pTIzfgdGXmGGtBFY13BwiJvd4/i2wIDAQABAoIBABk8XWWX+IKdFcXX LSt3IpmZmvSNDniktLday8IXLjrCTSY2sBq9C0U159zFQsIAaPqCvGYcqZ65StfL MEzoLdVlTiHzUy4vFFVRhYue0icjh/EXn9jv5ENIfSXSCmgbRyDfYZ25X5/t817X nOo6q21mwBaGJ5KrywTtxEGi2OBKZrIbBrpJLhCXJc5xfuKT6DRa9X/OBSBiGKJP V9wHcZJkPG1HnC8izvQ37kNN/NyYE+8AGdYXQVNbTHq/emNLbEbdcR3tpGZamM9Q TwG5WsDPAnXnRsEEYvlVTOBI6DqdvkyBxM35iqd5aAc6i/Iu04Unfhhc5pAXmmIB a22GHcECgYEA7OheVHDDP8quO2qZjqaTlMbMnXnrFXJ41llFMoivTW9EmlTl9dOC fnkHEBcFCTPV0m6S2AQjt9QOgPqCFAq1r3J/xvEGBtl/UKnPRmjqXFgl0ENtGn5t w9wj/CsOPD05KkXXtXP+MyLPRD6gAxiQCTnXjvsLuVfP+E9BO2EQXScCgYEA2K2x QtcAAalrk3c0KzNVESzyFlf3ddEXThShVblSa7r6Ka9q9sxN/Xe2B+1oemPJm26G PfqKgxdKX0R0jl4f5pRBWKoarzWtUge/su8rx/xzbY/1hFKVuimtc6oTeU5xsOTS PVuCz4bxDTVhrbmKqbmMgqy17jfPA4BrF1FMRS0CgYBdMA4i4vQ6fIxKfOUIMsfs hsJn01RAbHXRwu2wMgnayMDQgEKwjtFO1GaN0rA9bXFXQ/1pET/HiJdn7qIKJihP aheO9rHrMdSdsx4AUTaWummtYUhiWobsuwRApeMEmQSKd0yhaI3+KVwkOQoSDbBi oKkE6gUzk7IPt4UuSUD5kwKBgQCjo/IGr8dieegz08gDhF4PfalLdJ4ATaxTHMOH sVFs6SY7Sy72Ou//qGRCcmsAW9KL35nkvw3S2Ukiz9lTGATxqC/93WIPxvMhy5Zc dcLT43XtXdanW5OWqBlGDEFu0O6OERIyoqUVRC1Ss2kUwdbWPbq/id5Qjbd7RoYa cxyt9QKBgF4bFLw1Iw2RBngQxIzoDbElEqme20FUyGGzyFQtxVwmwNr4OY5UzJzX 7G6diyzGrvRX81Yw616ppKJUJVr/zRc13K+eRXXKtNpGkf35B+1NDDjjWZpIHqgx Xb9WSr07saxZQbxBPQyTlb0Q9Tu2djAq2/o/nYD1/50/fXUTuWMB -----END RSA PRIVATE KEY----- } module Formats BASIC = { 'RequestId' => String } end end end fog-1.19.0/tests/aws/requests/iam/role_tests.rb0000644000004100000410000001207312261242552021476 0ustar www-datawww-dataShindo.tests('AWS::IAM | role requests', ['aws']) do tests('success') do @role = { 'Arn' => String, 'AssumeRolePolicyDocument' => String, 'CreateDate' => Time, 'Path' => String, 'RoleId' => String, 'RoleName' => String } @role_format = { 'Role' => @role, 'RequestId' => String } tests("#create_role('fogrole')").formats(@role_format) do pending if Fog.mocking? Fog::AWS[:iam].create_role('fogrole', Fog::AWS::IAM::EC2_ASSUME_ROLE_POLICY).body end tests("#get_role('fogrole')").formats(@role_format) do pending if Fog.mocking? Fog::AWS[:iam].get_role('fogrole').body end @list_roles_format = { 'Roles' => [{ 'Arn' => String, 'AssumeRolePolicyDocument' => String, 'CreateDate' => Time, 'Path' => String, 'RoleId' => String, 'RoleName' => String }], 'RequestId' => String, 'IsTruncated' => Fog::Boolean, } tests("#list_roles").formats(@list_roles_format) do pending if Fog.mocking? body = Fog::AWS[:iam].list_roles.body returns(true){!! body['Roles'].detect {|role| role['RoleName'] == 'fogrole'}} body end @profile_format = { 'InstanceProfile' => { 'Arn' => String, 'CreateDate' => Time, 'Path' => String, 'InstanceProfileId' => String, 'InstanceProfileName' => String, 'Roles' => [@role] }, 'RequestId' => String } tests("#create_instance_profile('fogprofile')").formats(@profile_format) do pending if Fog.mocking? Fog::AWS[:iam].create_instance_profile('fogprofile').body end tests("#get_instance_profile('fogprofile')").formats(@profile_format) do pending if Fog.mocking? Fog::AWS[:iam].get_instance_profile('fogprofile').body end tests("#add_role_to_instance_profile('fogprofile','fogrole')").formats(AWS::IAM::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:iam].add_role_to_instance_profile('fogrole', 'fogprofile').body end @profiles_format = { 'InstanceProfiles' => [{ 'Arn' => String, 'CreateDate' => Time, 'Path' => String, 'InstanceProfileId' => String, 'InstanceProfileName' => String, 'Roles' => [@role] }], 'IsTruncated' => Fog::Boolean, 'RequestId' => String } tests("list_instance_profiles_for_role('fogrole')").formats(@profiles_format) do pending if Fog.mocking? body = Fog::AWS[:iam].list_instance_profiles_for_role('fogrole').body returns(['fogprofile']) { body['InstanceProfiles'].collect {|hash| hash['InstanceProfileName']}} body end tests("list_instance_profiles").formats(@profiles_format) do pending if Fog.mocking? Fog::AWS[:iam].list_instance_profiles.body end sample_policy = {"Statement" => [{"Effect" => "Allow", "Action" => "*", "Resource" => "*"}]} tests("put_role_policy").formats(AWS::IAM::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:iam].put_role_policy('fogrole', 'fogpolicy', sample_policy).body end @get_role_policy_format = { 'Policy' => { 'RoleName' => String, 'PolicyName' => String, 'PolicyDocument' => Hash, }, 'RequestId' => String } tests("get_role_policy").formats(@get_role_policy_format) do pending if Fog.mocking? body = Fog::AWS[:iam].get_role_policy('fogrole','fogpolicy').body returns('fogpolicy') {body['Policy']['PolicyName']} returns(sample_policy){body['Policy']['PolicyDocument']} body end @list_role_policies_format = { 'PolicyNames' => [String], 'IsTruncated' => Fog::Boolean, 'RequestId' => String } tests("list_role_policies").formats(@list_role_policies_format) do pending if Fog.mocking? body = Fog::AWS[:iam].list_role_policies('fogrole').body returns(['fogpolicy']) {body['PolicyNames']} body end tests("delete_role_policy").formats(AWS::IAM::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:iam].delete_role_policy('fogrole', 'fogpolicy').body end returns([]) do pending if Fog.mocking? Fog::AWS[:iam].list_role_policies('fogrole').body['PolicyNames'] end tests("remove_role_from_instance_profile").formats(AWS::IAM::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:iam].remove_role_from_instance_profile('fogrole', 'fogprofile').body end returns([]) do pending if Fog.mocking? Fog::AWS[:iam].list_instance_profiles_for_role('fogrole').body['InstanceProfiles'] end tests("#delete_instance_profile('fogprofile'").formats(AWS::IAM::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:iam].delete_instance_profile('fogprofile').body end tests("#delete_role('fogrole'").formats(AWS::IAM::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:iam].delete_role('fogrole').body end end end fog-1.19.0/tests/aws/requests/iam/group_policy_tests.rb0000644000004100000410000000277312261242552023256 0ustar www-datawww-dataShindo.tests('AWS::IAM | group policy requests', ['aws']) do Fog::AWS[:iam].create_group('fog_group_policy_tests') tests('success') do @policy = {"Statement" => [{"Effect" => "Allow", "Action" => "*", "Resource" => "*"}]} tests("#put_group_policy('fog_group_policy_tests', 'fog_policy', #{@policy.inspect})").formats(AWS::IAM::Formats::BASIC) do Fog::AWS[:iam].put_group_policy('fog_group_policy_tests', 'fog_policy', @policy).body end @group_policies_format = { 'IsTruncated' => Fog::Boolean, 'PolicyNames' => [String], 'RequestId' => String } tests("list_group_policies('fog_group_policy_tests')").formats(@group_policies_format) do pending if Fog.mocking? Fog::AWS[:iam].list_group_policies('fog_group_policy_tests').body end @group_policy_format = { 'GroupName' => String, 'PolicyName' => String, 'PolicyDocument' => Hash, } tests("#get_group_policy('fog_group_policy_tests', 'fog_policy'").formats(@group_policy_format) do Fog::AWS[:iam].get_group_policy('fog_policy', 'fog_group_policy_tests').body['Policy'] end tests("#delete_group_policy('fog_group_policy_tests', 'fog_policy')").formats(AWS::IAM::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:iam].delete_group_policy('fog_group_policy_tests', 'fog_policy').body end end tests('failure') do test('failing conditions') end unless Fog.mocking? Fog::AWS[:iam].delete_group('fog_group_policy_tests') end end fog-1.19.0/tests/aws/requests/iam/login_profile_tests.rb0000644000004100000410000000362112261242552023364 0ustar www-datawww-dataShindo.tests('AWS::IAM | user requests', ['aws']) do unless Fog.mocking? Fog::AWS[:iam].create_user('fog_user') end tests('success') do @login_profile_format = { 'LoginProfile' => { 'UserName' => String, 'CreateDate' => Time }, 'RequestId' => String } tests("#create_login_profile('fog_user')").formats(@login_profile_format) do pending if Fog.mocking? Fog::AWS[:iam].create_login_profile('fog_user', 'somepassword').body end tests("#get_login_profile('fog_user')").formats(@login_profile_format) do pending if Fog.mocking? result = Fog::AWS[:iam].get_login_profile('fog_user').body returns('fog_user') {result['LoginProfile']['UserName']} result end tests("#update_login_profile('fog_user')").formats(AWS::IAM::Formats::BASIC) do pending if Fog.mocking? begin Fog::AWS[:iam].update_login_profile('fog_user', 'otherpassword').body rescue Excon::Errors::Conflict #profile cannot be updated or deleted until it has finished creating; api provides no way of telling whether creation process complete sleep 5 retry end end tests("#delete_login_profile('fog_user')").formats(AWS::IAM::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:iam].delete_login_profile('fog_user').body end tests("#get_login_profile('fog_user')") do pending if Fog.mocking? raises(Excon::Errors::NotFound) {Fog::AWS[:iam].get_login_profile('fog_user')} end end tests('failure') do tests('get login profile for non existing user') do pending if Fog.mocking? raises(Fog::AWS::IAM::NotFound) { Fog::AWS[:iam].get_login_profile('idontexist')} raises(Fog::AWS::IAM::NotFound) { Fog::AWS[:iam].delete_login_profile('fog_user')} end end unless Fog.mocking? Fog::AWS[:iam].delete_user('fog_user') end end fog-1.19.0/tests/aws/requests/iam/access_key_tests.rb0000644000004100000410000000322512261242552022645 0ustar www-datawww-dataShindo.tests('AWS::IAM | access key requests', ['aws']) do Fog::AWS[:iam].create_user('fog_access_key_tests') tests('success') do @access_key_format = { 'AccessKey' => { 'AccessKeyId' => String, 'UserName' => String, 'SecretAccessKey' => String, 'Status' => String }, 'RequestId' => String } tests("#create_access_key('UserName' => 'fog_access_key_tests')").formats(@access_key_format) do data = Fog::AWS[:iam].create_access_key('UserName' => 'fog_access_key_tests').body @access_key_id = data['AccessKey']['AccessKeyId'] data end @access_keys_format = { 'AccessKeys' => [{ 'AccessKeyId' => String, 'Status' => String }], 'IsTruncated' => Fog::Boolean, 'RequestId' => String } tests("#list_access_keys('Username' => 'fog_access_key_tests')").formats(@access_keys_format) do Fog::AWS[:iam].list_access_keys('UserName' => 'fog_access_key_tests').body end tests("#update_access_key('#{@access_key_id}', 'Inactive', 'UserName' => 'fog_access_key_tests')").formats(AWS::IAM::Formats::BASIC) do pending if Fog.mocking? Fog::AWS[:iam].update_access_key(@access_key_id, 'Inactive', 'UserName' => 'fog_access_key_tests').body end tests("#delete_access_key('#{@access_key_id}', 'UserName' => 'fog_access_key_tests)").formats(AWS::IAM::Formats::BASIC) do Fog::AWS[:iam].delete_access_key(@access_key_id, 'UserName' => 'fog_access_key_tests').body end end tests('failure') do test('failing conditions') end Fog::AWS[:iam].delete_user('fog_access_key_tests') end fog-1.19.0/tests/aws/requests/iam/server_certificate_tests.rb0000644000004100000410000001125412261242552024405 0ustar www-datawww-dataShindo.tests('AWS::IAM | server certificate requests', ['aws']) do @key_name = 'fog-test' @key_name_chained = 'fog-test-chained' @certificate_format = { 'Arn' => String, 'Path' => String, 'ServerCertificateId' => String, 'ServerCertificateName' => String, 'UploadDate' => Time } @upload_format = { 'Certificate' => @certificate_format, 'RequestId' => String } @update_format = { 'RequestId' => String } @get_server_certificate_format = { 'Certificate' => @certificate_format, 'RequestId' => String } @list_format = { 'Certificates' => [@certificate_format] } tests('#upload_server_certificate') do public_key = AWS::IAM::SERVER_CERT private_key = AWS::IAM::SERVER_CERT_PRIVATE_KEY private_key_pkcs8 = AWS::IAM::SERVER_CERT_PRIVATE_KEY_PKCS8 private_key_mismatch = AWS::IAM::SERVER_CERT_PRIVATE_KEY_MISMATCHED tests('empty public key').raises(Fog::AWS::IAM::ValidationError) do Fog::AWS::IAM.new.upload_server_certificate('', private_key, @key_name) end tests('empty private key').raises(Fog::AWS::IAM::ValidationError) do Fog::AWS::IAM.new.upload_server_certificate(public_key, '', @key_name) end tests('invalid public key').raises(Fog::AWS::IAM::MalformedCertificate) do Fog::AWS::IAM.new.upload_server_certificate('abcde', private_key, @key_name) end tests('invalid private key').raises(Fog::AWS::IAM::MalformedCertificate) do Fog::AWS::IAM.new.upload_server_certificate(public_key, 'abcde', @key_name) end tests('non-RSA private key').raises(Fog::AWS::IAM::MalformedCertificate) do Fog::AWS::IAM.new.upload_server_certificate(public_key, private_key_pkcs8, @key_name) end tests('mismatched private key').raises(Fog::AWS::IAM::KeyPairMismatch) do Fog::AWS::IAM.new.upload_server_certificate(public_key, private_key_mismatch, @key_name) end tests('format').formats(@upload_format) do Fog::AWS::IAM.new.upload_server_certificate(public_key, private_key, @key_name).body end tests('format with chain').formats(@upload_format) do Fog::AWS::IAM.new.upload_server_certificate(public_key, private_key, @key_name_chained, { 'CertificateChain' => public_key }).body end tests('duplicate name').raises(Fog::AWS::IAM::EntityAlreadyExists) do Fog::AWS::IAM.new.upload_server_certificate(public_key, private_key, @key_name) end end tests('#update_server_certificate') do public_key = AWS::IAM::SERVER_CERT private_key = AWS::IAM::SERVER_CERT_PRIVATE_KEY key_name = "update-key" Fog::AWS::IAM.new.upload_server_certificate(public_key, private_key, key_name) tests('duplicate name').raises(Fog::AWS::IAM::EntityAlreadyExists) do other_key_name = "other-key-name" Fog::AWS::IAM.new.upload_server_certificate(public_key, private_key, other_key_name) Fog::AWS::IAM.new.update_server_certificate(key_name, {'NewServerCertificateName' => other_key_name}) end tests('unknown name').raises(Fog::AWS::IAM::NotFound) do Fog::AWS::IAM.new.update_server_certificate("unknown-key-name", {'NewServerCertificateName' => "other-keyname"}) end tests('format').formats(@update_format) do Fog::AWS::IAM.new.update_server_certificate(key_name).body end tests('updates name') do other_key_name = "successful-update-key-name" Fog::AWS::IAM.new.update_server_certificate(key_name, {'NewServerCertificateName' => other_key_name}) returns(true) { Fog::AWS::IAM.new.get_server_certificate(other_key_name).body['Certificate']['ServerCertificateName'] == other_key_name } end end tests('#get_server_certificate').formats(@get_server_certificate_format) do tests('raises NotFound').raises(Fog::AWS::IAM::NotFound) do Fog::AWS::IAM.new.get_server_certificate("#{@key_name}fake") end Fog::AWS::IAM.new.get_server_certificate(@key_name).body end tests('#list_server_certificates').formats(@list_format) do result = Fog::AWS::IAM.new.list_server_certificates.body tests('includes key name') do returns(true) { result['Certificates'].any?{|c| c['ServerCertificateName'] == @key_name} } end result end tests("#list_server_certificates('path-prefix' => '/'").formats(@list_format) do result = Fog::AWS::IAM.new.list_server_certificates('PathPrefix' => '/').body tests('includes key name') do returns(true) { result['Certificates'].any?{|c| c['ServerCertificateName'] == @key_name} } end result end tests('#delete_server_certificate').formats(AWS::IAM::Formats::BASIC) do Fog::AWS::IAM.new.delete_server_certificate(@key_name).body end Fog::AWS::IAM.new.delete_server_certificate(@key_name_chained) end fog-1.19.0/tests/aws/requests/iam/group_tests.rb0000644000004100000410000000171512261242552021672 0ustar www-datawww-dataShindo.tests('AWS::IAM | group requests', ['aws']) do tests('success') do @group_format = { 'Group' => { 'Arn' => String, 'GroupId' => String, 'GroupName' => String, 'Path' => String }, 'RequestId' => String } tests("#create_group('fog_group')").formats(@group_format) do Fog::AWS[:iam].create_group('fog_group').body end @groups_format = { 'Groups' => [{ 'Arn' => String, 'GroupId' => String, 'GroupName' => String, 'Path' => String }], 'IsTruncated' => Fog::Boolean, 'RequestId' => String } tests("#list_groups").formats(@groups_format) do Fog::AWS[:iam].list_groups.body end tests("#delete_group('fog_group')").formats(AWS::IAM::Formats::BASIC) do Fog::AWS[:iam].delete_group('fog_group').body end end tests('failure') do test('failing conditions') end end fog-1.19.0/tests/aws/requests/iam/user_policy_tests.rb0000644000004100000410000000261112261242552023067 0ustar www-datawww-dataShindo.tests('AWS::IAM | user policy requests', ['aws']) do Fog::AWS[:iam].create_user('fog_user_policy_tests') tests('success') do @policy = {"Statement" => [{"Effect" => "Allow", "Action" => "*", "Resource" => "*"}]} tests("#put_user_policy('fog_user_policy_tests', 'fog_policy', #{@policy.inspect})").formats(AWS::IAM::Formats::BASIC) do Fog::AWS[:iam].put_user_policy('fog_user_policy_tests', 'fog_policy', @policy).body end @user_policies_format = { 'IsTruncated' => Fog::Boolean, 'PolicyNames' => [String], 'RequestId' => String } tests("#list_user_policies('fog_user_policy_tests')").formats(@user_policies_format) do Fog::AWS[:iam].list_user_policies('fog_user_policy_tests').body end @user_policy_format = { 'UserName' => String, 'PolicyName' => String, 'PolicyDocument' => Hash, } tests("#get_user_policy('fog_user_policy_tests', 'fog_policy'").formats(@user_policy_format) do Fog::AWS[:iam].get_user_policy('fog_policy', 'fog_user_policy_tests').body['Policy'] end tests("#delete_user_policy('fog_user_policy_tests', 'fog_policy')").formats(AWS::IAM::Formats::BASIC) do Fog::AWS[:iam].delete_user_policy('fog_user_policy_tests', 'fog_policy').body end end tests('failure') do test('failing conditions') end Fog::AWS[:iam].delete_user('fog_user_policy_tests') end fog-1.19.0/tests/aws/requests/iam/user_tests.rb0000644000004100000410000000372112261242552021513 0ustar www-datawww-dataShindo.tests('AWS::IAM | user requests', ['aws']) do Fog::AWS[:iam].create_group('fog_user_tests') tests('success') do @user_format = { 'User' => { 'Arn' => String, 'Path' => String, 'UserId' => String, 'UserName' => String, 'CreateDate' => Time }, 'RequestId' => String } tests("#create_user('fog_user')").formats(@user_format) do Fog::AWS[:iam].create_user('fog_user').body end @users_format = { 'Users' => [{ 'Arn' => String, 'Path' => String, 'UserId' => String, 'UserName' => String, 'CreateDate' => Time }], 'IsTruncated' => Fog::Boolean, 'RequestId' => String } tests("#list_users").formats(@users_format) do Fog::AWS[:iam].list_users.body end tests("#get_user").formats(@user_format) do Fog::AWS[:iam].get_user('fog_user').body end tests("#add_user_to_group('fog_user_tests', 'fog_user')").formats(AWS::IAM::Formats::BASIC) do Fog::AWS[:iam].add_user_to_group('fog_user_tests', 'fog_user').body end @groups_format = { 'GroupsForUser' => [{ 'Arn' => String, 'GroupId' => String, 'GroupName' => String, 'Path' => String }], 'IsTruncated' => Fog::Boolean, 'RequestId' => String } tests("#list_groups_for_user('fog_user')").formats(@groups_format) do Fog::AWS[:iam].list_groups_for_user('fog_user').body end tests("#remove_user_from_group('fog_user_tests', 'fog_user')").formats(AWS::IAM::Formats::BASIC) do Fog::AWS[:iam].remove_user_from_group('fog_user_tests', 'fog_user').body end tests("#delete_user('fog_user')").formats(AWS::IAM::Formats::BASIC) do Fog::AWS[:iam].delete_user('fog_user').body end end tests('failure') do test('failing conditions') end Fog::AWS[:iam].delete_group('fog_user_tests') end fog-1.19.0/tests/aws/requests/simpledb/0000755000004100000410000000000012261242552020014 5ustar www-datawww-datafog-1.19.0/tests/aws/requests/simpledb/helper.rb0000644000004100000410000000023312261242552021616 0ustar www-datawww-dataclass AWS module SimpleDB module Formats BASIC = { 'BoxUsage' => Float, 'RequestId' => String } end end end fog-1.19.0/tests/aws/requests/simpledb/attributes_tests.rb0000644000004100000410000001042712261242552023755 0ustar www-datawww-dataShindo.tests('AWS::SimpleDB | attributes requests', ['aws']) do @domain_name = "fog_domain_#{Time.now.to_f.to_s.gsub('.','')}" Fog::AWS[:simpledb].create_domain(@domain_name) tests('success') do tests("#batch_put_attributes('#{@domain_name}', { 'a' => { 'b' => 'c', 'd' => 'e' }, 'x' => { 'y' => 'z' } }).body").formats(AWS::SimpleDB::Formats::BASIC) do Fog::AWS[:simpledb].batch_put_attributes(@domain_name, { 'a' => { 'b' => 'c', 'd' => 'e' }, 'x' => { 'y' => 'z' } }).body end tests("#get_attributes('#{@domain_name}', 'a', {'ConsistentRead' => true}).body['Attributes']").returns({'b' => ['c'], 'd' => ['e']}) do Fog::AWS[:simpledb].get_attributes(@domain_name, 'a', {'ConsistentRead' => true}).body['Attributes'] end tests("#get_attributes('#{@domain_name}', 'AttributeName' => 'notanattribute')").succeeds do Fog::AWS[:simpledb].get_attributes(@domain_name, 'AttributeName' => 'notanattribute') end tests("#select('select * from #{@domain_name}', {'ConsistentRead' => true}).body['Items']").returns({'a' => { 'b' => ['c'], 'd' => ['e']}, 'x' => { 'y' => ['z'] } }) do pending if Fog.mocking? Fog::AWS[:simpledb].select("select * from #{@domain_name}", {'ConsistentRead' => true}).body['Items'] end tests("#put_attributes('#{@domain_name}', 'conditional', { 'version' => '1' }).body").formats(AWS::SimpleDB::Formats::BASIC) do Fog::AWS[:simpledb].put_attributes(@domain_name, 'conditional', { 'version' => '1' }).body end tests("#put_attributes('#{@domain_name}', 'conditional', { 'version' => '2' }, :expect => { 'version' => '1' }, :replace => ['version']).body").formats(AWS::SimpleDB::Formats::BASIC) do Fog::AWS[:simpledb].put_attributes(@domain_name, 'conditional', { 'version' => '2' }, :expect => { 'version' => '1' }, :replace => ['version']).body end # Verify that we can delete individual attributes. tests("#delete_attributes('#{@domain_name}', 'a', {'d' => []})").succeeds do Fog::AWS[:simpledb].delete_attributes(@domain_name, 'a', {'d' => []}).body end # Verify that individually deleted attributes are actually removed. tests("#get_attributes('#{@domain_name}', 'a', {'AttributeName' => ['d'], 'ConsistentRead' => true}).body['Attributes']").returns({}) do Fog::AWS[:simpledb].get_attributes(@domain_name, 'a', {'AttributeName' => ['d'], 'ConsistentRead' => true}).body['Attributes'] end tests("#delete_attributes('#{@domain_name}', 'a').body").formats(AWS::SimpleDB::Formats::BASIC) do Fog::AWS[:simpledb].delete_attributes(@domain_name, 'a').body end # Verify that we can delete entire domain, item combinations. tests("#delete_attributes('#{@domain_name}', 'a').body").succeeds do Fog::AWS[:simpledb].delete_attributes(@domain_name, 'a').body end # Verify that deleting a domain, item combination removes all related attributes. tests("#get_attributes('#{@domain_name}', 'a', {'ConsistentRead' => true}).body['Attributes']").returns({}) do Fog::AWS[:simpledb].get_attributes(@domain_name, 'a', {'ConsistentRead' => true}).body['Attributes'] end end tests('failure') do tests("#batch_put_attributes('notadomain', { 'a' => { 'b' => 'c' }, 'x' => { 'y' => 'z' } })").raises(Excon::Errors::BadRequest) do Fog::AWS[:simpledb].batch_put_attributes('notadomain', { 'a' => { 'b' => 'c' }, 'x' => { 'y' => 'z' } }) end tests("#get_attributes('notadomain', 'a')").raises(Excon::Errors::BadRequest) do Fog::AWS[:simpledb].get_attributes('notadomain', 'a') end tests("#put_attributes('notadomain', 'conditional', { 'version' => '1' })").raises(Excon::Errors::BadRequest) do Fog::AWS[:simpledb].put_attributes('notadomain', 'foo', { 'version' => '1' }) end tests("#put_attributes('#{@domain_name}', 'conditional', { 'version' => '2' }, :expect => { 'version' => '1' }, :replace => ['version'])").raises(Excon::Errors::Conflict) do Fog::AWS[:simpledb].put_attributes(@domain_name, 'conditional', { 'version' => '2' }, :expect => { 'version' => '1' }, :replace => ['version']) end tests("#delete_attributes('notadomain', 'a')").raises(Excon::Errors::BadRequest) do Fog::AWS[:simpledb].delete_attributes('notadomain', 'a') end end Fog::AWS[:simpledb].delete_domain(@domain_name) end fog-1.19.0/tests/aws/requests/simpledb/domain_tests.rb0000644000004100000410000000303712261242552023035 0ustar www-datawww-dataShindo.tests('AWS::SimpleDB | domain requests', ['aws']) do @domain_metadata_format = AWS::SimpleDB::Formats::BASIC.merge({ 'AttributeNameCount' => Integer, 'AttributeNamesSizeBytes' => Integer, 'AttributeValueCount' => Integer, 'AttributeValuesSizeBytes' => Integer, 'ItemCount' => Integer, 'ItemNamesSizeBytes' => Integer, 'Timestamp' => Time }) @domain_name = "fog_domain_#{Time.now.to_f.to_s.gsub('.','')}" tests('success') do tests("#create_domain(#{@domain_name})").formats(AWS::SimpleDB::Formats::BASIC) do Fog::AWS[:simpledb].create_domain(@domain_name).body end tests("#create_domain(#{@domain_name})").succeeds do Fog::AWS[:simpledb].create_domain(@domain_name) end tests("#domain_metadata(#{@domain_name})").formats(@domain_metadata_format) do Fog::AWS[:simpledb].domain_metadata(@domain_name).body end tests("#list_domains").formats(AWS::SimpleDB::Formats::BASIC.merge('Domains' => [String])) do Fog::AWS[:simpledb].list_domains.body end tests("#delete_domain(#{@domain_name})").formats(AWS::SimpleDB::Formats::BASIC) do Fog::AWS[:simpledb].delete_domain(@domain_name).body end tests("#delete_domain(#{@domain_name})").succeeds do Fog::AWS[:simpledb].delete_domain(@domain_name) end end tests('failure') do tests("#domain_metadata('notadomain')").raises(Excon::Errors::BadRequest) do Fog::AWS[:simpledb].domain_metadata('notadomain') end end end fog-1.19.0/tests/aws/parsers/0000755000004100000410000000000012261242552016021 5ustar www-datawww-datafog-1.19.0/tests/aws/parsers/elb/0000755000004100000410000000000012261242552016563 5ustar www-datawww-datafog-1.19.0/tests/aws/parsers/elb/describe_load_balancers.rb0000644000004100000410000000455612261242552023713 0ustar www-datawww-datarequire 'fog/xml' require 'fog/aws/parsers/elb/describe_load_balancers' DESCRIBE_LOAD_BALANCERS_RESULT = <<-EOF 2013-08-01T15:47:20.930Z fog-test-elb 30 TCP:80 10 5 2 HTTP 80 HTTP 80 us-east-1a fog-test-elb-1965660309.us-east-1.elb.amazonaws.com Z3DZXE0Q79N41H internet-facing amazon-elb amazon-elb-sg fog-test-elb-1965660309.us-east-1.elb.amazonaws.com a6ea2117-fac1-11e2-abd3-1740ab4ef14e EOF Shindo.tests('AWS::ELB | parsers | describe_load_balancers', ['aws', 'elb', 'parser']) do tests('parses the xml').formats(AWS::ELB::Formats::DESCRIBE_LOAD_BALANCERS) do parser = Nokogiri::XML::SAX::Parser.new(Fog::Parsers::AWS::ELB::DescribeLoadBalancers.new) parser.parse(DESCRIBE_LOAD_BALANCERS_RESULT) parser.document.response end end fog-1.19.0/tests/aws/credentials_tests.rb0000644000004100000410000000417412261242552020414 0ustar www-datawww-dataShindo.tests('AWS | credentials', ['aws']) do old_mock_value = Excon.defaults[:mock] Excon.stubs.clear begin Excon.defaults[:mock] = true default_credentials = Fog::Compute::AWS.fetch_credentials({}) Excon.stub({:method => :get, :path => "/latest/meta-data/iam/security-credentials/"}, {:status => 200, :body => 'arole'}) expires_at = Time.at(Time.now.to_i + 500) credentials = { 'AccessKeyId' => 'dummykey', 'SecretAccessKey' => 'dummysecret', 'Token' => 'dummytoken', 'Expiration' => expires_at.xmlschema } Excon.stub({:method => :get, :path => "/latest/meta-data/iam/security-credentials/arole"}, {:status => 200, :body => Fog::JSON.encode(credentials)}) tests("#fetch_credentials") do returns({:aws_access_key_id => 'dummykey', :aws_secret_access_key => 'dummysecret', :aws_session_token => 'dummytoken', :aws_credentials_expire_at => expires_at}) { Fog::Compute::AWS.fetch_credentials(:use_iam_profile => true) } end compute = Fog::Compute::AWS.new(:use_iam_profile => true) tests("#refresh_credentials_if_expired") do returns(nil){compute.refresh_credentials_if_expired} end credentials['AccessKeyId'] = 'newkey' credentials['SecretAccessKey'] = 'newsecret' credentials['Expiration'] = (expires_at + 10).xmlschema Excon.stub({:method => :get, :path => "/latest/meta-data/iam/security-credentials/arole"}, {:status => 200, :body => Fog::JSON.encode(credentials)}) Fog::Time.now = expires_at + 1 tests("#refresh_credentials_if_expired") do returns(true){compute.refresh_credentials_if_expired} returns("newkey"){ compute.instance_variable_get(:@aws_access_key_id)} end Fog::Time.now = Time.now tests("#fetch_credentials when the url 404s") do Excon.stub({:method => :get, :path => "/latest/meta-data/iam/security-credentials/"}, {:status => 404, :body => 'not bound'}) returns(default_credentials) {Fog::Compute::AWS.fetch_credentials(:use_iam_profile => true)} end ensure Excon.stubs.clear Excon.defaults[:mock] = old_mock_value end end fog-1.19.0/tests/aws/models/0000755000004100000410000000000012261242552015625 5ustar www-datawww-datafog-1.19.0/tests/aws/models/storage/0000755000004100000410000000000012261242552017271 5ustar www-datawww-datafog-1.19.0/tests/aws/models/storage/versions_tests.rb0000644000004100000410000000332112261242552022707 0ustar www-datawww-dataShindo.tests("Storage[:aws] | versions", ["aws"]) do file_attributes = { :key => 'fog_file_tests', :body => lorem_file, :public => true } directory_attributes = { :key => uniq_id('fogfilestests') } model_tests(Fog::Storage[:aws].directories, directory_attributes, Fog.mocking?) do @instance.versioning = true versions = [] versions << @instance.service.put_object(@instance.key, 'one', 'abcde').headers['x-amz-version-id'] puts versions.first versions << @instance.service.put_object(@instance.key, 'one', '32423').headers['x-amz-version-id'] versions << @instance.service.delete_object(@instance.key, 'one').headers['x-amz-version-id'] versions.reverse! puts versions.first versions << @instance.service.put_object(@instance.key, 'two', 'aoeu').headers['x-amz-version-id'] tests('#versions') do tests('#versions.size includes versions (including DeleteMarkers) for all keys').returns(4) do @instance.versions.all.size end tests('#versions returns the correct versions').returns(versions) do @instance.versions.all.collect(&:version) end end tests("#all") do tests("#all for a directory returns all versions, regardless of key").returns(versions) do @instance.versions.all.collect(&:version) end tests("#all for file returns only versions for that file").returns(1) do @instance.files.get('two').versions.all.collect(&:version).size end tests("#all for file returns only versions for that file").returns(versions.last) do @instance.files.get('two').versions.all.collect(&:version).first end end @instance.versions.each(&:destroy) end end fog-1.19.0/tests/aws/models/storage/file_tests.rb0000644000004100000410000000421312261242552021757 0ustar www-datawww-dataShindo.tests("Storage[:aws] | file", ["aws"]) do require 'tempfile' file_attributes = { :key => 'fog_file_tests', :body => lorem_file, :public => true } directory_attributes = { :key => uniq_id("fogfilestests") } @directory = Fog::Storage[:aws].directories.create(directory_attributes) model_tests(@directory.files, file_attributes, Fog.mocking?) do tests("#version") do tests("#version should be null if versioning isn't enabled").returns(nil) do @instance.version end end end @directory.versioning = true model_tests(@directory.files, file_attributes, Fog.mocking?) do tests("#version") do tests("#version should not be null if versioning is enabled").returns(false) do @instance.version == nil end end @directory.files.create(:key => @instance.key) @instance.destroy tests("#versions") do tests('#versions.size includes versions (including DeleteMarkers) for all keys').returns(3) do @instance.versions.size end tests('#versions are all for the correct key').returns(true) do # JRuby 1.7.5+ issue causes a SystemStackError: stack level too deep # https://github.com/jruby/jruby/issues/1265 pending if RUBY_PLATFORM == "java" and JRUBY_VERSION =~ /1\.7\.[5-8]/ @instance.versions.all? { |v| v.key == @instance.key } end end tests("#destroy") do tests("#destroy a specific version should delete the version, not create a DeleteMarker").returns(2) do @instance.destroy('versionId' => @instance.version) @instance.versions.all.size end end tests("multipart upload") do pending if Fog.mocking? # A 6MB file @large_file = Tempfile.new("fog-test-aws-s3-multipart") 6.times { @large_file.write("x" * (1024**2)) } @large_file.rewind tests("#save(:multipart_chunk_size => 5242880)").succeeds do @directory.files.create(:key => 'multipart-upload', :body => @large_file, :multipart_chunk_size => 5242880) end @large_file.close end end @directory.versions.each(&:destroy) @directory.destroy end fog-1.19.0/tests/aws/models/storage/directory_tests.rb0000644000004100000410000000462012261242552023046 0ustar www-datawww-dataShindo.tests("Storage[:aws] | directory", ["aws"]) do directory_attributes = { :key => uniq_id('fogdirectorytests') } model_tests(Fog::Storage[:aws].directories, directory_attributes, Fog.mocking?) do tests("#public_url").returns(nil) do @instance.public_url end @instance.acl = 'public-read' @instance.save tests("#public_url").returns(true) do if @instance.public_url =~ %r[\Ahttps://fogdirectorytests-[\da-f]+\.s3\.amazonaws\.com/\z] true else @instance.public_url end end end directory_attributes = { :key => uniq_id('different-region'), :location => 'eu-west-1', } model_tests(Fog::Storage[:aws].directories, directory_attributes, Fog.mocking?) do tests("#location").returns('eu-west-1') do @instance.location end tests("#location").returns('eu-west-1') do Fog::Storage[:aws].directories.get(@instance.identity).location end end directory_attributes = { :key => uniq_id('fogdirectorytests') } model_tests(Fog::Storage[:aws].directories, directory_attributes, Fog.mocking?) do tests("#versioning=") do tests("#versioning=(true)").succeeds do @instance.versioning = true end tests("#versioning=(true) sets versioning to 'Enabled'").returns('Enabled') do @instance.versioning = true @instance.service.get_bucket_versioning(@instance.key).body['VersioningConfiguration']['Status'] end tests("#versioning=(false)").succeeds do (@instance.versioning = false).equal? false end tests("#versioning=(false) sets versioning to 'Suspended'").returns('Suspended') do @instance.versioning = false @instance.service.get_bucket_versioning(@instance.key).body['VersioningConfiguration']['Status'] end end end model_tests(Fog::Storage[:aws].directories, directory_attributes, Fog.mocking?) do tests("#versioning?") do tests("#versioning? false if not enabled").returns(false) do @instance.versioning? end tests("#versioning? true if enabled").returns(true) do @instance.service.put_bucket_versioning(@instance.key, 'Enabled') @instance.versioning? end tests("#versioning? false if suspended").returns(false) do @instance.service.put_bucket_versioning(@instance.key, 'Suspended') @instance.versioning? end end end end fog-1.19.0/tests/aws/models/storage/files_tests.rb0000644000004100000410000000354312261242552022147 0ustar www-datawww-dataShindo.tests("Storage[:aws] | files", ["aws"]) do file_attributes = { :key => 'fog_file_tests', :body => lorem_file, :public => true } directory_attributes = { :key => uniq_id('fogfilestests') } @directory = Fog::Storage[:aws].directories.create(directory_attributes) @directory.versioning = true model_tests(@directory.files, file_attributes, Fog.mocking?) do v1 = @instance.version v2 = @directory.service.put_object(@directory.key, @instance.key, 'version 2 content').headers['x-amz-version-id'] v3 = @directory.service.delete_object(@directory.key, @instance.key).headers['x-amz-version-id'] v4 = @directory.service.put_object(@directory.key, @instance.key, 'version 3 content').headers['x-amz-version-id'] tests("#get") do tests("#get without version fetches the latest version").returns(v4) do @directory.files.get(@instance.key).version end tests("#get with version fetches that exact version").returns(v2) do @directory.files.get(@instance.key, 'versionId' => v2).version end tests("#get with a deleted version returns nil").returns(nil) do pending # getting 405 Method Not Allowed @directory.files.get(@instance.key, 'versionId' => v3) end end tests("#head") do tests("#head without version fetches the latest version").returns(v4) do @directory.files.head(@instance.key).version end tests("#head with version fetches that exact version").returns(v2) do @directory.files.head(@instance.key, 'versionId' => v2).version end tests("#head with a deleted version returns nil").returns(nil) do pending # getting 405 Method Not Allowed @directory.files.head(@instance.key, 'versionId' => v3) end end end @directory.versions.each(&:destroy) @directory.destroy end fog-1.19.0/tests/aws/models/storage/url_tests.rb0000644000004100000410000000154112261242552021643 0ustar www-datawww-data# encoding: utf-8 Shindo.tests('AWS | url', ["aws"]) do @expires = Time.utc(2013,1,1).utc.to_i @storage = Fog::Storage.new( :provider => 'AWS', :aws_access_key_id => '123', :aws_secret_access_key => 'abc', :region => 'us-east-1' ) @file = @storage.directories.new(:key => 'fognonbucket').files.new(:key => 'test.txt') if Fog.mock? signature = Fog::Storage::AWS.new.signature(nil, nil) else signature = 'tajHIhKHAdFYsigmzybCpaq8N0Q%3D' end if RUBY_VERSION > '1.8.7' # ruby 1.8.x doesn't provide hash ordering tests('#url w/ response-cache-control').returns( "https://fognonbucket.s3.amazonaws.com/test.txt?response-cache-control=No-cache&AWSAccessKeyId=123&Signature=#{signature}&Expires=1356998400" ) do @file.url(@expires, :query => { 'response-cache-control' => 'No-cache' }) end end end fog-1.19.0/tests/aws/models/storage/version_tests.rb0000644000004100000410000000261612261242552022532 0ustar www-datawww-dataShindo.tests("Storage[:aws] | version", ["aws"]) do file_attributes = { :key => 'fog_file_tests', :body => lorem_file, :public => true } directory_attributes = { :key => uniq_id('fogfilestests') } @directory = Fog::Storage[:aws].directories.create(directory_attributes) @directory.versioning = true model_tests(@directory.files, file_attributes, Fog.mocking?) do @version_instance = @instance.versions.first @directory.service.put_object(@directory.key, @instance.key, 'second version content') tests("#file") do tests("#file should return the object associated with the version").returns(@version_instance.version) do @version_instance.file.version end end tests("#delete_marker") do tests("#delete_marker should be false if the version isn't a DeleteMarker'").returns(false) do @version_instance.delete_marker end tests("#delete_marker should be true if the version is a DeleteMarker'").returns(true) do @instance.destroy @instance.versions.all.first.delete_marker end end tests("#destroy") do tests("#destroy removes the specific version").returns(false) do @version_instance.destroy @instance.versions.all.collect(&:version).include?(@version_instance.version) end end end @directory.versions.each(&:destroy) @directory.destroy end fog-1.19.0/tests/aws/models/auto_scaling/0000755000004100000410000000000012261242552020275 5ustar www-datawww-datafog-1.19.0/tests/aws/models/auto_scaling/groups_test.rb0000644000004100000410000000127512261242552023205 0ustar www-datawww-dataShindo.tests('AWS::AutoScaling | group', ['aws', 'auto_scaling_m']) do params = { :id => uniq_id, :auto_scaling_group_name => "name", :availability_zones => [], :launch_configuration_name => "lc" } lc_params = { :id => params[:launch_configuration_name], :image_id => "image-id", :instance_type => "instance-type", } Fog::AWS[:auto_scaling].configurations.new(lc_params).save model_tests(Fog::AWS[:auto_scaling].groups, params, true) do @instance.update end test("setting attributes in the constructor") do group = Fog::AWS[:auto_scaling].groups.new(:min_size => 1, :max_size => 2) group.min_size == 1 && group.max_size == 2 end end fog-1.19.0/tests/aws/models/auto_scaling/helper.rb0000644000004100000410000000000012261242552022067 0ustar www-datawww-datafog-1.19.0/tests/aws/models/auto_scaling/instances_tests.rb0000644000004100000410000000030312261242552024027 0ustar www-datawww-dataShindo.tests('AWS::AutoScaling | instances', ['aws', 'auto_scaling_m']) do pending # FIXME: instance#save is not defined #collection_tests(Fog::AWS[:auto_scaling].instances, {}, false) end fog-1.19.0/tests/aws/models/auto_scaling/configurations_tests.rb0000644000004100000410000000041012261242552025071 0ustar www-datawww-dataShindo.tests('AWS::AutoScaling | configurations', ['aws', 'auto_scaling_m']) do params = { :id => uniq_id, :image_id => 'ami-8c1fece5', :instance_type => 't1.micro' } collection_tests(Fog::AWS[:auto_scaling].configurations, params, false) end fog-1.19.0/tests/aws/models/auto_scaling/configuration_test.rb0000644000004100000410000000045512261242552024534 0ustar www-datawww-dataShindo.tests('AWS::AutoScaling | configuration', ['aws', 'auto_scaling_m']) do params = { :id => uniq_id, :image_id => 'ami-8c1fece5', :instance_type => 't1.micro' } model_tests(Fog::AWS[:auto_scaling].configurations, params, false) do @instance.wait_for { ready? } end end fog-1.19.0/tests/aws/models/auto_scaling/activities_tests.rb0000644000004100000410000000031012261242552024202 0ustar www-datawww-dataShindo.tests('AWS::AutoScaling | activities', ['aws', 'auto_scaling_m']) do pending # FIXME: activity#save is not implemented collection_tests(Fog::AWS[:auto_scaling].activities, {}, false) end fog-1.19.0/tests/aws/models/beanstalk/0000755000004100000410000000000012261242552017571 5ustar www-datawww-datafog-1.19.0/tests/aws/models/beanstalk/versions_tests.rb0000644000004100000410000000253012261242552023210 0ustar www-datawww-dataShindo.tests("Fog::AWS[:beanstalk] | versions", ['aws', 'beanstalk']) do pending if Fog.mocking? @beanstalk = Fog::AWS[:beanstalk] @application_name = uniq_id('fog-test-app') @version_name = uniq_id('fog-test-version') @version_description = 'A nice description' @application = @beanstalk.applications.create({:name => @application_name}) params = { :application_name => @application_name, :label => @version_name, :description => @version_description } collection = @beanstalk.versions tests('success') do tests("#new(#{params.inspect})").succeeds do pending if Fog.mocking? collection.new(params) end tests("#create(#{params.inspect})").succeeds do pending if Fog.mocking? @instance = collection.create(params) end tests("#all").succeeds do pending if Fog.mocking? collection.all end tests("#get(#{@application_name}, #{@version_name})").succeeds do pending if Fog.mocking? collection.get(@application_name, @version_name) end if !Fog.mocking? @instance.destroy end end tests('failure') do tests("#get(#{@application_name}, #{@version_name})").returns(nil) do pending if Fog.mocking? collection.get(@application_name, @version_name) end end # delete application @application.destroy endfog-1.19.0/tests/aws/models/beanstalk/environment_tests.rb0000644000004100000410000000646312261242552023715 0ustar www-datawww-dataShindo.tests("Fog::AWS[:beanstalk] | environment", ['aws', 'beanstalk']) do pending if Fog.mocking? @beanstalk = Fog::AWS[:beanstalk] @application_name = uniq_id('fog-test-app') @environment_name = uniq_id('fog-test-env') @version_names = [] # Create two unique version names 2.times { @version_names << uniq_id('fog-test-version') } @application = @beanstalk.applications.create({:name => @application_name}) @versions = [] @version_names.each { |name| @versions << @beanstalk.versions.create({ :label => name, :application_name => @application_name, }) } @environment_opts = { :application_name => @application_name, :name => @environment_name, :version_label => @version_names[0], :solution_stack_name => '32bit Amazon Linux running Tomcat 7' } # Note: These model tests can take quite a bit of time to run, about 10 minutes typically. model_tests(@beanstalk.environments, @environment_opts, false) do # Wait for initial ready before next tests. tests("#ready?").succeeds do @instance.wait_for { ready? } end tests("#healthy?").succeeds do @instance.wait_for { healthy? } end test("#events") do # There should be some events now. @instance.events.length > 0 end test("#version") do @instance.version.label == @version_names[0] end test("#version= string") do # Set to version 2 @instance.version = @version_names[1] count = 0 if @instance.version.label == @version_names[1] @instance.events.each { |event| if event.message == "Environment update is starting." count = count + 1 end } end count == 1 end tests("#ready? after version= string").succeeds do @instance.wait_for { ready? } end test("#version= version object") do # reset back to first version using version object @instance.version = @versions[0] count = 0 if @instance.version.label == @version_names[0] @instance.events.each { |event| if event.message == "Environment update is starting." count = count + 1 end } end # Pass if we have two environment updating events count == 2 end tests("#ready? after version= version object").succeeds do @instance.wait_for { ready? } end test('#restart_app_server') do @instance.restart_app_server passed = false @instance.events.each { |event| if event.message == "restartAppServer is starting." passed = true end } passed end test('#rebuild') do @instance.rebuild passed = false @instance.events.each { |event| if event.message == "rebuildEnvironment is starting." passed = true end } passed end # Wait for ready or next tests may fail tests("#ready? after rebuild").succeeds do @instance.wait_for { ready? } end end # Wait for instance to terminate before deleting application tests('#terminated?').succeeds do @instance.wait_for { terminated? } end # delete application @application.destroy end fog-1.19.0/tests/aws/models/beanstalk/template_tests.rb0000644000004100000410000000244312261242552023156 0ustar www-datawww-dataShindo.tests("Fog::AWS[:beanstalk] | template", ['aws', 'beanstalk']) do pending if Fog.mocking? @beanstalk = Fog::AWS[:beanstalk] @application_name = uniq_id('fog-test-app') @template_name = uniq_id('fog-test-template') @template_description = 'A nice description' @application = @beanstalk.applications.create({:name => @application_name}) @template_opts = { :application_name => @application_name, :name => @template_name, :description => @template_description, :solution_stack_name => '32bit Amazon Linux running Tomcat 7' } model_tests(@beanstalk .templates, @template_opts, false) do test("#attributes") do @instance.name == @template_name && @instance.description == @template_description && @instance.application_name == @application_name && @instance.solution_stack_name == @template_opts[:solution_stack_name] end test("#options") do options = @instance.options passed = false if options.each { |option| # See if we recognize at least one option if option["Name"] == 'LoadBalancerHTTPPort' && option["Namespace"] == 'aws:elb:loadbalancer' passed = true end } end passed end end # delete application @application.destroy end fog-1.19.0/tests/aws/models/beanstalk/application_tests.rb0000644000004100000410000000352212261242552023645 0ustar www-datawww-dataShindo.tests("Fog::AWS[:beanstalk] | application", ['aws', 'beanstalk']) do pending if Fog.mocking? @application_opts = { :name => uniq_id('fog-test-app'), :description => 'A nice description.' } model_tests(Fog::AWS[:beanstalk].applications, @application_opts, false) do test("#attributes") do @instance.name == @application_opts[:name] && @instance.description == @application_opts[:description] end test("#events") do # There should be some events now. @instance.events.length > 0 end version_name = uniq_id('fog-test-ver') @instance.versions.create( :application_name => @instance.name, :label => version_name ) test("#versions") do # We should have one version. @instance.versions.length == 1 end template_name = uniq_id('fog-test-template') @instance.templates.create( :application_name => @instance.name, :name => template_name, :solution_stack_name => '32bit Amazon Linux running Tomcat 7' ) test('#templates') do # We should have one template now. @instance.templates.length == 1 end environment_name = uniq_id('fog-test-env') environment = @instance.environments.create( :application_name => @instance.name, :name => environment_name, :version_label => version_name, :solution_stack_name => '32bit Amazon Linux running Tomcat 7' ) # Go ahead an terminate immediately. environment.destroy # Create an environment test("#environments") do # We should have one environment now. @instance.environments.length == 1 end # Must wait for termination before destroying application tests("waiting for test environment to terminate").succeeds do environment.wait_for { terminated? } end end end fog-1.19.0/tests/aws/models/beanstalk/applications_tests.rb0000644000004100000410000000031712261242552024027 0ustar www-datawww-dataShindo.tests("Fog::AWS[:beanstalk] | applications", ['aws', 'beanstalk']) do pending if Fog.mocking? collection_tests(Fog::AWS[:beanstalk].applications, {:name => uniq_id('fog-test-app')}, false) end fog-1.19.0/tests/aws/models/beanstalk/templates_tests.rb0000644000004100000410000000264712261242552023347 0ustar www-datawww-dataShindo.tests("Fog::AWS[:beanstalk] | templates", ['aws', 'beanstalk']) do pending if Fog.mocking? @beanstalk = Fog::AWS[:beanstalk] @application_name = uniq_id('fog-test-app') @template_name = uniq_id('fog-test-template') @template_description = 'A nice description' @application = @beanstalk.applications.create({:name => @application_name}) params = { :application_name => @application_name, :name => @template_name, :description => @template_description, :solution_stack_name => '32bit Amazon Linux running Tomcat 7' } collection = @beanstalk.templates tests('success') do tests("#new(#{params.inspect})").succeeds do pending if Fog.mocking? collection.new(params) end tests("#create(#{params.inspect})").succeeds do pending if Fog.mocking? @instance = collection.create(params) end tests("#all").succeeds do pending if Fog.mocking? collection.all end tests("#get(#{@application_name}, #{@template_name})").succeeds do pending if Fog.mocking? collection.get(@application_name, @template_name) end if !Fog.mocking? @instance.destroy end end tests('failure') do tests("#get(#{@application_name}, #{@template_name})").returns(nil) do pending if Fog.mocking? collection.get(@application_name, @template_name) end end # delete application @application.destroy endfog-1.19.0/tests/aws/models/beanstalk/environments_tests.rb0000644000004100000410000000200412261242552024063 0ustar www-datawww-dataShindo.tests("Fog::AWS[:beanstalk] | environments", ['aws', 'beanstalk']) do pending if Fog.mocking? @beanstalk = Fog::AWS[:beanstalk] @application_name = uniq_id('fog-test-app') @environment_name = uniq_id('fog-test-env') @version_name = uniq_id('fog-test-version') # Create an application/version to use for testing. @version = @beanstalk.versions.create({ :label => @version_name, :application_name => @application_name, :auto_create_application => true }) @application = @beanstalk.applications.get(@application_name) @environment_opts = { :application_name => @application_name, :name => @environment_name, :version_label => @version_name, :solution_stack_name => '32bit Amazon Linux running Tomcat 7' } collection_tests(@beanstalk.environments, @environment_opts, false) # Wait for instance to terminate before deleting application @instance.wait_for { terminated? } # delete application @application.destroy endfog-1.19.0/tests/aws/models/beanstalk/version_tests.rb0000644000004100000410000000347712261242552023040 0ustar www-datawww-dataShindo.tests("Fog::AWS[:beanstalk] | version", ['aws', 'beanstalk']) do pending if Fog.mocking? @beanstalk = Fog::AWS[:beanstalk] @application_name = uniq_id('fog-test-app') @version_name = uniq_id('fog-test-version') @version_description = 'A nice description' @application = @beanstalk.applications.create({:name => @application_name}) @version_opts = { :application_name => @application_name, :label => @version_name, :description => @version_description } model_tests(@beanstalk.versions, @version_opts, false) do test("attributes") do @instance.label == @version_name && @instance.description == @version_description && @instance.application_name == @application_name end test("#events") do # There should be some events now. @instance.events.length > 0 end test("#update description") do new_description = "A completely new description." @instance.description = new_description @instance.update passed = false if @instance.description == new_description # reload version from AWS to verify save is committed to server, not just on local object if @beanstalk.versions.get(@application_name, @version_name).description == new_description passed = true end end passed end test("#update description empty") do @instance.description = '' # Set to empty to nil out @instance.update passed = false if @instance.description == nil # reload version from AWS to verify save is committed to server, not just on local object if @beanstalk.versions.get(@application_name, @version_name).description == nil passed = true end end passed end end # delete application @application.destroy end fog-1.19.0/tests/aws/models/cloud_watch/0000755000004100000410000000000012261242552020121 5ustar www-datawww-datafog-1.19.0/tests/aws/models/cloud_watch/alarm_data_tests.rb0000644000004100000410000000213512261242552023756 0ustar www-datawww-dataShindo.tests("AWS::CloudWatch | alarm_data", ['aws', 'cloudwatch']) do pending if Fog.mocking? tests('success') do tests("#all").succeeds do Fog::AWS[:cloud_watch].alarm_data.all end alarm_name_prefix = {'AlarmNamePrefix'=>'tmp'} tests("#all_by_prefix").succeeds do Fog::AWS[:cloud_watch].alarm_data.all(alarm_name_prefix) end namespace = 'AWS/EC2' metric_name = 'CPUUtilization' tests("#get").succeeds do Fog::AWS[:cloud_watch].alarm_data.get(namespace, metric_name).to_json end new_attributes = { :alarm_name => 'tmp-alarm', :comparison_operator => 'GreaterThanOrEqualToThreshold', :evaluation_periods => 1, :metric_name => 'tmp-metric-alarm', :namespace => 'fog-0.11.0', :period => 60, :statistic => 'Sum', :threshold => 5 } tests('#new').returns(new_attributes) do Fog::AWS[:cloud_watch].alarm_data.new(new_attributes).attributes end tests('#create').returns(new_attributes) do Fog::AWS[:cloud_watch].alarm_data.create(new_attributes).attributes end end end fog-1.19.0/tests/aws/models/cloud_watch/metrics_tests.rb0000644000004100000410000000171212261242552023337 0ustar www-datawww-dataShindo.tests("AWS::CloudWatch | metrics", ['aws', 'cloudwatch']) do tests('success') do pending # FIXME: the hardcoded instance id won't be available tests("#all").succeeds do Fog::AWS[:cloud_watch].metrics.all end instanceId = 'i-fd713391' metricName = 'CPUUtilization' namespace = 'AWS/EC2' tests("#get").returns({:dimensions=>[{"Name"=>"InstanceId", "Value"=>instanceId}], :name=>metricName, :namespace=>namespace}) do Fog::AWS[:cloud_watch].metrics.get(namespace, metricName, {'InstanceId' => instanceId}).attributes end end tests('#each') do Fog.mock! tests("handle NextToken").returns(1001) do count = 0 Fog::AWS[:cloud_watch].metrics.each {|e| count += 1 } count end tests("yields Metrics instances").succeeds do all = [] Fog::AWS[:cloud_watch].metrics.each {|e| all << e } all.all? {|e| e.is_a?(Fog::AWS::CloudWatch::Metric) } end end end fog-1.19.0/tests/aws/models/cloud_watch/metric_statistics_tests.rb0000644000004100000410000000313212261242552025424 0ustar www-datawww-dataShindo.tests("AWS::CloudWatch | metric_statistics", ['aws', 'cloudwatch']) do tests('success') do pending if Fog.mocking? instanceId = 'i-420c352f' metricName = 'DiskReadBytes' namespace = 'AWS/EC2' startTime = (Time.now-600).iso8601 endTime = Time.now.iso8601 period = 60 statisticTypes = ['Minimum','Maximum','Sum','SampleCount','Average'] tests("#all").succeeds do @statistics = Fog::AWS[:cloud_watch].metric_statistics.all({'Statistics' => statisticTypes, 'StartTime' => startTime, 'EndTime' => endTime, 'Period' => period, 'MetricName' => metricName, 'Namespace' => namespace, 'Dimensions' => [{'Name' => 'InstanceId', 'Value' => instanceId}]}) end tests("#all_not_empty").returns(true) do @statistics.length > 0 end new_attributes = { :namespace => 'Custom/Test', :metric_name => 'ModelTest', :value => 9, :unit => 'None' } tests('#new').returns(new_attributes) do Fog::AWS[:cloud_watch].metric_statistics.new(new_attributes).attributes end tests('#create').returns(new_attributes) do Fog::AWS[:cloud_watch].metric_statistics.create(new_attributes).attributes end stats_set_attributes = { :namespace => 'Custom/Test', :metric_name => 'ModelTest', :minimum => 0, :maximum => 4, :sum => 10, :sample_count => 5, :average => 2, :unit => 'None' } tests('#create_stats_set').returns(stats_set_attributes) do Fog::AWS[:cloud_watch].metric_statistics.create(stats_set_attributes).attributes end end endfog-1.19.0/tests/aws/models/cloud_watch/alarm_history_tests.rb0000644000004100000410000000102212261242552024540 0ustar www-datawww-dataShindo.tests("AWS::CloudWatch | alarm_histories", ['aws', 'cloudwatch']) do pending if Fog.mocking? tests('success') do tests("#all").succeeds do Fog::AWS[:cloud_watch].alarm_histories.all end new_attributes = { :alarm_name => 'tmp-alarm', :end_date => '', :history_item_type => 'StateUpdate', :max_records => 1, :start_date => '' } tests('#new').returns(new_attributes) do Fog::AWS[:cloud_watch].alarm_histories.new(new_attributes).attributes end end end fog-1.19.0/tests/aws/models/glacier/0000755000004100000410000000000012261242552017233 5ustar www-datawww-datafog-1.19.0/tests/aws/models/glacier/model_tests.rb0000644000004100000410000000275212261242552022110 0ustar www-datawww-dataShindo.tests('AWS::Glacier | models', ['aws', 'glacier']) do pending if Fog.mocking? tests('success') do tests('vaults') do tests('getting a missing vault') do returns(nil) { Fog::AWS[:glacier].vaults.get('no-such-vault') } end vault = nil tests('creating a vault') do vault = Fog::AWS[:glacier].vaults.create :id => 'Fog-Test-Vault' tests("id is Fog-Test-Vault").returns('Fog-Test-Vault') {vault.id} end tests('all') do tests('contains vault').returns(true) { Fog::AWS[:glacier].vaults.collect {|vault| vault.id}.include?(vault.id)} end tests('destroy') do vault.destroy tests('removes vault').returns(nil) {Fog::AWS[:glacier].vaults.get(vault.id)} end end tests("archives") do vault = Fog::AWS[:glacier].vaults.create :id => 'Fog-Test-Vault-upload' tests('create') do archive = vault.archives.create(:body => 'data') tests('sets id').returns(true) {!archive.id.nil?} archive.destroy end tests('create multipart') do body = StringIO.new('x'*1024*1024*2) body.rewind archive = vault.archives.create(:body => body, :multipart_chunk_size => 1024*1024) tests('sets id').returns(true) {!archive.id.nil?} archive.destroy end end vault = Fog::AWS[:glacier].vaults.create :id => 'Fog-Test-Vault' tests("jobs") do tests('all').returns([]) {vault.jobs} end vault.destroy end endfog-1.19.0/tests/aws/models/dns/0000755000004100000410000000000012261242552016411 5ustar www-datawww-datafog-1.19.0/tests/aws/models/dns/zones_tests.rb0000644000004100000410000000023712261242552021320 0ustar www-datawww-dataShindo.tests("Fog::DNS[:aws] | zones", ['aws', 'dns']) do params = {:domain => generate_unique_domain } collection_tests(Fog::DNS[:aws].zones, params) end fog-1.19.0/tests/aws/models/dns/zone_tests.rb0000644000004100000410000000023112261242552021127 0ustar www-datawww-dataShindo.tests("Fog::DNS[:aws] | zone", ['aws', 'dns']) do params = {:domain => generate_unique_domain } model_tests(Fog::DNS[:aws].zones, params) end fog-1.19.0/tests/aws/models/dns/records_tests.rb0000644000004100000410000000206512261242552021624 0ustar www-datawww-dataShindo.tests("Fog::DNS[:aws] | records", ['aws', 'dns']) do tests("zones#create").succeeds do @zone = Fog::DNS[:aws].zones.create(:domain => generate_unique_domain) end param_groups = [ # A record { :name => @zone.domain, :type => 'A', :ttl => 3600, :value => ['1.2.3.4'] }, # CNAME record { :name => "www.#{@zone.domain}", :type => "CNAME", :ttl => 300, :value => @zone.domain} ] param_groups.each do |params| collection_tests(@zone.records, params) end records = [] 100.times do |i| records << @zone.records.create(:name => "#{i}.#{@zone.domain}", :type => "A", :ttl => 3600, :value => ['1.2.3.4']) end records << @zone.records.create(:name => "*.#{@zone.domain}", :type => "A", :ttl => 3600, :value => ['1.2.3.4']) tests("#all!").returns(101) do @zone.records.all!.size end tests("#all wildcard parsing").returns(true) do @zone.records.map(&:name).include?("*.#{@zone.domain}") end records.each do |record| record.destroy end tests("zones#destroy").succeeds do @zone.destroy end end fog-1.19.0/tests/aws/models/dns/record_tests.rb0000644000004100000410000000161112261242552021435 0ustar www-datawww-dataShindo.tests("Fog::Dns[:aws] | record", ['aws', 'dns']) do tests("zones#create").succeeds do @zone = Fog::DNS[:aws].zones.create(:domain => generate_unique_domain) end params = { :name => @zone.domain, :type => 'A', :ttl => 3600, :value => ['1.2.3.4'] } model_tests(@zone.records, params) do # Newly created records should have a change id tests("#change_id") do returns(true) { @instance.change_id != nil } end # Waits for changes to sync to all Route 53 DNS servers. Usually takes ~30 seconds to complete. tests("#ready? - may take a minute to complete...").succeeds do @instance.wait_for { ready? } end tests("#modify") do new_value = ['5.5.5.5'] returns(true) { @instance.modify(:value => new_value) } returns(new_value) { @instance.value } end end tests("zones#destroy").succeeds do @zone.destroy end end fog-1.19.0/tests/aws/models/elb/0000755000004100000410000000000012261242552016367 5ustar www-datawww-datafog-1.19.0/tests/aws/models/elb/model_tests.rb0000644000004100000410000003207212261242552021242 0ustar www-datawww-dataShindo.tests('AWS::ELB | models', ['aws', 'elb']) do require 'fog' @availability_zones = Fog::Compute[:aws].describe_availability_zones('state' => 'available').body['availabilityZoneInfo'].collect{ |az| az['zoneName'] } @key_name = 'fog-test-model' @vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24') @vpc_id = @vpc.id @subnet = Fog::Compute[:aws].subnets.create({:vpc_id => @vpc_id, :cidr_block => '10.0.10.0/24'}) @subnet_id = @subnet.subnet_id @scheme = 'internal' @igw=Fog::Compute[:aws].internet_gateways.create @igw_id = @igw.id @igw.attach(@vpc_id) tests('success') do tests('load_balancers') do tests('getting a missing elb') do returns(nil) { Fog::AWS[:elb].load_balancers.get('no-such-elb') } end end tests('listeners') do tests("default attributes") do listener = Fog::AWS[:elb].listeners.new tests('instance_port is 80').returns(80) { listener.instance_port } tests('instance_protocol is HTTP').returns('HTTP') { listener.instance_protocol } tests('lb_port is 80').returns(80) { listener.lb_port } tests('protocol is HTTP').returns('HTTP') { listener.protocol } tests('policy_names is empty').returns([]) { listener.policy_names } end tests("specifying attributes") do attributes = {:instance_port => 2000, :instance_protocol => 'SSL', :lb_port => 2001, :protocol => 'SSL', :policy_names => ['fake'] } listener = Fog::AWS[:elb].listeners.new(attributes) tests('instance_port is 2000').returns(2000) { listener.instance_port } tests('instance_protocol is SSL').returns('SSL') { listener.instance_protocol } tests('lb_port is 2001').returns(2001) { listener.lb_port } tests('protocol is SSL').returns('SSL') { listener.protocol } tests('policy_names is [ fake ]').returns(['fake']) { listener.policy_names } end end elb = nil elb_id = 'fog-test' tests('create') do tests('without availability zones') do elb = Fog::AWS[:elb].load_balancers.create(:id => elb_id, :availability_zones => @availability_zones) tests("availability zones are correct").returns(@availability_zones.sort) { elb.availability_zones.sort } tests("dns names is set").returns(true) { elb.dns_name.is_a?(String) } tests("created_at is set").returns(true) { Time === elb.created_at } tests("policies is empty").returns([]) { elb.policies } tests("default listener") do tests("1 listener").returns(1) { elb.listeners.size } tests("params").returns(Fog::AWS[:elb].listeners.new.to_params) { elb.listeners.first.to_params } end end tests('with vpc') do Fog::Compute[:aws].ec2_compatibility_mode(false) elb2 = Fog::AWS[:elb].load_balancers.create(:id => "#{elb_id}-2", :subnet_ids => [@subnet_id]) tests("elb source group should be default_elb*").returns(true) { !!(elb2.source_group["GroupName"] =~ /default_elb_*/) } tests("should have a 'default_elb_*' security group").returns(true) { Fog::Compute[:aws].security_groups.all.any? { |sg| sg.name =~ /default_elb/ } } tests("subnet ids are correct").returns(@subnet_id) { elb2.subnet_ids.first } elb2.destroy end tests('with vpc internal') do elb2 = Fog::AWS[:elb].load_balancers.create(:id => "#{elb_id}-2", :subnet_ids => [@subnet_id], :scheme => 'internal') tests("scheme is internal").returns(@scheme) { elb2.scheme } elb2.destroy end if !Fog.mocking? @igw.detach(@vpc_id) @igw.destroy @subnet.destroy sleep 5 @vpc.destroy end tests('with availability zones') do Fog::Compute[:aws].ec2_compatibility_mode(true) azs = @availability_zones[1..-1] elb2 = Fog::AWS[:elb].load_balancers.create(:id => "#{elb_id}-2", :availability_zones => azs) tests("elb source group should be amazon-elb-sg").returns(true) { elb2.source_group["GroupName"] == 'amazon-elb-sg' } tests("availability zones are correct").returns(azs.sort) { elb2.availability_zones.sort } elb2.destroy end # Need to sleep here for IAM changes to propgate tests('with ListenerDescriptions') do @certificate = Fog::AWS[:iam].upload_server_certificate(AWS::IAM::SERVER_CERT, AWS::IAM::SERVER_CERT_PRIVATE_KEY, @key_name).body['Certificate'] sleep(10) unless Fog.mocking? listeners = [{ 'Listener' => { 'LoadBalancerPort' => 2030, 'InstancePort' => 2030, 'Protocol' => 'HTTP' }, 'PolicyNames' => [] }, { 'Listener' => { 'LoadBalancerPort' => 443, 'InstancePort' => 443, 'Protocol' => 'HTTPS', 'InstanceProtocol' => 'HTTPS', 'SSLCertificateId' => @certificate['Arn'] }, 'PolicyNames' => [] }] elb3 = Fog::AWS[:elb].load_balancers.create(:id => "#{elb_id}-3", 'ListenerDescriptions' => listeners, :availability_zones => @availability_zones) tests('there are 2 listeners').returns(2) { elb3.listeners.count } tests('instance_port is 2030').returns(2030) { elb3.listeners.first.instance_port } tests('lb_port is 2030').returns(2030) { elb3.listeners.first.lb_port } tests('protocol is HTTP').returns('HTTP') { elb3.listeners.first.protocol } tests('protocol is HTTPS').returns('HTTPS') { elb3.listeners.last.protocol } tests('instance_protocol is HTTPS').returns('HTTPS') { elb3.listeners.last.instance_protocol } elb3.destroy end tests('with invalid Server Cert ARN').raises(Fog::AWS::IAM::NotFound) do listeners = [{ 'Listener' => { 'LoadBalancerPort' => 443, 'InstancePort' => 80, 'Protocol' => 'HTTPS', 'InstanceProtocol' => 'HTTPS', "SSLCertificateId" => "fakecert"} }] Fog::AWS[:elb].load_balancers.create(:id => "#{elb_id}-4", "ListenerDescriptions" => listeners, :availability_zones => @availability_zones) end end tests('all') do elb_ids = Fog::AWS[:elb].load_balancers.all.map{|e| e.id} tests("contains elb").returns(true) { elb_ids.include? elb_id } end if Fog.mocking? tests('all marker support') do extra_elb_ids = (1..1000).map {|n| Fog::AWS[:elb].load_balancers.create(:id => "#{elb_id}-extra-#{n}").id } tests('returns all elbs').returns(true) { (extra_elb_ids - Fog::AWS[:elb].load_balancers.all.map {|e| e.id }).empty? } end end tests('get') do tests('ids match').returns(elb_id) { Fog::AWS[:elb].load_balancers.get(elb_id).id } tests('nil id').returns(nil) { Fog::AWS[:elb].load_balancers.get(nil) } end tests('creating a duplicate elb') do raises(Fog::AWS::ELB::IdentifierTaken) do Fog::AWS[:elb].load_balancers.create(:id => elb_id, :availability_zones => ['us-east-1d']) end end tests('registering an invalid instance') do raises(Fog::AWS::ELB::InvalidInstance) { elb.register_instances('i-00000000') } end tests('deregistering an invalid instance') do raises(Fog::AWS::ELB::InvalidInstance) { elb.deregister_instances('i-00000000') } end server = Fog::Compute[:aws].servers.create server.wait_for { ready? } tests('register instance') do begin elb.register_instances(server.id) rescue Fog::AWS::ELB::InvalidInstance # It may take a moment for a newly created instances to be visible to ELB requests raise if @retried_registered_instance @retried_registered_instance = true sleep 1 retry end returns([server.id]) { elb.instances } end tests('instance_health') do returns('OutOfService') do elb.instance_health.detect{|hash| hash['InstanceId'] == server.id}['State'] end returns([server.id]) { elb.instances_out_of_service } end tests('deregister instance') do elb.deregister_instances(server.id) returns([]) { elb.instances } end server.destroy tests('disable_availability_zones') do elb.disable_availability_zones(@availability_zones[1..-1]) returns(@availability_zones[0..0]) { elb.availability_zones.sort } end tests('enable_availability_zones') do elb.enable_availability_zones(@availability_zones[1..-1]) returns(@availability_zones) { elb.availability_zones.sort } end tests('cross_zone_load_balancing') do returns(false) {elb.cross_zone_load_balancing?} elb.cross_zone_load_balancing = true returns(true) {elb.cross_zone_load_balancing?} end tests('default health check') do default_health_check = { "HealthyThreshold"=>10, "Timeout"=>5, "UnhealthyThreshold"=>2, "Interval"=>30, "Target"=>"TCP:80" } returns(default_health_check) { elb.health_check } end tests('configure_health_check') do new_health_check = { "HealthyThreshold"=>5, "Timeout"=>10, "UnhealthyThreshold"=>3, "Interval"=>15, "Target"=>"HTTP:80/index.html" } elb.configure_health_check(new_health_check) returns(new_health_check) { elb.health_check } end tests('listeners') do tests('default') do returns(1) { elb.listeners.size } listener = elb.listeners.first returns([80,80,'HTTP','HTTP', []]) { [listener.instance_port, listener.lb_port, listener.protocol, listener.instance_protocol, listener.policy_names] } end tests('#get') do returns(80) { elb.listeners.get(80).lb_port } end tests('create') do new_listener = { 'InstancePort' => 443, 'LoadBalancerPort' => 443, 'Protocol' => 'TCP', 'InstanceProtocol' => 'TCP'} elb.listeners.create(:instance_port => 443, :lb_port => 443, :protocol => 'TCP', :instance_protocol => 'TCP') returns(2) { elb.listeners.size } returns(443) { elb.listeners.get(443).lb_port } end tests('destroy') do elb.listeners.get(443).destroy returns(nil) { elb.listeners.get(443) } end end tests('policies') do app_policy_id = 'my-app-policy' tests 'are empty' do returns([]) { elb.policies.to_a } end tests('#all') do returns([]) { elb.policies.all.to_a } end tests('create app policy') do elb.policies.create(:id => app_policy_id, :cookie => 'my-app-cookie', :cookie_stickiness => :app) returns(app_policy_id) { elb.policies.first.id } returns("my-app-cookie") { elb.policies.get(app_policy_id).cookie } end tests('get policy') do returns(app_policy_id) { elb.policies.get(app_policy_id).id } end tests('destroy app policy') do elb.policies.first.destroy returns([]) { elb.policies.to_a } end lb_policy_id = 'my-lb-policy' tests('create lb policy') do elb.policies.create(:id => lb_policy_id, :expiration => 600, :cookie_stickiness => :lb) returns(lb_policy_id) { elb.policies.first.id } end tests('setting a listener policy') do elb.set_listener_policy(80, lb_policy_id) returns([lb_policy_id]) { elb.listeners.get(80).policy_names } returns(600) { elb.policies.get(lb_policy_id).expiration } end tests('unsetting a listener policy') do elb.unset_listener_policy(80) returns([]) { elb.listeners.get(80).policy_names } end public_key_policy_id = 'fog-public-key-policy' tests('create public key policy') do elb.policies.create(:id => public_key_policy_id, :type_name => 'PublicKeyPolicyType', :policy_attributes => {'PublicKey' => AWS::IAM::SERVER_CERT_PUBLIC_KEY}) policy = elb.policies.get(public_key_policy_id) returns(public_key_policy_id) { policy.id } returns("PublicKeyPolicyType") { policy.type_name } returns(AWS::IAM::SERVER_CERT_PUBLIC_KEY) { policy.policy_attributes["PublicKey"] } end tests('a malformed policy') do raises(ArgumentError) { elb.policies.create(:id => 'foo', :cookie_stickiness => 'invalid stickiness') } end end tests('backend server descriptions') do tests('default') do returns(0) { elb.backend_server_descriptions.size } end tests('with a backend policy') do policy = "EnableProxyProtocol" port = 80 elb.policies.create(:id => policy, :type_name => 'ProxyProtocolPolicyType', :policy_attributes => { "ProxyProtocol" => true }) Fog::AWS[:elb].set_load_balancer_policies_for_backend_server(elb.id, port, [policy]).body elb.reload returns([policy]) { elb.backend_server_descriptions.get(port).policy_names } end end tests('setting a new ssl certificate id') do elb.listeners.create(:instance_port => 443, :lb_port => 443, :protocol => 'HTTPS', :instance_protocol => 'HTTPS', :ssl_id => @certificate['Arn']) elb.set_listener_ssl_certificate(443, @certificate['Arn']) end tests('destroy') do elb.destroy end Fog::AWS[:iam].delete_server_certificate(@key_name) @igw.destroy @subnet.destroy @vpc.destroy end end fog-1.19.0/tests/aws/models/data_pipeline/0000755000004100000410000000000012261242552020423 5ustar www-datawww-datafog-1.19.0/tests/aws/models/data_pipeline/pipeline_tests.rb0000644000004100000410000000045112261242552023777 0ustar www-datawww-dataShindo.tests("AWS::DataPipeline | pipelines", ['aws', 'data_pipeline']) do pending if Fog.mocking? unique_id = uniq_id model_tests(Fog::AWS[:data_pipeline].pipelines, { :id => unique_id, :name => "#{unique_id}-name", :unique_id => unique_id }) do @instance.wait_for { state } end end fog-1.19.0/tests/aws/models/data_pipeline/pipelines_tests.rb0000644000004100000410000000045612261242552024167 0ustar www-datawww-dataShindo.tests("AWS::DataPipeline | pipelines", ['aws', 'data_pipeline']) do pending if Fog.mocking? unique_id = uniq_id collection_tests(Fog::AWS[:data_pipeline].pipelines, { :id => unique_id, :name => "#{unique_id}-name", :unique_id => unique_id }) do @instance.wait_for { state } end end fog-1.19.0/tests/aws/models/cdn/0000755000004100000410000000000012261242552016371 5ustar www-datawww-datafog-1.19.0/tests/aws/models/cdn/streaming_distribution_tests.rb0000644000004100000410000000113612261242552024731 0ustar www-datawww-dataShindo.tests("Fog::CDN[:aws] | streaming_distribution", ['aws', 'cdn']) do params = { :s3_origin => { 'DNSName' => 'fog_test_cdn.s3.amazonaws.com'}, :enabled => true } model_tests(Fog::CDN[:aws].streaming_distributions, params, true) do # distribution needs to be ready before being disabled tests("#ready? - may take 15 minutes to complete...").succeeds do @instance.wait_for { ready? } end # and disabled before being distroyed tests("#disable - may take 15 minutes to complete...").succeeds do @instance.disable @instance.wait_for { ready? } end end end fog-1.19.0/tests/aws/models/cdn/streaming_distributions_tests.rb0000644000004100000410000000114312261242552025112 0ustar www-datawww-dataShindo.tests("Fog::CDN[:aws] | streaming_distributions", ['aws', 'cdn']) do params = { :s3_origin => { 'DNSName' => 'fog_test_cdn.s3.amazonaws.com'}, :enabled => true} collection_tests(Fog::CDN[:aws].streaming_distributions, params, true) do # distribution needs to be ready before being disabled tests("#ready? - may take 15 minutes to complete...").succeeds do @instance.wait_for { ready? } end # and disabled before being distroyed tests("#disable - may take 15 minutes to complete...").succeeds do @instance.disable @instance.wait_for { ready? } end end end fog-1.19.0/tests/aws/models/cdn/distribution_tests.rb0000644000004100000410000000111212261242552022652 0ustar www-datawww-dataShindo.tests("Fog::CDN[:aws] | distribution", ['aws', 'cdn']) do params = { :s3_origin => { 'DNSName' => 'fog_test_cdn.s3.amazonaws.com'}, :enabled => true } model_tests(Fog::CDN[:aws].distributions, params, true) do # distribution needs to be ready before being disabled tests("#ready? - may take 15 minutes to complete...").succeeds do @instance.wait_for { ready? } end # and disabled before being distroyed tests("#disable - may take 15 minutes to complete...").succeeds do @instance.disable @instance.wait_for { ready? } end end end fog-1.19.0/tests/aws/models/cdn/distributions_tests.rb0000644000004100000410000000111712261242552023042 0ustar www-datawww-dataShindo.tests("Fog::CDN[:aws] | distributions", ['aws', 'cdn']) do params = { :s3_origin => { 'DNSName' => 'fog_test_cdn.s3.amazonaws.com'}, :enabled => true} collection_tests(Fog::CDN[:aws].distributions, params, true) do # distribution needs to be ready before being disabled tests("#ready? - may take 15 minutes to complete...").succeeds do @instance.wait_for { ready? } end # and disabled before being distroyed tests("#disable - may take 15 minutes to complete...").succeeds do @instance.disable @instance.wait_for { ready? } end end end fog-1.19.0/tests/aws/models/cdn/invalidations_tests.rb0000644000004100000410000000105412261242552023004 0ustar www-datawww-dataShindo.tests("Fog::CDN[:aws] | invalidations", ['aws', 'cdn']) do tests("distributions#create").succeeds do @distribution = Fog::CDN[:aws].distributions.create(:s3_origin => {'DNSName' => 'fog_test.s3.amazonaws.com'}, :enabled => true) end collection_tests(@distribution.invalidations, { :paths => [ '/index.html' ]}, true) tests("distribution#destroy - may take 15/20 minutes to complete").succeeds do @distribution.wait_for { ready? } @distribution.disable @distribution.wait_for { ready? } @distribution.destroy end end fog-1.19.0/tests/aws/models/cdn/invalidation_tests.rb0000644000004100000410000000163612261242552022627 0ustar www-datawww-dataShindo.tests("Fog::CDN[:aws] | invalidation", ['aws', 'cdn']) do tests("distributions#create").succeeds do @distribution = Fog::CDN[:aws].distributions.create(:s3_origin => {'DNSName' => 'fog_test.s3.amazonaws.com'}, :enabled => true) end params = { :paths => [ '/index.html', '/path/to/index.html' ] } model_tests(@distribution.invalidations, params, true) do tests("#id") do returns(true) { @instance.identity != nil } end tests("#paths") do returns([ '/index.html', '/path/to/index.html' ].sort) { @instance.paths.sort } end tests("#ready? - may take 15 minutes to complete...").succeeds do @instance.wait_for { ready? } end end tests("distribution#destroy - may take around 15/20 minutes to complete...").succeeds do @distribution.wait_for { ready? } @distribution.disable @distribution.wait_for { ready? } @distribution.destroy end end fog-1.19.0/tests/aws/models/rds/0000755000004100000410000000000012261242552016415 5ustar www-datawww-datafog-1.19.0/tests/aws/models/rds/security_group_tests.rb0000644000004100000410000000336412261242552023255 0ustar www-datawww-dataShindo.tests("AWS::RDS | security_group", ['aws', 'rds']) do group_name = 'fog-test' params = {:id => group_name, :description => 'fog test'} model_tests(Fog::AWS[:rds].security_groups, params) do tests("#description").returns('fog test') { @instance.description } tests("#authorize_ec2_security_group").succeeds do @ec2_sec_group = Fog::Compute[:aws].security_groups.create(:name => 'fog-test', :description => 'fog test') @instance.authorize_ec2_security_group(@ec2_sec_group.name) returns('authorizing') do @instance.ec2_security_groups.detect{|h| h['EC2SecurityGroupName'] == @ec2_sec_group.name}['Status'] end end @instance.wait_for { ready? } tests("#revoke_ec2_security_group").succeeds do pending if Fog.mocking? @instance.revoke_ec2_security_group(@ec2_sec_group.name) returns('revoking') do @instance.ec2_security_groups.detect{|h| h['EC2SecurityGroupName'] == @ec2_sec_group.name}['Status'] end @instance.wait_for { ready? } returns(false) { @instance.ec2_security_groups.any?{|h| h['EC2SecurityGroupName'] == @ec2_sec_group.name} } @ec2_sec_group.destroy end tests("#authorize_cidrip").succeeds do @cidr = '127.0.0.1/32' @instance.authorize_cidrip(@cidr) returns('authorizing') { @instance.ip_ranges.detect{|h| h['CIDRIP'] == @cidr}['Status'] } end tests("#revoke_cidrip").succeeds do pending if Fog.mocking? @instance.wait_for { ready? } @instance.revoke_cidrip(@cidr) returns('revoking') { @instance.ip_ranges.detect{|h| h['CIDRIP'] == @cidr}['Status'] } @instance.wait_for { ready? } returns(false) { @instance.ip_ranges.any?{|h| h['CIDRIP'] == @cidr} } end end end fog-1.19.0/tests/aws/models/rds/snapshots_tests.rb0000644000004100000410000000051512261242552022207 0ustar www-datawww-dataShindo.tests("AWS::RDS | snapshots", ['aws', 'rds']) do @server = Fog::AWS[:rds].servers.create(rds_default_server_params) @server.wait_for { ready? } params = {:id => uniq_id, :instance_id => @server.id} collection_tests(Fog::AWS[:rds].snapshots, params) do @instance.wait_for { ready? } end @server.destroy end fog-1.19.0/tests/aws/models/rds/helper.rb0000644000004100000410000000030612261242552020220 0ustar www-datawww-datadef rds_default_server_params { :id => uniq_id, :allocated_storage => 5, :engine => 'mysql', :master_username => 'foguser', :password => 'fogpassword', :backup_retention_period => 0 } end fog-1.19.0/tests/aws/models/rds/parameter_groups_tests.rb0000644000004100000410000000041612261242552023544 0ustar www-datawww-dataShindo.tests("AWS::RDS | parameter_groups", ['aws', 'rds']) do group_name = 'fog-test' params = {:id => group_name, :family => 'mysql5.1', :description => group_name} pending if Fog.mocking? collection_tests(Fog::AWS[:rds].parameter_groups, params, false) end fog-1.19.0/tests/aws/models/rds/server_tests.rb0000644000004100000410000000713712261242552021502 0ustar www-datawww-dataShindo.tests("AWS::RDS | server", ['aws', 'rds']) do # Disabled due to https://github.com/fog/fog/1546 pending model_tests(Fog::AWS[:rds].servers, rds_default_server_params) do # We'll need this later; create it early to avoid waiting @instance_with_final_snapshot = Fog::AWS[:rds].servers.create(rds_default_server_params.merge(:id => uniq_id("fog-snapshot-test"), :backup_retention_period => 1)) @instance.wait_for(20*60) { ready? } test('#read_replica_identifiers is []') do returns([]) { @instance.read_replica_identifiers } end tests('#snapshots') do snapshot = nil tests('#create').succeeds do snapshot = @instance.snapshots.create(:id => 'fog-test-snapshot') end snapshot.wait_for { ready?} @instance.wait_for { ready? } returns(true) { @instance.snapshots.map{|s| s.id}.include?(snapshot.id) } snapshot.destroy end tests("#modify").succeeds do pending if Fog.mocking? orig_parameter_group = @instance.db_parameter_groups.first['DBParameterGroupName'] parameter_group = Fog::AWS[:rds].parameter_groups.create(:id => uniq_id, :family => 'mysql5.5', :description => 'fog-test') orig_security_groups = @instance.db_security_groups.map{|h| h['DBSecurityGroupName']} security_group = Fog::AWS[:rds].security_groups.create(:id => uniq_id, :description => 'fog-test') modify_options = { 'DBParameterGroupName' => parameter_group.id, 'DBSecurityGroups' => orig_security_groups + [security_group.id] } @instance.modify(true, modify_options) @instance.wait_for { ready? } returns(parameter_group.id, 'new parameter group') do @instance.db_parameter_groups.first['DBParameterGroupName'] end returns(true, "new security group") do @instance.db_security_groups.any?{|hash| hash['DBSecurityGroupName'] == security_group.id} end @instance.reboot @instance.wait_for { state == 'rebooting' } @instance.wait_for { ready? } # Restore back to original state using symbols restore_options = { :parameter_group_name => orig_parameter_group, :security_group_names => orig_security_groups } @instance.modify(true, restore_options) @instance.reboot @instance.wait_for { state == 'rebooting' } @instance.wait_for do ready? && db_security_groups.all? {|hash| hash['Status'] == 'active'} && db_parameter_groups.all? {|hash| hash['ParameterApplyStatus'] == 'in-sync' } end parameter_group.destroy security_group.destroy end tests("#reboot").succeeds do @instance.reboot end @instance.wait_for { state == 'rebooting' } @instance.wait_for { ready? } tests('#create_read_replica').succeeds do replica = @instance_with_final_snapshot.create_read_replica(uniq_id('fog-replica')) @instance_with_final_snapshot.reload returns([replica.id]) { @instance_with_final_snapshot.read_replica_identifiers } returns(@instance_with_final_snapshot.id) { replica.read_replica_source } replica.wait_for { ready? } replica.destroy end test("Destroying with a final snapshot") do final_snapshot_id = 'fog-test-snapshot' @instance_with_final_snapshot.wait_for { ready? } @instance_with_final_snapshot.destroy(final_snapshot_id) returns(true, "Final snapshot created") do @final_snapshot = Fog::AWS[:rds].snapshots.get(final_snapshot_id) !@final_snapshot.nil? end @final_snapshot.wait_for { ready? } @final_snapshot.destroy end end end fog-1.19.0/tests/aws/models/rds/tagging_tests.rb0000644000004100000410000000132412261242552021604 0ustar www-datawww-dataShindo.tests("AWS::RDS | tagging", ['aws', 'rds']) do @server = Fog::AWS[:rds].servers.create(rds_default_server_params) Formatador.display_line "Creating RDS instance #{@server.id}" Formatador.display_line "Waiting for instance #{@server.id} to be ready" @server.wait_for { ready? } tags1 = {'key1' => 'val1'} tags2 = {'key2' => 'val2'} tests "add and remove tags from a running RDS model" do returns({}) { @server.tags } returns(tags1) { @server.add_tags tags1 } returns(tags1.merge tags2) { @server.add_tags tags2 } returns(tags2) { @server.remove_tags tags1.keys } returns(tags2) { @server.tags } end @server.destroy end fog-1.19.0/tests/aws/models/rds/security_groups_tests.rb0000644000004100000410000000027112261242552023432 0ustar www-datawww-dataShindo.tests("AWS::RDS | security groups", ['aws', 'rds']) do params = {:id => 'fog-test', :description => 'fog test'} collection_tests(Fog::AWS[:rds].security_groups, params) end fog-1.19.0/tests/aws/models/rds/snapshot_tests.rb0000644000004100000410000000050712261242552022025 0ustar www-datawww-dataShindo.tests("AWS::RDS | snapshot", ['aws', 'rds']) do @server = Fog::AWS[:rds].servers.create(rds_default_server_params) @server.wait_for { ready? } params = {:id => uniq_id, :instance_id => @server.id} model_tests(Fog::AWS[:rds].snapshots, params) do @instance.wait_for { ready? } end @server.destroy end fog-1.19.0/tests/aws/models/rds/servers_tests.rb0000644000004100000410000000025412261242552021656 0ustar www-datawww-dataShindo.tests("AWS::RDS | servers", ['aws', 'rds']) do collection_tests(Fog::AWS[:rds].servers, rds_default_server_params) do @instance.wait_for { ready? } end end fog-1.19.0/tests/aws/models/rds/parameter_group_tests.rb0000644000004100000410000000137612261242552023367 0ustar www-datawww-dataShindo.tests("AWS::RDS | parameter_group", ['aws', 'rds']) do group_name = 'fog-test' params = {:id => group_name, :family => 'mysql5.1', :description => group_name} pending if Fog.mocking? model_tests(Fog::AWS[:rds].parameter_groups, params, false) do tests('#parameters') do #search for a sample parameter tests 'contains parameters' do returns(true){ @instance.parameters.any? {|p| p.name == 'query_cache_size'}} end end tests('#modify') do @instance.modify([{:name => 'query_cache_size', :value => '6553600', :apply_method => 'immediate'}]) tests 'parameter has changed' do returns('6553600'){@instance.parameters.detect {|p| p.name == 'query_cache_size'}.value} end end end end fog-1.19.0/tests/aws/models/rds/instance_option_tests.rb0000644000004100000410000000047312261242552023364 0ustar www-datawww-dataShindo.tests("AWS::RDS | db instance options", ['aws', 'rds']) do params = {:engine => 'mysql'} pending if Fog.mocking? tests('#options') do tests 'contains options' do @instance = Fog::AWS[:rds].instance_options.new(params) returns(true) { @instance.engine == 'mysql' } end end end fog-1.19.0/tests/aws/models/compute/0000755000004100000410000000000012261242552017301 5ustar www-datawww-datafog-1.19.0/tests/aws/models/compute/security_group_tests.rb0000644000004100000410000000363512261242552024142 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | security_group", ['aws']) do model_tests(Fog::Compute[:aws].security_groups, {:description => 'foggroupdescription', :name => 'foggroupname'}, true) tests("authorize and revoke helpers") do @group = Fog::Compute[:aws].security_groups.create(:name => "foggroup", :description => "fog group desc") @other_group = Fog::Compute[:aws].security_groups.create(:name => 'fog other group', :description => 'another fog group') @other_group.reload test("authorize access by another security group") do @group.authorize_group_and_owner(@other_group.name) @group.reload @group.ip_permissions.size == 3 end test("revoke access from another security group") do @group.revoke_group_and_owner(@other_group.name) @group.reload @group.ip_permissions.empty? end test("authorize access to a port range") do @group.authorize_port_range(5000..6000) @group.reload @group.ip_permissions.size == 1 end test("revoke access to a port range") do @group.revoke_port_range(5000..6000) @group.reload @group.ip_permissions.empty? end group_forms = [ "#{@other_group.owner_id}:#{@other_group.group_id}", # deprecated form @other_group.group_id, {@other_group.owner_id => @other_group.group_id} ] group_forms.each do |group_arg| test("authorize port range access by another security group #{group_arg.inspect}") do @other_group.reload @group.authorize_port_range(5000..6000, {:group => group_arg}) @group.reload @group.ip_permissions.size == 1 end test("revoke port range access by another security group") do @other_group.reload @group.revoke_port_range(5000..6000, {:group => group_arg}) @group.reload @group.ip_permissions.empty? end end @other_group.destroy @group.destroy end end fog-1.19.0/tests/aws/models/compute/snapshots_tests.rb0000644000004100000410000000045112261242552023072 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | snapshots", ['aws']) do @volume = Fog::Compute[:aws].volumes.create(:availability_zone => 'us-east-1a', :size => 1) @volume.wait_for { ready? } collection_tests(Fog::Compute[:aws].snapshots, {:volume_id => @volume.identity}, true) @volume.destroy endfog-1.19.0/tests/aws/models/compute/vpcs_tests.rb0000644000004100000410000000022012261242552022015 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | vpcs", ['aws']) do collection_tests(Fog::Compute[:aws].vpcs, {:cidr_block => '10.0.10.0/28'}, true) end fog-1.19.0/tests/aws/models/compute/server_tests.rb0000644000004100000410000000374712261242552022371 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | monitor", ['aws']) do @instance = Fog::Compute[:aws].servers.new [:addresses, :flavor, :key_pair, :key_pair=, :volumes, :associate_public_ip].each do |association| responds_to(association) end tests('new instance') do test('#monitor = true') do @instance.monitor = true @instance.attributes[:monitoring] == true end test('#monitor = false') do @instance.monitor = false @instance.attributes[:monitoring] == false end test('#associate_public_ip = true') do @instance.associate_public_ip = true @instance.attributes[:associate_public_ip] == true end test('#associate_public_ip = false') do @instance.associate_public_ip = false @instance.associate_public_ip == false end end tests('existing instance') do @instance.save [:id, :availability_zone, :flavor_id, :kernel_id, :image_id, :state].each do |attr| test("instance##{attr} should not contain whitespace") do nil == @instance.send(attr).match(/\s/) end end test('#monitor = true') do @instance.monitor = true @instance.monitoring == true end test('#monitor = false') do @instance.monitor = false @instance.monitoring == false end test('#associate_public_ip = true') do @instance.associate_public_ip = true @instance.attributes[:associate_public_ip] == true end test('#associate_public_ip = false') do @instance.associate_public_ip = false @instance.associate_public_ip == false end end @instance.destroy tests('tags') do @instance = Fog::Compute[:aws].servers.create(:tags => {'key' => 'value'}) @instance.wait_for { ready? } tests('@instance.reload.tags').returns({'key' => 'value'}) do @instance.reload.tags end unless Fog.mocking? Fog::Compute[:aws].tags.all('resource-id' => @instance.identity).each {|tag| tag.destroy} end @instance.destroy end end fog-1.19.0/tests/aws/models/compute/security_groups_tests.rb0000644000004100000410000000030612261242552024315 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | security_groups", ['aws']) do collection_tests(Fog::Compute[:aws].security_groups, {:description => 'foggroupdescription', :name => 'foggroupname'}, true) end fog-1.19.0/tests/aws/models/compute/subnet_tests.rb0000644000004100000410000000043212261242552022347 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | subnet", ['aws']) do @vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24') model_tests(Fog::Compute[:aws].subnets, {:vpc_id => @vpc.id, :cidr_block => '10.0.10.0/28', :availability_zone => 'us-east-1b'}, true) @vpc.destroy end fog-1.19.0/tests/aws/models/compute/snapshot_tests.rb0000644000004100000410000000044412261242552022711 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | snapshot", ['aws']) do @volume = Fog::Compute[:aws].volumes.create(:availability_zone => 'us-east-1a', :size => 1) @volume.wait_for { ready? } model_tests(Fog::Compute[:aws].snapshots, {:volume_id => @volume.identity}, true) @volume.destroy end fog-1.19.0/tests/aws/models/compute/volumes_tests.rb0000644000004100000410000000027512261242552022546 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | volumes", ['aws']) do collection_tests(Fog::Compute[:aws].volumes, {:availability_zone => 'us-east-1a', :size => 1, :device => '/dev/sdz1'}, true) endfog-1.19.0/tests/aws/models/compute/dhcp_option_tests.rb0000644000004100000410000000034012261242552023353 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | dhcp_options", ['aws']) do model_tests(Fog::Compute[:aws].dhcp_options, {'dhcp_configuration_set' => {'domain-name' => 'example.com', 'domain-name-servers' => '10.10.10.10'}}, true) end fog-1.19.0/tests/aws/models/compute/internet_gateway_tests.rb0000644000004100000410000000020512261242552024416 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | internet_gateway", ['aws']) do model_tests(Fog::Compute[:aws].internet_gateways , {}, true) end fog-1.19.0/tests/aws/models/compute/key_pair_tests.rb0000644000004100000410000000110012261242552022643 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | key_pair", ['aws']) do model_tests(Fog::Compute[:aws].key_pairs, {:name => 'fogkeyname'}, true) after do @keypair.destroy end tests("new keypair") do @keypair = Fog::Compute[:aws].key_pairs.create(:name => 'testkey') test ("writable?") do @keypair.writable? == true end end tests("existing keypair") do Fog::Compute[:aws].key_pairs.create(:name => 'testkey') @keypair = Fog::Compute[:aws].key_pairs.get('testkey') test("writable?") do @keypair.writable? == false end end end fog-1.19.0/tests/aws/models/compute/key_pairs_tests.rb0000644000004100000410000000022012261242552023030 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | key_pairs", ['aws']) do collection_tests(Fog::Compute[:aws].key_pairs, {:name => 'fogkeyname'}, true) endfog-1.19.0/tests/aws/models/compute/dhcp_options_tests.rb0000644000004100000410000000034512261242552023543 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | dhcp_options", ['aws']) do collection_tests(Fog::Compute[:aws].dhcp_options, {'dhcp_configuration_set' => {'domain-name' => 'example.com', 'domain-name-servers' => '10.10.10.10'}}, true) end fog-1.19.0/tests/aws/models/compute/subnets_tests.rb0000644000004100000410000000044212261242552022533 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | subnets", ['aws']) do @vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/28') collection_tests(Fog::Compute[:aws].subnets, { :vpc_id => @vpc.id, :cidr_block => '10.0.10.0/28', :availability_zone => 'us-east-1c'}, true) @vpc.destroy end fog-1.19.0/tests/aws/models/compute/vpc_tests.rb0000644000004100000410000000021012261242552021631 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | vpc", ['aws']) do model_tests(Fog::Compute[:aws].vpcs, {:cidr_block => '10.0.10.0/28'}, true) end fog-1.19.0/tests/aws/models/compute/volume_tests.rb0000644000004100000410000000173712261242552022367 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | volume", ['aws']) do @server = Fog::Compute[:aws].servers.create @server.wait_for { ready? } model_tests(Fog::Compute[:aws].volumes, {:availability_zone => @server.availability_zone, :size => 1, :device => '/dev/sdz1', :tags => {"key" => "value"}}, true) do @instance.wait_for { ready? } tests('#server = @server').succeeds do @instance.server = @server end @instance.wait_for { state == 'in-use' } tests('#server').succeeds do @instance.server.id == @server.id end tests('#server = nil').succeeds do (@instance.server = nil).nil? end @instance.wait_for { ready? } @instance.server = @server @instance.wait_for { state == 'in-use' } tests('#force_detach').succeeds do @instance.force_detach end @instance.wait_for { ready? } tests('@instance.reload.tags').returns({'key' => 'value'}) do @instance.reload.tags end end @server.destroy end fog-1.19.0/tests/aws/models/compute/addresses_tests.rb0000644000004100000410000000017312261242552023026 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | addresses", ['aws']) do collection_tests(Fog::Compute[:aws].addresses, {}, true) endfog-1.19.0/tests/aws/models/compute/address_tests.rb0000644000004100000410000000103212261242552022471 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | address", ['aws']) do model_tests(Fog::Compute[:aws].addresses, {}, true) do @server = Fog::Compute[:aws].servers.create @server.wait_for { ready? } tests('#server=').succeeds do @instance.server = @server end tests('#server') do test(' == @server') do @server.reload @instance.server.public_ip_address == @instance.public_ip end end @server.destroy end model_tests(Fog::Compute[:aws].addresses, { :domain => "vpc" }, true) end fog-1.19.0/tests/aws/models/compute/internet_gateways_tests.rb0000644000004100000410000000021312261242552024600 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | internet_gateways", ['aws']) do collection_tests(Fog::Compute[:aws].internet_gateways, {}, true) end fog-1.19.0/tests/aws/models/compute/network_interfaces_test.rb0000644000004100000410000000076612261242552024572 0ustar www-datawww-dataShindo.tests("Fog::Compute[:aws] | network_interfaces", ['aws']) do @vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24') @subnet = Fog::Compute[:aws].subnets.create('vpc_id' => @vpc.id, 'cidr_block' => '10.0.10.16/28') @subnet_id = @subnet.subnet_id collection_tests(Fog::Compute[:aws].network_interfaces, {:description => 'nic_desc', :name => 'nic_name', :subnet_id => @subnet_id}, true) @subnet.destroy @vpc.destroy end fog-1.19.0/tests/aws/models/elasticache/0000755000004100000410000000000012261242552020072 5ustar www-datawww-datafog-1.19.0/tests/aws/models/elasticache/parameter_groups_tests.rb0000644000004100000410000000063112261242552025220 0ustar www-datawww-dataShindo.tests('AWS::Elasticache | parameter groups', ['aws', 'elasticache']) do group_name = 'fog-test' description = 'Fog Test' pending if Fog.mocking? model_tests( AWS[:elasticache].parameter_groups, {:id => group_name, :description => description}, false ) collection_tests( AWS[:elasticache].parameter_groups, {:id => group_name, :description => description}, false ) end fog-1.19.0/tests/aws/models/elasticache/security_groups_tests.rb0000644000004100000410000000254212261242552025112 0ustar www-datawww-dataShindo.tests('AWS::Elasticache | security groups', ['aws', 'elasticache']) do group_name = 'fog-test' description = 'Fog Test' pending if Fog.mocking? model_tests( AWS[:elasticache].security_groups, {:id => group_name, :description => description}, false ) do # An EC2 group to authorize ec2_group = Fog::Compute.new(:provider => 'AWS').security_groups.create( :name => 'fog-test-elasticache', :description => 'fog test' ) # Reload to get the instance owner_id @instance.reload tests('#authorize_ec2_group') do @instance.authorize_ec2_group(ec2_group.name) returns('authorizing') do group = @instance.ec2_groups.detect do |g| g['EC2SecurityGroupName'] == ec2_group.name end group['Status'] end returns(false, 'not ready') { @instance.ready? } end @instance.wait_for { ready? } tests('#revoke_ec2_group') do @instance.revoke_ec2_group(ec2_group.name) returns('revoking') do group = @instance.ec2_groups.detect do |g| g['EC2SecurityGroupName'] == ec2_group.name end group['Status'] end returns(false, 'not ready') { @instance.ready? } end ec2_group.destroy end collection_tests( AWS[:elasticache].security_groups, {:id => group_name, :description => description}, false ) end fog-1.19.0/tests/aws/models/elasticache/cluster_tests.rb0000644000004100000410000000224212261242552023322 0ustar www-datawww-dataShindo.tests('AWS::Elasticache | cache clusters', ['aws', 'elasticache']) do cluster_params = { :id => "fog-test-cluster-#{rand(999).to_s}", :node_type => 'cache.m1.large', :security_groups => ['default'], :engine => 'memcached', :num_nodes => 1 } pending if Fog.mocking? Formatador.display_line "Creating cluster #{cluster_params[:id]}..." model_tests(AWS[:elasticache].clusters, cluster_params, false) do @instance.reload # Reload to get the cluster info from AWS Formatador.display_line "Waiting for #{@instance.id} "+ "to become available (#{@instance.status})..." @instance.wait_for {ready?} end # Single model is still deleting, so re-randomize the cluster ID cluster_params[:id] = "fog-test-cluster-#{rand(999).to_s}" Formatador.display_line "Creating cluster #{cluster_params[:id]}..." collection_tests(AWS[:elasticache].clusters, cluster_params, false) do @instance.reload # Reload to get the cluster info from AWS Formatador.display_line "Waiting for #{@instance.id} "+ "to become available (#{@instance.status})..." @instance.wait_for {ready?} end end fog-1.19.0/tests/aws/models/iam/0000755000004100000410000000000012261242552016373 5ustar www-datawww-datafog-1.19.0/tests/aws/models/iam/users_tests.rb0000644000004100000410000000347512261242552021314 0ustar www-datawww-dataShindo.tests("Fog::Compute[:iam] | users", ['aws','iam']) do Fog.mock! @iam = Fog::AWS[:iam] @user_one_name = 'fake_user_one' @user_two_name = 'fake_user_two' @user_three_name = 'fake_user_three' @user_three_path = '/path/to/fake_user_three/' @user_four_name = 'fake_user_four' tests('#create').succeeds do @user_one = @iam.users.create(:id => @user_one_name) @user_one.id == @user_one_name end tests('#all','there is only one user').succeeds do @iam.users.size == 1 end tests('#all','the only user should match').succeeds do @iam.users.first.id == @user_one_name end tests('#create','a second user').succeeds do @user_two = @iam.users.create(:id => @user_two_name) @user_two.id == @user_two_name end tests('#all','there are two users').succeeds do @iam.users.size == 2 end tests('#get','an existing user').succeeds do @iam.users.get(@user_one_name).id == @user_one_name end tests('#get',"returns nil if the user doesn't exists").succeeds do @iam.users.get('non-exists') == nil end tests('#policies','it has no policies').succeeds do @iam.users.get(@user_one_name).policies.empty? end tests('#access_keys','it has no keys').succeeds do @iam.users.get(@user_one_name).access_keys.empty? end tests('#create', 'assigns path').succeeds do @user_three = @iam.users.create(:id => @user_three_name, :path => @user_three_path) @user_three.path == @user_three_path end tests('#create', 'defaults path to /').succeeds do @user_four = @iam.users.create(:id => @user_four_name) @user_four.path == '/' end tests('#destroy','an existing user').succeeds do @iam.users.get(@user_one_name).destroy end tests('#destroy','clean up remaining user').succeeds do @iam.users.get(@user_two_name).destroy end endfog-1.19.0/tests/aws/models/iam/access_keys_tests.rb0000644000004100000410000000252112261242552022436 0ustar www-datawww-dataShindo.tests("Fog::Compute[:iam] | access_keys", ['aws','iam']) do Fog.mock! iam = Fog::AWS[:iam] @username = 'fake_user' @user = iam.users.create(:id => @username) tests('#all', 'there are no access keys for a new user').succeeds do @user.access_keys.empty? end tests('#create','an access key').succeeds do access_key = @user.access_keys.create access_key.id =~ /[A-Z0-9]{20}/ access_key.secret_access_key =~ /[\S]{40}/ access_key.status == "Active" access_key.username == @username @access_key_id = access_key.id end @user.access_keys.create tests('#all','there are two access keys').succeeds do @user.access_keys.size == 2 end tests('#get') do tests('a valid access key id').succeeds do access_key = @user.access_keys.get(@access_key_id) access_key.id == @access_key_id access_key.secret_access_key == nil access_key.status == "Active" access_key.username == @username end tests('an invalid access key').succeeds do @user.access_keys.get('non-existing') == nil end end tests('#destroy', 'decrease by one the number of access keys').succeeds do size = @user.access_keys.size @user.access_keys.get(@access_key_id).destroy @user.access_keys.size == ( size - 1 ) end # clean up @user.destroy endfog-1.19.0/tests/aws/models/iam/roles_tests.rb0000644000004100000410000000336212261242552021272 0ustar www-datawww-dataShindo.tests("Fog::Compute[:iam] | roles", ['aws','iam']) do pending if Fog.mocking? @iam = Fog::AWS[:iam] @role_one_name = 'fake_role_one' @role_two_name = 'fake_role_two' @role_three_name = 'fake_role_three' @role_three_path = '/path/to/fake_role_three/' @role_four_name = 'fake_role_four' tests('#create').succeeds do @role_one = @iam.roles.create(:rolename => @role_one_name) @role_one.rolename == @role_one_name end tests('#all','there is only one role').succeeds do @iam.roles.size == 1 end tests('#all','the only role should match').succeeds do @iam.roles.first.rolename == @role_one_name end tests('#create','a second role').succeeds do @role_two = @iam.roles.create(:rolename => @role_two_name) @role_two.rolename == @role_two_name end tests('#all','there are two roles').succeeds do @iam.roles.size == 2 end tests('#get','an existing role').succeeds do @iam.roles.get(@role_one_name).rolename == @role_one_name end tests('#get',"returns nil if the role doesn't exists").succeeds do @iam.roles.get('non-exists') == nil end tests('#create', 'assigns path').succeeds do @role_three = @iam.roles.create(:rolename => @role_three_name, :path => @role_three_path) @role_three.path == @role_three_path end tests('#create', 'defaults path to /').succeeds do @role_four = @iam.roles.create(:rolename => @role_four_name) @role_four.path == '/' end tests('#destroy','an existing role').succeeds do @iam.roles.get(@role_one_name).destroy end tests('#destroy','clean up remaining roles').succeeds do @iam.roles.get(@role_two_name).destroy @iam.roles.get(@role_three_name).destroy @iam.roles.get(@role_four_name).destroy end endfog-1.19.0/tests/aws/models/iam/policies_tests.rb0000644000004100000410000000277412261242552021763 0ustar www-datawww-dataShindo.tests("Fog::Compute[:iam] | policies", ['aws','iam']) do Fog.mock! iam = Fog::AWS[:iam] @username = 'fake_user' @user = iam.users.create(:id => @username) @policy_document = {"Statement"=>[{"Action"=>["sqs:*"], "Effect"=>"Allow", "Resource"=>"*"}]} @policy_name = 'fake-sqs-policy' tests('#all', 'there is no policies').succeeds do @user.policies.empty? end tests('#create') do tests('a valid policy').succeeds do policy = @user.policies.create(:id => @policy_name, :document => @policy_document) policy.id == @policy_name policy.username == @username policy.document == @policy_document end # The mocking doesn't validate the document policy #tests('an invalid valid policy').succeeds do # raises(Fog::AWS::IAM::Error) { @user.policies.create(id: 'non-valid-document', document: 'invalid json blob') } #end end @user.policies.create(:id => 'another-policy', :document => {}) tests('#all','there are two policies').succeeds do @user.policies.size == 2 end tests('#get') do tests('a valid policy').succeeds do policy = @user.policies.get(@policy_name) policy.id == @polic_name policy.username == @username policy.document == @policy_document end tests('an invalid policy').succeeds do @user.policies.get('non-existing') == nil end end tests('#destroy').succeeds do @user.policies.get(@policy_name).destroy end # clean up @user.destroy endfog-1.19.0/tests/aws/signed_params_tests.rb0000644000004100000410000000077212261242552020733 0ustar www-datawww-data# encoding: utf-8 Shindo.tests('AWS | signed_params', ['aws']) do returns( Fog::AWS.escape( "'Stöp!' said Fred_-~./" ) ) { "%27St%C3%B6p%21%27%20said%20Fred_-~.%2F" } tests('Keys should be canonicalised using Unicode NFC') do returns( Fog::AWS.escape( ["00E9".to_i(16)].pack("U*") ) ) { "%C3%A9" } tests('Characters with combining mark should be combined and then escaped') do returns( Fog::AWS.escape( ["0065".to_i(16), "0301".to_i(16)].pack("U*") ) ) { "%C3%A9" } end end end fog-1.19.0/tests/aws/storage_tests.rb0000644000004100000410000000037312261242552017560 0ustar www-datawww-data# encoding: utf-8 Shindo.tests('AWS Storage | escape', ['aws']) do tests('Keys can contain a hierarchical prefix which should not be escaped') do returns( Fog::Storage::AWS.new.send(:escape, "key/with/prefix") ) { "key/with/prefix" } end end fog-1.19.0/tests/storage/0000755000004100000410000000000012261242552015214 5ustar www-datawww-datafog-1.19.0/tests/storage/helper.rb0000644000004100000410000000060712261242552017023 0ustar www-datawww-datadef storage_providers { :aws => { :mocked => true }, :google => { :mocked => true }, :hp => { :mocked => true }, :internetarchive => { :mocked => true }, :local => { :mocked => false }, :ninefold => { :mocked => false }, :rackspace => { :mocked => false } } end fog-1.19.0/tests/storage/models/0000755000004100000410000000000012261242552016477 5ustar www-datawww-datafog-1.19.0/tests/storage/models/directory_test.rb0000644000004100000410000000127112261242552022070 0ustar www-datawww-datafor provider, config in storage_providers Shindo.tests("Storage[:#{provider}] | directory", [provider.to_s]) do if !Fog.mocking? || config[:mocked] directory_attributes = { :key => 'fogdirectorytests' }.merge!(config[:directory_attributes] || {}) model_tests(Fog::Storage[provider].directories, directory_attributes, config[:mocked]) do tests("#public=(true)").succeeds do pending if Fog.mocking? && !config[:mocked] @instance.public=(true) end tests('responds_to(:public_url)') do pending if Fog.mocking? && !config[:mocked] responds_to(:public_url) end end end end end fog-1.19.0/tests/storage/models/file_tests.rb0000644000004100000410000000213612261242552021167 0ustar www-datawww-datafor provider, config in storage_providers Shindo.tests("Storage[:#{provider}] | file", [provider.to_s]) do if !Fog.mocking? || config[:mocked] file_attributes = { :key => 'fog_file_tests', :body => lorem_file, :public => true }.merge!(config[:file_attributes] || {}) directory_attributes = { :key => 'fogfilestests' }.merge!(config[:directory_attributes] || {}) @directory = Fog::Storage[provider].directories.create(directory_attributes) model_tests(@directory.files, file_attributes, config[:mocked]) do responds_to(:public_url) tests("#public=(true)").succeeds do pending if Fog.mocking? && !config[:mocked] || !Fog::Storage[provider].respond_to?(:public=) @instance.public=(true) end test("@instance.public_url.nil? || Excon.get(@instance.public_url).body == lorem_file.read") do pending if Fog.mocking? @instance.public_url.nil? || Excon.get(@instance.public_url).body == lorem_file.read end end @directory.destroy end end end fog-1.19.0/tests/storage/models/files_tests.rb0000644000004100000410000000114412261242552021350 0ustar www-datawww-datafor provider, config in storage_providers Shindo.tests("Storage[:#{provider}] | files", [provider.to_s]) do if !Fog.mocking? || config[:mocked] file_attributes = { :key => 'fog_files_tests', :body => lorem_file }.merge!(config[:file_attributes] || {}) directory_attributes = { :key => 'fogfilestests' }.merge!(config[:directory_attributes] || {}) @directory = Fog::Storage[provider].directories.create(directory_attributes) collection_tests(@directory.files, file_attributes, config[:mocked]) @directory.destroy end end end fog-1.19.0/tests/storage/models/directories_tests.rb0000644000004100000410000000062012261242552022560 0ustar www-datawww-datafor provider, config in storage_providers Shindo.tests("Storage[:#{provider}] | directories", [provider.to_s]) do if !Fog.mocking? || config[:mocked] directory_attributes = { :key => 'fogdirectoriestests', }.merge!(config[:directory_attributes] || {}) collection_tests(Fog::Storage[provider].directories, directory_attributes, config[:mocked]) end end endfog-1.19.0/tests/helper.rb0000644000004100000410000000352012261242552015354 0ustar www-datawww-datarequire 'simplecov' if ENV['COVERAGE'] != 'false' && RUBY_VERSION != "1.9.2" require 'coveralls' SimpleCov.command_name "shindo:#{Process.pid.to_s}" SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter ] SimpleCov.merge_timeout 3600 SimpleCov.start end ENV['FOG_RC'] = ENV['FOG_RC'] || File.expand_path('../.fog', __FILE__) ENV['FOG_CREDENTIAL'] = ENV['FOG_CREDENTIAL'] || 'default' require 'fog' require 'fog/bin' # for available_providers and registered_providers Excon.defaults.merge!(:debug_request => true, :debug_response => true) require File.expand_path(File.join(File.dirname(__FILE__), 'helpers', 'mock_helper')) 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 # check to see which credentials are available and add others to the skipped tags list all_providers = Fog.registered_providers.map {|provider| provider.downcase} # Manually remove these providers since they are local applications, not lacking credentials all_providers = all_providers - ["libvirt", "vmfusion", "openvz"] available_providers = Fog.available_providers.map {|provider| provider.downcase} unavailable_providers = all_providers - available_providers for provider in unavailable_providers Formatador.display_line("[yellow]Skipping tests for [bold]#{provider}[/] [yellow]due to lacking credentials (add some to '#{Fog.credentials_path}' to run them)[/]") Thread.current[:tags] << ('-' << provider) end # mark libvirt tests pending if not setup begin require('ruby-libvirt') rescue LoadError Formatador.display_line("[yellow]Skipping tests for [bold]libvirt[/] [yellow]due to missing `ruby-libvirt` gem.[/]") Thread.current[:tags] << '-libvirt' end fog-1.19.0/tests/zerigo/0000755000004100000410000000000012261242552015047 5ustar www-datawww-datafog-1.19.0/tests/zerigo/requests/0000755000004100000410000000000012261242552016722 5ustar www-datawww-datafog-1.19.0/tests/zerigo/requests/dns/0000755000004100000410000000000012261242552017506 5ustar www-datawww-datafog-1.19.0/tests/zerigo/requests/dns/dns_tests.rb0000644000004100000410000002671612261242552022055 0ustar www-datawww-dataShindo.tests('Fog::DNS[:zerigo] | DNS requests', ['zerigo', 'dns']) do # tests assume have a free acccount - ie need to limit # of zones to max of 3 MAX_ZONE_COUNT = 3 @domain = '' @org_zone_count = 0 @new_zones = [] @new_records =[] def generate_unique_domain( with_trailing_dot = false) #get time (with 1/100th of sec accuracy) #want unique domain name and if provider is fast, this can be called more than once per second time= (Time.now.to_f * 100).to_i domain = 'test-' + time.to_s + '.com' if with_trailing_dot domain+= '.' end domain end tests( 'success') do test('get current zone count') do pending if Fog.mocking? @org_zone_count= 0 response = Fog::DNS[:zerigo].count_zones() if response.status == 200 @org_zone_count = response.body['count'] end response.status == 200 end test('create zone - simple') do pending if Fog.mocking? options = { :nx_ttl => 1800 } domain = generate_unique_domain response = Fog::DNS[:zerigo].create_zone( domain, 3600, 'pri_sec', options) if response.status == 201 zone_id = response.body['id'] #worked so can now delete response = Fog::DNS[:zerigo].delete_zone( zone_id) end response.status == 200 end test('create zone - set zerigo as slave') do pending if Fog.mocking? options = { :active => 'N', :ns1=> '2.3.4.5' } domain= generate_unique_domain response = Fog::DNS[:zerigo].create_zone( domain, 14400, 'sec', options ) if response.status == 201 zone_id = response.body['id'] #worked so can now delete response = Fog::DNS[:zerigo].delete_zone( zone_id) end response.status == 200 end test('create zone - set zerigo as master') do pending if Fog.mocking? domain= generate_unique_domain options = { :active => 'N', :slave_nameservers=> "ns1.#{domain},ns2.#{domain}" } response = Fog::DNS[:zerigo].create_zone( domain, 14400, 'pri', options ) if response.status == 201 zone_id = response.body['id'] #worked so can now delete response = Fog::DNS[:zerigo].delete_zone( zone_id) end response.status == 200 end test('create zone - set all parameters') do pending if Fog.mocking? @domain = generate_unique_domain options = { :nx_ttl => 1800, :active => 'N', :hostmaster => "netops@#{@domain}", :notes => 'for client ABC', :tag_list=> 'sample-tag' } response = Fog::DNS[:zerigo].create_zone( @domain, 14400, 'pri', options ) if response.status == 201 @zone_id = response.body['id'] @new_zones << @zone_id end response.status == 201 end test("get zone #{@zone_id} for #{@domain}- check all parameters") do pending if Fog.mocking? result= false response = Fog::DNS[:zerigo].get_zone( @zone_id) if response.status == 200 zone = response.body if (zone['ns-type'] == 'pri') and (zone['tag-list'] == 'sample-tag') and (zone['default-ttl'] == 14400) and (zone['nx-ttl'] == 1800) and (zone['updated-at'].length > 0) and (zone['created-at'].length > 0) and (zone['domain'] == @domain) and (zone['notes'] == 'for client ABC') and (zone['id'] == @zone_id) result = true end result end end test("update zone #{@zone_id} - set notes & tags") do pending if Fog.mocking? options = { :notes => 'for client XYZ', :tag_list=> 'testing-tag' } response = Fog::DNS[:zerigo].update_zone( @zone_id, options ) response.status == 200 end test("get zone #{@zone_id} - check updated parameters") do pending if Fog.mocking? result= false response = Fog::DNS[:zerigo].get_zone( @zone_id) if response.status == 200 zone = response.body if (zone['tag-list'] == 'testing-tag') and (zone['notes'] == 'for client XYZ') result = true end result end end test("get zone stats for #{@zone_id}") do pending if Fog.mocking? result= false response = Fog::DNS[:zerigo].get_zone_stats( @zone_id) if response.status == 200 zone = response.body if (zone['domain'] == @domain) and (zone['id'] == @zone_id) and (zone['period-begin'].length > 0) and (zone['period-end'].length > 0) result= true end result end end test("list zones - make sure total count is #{@org_zone_count+1}") do pending if Fog.mocking? result= false response = Fog::DNS[:zerigo].list_zones() if response.status == 200 zones = response.body['zones'] if (@org_zone_count+1) == zones.count result= true; end end result end test('list zones with pagination') do pending if Fog.mocking? result = false # make enough zones to paginate number_zones_to_create = MAX_ZONE_COUNT-@org_zone_count-1 number_zones_to_create.times do |i| domain = generate_unique_domain options = { :nx_ttl => 1800, :active => 'N', :hostmaster => "netops@#{domain}", :notes => 'for client ABC', :tag_list=> "sample-tag-#{i}" } response = Fog::DNS[:zerigo].create_zone( domain, 14400, 'pri', options ) if response.status == 201 @new_zones << response.body['id'] else return false end end total_zone_count_response = Fog::DNS[:zerigo].list_zones() if total_zone_count_response.status == 200 if number_zones_to_create > 0 zones_we_should_see = @new_zones.dup total_zone_count = total_zone_count_response.headers['X-Query-Count'].to_i else zones_we_should_see = total_zone_count_response.body['zones'].collect {|z| z['id']} total_zone_count = zones_we_should_see.count end total_zone_count.times do |i| # zerigo pages are 1-indexed, not 0-indexed response = Fog::DNS[:zerigo].list_zones(:per_page => 1, :page => i+1) zones = response.body['zones'] if 1 == zones.count zones_we_should_see.delete(zones.first['id']) end end if zones_we_should_see.empty? result = true end end result end test('create record - simple A record') do pending if Fog.mocking? host= 'www' options = { :hostname => host } response = Fog::DNS[:zerigo].create_host( @zone_id, 'A', '1.2.3.4', options) if response.status == 201 record_id = response.body['id'] @new_records << record_id end response.status == 201 end test('create record - CNAME record') do pending if Fog.mocking? host = 'mail' options = { :hostname => host } response = Fog::DNS[:zerigo].create_host( @zone_id, 'CNAME', @domain, options) if response.status == 201 record_id = response.body['id'] @new_records << record_id end response.status == 201 end test('create record - NS record') do pending if Fog.mocking? #note, when use create_host for a NS record, it needs to be a delation #rather than a NS record for the main domain (those NS records are setup #using the zone methods) sub_domain = 'subdomain' # that we want to delete DNS for ns_host = 'ns.' + @domain options = { :hostname => sub_domain} response = Fog::DNS[:zerigo].create_host( @zone_id, 'NS', ns_host, options) if response.status == 201 record_id = response.body['id'] @new_records << record_id end response.status == 201 end test('create record - MX record') do pending if Fog.mocking? mail_domain = 'mail.' + @domain options = { :hostname => @domain, :ttl => 3600, :priority => '3'} response = Fog::DNS[:zerigo].create_host( @zone_id, 'MX', mail_domain, options) if response.status == 201 @record_id = response.body['id'] @new_records << @record_id end response.status == 201 end test("get host #{@record_id}") do pending if Fog.mocking? result = false response = Fog::DNS[:zerigo].get_host( @record_id) if response.status == 200 host = response.body if (host['id'] == @record_id) and (host['host-type'] == 'MX') and (host['created-at'].length > 0) and (host['updated-at'].length > 0) result = true end end result end test("update host #{@record_id}") do pending if Fog.mocking? result = false options = { :priority => 7 } response = Fog::DNS[:zerigo].update_host( @record_id, options) if response.status == 200 response = Fog::DNS[:zerigo].get_host( @record_id) if response.status == 200 host= response.body if (host['priority'] == 7) result = true end end end result end test('count host records') do pending if Fog.mocking? host_count = 0 response = Fog::DNS[:zerigo].count_hosts( @zone_id) if response.status == 200 host_count = response.body['count'] end host_count == 4 end test('list host records') do pending if Fog.mocking? result = false response = Fog::DNS[:zerigo].list_hosts( @zone_id) if response.status == 200 hosts = response.body['hosts'] if (hosts.count == 4) hosts.each { |host| if (host['id'] > 0) and (host['fqdn'].length > 0) and (host['host-type'].length > 0) and (host['created-at'].length > 0) and (host['updated-at'].length > 0) result = true end } end end result end test("find host: mail.#{@domain}") do pending if Fog.mocking? result = false host = 'mail.' + @domain response = Fog::DNS[:zerigo].find_hosts( host) if response.status == 200 hosts = response.body['hosts'] host_count = hosts.count if (host_count == 1) result = true end end result end test("find host: mail.#{@domain} - method 2") do pending if Fog.mocking? result = false host = 'mail.' + @domain response = Fog::DNS[:zerigo].find_hosts( host, @zone_id) if response.status == 200 hosts = response.body['hosts'] host_count = hosts.count if (host_count == 1) result = true end end result end test("delete #{@new_records.count} records created") do pending if Fog.mocking? result= true @new_records.each { |record_id| response = Fog::DNS[:zerigo].delete_host( record_id) if response.status != 200 result= false; end } result end test("delete #{@new_zones.count} zones created") do pending if Fog.mocking? result= true @new_zones.each { |zone_id| response = Fog::DNS[:zerigo].delete_zone( zone_id) if response.status != 200 result= false; end } result end end tests( 'failure') do end end fog-1.19.0/tests/openstack/0000755000004100000410000000000012261242552015537 5ustar www-datawww-datafog-1.19.0/tests/openstack/authenticate_tests.rb0000644000004100000410000001302512261242552021765 0ustar www-datawww-dataShindo.tests('OpenStack | authenticate', ['openstack']) do begin @old_mock_value = Excon.defaults[:mock] Excon.defaults[:mock] = true Excon.stubs.clear expires = Time.now.utc + 600 token = Fog::Mock.random_numbers(8).to_s tenant_token = Fog::Mock.random_numbers(8).to_s body = { "access" => { "token" => { "expires" => expires.iso8601, "id" => token, "tenant" => { "enabled" => true, "description" => nil, "name" => "admin", "id" => tenant_token, } }, "serviceCatalog" => [{ "endpoints" => [{ "adminURL" => "http://example:8774/v2/#{tenant_token}", "region" => "RegionOne", "internalURL" => "http://example:8774/v2/#{tenant_token}", "id" => Fog::Mock.random_numbers(8).to_s, "publicURL" => "http://example:8774/v2/#{tenant_token}" }], "endpoints_links" => [], "type" => "compute", "name" => "nova" }, { "endpoints" => [{ "adminURL" => "http://example:9292", "region" => "RegionOne", "internalURL" => "http://example:9292", "id" => Fog::Mock.random_numbers(8).to_s, "publicURL" => "http://example:9292" }], "endpoints_links" => [], "type" => "image", "name" => "glance" }], "user" => { "username" => "admin", "roles_links" => [], "id" => Fog::Mock.random_numbers(8).to_s, "roles" => [ { "name" => "admin" }, { "name" => "KeystoneAdmin" }, { "name" => "KeystoneServiceAdmin" } ], "name" => "admin" }, "metadata" => { "is_admin" => 0, "roles" => [ Fog::Mock.random_numbers(8).to_s, Fog::Mock.random_numbers(8).to_s, Fog::Mock.random_numbers(8).to_s,]}}} tests("v2") do Excon.stub({ :method => 'POST', :path => "/v2.0/tokens" }, { :status => 200, :body => Fog::JSON.encode(body) }) expected = { :user => body['access']['user'], :tenant => body['access']['token']['tenant'], :identity_public_endpoint => nil, :server_management_url => body['access']['serviceCatalog']. first['endpoints'].first['publicURL'], :token => token, :expires => expires.iso8601, :current_user_id => body['access']['user']['id'], :unscoped_token => token, } returns(expected) do Fog::OpenStack.authenticate_v2( :openstack_auth_uri => URI('http://example/v2.0/tokens'), :openstack_tenant => 'admin', :openstack_service_type => %w[compute]) end end tests("v2 missing service") do Excon.stub({ :method => 'POST', :path => "/v2.0/tokens" }, { :status => 200, :body => Fog::JSON.encode(body) }) raises(Fog::Errors::NotFound, 'Could not find service network. Have compute, image') do Fog::OpenStack.authenticate_v2( :openstack_auth_uri => URI('http://example/v2.0/tokens'), :openstack_tenant => 'admin', :openstack_service_type => %w[network]) end end tests("v2 auth with two compute services") do body_clone = body.clone body_clone["access"]["serviceCatalog"] << { "endpoints" => [{ "adminURL" => "http://example2:8774/v2/#{tenant_token}", "region" => "RegionOne", "internalURL" => "http://example2:8774/v2/#{tenant_token}", "id" => Fog::Mock.random_numbers(8).to_s, "publicURL" => "http://example2:8774/v2/#{tenant_token}" }], "endpoints_links" => [], "type" => "compute", "name" => "nova2" } Excon.stub({ :method => 'POST', :path => "/v2.0/tokens" }, { :status => 200, :body => Fog::JSON.encode(body_clone) }) returns("http://example2:8774/v2/#{tenant_token}") do Fog::OpenStack.authenticate_v2( :openstack_auth_uri => URI('http://example/v2.0/tokens'), :openstack_tenant => 'admin', :openstack_service_type => %w[compute], :openstack_service_name => 'nova2')[:server_management_url] end end tests("legacy v1 auth") do headers = { "X-Storage-Url" => "https://swift.myhost.com/v1/AUTH_tenant", "X-Auth-Token" => "AUTH_yui193bdc00c1c46c5858788yuio0e1e2p", "X-Trans-Id" => "iu99nm9999f9b999c9b999dad9cd999e99", "Content-Length" => "0", "Date" => "Wed, 07 Aug 2013 11:11:11 GMT" } Excon.stub({:method => 'GET', :path => "/auth/v1.0"}, {:status => 200, :body => "", :headers => headers}) returns("https://swift.myhost.com/v1/AUTH_tenant") do Fog::OpenStack.authenticate_v1( :openstack_auth_uri => URI('https://swift.myhost.com/auth/v1.0'), :openstack_username => 'tenant:dev', :openstack_api_key => 'secret_key', :openstack_service_type => %w[storage])[:server_management_url] end end ensure Excon.stubs.clear Excon.defaults[:mock] = @old_mock_value end end fog-1.19.0/tests/openstack/requests/0000755000004100000410000000000012261242552017412 5ustar www-datawww-datafog-1.19.0/tests/openstack/requests/orchestration/0000755000004100000410000000000012261242552022276 5ustar www-datawww-datafog-1.19.0/tests/openstack/requests/orchestration/stack_tests.rb0000644000004100000410000000210512261242552025150 0ustar www-datawww-dataShindo.tests('Fog::Orchestration[:openstack] | stack requests', ['openstack']) do @stack_format = { 'links' => Array, 'id' => String, 'stack_name' => String, 'description' => Fog::Nullable::String, 'stack_status' => String, 'stack_status_reason' => String, 'creation_time' => Time, 'updated_time' => Time } @create_format = { 'id' => String, 'links' => Array, } tests('success') do tests('#create_stack("teststack")').formats(@create_format) do Fog::Orchestration[:openstack].create_stack("teststack").body end tests('#list_stacks').formats({'stacks' => [@stack_format]}) do Fog::Orchestration[:openstack].list_stacks.body end tests('#update_stack("teststack")').formats({}) do Fog::Orchestration[:openstack].update_stack("teststack").body end tests('#delete_stack("teststack", "id")').formats({}) do Fog::Orchestration[:openstack].delete_stack("teststack", "id").body end end end fog-1.19.0/tests/openstack/requests/network/0000755000004100000410000000000012261242552021103 5ustar www-datawww-datafog-1.19.0/tests/openstack/requests/network/port_tests.rb0000644000004100000410000000414512261242552023642 0ustar www-datawww-dataShindo.tests('Fog::Network[:openstack] | port requests', ['openstack']) do @port_format = { 'id' => String, 'name' => String, 'network_id' => String, 'fixed_ips' => Array, 'mac_address' => String, 'status' => String, 'admin_state_up' => Fog::Boolean, 'device_owner' => String, 'device_id' => String, 'tenant_id' => String, } tests('success') do tests('#create_port').formats({'port' => @port_format}) do network_id = 'net_id' attributes = {:name => 'port_name', :fixed_ips => [], :mac_address => 'fa:16:3e:62:91:7f', :admin_state_up => true, :device_owner => 'device_owner', :device_id => 'device_id', :tenant_id => 'tenant_id'} Fog::Network[:openstack].create_port(network_id, attributes).body end tests('#list_port').formats({'ports' => [@port_format]}) do Fog::Network[:openstack].list_ports.body end tests('#get_port').formats({'port' => @port_format}) do port_id = Fog::Network[:openstack].ports.all.first.id Fog::Network[:openstack].get_port(port_id).body end tests('#update_port').formats({'port' => @port_format}) do port_id = Fog::Network[:openstack].ports.all.first.id attributes = {:name => 'port_name', :fixed_ips => [], :admin_state_up => true, :device_owner => 'device_owner', :device_id => 'device_id'} Fog::Network[:openstack].update_port(port_id, attributes).body end tests('#delete_port').succeeds do port_id = Fog::Network[:openstack].ports.all.first.id Fog::Network[:openstack].delete_port(port_id) end end tests('failure') do tests('#get_port').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].get_port(0) end tests('#update_port').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].update_port(0, {}) end tests('#delete_port').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].delete_port(0) end end endfog-1.19.0/tests/openstack/requests/network/lb_member_tests.rb0000644000004100000410000000403412261242552024577 0ustar www-datawww-dataShindo.tests('Fog::Network[:openstack] | lb_member requests', ['openstack']) do @lb_member_format = { 'id' => String, 'pool_id' => String, 'address' => String, 'protocol_port' => Integer, 'weight' => Integer, 'status' => String, 'admin_state_up' => Fog::Boolean, 'tenant_id' => String, } tests('success') do tests('#create_lb_member').formats({'member' => @lb_member_format}) do pool_id = 'pool_id' address = '10.0.0.1' protocol_port = 80 weight = 100 attributes = {:admin_state_up => true, :tenant_id => 'tenant_id'} Fog::Network[:openstack].create_lb_member(pool_id, address, protocol_port, weight, attributes).body end tests('#list_lb_members').formats({'members' => [@lb_member_format]}) do Fog::Network[:openstack].list_lb_members.body end tests('#get_lb_member').formats({'member' => @lb_member_format}) do lb_member_id = Fog::Network[:openstack].lb_members.all.first.id Fog::Network[:openstack].get_lb_member(lb_member_id).body end tests('#update_lb_member').formats({'member' => @lb_member_format}) do lb_member_id = Fog::Network[:openstack].lb_members.all.first.id attributes = {:pool_id => 'new_pool_id', :weight => 50, :admin_state_up => false} Fog::Network[:openstack].update_lb_member(lb_member_id, attributes).body end tests('#delete_lb_member').succeeds do lb_member_id = Fog::Network[:openstack].lb_members.all.first.id Fog::Network[:openstack].delete_lb_member(lb_member_id) end end tests('failure') do tests('#get_lb_member').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].get_lb_member(0) end tests('#update_lb_member').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].update_lb_member(0, {}) end tests('#delete_lb_member').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].delete_lb_member(0) end end endfog-1.19.0/tests/openstack/requests/network/lb_pool_tests.rb0000644000004100000410000000552712261242552024311 0ustar www-datawww-dataShindo.tests('Fog::Network[:openstack] | lb_pool requests', ['openstack']) do @lb_pool_format = { 'id' => String, 'subnet_id' => String, 'protocol' => String, 'lb_method' => String, 'name' => String, 'description' => String, 'health_monitors' => Array, 'members' => Array, 'status' => String, 'admin_state_up' => Fog::Boolean, 'vip_id' => Fog::Nullable::String, 'tenant_id' => String, 'active_connections' => Fog::Nullable::Integer, 'bytes_in' => Fog::Nullable::Integer, 'bytes_out' => Fog::Nullable::Integer, 'total_connections' => Fog::Nullable::Integer } @lb_pool_stats_format = { 'active_connections' => Integer, 'bytes_in' => Integer, 'bytes_out' => Integer, 'total_connections' => Integer } tests('success') do tests('#create_lb_pool').formats({'pool' => @lb_pool_format}) do subnet_id = 'subnet_id' protocol = 'HTTP' lb_method = 'ROUND_ROBIN' attributes = {:name => 'test-pool', :description => 'Test Pool', :admin_state_up => true, :tenant_id => 'tenant_id'} Fog::Network[:openstack].create_lb_pool(subnet_id, protocol, lb_method, attributes).body end tests('#list_lb_pools').formats({'pools' => [@lb_pool_format]}) do Fog::Network[:openstack].list_lb_pools.body end tests('#get_lb_pool').formats({'pool' => @lb_pool_format}) do lb_pool_id = Fog::Network[:openstack].lb_pools.all.first.id Fog::Network[:openstack].get_lb_pool(lb_pool_id).body end tests('#get_lb_pool_stats').formats({'stats' => @lb_pool_stats_format}) do lb_pool_id = Fog::Network[:openstack].lb_pools.all.first.id Fog::Network[:openstack].get_lb_pool_stats(lb_pool_id).body end tests('#update_lb_pool').formats({'pool' => @lb_pool_format}) do lb_pool_id = Fog::Network[:openstack].lb_pools.all.first.id attributes = {:name => 'new-test-pool', :description => 'New Test Pool', :lb_method => 'LEAST_CONNECTIONS', :admin_state_up => false} Fog::Network[:openstack].update_lb_pool(lb_pool_id, attributes).body end tests('#delete_lb_pool').succeeds do lb_pool_id = Fog::Network[:openstack].lb_pools.all.first.id Fog::Network[:openstack].delete_lb_pool(lb_pool_id) end end tests('failure') do tests('#get_lb_pool').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].get_lb_pool(0) end tests('#update_lb_pool').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].update_lb_pool(0, {}) end tests('#delete_lb_pool').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].delete_lb_pool(0) end end endfog-1.19.0/tests/openstack/requests/network/subnet_tests.rb0000644000004100000410000000440612261242552024156 0ustar www-datawww-dataShindo.tests('Fog::Network[:openstack] | subnet requests', ['openstack']) do @subnet_format = { 'id' => String, 'name' => String, 'network_id' => String, 'cidr' => String, 'ip_version' => Integer, 'gateway_ip' => String, 'allocation_pools' => Array, 'dns_nameservers' => Array, 'host_routes' => Array, 'enable_dhcp' => Fog::Boolean, 'tenant_id' => String, } tests('success') do tests('#create_subnet').formats({'subnet' => @subnet_format}) do network_id = 'net_id' cidr = '10.2.2.0/24' ip_version = 4 attributes = {:name => 'subnet_name', :gateway_ip => '10.2.2.1', :allocation_pools => [], :dns_nameservers => [], :host_routes => [], :enable_dhcp => true, :tenant_id => 'tenant_id'} Fog::Network[:openstack].create_subnet(network_id, cidr, ip_version, attributes).body end tests('#list_subnet').formats({'subnets' => [@subnet_format]}) do Fog::Network[:openstack].list_subnets.body end tests('#get_subnet').formats({'subnet' => @subnet_format}) do subnet_id = Fog::Network[:openstack].subnets.all.first.id Fog::Network[:openstack].get_subnet(subnet_id).body end tests('#update_subnet').formats({'subnet' => @subnet_format}) do subnet_id = Fog::Network[:openstack].subnets.all.first.id attributes = {:name => 'subnet_name', :gateway_ip => '10.2.2.1', :dns_nameservers => [], :host_routes => [], :enable_dhcp => true} Fog::Network[:openstack].update_subnet(subnet_id, attributes).body end tests('#delete_subnet').succeeds do subnet_id = Fog::Network[:openstack].subnets.all.first.id Fog::Network[:openstack].delete_subnet(subnet_id) end end tests('failure') do tests('#get_subnet').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].get_subnet(0) end tests('#update_subnet').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].update_subnet(0, {}) end tests('#delete_subnet').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].delete_subnet(0) end end endfog-1.19.0/tests/openstack/requests/network/router_tests.rb0000644000004100000410000000455412261242552024202 0ustar www-datawww-dataShindo.tests('Fog::Network[:openstack] | router requests', ['openstack']) do @router_format = { 'id' => String, 'name' => String, 'status' => String, 'admin_state_up' => Fog::Boolean, 'tenant_id' => String, 'external_gateway_info' => Fog::Nullable::Hash, } tests('success') do tests('#create_router').formats({'router' => @router_format}) do attributes = { :admin_state_up => true, :tenant_id => 'tenant_id' } Fog::Network[:openstack].create_router('router_name', attributes).body end tests('#list_routers').formats({'routers' => [@router_format]}) do Fog::Network[:openstack].list_routers.body end tests('#get_router').formats({'router' => @router_format}) do router_id = Fog::Network[:openstack].routers.all.first.id Fog::Network[:openstack].get_router(router_id).body end tests('#update_router').formats({'router' => @router_format}) do router_id = Fog::Network[:openstack].routers.all.first.id attributes = {} { :name => 'net_name', :external_gateway_info => { :network_id => 'net_id' }, :status => 'ACTIVE', :admin_state_up => 'true' } Fog::Network[:openstack].update_router(router_id, attributes).body end tests('#update_router_with_network').formats({'router' => @router_format}) do router_id = Fog::Network[:openstack].routers.all.first.id net = Fog::Network[:openstack].networks.first attributes = {} { :name => 'net_name', :external_gateway_info => net, :status => 'ACTIVE', :admin_state_up => 'true' } Fog::Network[:openstack].update_router(router_id, attributes).body end tests('#delete_router').succeeds do router_id = Fog::Network[:openstack].routers.all.last.id Fog::Network[:openstack].delete_router(router_id) end end tests('failure') do tests('#get_router').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].get_router(0) end tests('#update_router').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].update_router(0, {}) end tests('#delete_router').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].delete_router(0) end end end fog-1.19.0/tests/openstack/requests/network/network_tests.rb0000644000004100000410000000667712261242552024363 0ustar www-datawww-dataShindo.tests('Fog::Network[:openstack] | network requests', ['openstack']) do @network_format = { 'id' => String, 'name' => String, 'subnets' => Array, 'shared' => Fog::Boolean, 'status' => String, 'admin_state_up' => Fog::Boolean, 'tenant_id' => String, } @network_format_extensions = { 'router:external' => Fog::Boolean, 'provider:network_type' => String, 'provider:physical_network' => Fog::Nullable::String, 'provider:segmentation_id' => Integer } tests('success') do tests('#create_network').formats({'network' => @network_format}) do attributes = { :name => 'net_name', :shared => false, :admin_state_up => true, :tenant_id => 'tenant_id' } Fog::Network[:openstack].create_network(attributes).body end tests('#create_network+provider extensions').formats( {'network' => @network_format.merge(@network_format_extensions)} ) do attributes = { :name => 'net_name', :shared => false, :admin_state_up => true, :tenant_id => 'tenant_id', :router_external => true, # local, gre, vlan. Depends on the provider. # May rise an exception if the network_type isn't valid: # QuantumError: "Invalid input for operation: provider:physical_network" :provider_network_type => 'gre', :provider_segmentation_id => 22, } Fog::Network[:openstack].create_network(attributes).body end tests('#list_networks').formats({'networks' => [@network_format]}) do Fog::Network[:openstack].list_networks.body end tests('#get_network').formats({'network' => @network_format}) do network_id = Fog::Network[:openstack].networks.all.first.id Fog::Network[:openstack].get_network(network_id).body end tests('#update_network').formats({'network' => @network_format}) do network_id = Fog::Network[:openstack].networks.all.first.id attributes = {:name => 'net_name', :shared => false, :admin_state_up => true} Fog::Network[:openstack].update_network(network_id, attributes).body end tests('#delete_network').succeeds do network_id = Fog::Network[:openstack].networks.all.first.id Fog::Network[:openstack].delete_network(network_id) end end tests('failure') do tests('#create_network+provider extensions').raises( Excon::Errors::BadRequest ) do pending if Fog.mocking? attributes = { :name => 'net_name', :shared => false, :admin_state_up => true, :tenant_id => 'tenant_id', :router_external => true, # QuantumError: "Invalid input for operation: provider:physical_network" :provider_network_type => 'foobar', :provider_segmentation_id => 22, } Fog::Network[:openstack].create_network(attributes) end tests('#get_network').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].get_network(0) end tests('#update_network').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].update_network(0, {}) end tests('#delete_network').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].delete_network(0) end end # Cleaning up the mess Fog::Network[:openstack].networks.each do |n| Fog::Network[:openstack].delete_network(n.id) end end fog-1.19.0/tests/openstack/requests/network/quota_tests.rb0000644000004100000410000000343312261242552024006 0ustar www-datawww-dataShindo.tests('Fog::Network[:openstack] | quota requests', ['openstack']) do @tenant_id = Fog::Compute[:openstack].list_tenants.body['tenants'].first['id'] @quota_format = { 'subnet' => Fog::Nullable::Integer, 'router' => Fog::Nullable::Integer, 'port' => Fog::Nullable::Integer, 'network' => Fog::Nullable::Integer, 'floatingip' => Fog::Nullable::Integer } @quotas_format = [{ 'subnet' => Fog::Nullable::Integer, 'router' => Fog::Nullable::Integer, 'port' => Fog::Nullable::Integer, 'network' => Fog::Nullable::Integer, 'floatingip' => Fog::Nullable::Integer, 'tenant_id' => Fog::Nullable::String }] tests('success') do tests('#get_quotas').formats({ 'quotas' => @quotas_format }) do Fog::Network[:openstack].get_quotas.body end tests('#get_quota').formats(@quota_format) do @quota = Fog::Network[:openstack].get_quota(@tenant_id).body['quota'] end tests('#update_quota') do new_values = @quota.merge({ 'volumes' => @quota['subnet']/2, 'snapshots' => @quota['router']/2 }) succeeds do Fog::Network[:openstack].update_quota(@tenant_id, new_values.clone) end returns(new_values, 'returns new values') do Fog::Network[:openstack].get_quota(@tenant_id).body['quota'] end # set quota back to old values succeeds do Fog::Network[:openstack].update_quota(@tenant_id, @quota.clone) end # ensure old values are restored returns(@quota, 'old values restored') do Fog::Network[:openstack].get_quota(@tenant_id).body['quota'] end end tests('#delete_quota') do succeeds do Fog::Network[:openstack].delete_quota(@tenant_id) end end end end fog-1.19.0/tests/openstack/requests/network/lb_health_monitor_tests.rb0000644000004100000410000000725512261242552026354 0ustar www-datawww-dataShindo.tests('Fog::Network[:openstack] | lb_health_monitor requests', ['openstack']) do @lb_health_monitor_format = { 'id' => String, 'type' => String, 'delay' => Integer, 'timeout' => Integer, 'max_retries' => Integer, 'http_method' => String, 'url_path' => String, 'expected_codes' => String, 'status' => String, 'admin_state_up' => Fog::Boolean, 'tenant_id' => String, } tests('success') do before do @lb_pool = Fog::Network[:openstack].lb_pools.create(:subnet_id => 'subnet_id', :protocol => 'HTTP', :lb_method => 'ROUND_ROBIN') end after do @lb_pool.destroy end tests('#create_lb_health_monitor').formats({'health_monitor' => @lb_health_monitor_format}) do type = 'PING' delay = 1 timeout = 5 max_retries = 10 attributes = {:http_method => 'GET', :url_path => '/', :expected_codes => '200, 201', :admin_state_up => true, :tenant_id => 'tenant_id'} Fog::Network[:openstack].create_lb_health_monitor(type, delay, timeout, max_retries, attributes).body end tests('#list_lb_health_monitors').formats({'health_monitors' => [@lb_health_monitor_format]}) do Fog::Network[:openstack].list_lb_health_monitors.body end tests('#get_lb_health_monitor').formats({'health_monitor' => @lb_health_monitor_format}) do lb_health_monitor_id = Fog::Network[:openstack].lb_health_monitors.all.first.id Fog::Network[:openstack].get_lb_health_monitor(lb_health_monitor_id).body end tests('#update_lb_health_monitor').formats({'health_monitor' => @lb_health_monitor_format}) do lb_health_monitor_id = Fog::Network[:openstack].lb_health_monitors.all.first.id attributes = {:delay => 5, :timeout => 10, :max_retries => 20, :http_method => 'POST', :url_path => '/varz', :expected_codes => '200', :admin_state_up => false} Fog::Network[:openstack].update_lb_health_monitor(lb_health_monitor_id, attributes).body end tests('#associate_lb_health_monitor').succeeds do lb_health_monitor_id = Fog::Network[:openstack].lb_health_monitors.all.first.id Fog::Network[:openstack].associate_lb_health_monitor(@lb_pool.id, lb_health_monitor_id) end tests('#disassociate_lb_health_monitor').succeeds do lb_health_monitor_id = Fog::Network[:openstack].lb_health_monitors.all.first.id Fog::Network[:openstack].disassociate_lb_health_monitor(@lb_pool.id, lb_health_monitor_id) end tests('#delete_lb_health_monitor').succeeds do lb_health_monitor_id = Fog::Network[:openstack].lb_health_monitors.all.first.id Fog::Network[:openstack].delete_lb_health_monitor(lb_health_monitor_id) end end tests('failure') do tests('#get_lb_health_monitor').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].get_lb_health_monitor(0) end tests('#update_lb_health_monitor').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].update_lb_health_monitor(0, {}) end tests('#associate_lb_health_monitor').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].associate_lb_health_monitor(0, 0) end tests('#disassociate_lb_health_monitor').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].disassociate_lb_health_monitor(0, 0) end tests('#delete_lb_health_monitor').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].delete_lb_health_monitor(0) end end endfog-1.19.0/tests/openstack/requests/network/lb_vip_tests.rb0000644000004100000410000000512412261242552024127 0ustar www-datawww-dataShindo.tests('Fog::Network[:openstack] | lb_vip requests', ['openstack']) do @lb_vip_format = { 'id' => String, 'subnet_id' => String, 'pool_id' => String, 'protocol' => String, 'protocol_port' => Integer, 'name' => String, 'description' => String, 'address' => String, 'port_id' => String, 'session_persistence' => Hash, 'connection_limit' => Integer, 'status' => String, 'admin_state_up' => Fog::Boolean, 'tenant_id' => String, } tests('success') do tests('#create_lb_vip').formats({'vip' => @lb_vip_format}) do subnet_id = 'subnet_id' pool_id = 'pool_id' protocol = 'HTTP' protocol_port = 80 attributes = {:name => 'test-vip', :description => 'Test VIP', :address => '10.0.0.1', :connection_limit => 10, :session_persistence => { "cookie_name" => "COOKIE_NAME", "type" => "APP_COOKIE" }, :admin_state_up => true, :tenant_id => 'tenant_id'} Fog::Network[:openstack].create_lb_vip(subnet_id, pool_id, protocol, protocol_port, attributes).body end tests('#list_lb_vips').formats({'vips' => [@lb_vip_format]}) do Fog::Network[:openstack].list_lb_vips.body end tests('#get_lb_vip').formats({'vip' => @lb_vip_format}) do lb_vip_id = Fog::Network[:openstack].lb_vips.all.first.id Fog::Network[:openstack].get_lb_vip(lb_vip_id).body end tests('#update_lb_vip').formats({'vip' => @lb_vip_format}) do lb_vip_id = Fog::Network[:openstack].lb_vips.all.first.id attributes = {:pool_id => 'new_pool_id', :name => 'new-test-vip', :description => 'New Test VIP', :connection_limit => 5, :session_persistence => { "type" => "HTTP_COOKIE" }, :admin_state_up => false} Fog::Network[:openstack].update_lb_vip(lb_vip_id, attributes).body end tests('#delete_lb_vip').succeeds do lb_vip_id = Fog::Network[:openstack].lb_vips.all.first.id Fog::Network[:openstack].delete_lb_vip(lb_vip_id) end end tests('failure') do tests('#get_lb_vip').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].get_lb_vip(0) end tests('#update_lb_vip').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].update_lb_vip(0, {}) end tests('#delete_lb_vip').raises(Fog::Network::OpenStack::NotFound) do Fog::Network[:openstack].delete_lb_vip(0) end end endfog-1.19.0/tests/openstack/requests/storage/0000755000004100000410000000000012261242552021056 5ustar www-datawww-datafog-1.19.0/tests/openstack/requests/storage/object_tests.rb0000644000004100000410000001500712261242552024076 0ustar www-datawww-dataShindo.tests('Fog::Storage[:openstack] | object requests', ["openstack"]) do unless Fog.mocking? @directory = Fog::Storage[:openstack].directories.create(:key => 'fogobjecttests') end module OpenStackStorageHelpers def override_path(path) @path = path end end tests('success') do tests("#put_object('fogobjecttests', 'fog_object')").succeeds do pending if Fog.mocking? Fog::Storage[:openstack].put_object('fogobjecttests', 'fog_object', lorem_file) end tests("#get_object('fogobjectests', 'fog_object')").succeeds do pending if Fog.mocking? Fog::Storage[:openstack].get_object('fogobjecttests', 'fog_object').body == lorem_file.read end tests("#get_object('fogobjecttests', 'fog_object', &block)").succeeds do pending if Fog.mocking? data = '' Fog::Storage[:openstack].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 pending if Fog.mocking? Fog::Storage[:openstack].head_object('fogobjecttests', 'fog_object') end tests("#delete_object('fogobjecttests', 'fog_object')").succeeds do pending if Fog.mocking? Fog::Storage[:openstack].delete_object('fogobjecttests', 'fog_object') end tests("#get_object_http_url('directory.identity', 'fog_object', expiration timestamp)").returns(true) do pending if Fog.mocking? object_url = Fog::Storage[:openstack].get_object_http_url(@directory.identity, 'fog_object', (Time.now + 60)) (object_url =~ /http:\/\/\S+\/v1\/AUTH_\S+\/#{@directory.identity}\/fog_object\?temp_url_sig=\S+&temp_url_expires=\d+/) != nil end tests("#get_object_https_url('directory.identity', 'fog_object', expiration timestamp)").returns(true) do pending if Fog.mocking? object_url = Fog::Storage[:openstack].get_object_https_url(@directory.identity, 'fog_object', (Time.now + 60)) (object_url =~ /https:\/\/\S+\/v1\/AUTH_\S+\/#{@directory.identity}\/fog_object\?temp_url_sig=\S+&temp_url_expires=\d+/) != nil end tests("put_object with block") do pending if Fog.mocking? 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[:openstack].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[:openstack].get_object('fogobjecttests', 'fog_block_object').body == lorem_file.read end tests('#delete_object').succeeds do Fog::Storage[:openstack].delete_object('fogobjecttests', 'fog_block_object') end end tests('#delete_multiple_objects') do pending if Fog.mocking? Fog::Storage[:openstack].put_object('fogobjecttests', 'fog_object', lorem_file) Fog::Storage[:openstack].put_object('fogobjecttests', 'fog_object2', lorem_file) Fog::Storage[:openstack].directories.create(:key => 'fogobjecttests2') Fog::Storage[:openstack].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[:openstack].delete_multiple_objects('fogobjecttests', ['fog_object', 'fog_object2']).body end returns(expected, 'deletes object and container') do Fog::Storage[:openstack].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::OpenStack::NotFound) do pending if Fog.mocking? Fog::Storage[:openstack].get_object('fogobjecttests', 'fog_non_object') end tests("#get_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::OpenStack::NotFound) do pending if Fog.mocking? Fog::Storage[:openstack].get_object('fognoncontainer', 'fog_non_object') end tests("#head_object('fogobjecttests', 'fog_non_object')").raises(Fog::Storage::OpenStack::NotFound) do pending if Fog.mocking? Fog::Storage[:openstack].head_object('fogobjecttests', 'fog_non_object') end tests("#head_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::OpenStack::NotFound) do pending if Fog.mocking? Fog::Storage[:openstack].head_object('fognoncontainer', 'fog_non_object') end tests("#delete_object('fogobjecttests', 'fog_non_object')").raises(Fog::Storage::OpenStack::NotFound) do pending if Fog.mocking? Fog::Storage[:openstack].delete_object('fogobjecttests', 'fog_non_object') end tests("#delete_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::OpenStack::NotFound) do pending if Fog.mocking? Fog::Storage[:openstack].delete_object('fognoncontainer', 'fog_non_object') end tests('#delete_multiple_objects') do pending if Fog.mocking? expected = { "Number Not Found" => 2, "Response Status" => "200 OK", "Errors" => [], "Number Deleted" => 0, "Response Body" => "" } returns(expected, 'reports missing objects') do Fog::Storage[:openstack].delete_multiple_objects('fogobjecttests', ['fog_non_object', 'fog_non_object2']).body end returns(expected, 'reports missing container') do Fog::Storage[:openstack].delete_multiple_objects('fognoncontainer', ['fog_non_object', 'fog_non_object2']).body end tests('deleting non-empty container') do Fog::Storage[:openstack].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" => "" } returns(expected, 'deletes object but not container') do Fog::Storage[:openstack].delete_multiple_objects(nil, ['fogobjecttests', 'fogobjecttests/fog_object']).body end end end end unless Fog.mocking? @directory.destroy end end fog-1.19.0/tests/openstack/requests/storage/large_object_tests.rb0000644000004100000410000003413612261242552025254 0ustar www-datawww-dataShindo.tests('Fog::Storage[:openstack] | large object requests', ['openstack']) do unless Fog.mocking? @directory = Fog::Storage[:openstack].directories.create(:key => 'foglargeobjecttests') @directory2 = Fog::Storage[:openstack].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' } } end tests('success') do tests('upload test segments').succeeds do pending if Fog.mocking? @segments.each_value do |segment| Fog::Storage[:openstack].put_object(segment[:container], segment[:name], segment[:data]) end end tests('dynamic large object requests') do pending if Fog.mocking? tests('#put_object_manifest alias').succeeds do Fog::Storage[:openstack].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[:openstack].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[:openstack].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[:openstack].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[:openstack].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[:openstack].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[:openstack].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[:openstack].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[:openstack].get_object(@directory2.identity, 'fog_large_object').body == expected end end end tests('static large object requests') do pending if Fog.mocking? 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[:openstack].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[:openstack].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[:openstack].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[:openstack].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[:openstack].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[:openstack].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[:openstack].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[:openstack].delete_static_large_object(@directory2.identity, 'fog_large_object').body end end end end end tests('failure') do tests('dynamic large object requests') do pending if Fog.mocking? tests('#put_dynamic_obj_manifest with missing container').raises(Fog::Storage::OpenStack::NotFound) do Fog::Storage[:openstack].put_dynamic_obj_manifest('fognoncontainer', 'fog_large_object') end end tests('static large object requests') do pending if Fog.mocking? tests('upload test segments').succeeds do Fog::Storage[:openstack].put_object(@segments[:a][:container], @segments[:a][:name], @segments[:a][:data]) Fog::Storage[:openstack].put_object(@segments[:b][:container], @segments[:b][:name], @segments[:b][:data]) end tests('#put_static_obj_manifest with missing container').raises(Fog::Storage::OpenStack::NotFound) do Fog::Storage[:openstack].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[:openstack].put_static_obj_manifest(@directory.identity, 'fog_large_object', segments) rescue => err error = err end raises(Excon::Errors::BadRequest) do raise error if error end returns(expected, 'returns error information') do Fog::JSON.decode(error.response.body) 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[:openstack].put_static_obj_manifest(@directory.identity, 'fog_large_object', segments) rescue => err error = err end raises(Excon::Errors::BadRequest) do raise error if error end returns(expected, 'returns error information') do Fog::JSON.decode(error.response.body) 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[:openstack].put_static_obj_manifest(@directory.identity, 'fog_large_object', segments) rescue => err error = err end raises(Excon::Errors::BadRequest) do raise error if error end returns(expected, 'returns error information') do Fog::JSON.decode(error.response.body) end end tests('#delete_static_large_object with missing container') do expected = { 'Number Not Found' => 1, 'Response Status' => '200 OK', 'Errors' => [], 'Number Deleted' => 0, 'Response Body' => '' } returns(expected, 'reports missing object') do Fog::Storage[:openstack].delete_static_large_object('fognoncontainer', 'fog_large_object').body end end tests('#delete_static_large_object with missing manifest') do expected = { 'Number Not Found' => 1, 'Response Status' => '200 OK', 'Errors' => [], 'Number Deleted' => 0, 'Response Body' => '' } returns(expected, 'reports missing manifest') do Fog::Storage[:openstack].delete_static_large_object(@directory.identity, 'fog_non_object').body end 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[:openstack].put_static_obj_manifest(@directory.identity, 'fog_large_object', segments) end tests('#delete_object segment :b').succeeds do Fog::Storage[:openstack].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[:openstack].delete_static_large_object(@directory.identity, 'fog_large_object').body end end end end end unless Fog.mocking? @directory.destroy @directory2.destroy end end fog-1.19.0/tests/openstack/requests/storage/container_tests.rb0000644000004100000410000000346512261242552024617 0ustar www-datawww-dataShindo.tests('Fog::Storage[:openstack] | container requests', ["openstack"]) do @container_format = [String] @containers_format = [{ 'bytes' => Integer, 'count' => Integer, 'name' => String }] tests('success') do tests("#put_container('fogcontainertests')").succeeds do pending if Fog.mocking? Fog::Storage[:openstack].put_container('fogcontainertests') end tests("#get_container('fogcontainertests')").formats(@container_format) do pending if Fog.mocking? Fog::Storage[:openstack].get_container('fogcontainertests').body end tests("#get_containers").formats(@containers_format) do pending if Fog.mocking? Fog::Storage[:openstack].get_containers.body end tests("#head_container('fogcontainertests')").succeeds do pending if Fog.mocking? Fog::Storage[:openstack].head_container('fogcontainertests') end tests("#head_containers").succeeds do pending if Fog.mocking? Fog::Storage[:openstack].head_containers end tests("#delete_container('fogcontainertests')").succeeds do pending if Fog.mocking? Fog::Storage[:openstack].delete_container('fogcontainertests') end end tests('failure') do tests("#get_container('fognoncontainer')").raises(Fog::Storage::OpenStack::NotFound) do pending if Fog.mocking? Fog::Storage[:openstack].get_container('fognoncontainer') end tests("#head_container('fognoncontainer')").raises(Fog::Storage::OpenStack::NotFound) do pending if Fog.mocking? Fog::Storage[:openstack].head_container('fognoncontainer') end tests("#delete_container('fognoncontainer')").raises(Fog::Storage::OpenStack::NotFound) do pending if Fog.mocking? Fog::Storage[:openstack].delete_container('fognoncontainer') end end end fog-1.19.0/tests/openstack/requests/volume/0000755000004100000410000000000012261242552020721 5ustar www-datawww-datafog-1.19.0/tests/openstack/requests/volume/quota_tests.rb0000644000004100000410000000257512261242552023632 0ustar www-datawww-dataShindo.tests('Fog::Volume[:openstack] | quota requests', ['openstack']) do @tenant_id = Fog::Compute[:openstack].list_tenants.body['tenants'].first['id'] @quota_set_format = { 'volumes' => Fog::Nullable::Integer, 'gigabytes' => Fog::Nullable::Integer, 'snapshots' => Fog::Nullable::Integer, 'id' => String } tests('success') do tests('#get_quota_defaults').formats({ 'quota_set' => @quota_set_format }) do Fog::Volume[:openstack].get_quota_defaults(@tenant_id).body end tests('#get_quota').formats(@quota_set_format) do @quota = Fog::Volume[:openstack].get_quota(@tenant_id).body['quota_set'] @quota end tests('#update_quota') do new_values = @quota.merge({ 'volumes' => @quota['volumes']/2, 'snapshots' => @quota['snapshots']/2 }) succeeds do Fog::Volume[:openstack].update_quota(@tenant_id, new_values.clone) end returns(new_values, 'returns new values') do Fog::Volume[:openstack].get_quota(@tenant_id).body['quota_set'] end # set quota back to old values succeeds do Fog::Volume[:openstack].update_quota(@tenant_id, @quota.clone) end # ensure old values are restored returns(@quota, 'old values restored') do Fog::Volume[:openstack].get_quota(@tenant_id).body['quota_set'] end end end end fog-1.19.0/tests/openstack/requests/metering/0000755000004100000410000000000012261242552021224 5ustar www-datawww-datafog-1.19.0/tests/openstack/requests/metering/meter_tests.rb0000644000004100000410000000265712261242552024121 0ustar www-datawww-dataShindo.tests('Fog::Metering[:openstack] | meter requests', ['openstack']) do @sample_format = { 'counter_name' => String, 'user_id' => String, 'resource_id' => String, 'timestamp' => String, 'resource_metadata' => Hash, 'source' => String, 'counter_unit' => String, 'counter_volume' => Float, 'project_id' => String, 'message_id' => String, 'counter_type' => String } @meter_format = { 'user_id' => String, 'name' => String, 'resource_id' => String, 'project_id' => String, 'type' => String, 'unit' => String } @statistics_format = { 'count' => Integer, 'duration_start' => String, 'min' => Float, 'max' => Float, 'duration_end' => String, 'period' => Integer, 'period_end' => String, 'duration' => Float, 'period_start' => String, 'avg' => Float, 'sum' => Float } tests('success') do tests('#list_meters').formats([@meter_format]) do Fog::Metering[:openstack].list_meters.body end tests('#get_samples').formats([@sample_format]) do Fog::Metering[:openstack].get_samples('test').body end tests('#get_statistics').formats([@statistics_format]) do Fog::Metering[:openstack].get_statistics('test').body end end end fog-1.19.0/tests/openstack/requests/metering/resource_tests.rb0000644000004100000410000000076112261242552024626 0ustar www-datawww-dataShindo.tests('Fog::Metering[:openstack] | resource requests', ['openstack']) do @resource_format = { 'resource_id' => String, 'project_id' => String, 'user_id' => String, 'metadata' => Hash, } tests('success') do tests('#list_resource').formats([@resource_format]) do Fog::Metering[:openstack].list_resources.body end tests('#get_resource').formats(@resource_format) do Fog::Metering[:openstack].get_resource('test').body end end end fog-1.19.0/tests/openstack/requests/identity/0000755000004100000410000000000012261242552021243 5ustar www-datawww-datafog-1.19.0/tests/openstack/requests/identity/helper.rb0000644000004100000410000000056312261242552023053 0ustar www-datawww-dataclass OpenStack module Identity def self.get_tenant_id identity = Fog::Identity[:openstack] ENV['OPENSTACK_TENANT_NAME'] || identity.list_tenants.body['tenants'].first['id'] end def self.get_user_id identity = Fog::Identity[:openstack] ENV['OPENSTACK_USER_ID'] || identity.list_users.body['users'].first['id'] end end end fog-1.19.0/tests/openstack/requests/identity/role_tests.rb0000644000004100000410000000330012261242552023747 0ustar www-datawww-dataShindo.tests('Fog::Identity[:openstack] | role requests', ['openstack']) do @role_format = { 'id' => String, 'name' => String } @user = Fog::Identity[:openstack].list_users.body['users'].first @tenant = Fog::Identity[:openstack].list_tenants.body['tenants'].first tests('success') do tests('#create_role("Role Name")').formats(@role_format, false) do @role = Fog::Identity[:openstack].create_role("Role Name").body['role'] end tests('#list_roles').formats({'roles' => [@role_format]}) do Fog::Identity[:openstack].list_roles.body end tests("#get_role('#{@role['id']}')").formats(@role_format) do Fog::Identity[:openstack].get_role(@role['id']).body['role'] end tests('#create_user_role(@tenant["id"], @user["id"], @role["id"])').formats(@role_format) do Fog::Identity[:openstack].create_user_role(@tenant['id'], @user['id'], @role['id']).body['role'] end tests("#list_roles_for_user_on_tenant('#{@tenant['id']}','#{@user['id']}')").formats([@role_format]) do Fog::Identity[:openstack].list_roles_for_user_on_tenant(@tenant['id'], @user['id']).body['roles'] end tests("#delete_user_role with tenant").returns("") do Fog::Identity[:openstack].delete_user_role(@tenant['id'], @user['id'], @role['id']).body end tests("#delete_user_role with tenant").formats(@role_format) do # FIXME - Response (under mocks) is empty String which does not match schema pending Fog::Identity[:openstack].delete_user_role(@tenant['id'], @user['id'], @role['id']).body end tests("#delete_role('#{@role['id']}')").succeeds do Fog::Identity[:openstack].delete_role(@role['id']).body end end end fog-1.19.0/tests/openstack/requests/identity/tenant_tests.rb0000644000004100000410000000340612261242552024306 0ustar www-datawww-dataShindo.tests('Fog::Identity[:openstack] | tenant requests', ['openstack']) do @tenant_format = { 'id' => String, 'name' => String, 'enabled' => Fog::Nullable::Boolean, 'description' => Fog::Nullable::String } @role_format = { 'id' => String, 'name' => String } @tenant_name = Fog::Mock.random_hex(64) @tenant_name_update = Fog::Mock.random_hex(64) @tenant_name_update2 = Fog::Mock.random_hex(64) tests('success') do tests('#list_tenants').formats({'tenants' => [@tenant_format], 'tenants_links' => []}) do Fog::Identity[:openstack].list_tenants.body end tests('#list_roles_for_user_on_tenant(0,1)'). formats({'roles' => [@role_format]}) do openstack = Fog::Identity[:openstack] openstack.list_roles_for_user_on_tenant( openstack.current_tenant['id'], OpenStack::Identity.get_user_id).body end tests('#create_tenant').formats({'tenant' => @tenant_format}) do @tenant = Fog::Identity[:openstack].create_tenant('name' => @tenant_name).body end tests('#get_tenant').formats({'tenant' => @tenant_format}) do Fog::Identity[:openstack].get_tenant(@tenant['tenant']['id']).body end tests('#update_tenant check format').formats({'tenant' => @tenant_format}) do @tenant = Fog::Identity[:openstack].update_tenant( @tenant['tenant']['id'], 'name' => @tenant_name_update).body end tests('#update_tenant update name').succeeds do @tenant = Fog::Identity[:openstack].update_tenant( @tenant['tenant']['id'], 'name' => @tenant_name_update2).body @tenant['tenant']['name'] == @tenant_name_update2 end tests('#delete_tenant').succeeds do Fog::Identity[:openstack].delete_tenant(@tenant['tenant']['id']) end end end fog-1.19.0/tests/openstack/requests/identity/ec2_credentials_tests.rb0000644000004100000410000000222312261242552026037 0ustar www-datawww-dataShindo.tests('Fog::Identity[:openstack] | EC2 credential requests', ['openstack']) do @credential_format = { 'access' => String, 'tenant_id' => String, 'secret' => String, 'user_id' => String, } @user_id = OpenStack::Identity.get_user_id @tenant_id = OpenStack::Identity.get_tenant_id tests('success') do tests('#create_ec2_credential'). formats({'credential' => @credential_format}) do response = Fog::Identity[:openstack]. create_ec2_credential(@user_id, @tenant_id) @ec2_credential = response.body['credential'] response.body end tests('#get_ec2_credential'). formats({'credential' => @credential_format}) do Fog::Identity[:openstack]. get_ec2_credential(@user_id, @ec2_credential['access']).body end tests('#list_ec2_credentials'). formats({'credentials' => [@credential_format]}) do Fog::Identity[:openstack]. list_ec2_credentials(@user_id).body end tests('#delete_ec2_credential').succeeds do Fog::Identity[:openstack]. delete_ec2_credential(@user_id, @ec2_credential['access']) end end end fog-1.19.0/tests/openstack/requests/identity/user_tests.rb0000644000004100000410000000253512261242552023775 0ustar www-datawww-dataShindo.tests('Fog::Identity[:openstack] | user requests', ['openstack']) do @user_format = { 'id' => String, 'name' => String, 'enabled' => Fog::Boolean, 'email' => String, 'tenantId' => Fog::Nullable::String } tests('success') do @user_name = Fog::Mock.random_hex(64) @user_name_update = Fog::Mock.random_hex(64) tests("#create_user('#{@user_name}', 'mypassword', 'morph@example.com', 't3n4nt1d', true)").formats(@user_format, false) do @user = Fog::Identity[:openstack].create_user(@user_name, "mypassword", "morph@example.com", OpenStack::Identity.get_tenant_id).body['user'] end tests('#list_users').formats({'users' => [@user_format]}) do Fog::Identity[:openstack].list_users.body end tests('#get_user_by_id').formats(@user_format) do Fog::Identity[:openstack].get_user_by_id(@user['id']).body['user'] end tests('#get_user_by_name').formats(@user_format) do Fog::Identity[:openstack].get_user_by_name(@user['name']).body['user'] end tests("#update_user(#{@user['id']}, :name => 'fogupdateduser')").succeeds do Fog::Identity[:openstack].update_user(@user['id'], :name => @user_name_update, :email => 'fog@test.com') end tests("#delete_user(#{@user['id']})").succeeds do Fog::Identity[:openstack].delete_user(@user['id']) end end end fog-1.19.0/tests/openstack/requests/compute/0000755000004100000410000000000012261242552021066 5ustar www-datawww-datafog-1.19.0/tests/openstack/requests/compute/security_group_tests.rb0000644000004100000410000000504012261242552025717 0ustar www-datawww-dataShindo.tests('Fog::Compute[:openstack] | security group requests', ['openstack']) do @security_group = Hash.new @security_group_rule = Hash.new @security_group_format = { "id" => Integer, "rules" => Array, "tenant_id" => String, "name" => String, "description" => String } @security_group_rule_format = { "id" => Integer, "from_port" => Integer, "to_port" => Integer, "ip_protocol" => String, "group" => Hash, "ip_range" => Hash, "parent_group_id" => Integer } tests('success') do tests('#create_security_group(name, description)').formats({"security_group" => @security_group_format}) do security_group = Fog::Compute[:openstack].create_security_group('from_shindo_test', 'this is from the shindo test').body @security_group_id = security_group['security_group']['id'] security_group end tests('#create_security_group_rule(parent_group_id, ip_protocol, from_port, to_port, cidr, group_id=nil)').formats({"security_group_rule" => @security_group_rule_format}) do security_group_rule = Fog::Compute[:openstack].create_security_group_rule(@security_group_id, "tcp", 2222, 3333, "20.20.20.20/24").body @security_group_rule_id = security_group_rule['security_group_rule']['id'] security_group_rule end tests('#list_security_groups').formats({"security_groups" => [@security_group_format]}) do Fog::Compute[:openstack].list_security_groups.body end tests('#get_security_group(security_group_id)').formats({"security_group" => @security_group_format}) do Fog::Compute[:openstack].get_security_group(@security_group_id).body end tests('#get_security_group_rule').formats({"security_group_rule" => @security_group_rule_format}) do Fog::Compute[:openstack].create_security_group_rule(@security_group_id, "tcp", 2222, 3333, "20.20.20.20/24").body Fog::Compute[:openstack].get_security_group_rule(@security_group_rule_id).body end tests('#delete_security_group_rule(security_group_rule_id)').succeeds do Fog::Compute[:openstack].delete_security_group_rule(@security_group_rule_id) end tests('#delete_security_group(security_group_id)').succeeds do Fog::Compute[:openstack].delete_security_group(@security_group_id) returns(false) { groups = Fog::Compute[:openstack].list_security_groups.body['security_groups'] groups.any? { |group| group['id'] == @security_group_id } } end end # tests('success') end fog-1.19.0/tests/openstack/requests/compute/helper.rb0000644000004100000410000000135412261242552022675 0ustar www-datawww-dataclass OpenStack module Compute module Formats SUMMARY = { 'id' => String, 'name' => String, 'links' => Array } end end end def get_flavor_ref compute = Fog::Compute[:openstack] ENV['OPENSTACK_FLAVOR_REF'] || compute.list_flavors.body['flavors'].first['id'] end def get_image_ref compute = Fog::Compute[:openstack] ENV['OPENSTACK_IMAGE_REF'] || compute.list_images.body['images'].first['id'] end def get_flavor_ref_resize # by default we simply add one to the default flavor ref ENV['OPENSTACK_FLAVOR_REF_RESIZE'] || (get_flavor_ref.to_i + 1).to_s end def set_password_enabled pw_enabled = ENV['OPENSTACK_SET_PASSWORD_ENABLED'] || "true" return pw_enabled == "true" end fog-1.19.0/tests/openstack/requests/compute/flavor_tests.rb0000644000004100000410000000551112261242552024130 0ustar www-datawww-dataShindo.tests('Fog::Compute[:openstack] | flavor requests', ['openstack']) do @flavor_format = { 'id' => String, 'name' => String, 'disk' => Integer, 'ram' => Integer, 'links' => Array, 'swap' => Fog::Nullable::String, 'rxtx_factor' => Fog::Nullable::Float, 'OS-FLV-EXT-DATA:ephemeral' => Integer, 'os-flavor-access:is_public' => Fog::Nullable::Boolean, 'OS-FLV-DISABLED:disabled' => Fog::Nullable::Boolean, 'vcpus' => Integer } tests('success') do tests('#get_flavor_details(1)').data_matches_schema(@flavor_format) do Fog::Compute[:openstack].get_flavor_details("1").body['flavor'] end tests('#list_flavors').data_matches_schema({'flavors' => [OpenStack::Compute::Formats::SUMMARY]}) do Fog::Compute[:openstack].list_flavors.body end tests('#list_flavors_detail').data_matches_schema({'flavors' => [@flavor_format]}) do Fog::Compute[:openstack].list_flavors_detail.body end tests('#create_flavor(attributes)').data_matches_schema({'flavor' => @flavor_format}) do attributes = {:flavor_id => '100', :name => 'shindo test flavor', :disk => 10, :ram => 10, :vcpus => 10, :swap => "0", :rxtx_factor => 2.4, :ephemeral => 0, :is_public => false} Fog::Compute[:openstack].create_flavor(attributes).body end tests('add_flavor_access(flavor_ref, tenant_id)').data_matches_schema({'flavor_access' => [{'tenant_id' => String, 'flavor_id' => String}]}) do Fog::Compute[:openstack].add_flavor_access(100, 1).body end tests('remove_flavor_access(flavor_ref, tenant_id)').data_matches_schema({'flavor_access' => []}) do Fog::Compute[:openstack].remove_flavor_access(100, 1).body end tests('list_tenants_with_flavor_access(flavor_ref)').data_matches_schema({'flavor_access' => [{'tenant_id' => String, 'flavor_id' => String}]}) do Fog::Compute[:openstack].list_tenants_with_flavor_access(100).body end tests('delete_flavor(flavor_id)').succeeds do Fog::Compute[:openstack].delete_flavor('100') end end tests('failure') do tests('#get_flavor_details(0)').raises(Fog::Compute::OpenStack::NotFound) do Fog::Compute[:openstack].get_flavor_details("0") end tests('add_flavor_access(1234, 1)').raises(Fog::Compute::OpenStack::NotFound) do pending if Fog.mocking? Fog::Compute[:openstack].add_flavor_access(1234, 1).body end tests('remove_flavor_access(1234, 1)').raises(Fog::Compute::OpenStack::NotFound) do pending if Fog.mocking? Fog::Compute[:openstack].remove_flavor_access(1234, 1).body end tests('list_tenants_with_flavor_access(1234)').raises(Fog::Compute::OpenStack::NotFound) do pending if Fog.mocking? Fog::Compute[:openstack].list_tenants_with_flavor_access(1234) end end end fog-1.19.0/tests/openstack/requests/compute/image_tests.rb0000644000004100000410000000312512261242552023720 0ustar www-datawww-datarequire 'fog/openstack' Shindo.tests('Fog::Compute[:openstack] | image requests', ['openstack']) do @image_format = { 'created' => Fog::Nullable::String, 'id' => String, 'name' => String, 'progress' => Fog::Nullable::Integer, 'status' => String, 'updated' => String, 'minRam' => Integer, 'minDisk' => Integer, 'server' => Fog::Nullable::Hash, 'metadata' => Hash, 'links' => Array } tests('success') do # Setup @image_id = Fog::Compute[:openstack].images[0].id unless Fog.mocking? Fog::Compute[:openstack].images.get(@image_id).wait_for { ready? } end tests("#get_image_details(#{@image_id})").formats(@image_format) do pending if Fog.mocking? Fog::Compute[:openstack].get_image_details(@image_id).body['image'] end tests('#list_images').formats({'images' => [OpenStack::Compute::Formats::SUMMARY]}) do Fog::Compute[:openstack].list_images.body end tests('#list_images_detail').formats({'images' => [@image_format]}) do Fog::Compute[:openstack].list_images_detail.body end # Teardown unless Fog.mocking? Fog::Compute[:openstack].images.get(@image_id).wait_for { ready? } end end tests('failure') do tests('#delete_image(0)').raises(Fog::Compute::OpenStack::NotFound) do pending if Fog.mocking? Fog::Compute[:openstack].delete_image(0) end tests('#get_image_details(0)').raises(Fog::Compute::OpenStack::NotFound) do pending if Fog.mocking? Fog::Compute[:openstack].get_image_details(0) end end end fog-1.19.0/tests/openstack/requests/compute/server_tests.rb0000644000004100000410000001464312261242552024153 0ustar www-datawww-dataShindo.tests('Fog::Compute[:openstack] | server requests', ['openstack']) do @detailed_server_format = { 'id' => String, 'addresses' => Hash, 'flavor' => Hash, 'hostId' => String, 'image' => Hash, 'metadata' => Hash, 'name' => String, 'progress' => Integer, 'status' => String, 'accessIPv4' => Fog::Nullable::String, 'accessIPv6' => Fog::Nullable::String, 'links' => Array, 'created' => String, 'updated' => String, 'user_id' => String, 'config_drive' => String, } @create_format = { 'adminPass' => String, 'id' => String, 'links' => Array, 'security_groups' => Fog::Nullable::Array, } @reservation_format = { 'reservation_id' => String, } @image_format = { 'created' => Fog::Nullable::String, 'id' => String, 'name' => String, 'progress' => Fog::Nullable::Integer, 'status' => String, 'updated' => String, 'minRam' => Integer, 'minDisk' => Integer, 'server' => Hash, 'metadata' => Hash, 'links' => Array } tests('success') do @image_id = get_image_ref @snapshot_id = nil @flavor_id = get_flavor_ref tests('#create_server("test", #{@image_id} , 19)').formats(@create_format, false) do data = Fog::Compute[:openstack].create_server("test", @image_id, @flavor_id).body['server'] @server_id = data['id'] data end Fog::Compute[:openstack].servers.get(@server_id).wait_for { ready? } #CREATE tests("#get_server_details(#{@server_id})").formats(@detailed_server_format, false) do Fog::Compute[:openstack].get_server_details(@server_id).body['server'] end #MULTI_CREATE tests('#create_server("test", #{@image_id} , 19, {"min_count" => 2, "return_reservation_id" => "True"})').formats(@reservation_format, false) do data = Fog::Compute[:openstack].create_server("test", @image_id, @flavor_id, {"min_count" => 2, "return_reservation_id" => "True"}).body @reservation_id = data['reservation_id'] data end tests('#validate_multi_create') do passed = false @multi_create_servers = [] if Fog.mocking? @multi_create_servers = [Fog::Mock.random_numbers(6).to_s, Fog::Mock.random_numbers(6).to_s] else @multi_create_servers = Fog::Compute[:openstack].list_servers_detail({'reservation_id' => @reservation_id}).body['servers'].map{|server| server['id']} end if (@multi_create_servers.size == 2) passed = true end end unless Fog.mocking? @multi_create_servers.each {|server| Fog::Compute[:openstack].servers.get(server).destroy } end #LIST #NOTE: we can remove strict=false if we remove uuid from GET /servers tests('#list_servers').formats({'servers' => [OpenStack::Compute::Formats::SUMMARY]}, false) do Fog::Compute[:openstack].list_servers.body end #DETAILS tests('#list_servers_detail').formats({'servers' => [@detailed_server_format]}, false) do Fog::Compute[:openstack].list_servers_detail.body end #CHANGE PASSWORD if set_password_enabled tests("#change_server_password(#{@server_id}, 'fogupdatedserver')").succeeds do Fog::Compute[:openstack].change_server_password(@server_id, 'foggy') end Fog::Compute[:openstack].servers.get(@server_id).wait_for { ready? } end #UPDATE SERVER NAME tests("#update_server(#{@server_id}, :name => 'fogupdatedserver')").succeeds do Fog::Compute[:openstack].update_server(@server_id, :name => 'fogupdatedserver') end Fog::Compute[:openstack].servers.get(@server_id).wait_for { ready? } #CREATE IMAGE WITH METADATA tests("#create_image(#{@server_id}, 'fog')").formats('image' => @image_format) do data = Fog::Compute[:openstack].create_image(@server_id, 'fog', {"foo" => "bar"}).body @snapshot_id = data['image']['id'] data end Fog::Compute[:openstack].images.get(@snapshot_id).wait_for { ready? } #REBUILD tests("#rebuild_server(#{@server_id}, #{@snapshot_id}, 'fog')").formats({'server' => @detailed_server_format}, false) do Fog::Compute[:openstack].rebuild_server(@server_id, @snapshot_id, 'fog', 'newpass', {"foo" => "bar"}).body end Fog::Compute[:openstack].servers.get(@server_id).wait_for { ready? } if not Fog.mocking? #RESIZE tests("#resize_server(#{@server_id}, #{get_flavor_ref_resize})").succeeds do Fog::Compute[:openstack].resize_server(@server_id, get_flavor_ref_resize) end Fog::Compute[:openstack].servers.get(@server_id).wait_for { self.state == 'VERIFY_RESIZE' } if not Fog.mocking? #RESIZE CONFIRM tests("#resize_confirm(#{@server_id}, #{get_flavor_ref_resize})").succeeds do Fog::Compute[:openstack].confirm_resize_server(@server_id) end Fog::Compute[:openstack].servers.get(@server_id).wait_for { ready? } if not Fog.mocking? #REBOOT - HARD tests("#reboot_server(#{@server_id}, 'HARD')").succeeds do Fog::Compute[:openstack].reboot_server(@server_id, 'HARD') end Fog::Compute[:openstack].servers.get(@server_id).wait_for { ready? } if not Fog.mocking? #REBOOT - SOFT tests("#reboot_server(#{@server_id}, 'SOFT')").succeeds do Fog::Compute[:openstack].reboot_server(@server_id, 'SOFT') end Fog::Compute[:openstack].servers.get(@server_id).wait_for { ready? } if not Fog.mocking? #DELETE tests("#delete_server(#{@server_id})").succeeds do Fog::Compute[:openstack].delete_server(@server_id) end #DELETE IMAGE tests("#delete_image(#{@snapshot_id})").succeeds do Fog::Compute[:openstack].delete_image(@snapshot_id) end end tests('failure') do tests('#delete_server(0)').raises(Fog::Compute::OpenStack::NotFound) do Fog::Compute[:openstack].delete_server(0) end tests('#get_server_details(0)').raises(Fog::Compute::OpenStack::NotFound) do Fog::Compute[:openstack].get_server_details(0) end tests("#update_server(0, :name => 'fogupdatedserver', :adminPass => 'fogupdatedserver')").raises(Fog::Compute::OpenStack::NotFound) do Fog::Compute[:openstack].update_server(0, :name => 'fogupdatedserver', :adminPass => 'fogupdatedserver') end tests('#reboot_server(0)').raises(Fog::Compute::OpenStack::NotFound) do pending if Fog.mocking? Fog::Compute[:openstack].reboot_server(0) end end end fog-1.19.0/tests/openstack/requests/compute/keypair_tests.rb0000644000004100000410000000151612261242552024304 0ustar www-datawww-dataShindo.tests('Fog::Compute[:openstack] | keypair requests', ['openstack']) do @keypair_format = { "public_key" => String, "private_key" => String, "user_id" => String, "name" => String, "fingerprint" => String } @keypair_list_format = { "public_key" => String, "name" => String, "fingerprint" => String } tests('success') do tests('#create_key_pair((key_name, public_key = nil))').formats({"keypair" => @keypair_format}) do Fog::Compute[:openstack].create_key_pair('from_shindo_test').body end tests('#list_key_pairs').formats({"keypairs" => [{"keypair" => @keypair_list_format}]}) do Fog::Compute[:openstack].list_key_pairs.body end tests('#delete_key_pair(key_name)').succeeds do Fog::Compute[:openstack].delete_key_pair('from_shindo_test') end end end fog-1.19.0/tests/openstack/requests/compute/tenant_tests.rb0000644000004100000410000000100712261242552024124 0ustar www-datawww-dataShindo.tests('Fog::Compute[:openstack] | tenant requests', ['openstack']) do @tenant_format = { 'id' => String, 'name' => String, 'enabled' => Fog::Boolean, 'description' => Fog::Nullable::String } tests('success') do tests('#list_tenants').formats({'tenants_links' => Array, 'tenants' => [@tenant_format]}) do Fog::Compute[:openstack].list_tenants.body end tests('#set_tenant("admin")').succeeds do Fog::Compute[:openstack].set_tenant("admin") end end end fog-1.19.0/tests/openstack/requests/compute/limit_tests.rb0000644000004100000410000000344712261242552023763 0ustar www-datawww-dataShindo.tests('Fog::Compute[:openstack] | limits requests', ['openstack']) do @rate_limit_format = { 'regex' => String, 'uri' => String, 'limit' => Array } @rate_limit_usage_format = { 'next-available' => String, 'unit' => String, 'verb' => String, 'remaining' => Fixnum, 'value' => Fixnum } @absolute_limits_format = { 'maxServerMeta' => Fixnum, 'maxTotalInstances' => Fixnum, 'maxPersonality' => Fixnum, 'maxImageMeta' => Fixnum, 'maxPersonalitySize' => Fixnum, 'maxSecurityGroupRules' => Fixnum, 'maxTotalKeypairs' => Fixnum, 'maxSecurityGroups' => Fixnum, 'maxTotalCores' => Fixnum, 'maxTotalFloatingIps' => Fixnum, 'maxTotalRAMSize' => Fixnum, 'totalCoresUsed' => Fixnum, 'totalRAMUsed' => Fixnum, 'totalInstancesUsed' => Fixnum, 'totalSecurityGroupsUsed' => Fixnum, 'totalFloatingIpsUsed' => Fixnum } @limits_format = { 'rate' => Array, 'absolute' => Hash } tests('success') do tests('#get_limits') do tests('format').formats(@limits_format) do Fog::Compute[:openstack].get_limits.body['limits'] end tests('rate limit format').formats(@rate_limit_format) do Fog::Compute[:openstack].get_limits.body['limits']['rate'].first end tests('rate limit usage format').formats(@rate_limit_usage_format) do Fog::Compute[:openstack].get_limits.body['limits']['rate'].first['limit'].first end tests('absolute limits format').formats(@absolute_limits_format) do Fog::Compute[:openstack].get_limits.body['limits']['absolute'] end end end end fog-1.19.0/tests/openstack/requests/compute/quota_tests.rb0000644000004100000410000000331612261242552023771 0ustar www-datawww-dataShindo.tests('Fog::Compute[:openstack] | quota requests', ['openstack']) do @tenant_id = Fog::Compute[:openstack].list_tenants.body['tenants'].first['id'] @quota_set_format = { 'key_pairs' => Fixnum, 'metadata_items' => Fixnum, 'injected_file_content_bytes' => Fixnum, 'injected_file_path_bytes' => Fixnum, 'injected_files' => Fixnum, 'ram' => Fixnum, 'floating_ips' => Fixnum, 'instances' => Fixnum, 'cores' => Fixnum, 'security_groups' => Fog::Nullable::Integer, 'security_group_rules' => Fog::Nullable::Integer, 'volumes' => Fog::Nullable::Integer, 'gigabytes' => Fog::Nullable::Integer, 'id' => String } tests('success') do tests('#get_quota_defaults').formats({ 'quota_set' => @quota_set_format }) do Fog::Compute[:openstack].get_quota_defaults(@tenant_id).body end tests('#get_quota').formats(@quota_set_format) do @quota = Fog::Compute[:openstack].get_quota(@tenant_id).body['quota_set'] @quota end tests('#update_quota') do new_values = @quota.merge({ 'floating_ips' => @quota['floating_ips']/2, 'cores' => @quota['cores']/2 }) succeeds do Fog::Compute[:openstack].update_quota(@tenant_id, new_values.clone) end returns(new_values, 'returns new values') do Fog::Compute[:openstack].get_quota(@tenant_id).body['quota_set'] end # set quota back to old values succeeds do Fog::Compute[:openstack].update_quota(@tenant_id, @quota.clone) end # ensure old values are restored returns(@quota, 'old values restored') do Fog::Compute[:openstack].get_quota(@tenant_id).body['quota_set'] end end end end fog-1.19.0/tests/openstack/requests/compute/volume_tests.rb0000644000004100000410000000243012261242552024143 0ustar www-datawww-datarequire 'fog/openstack' Shindo.tests('Fog::Compute[:openstack] | volume requests', ['openstack']) do @volume_format = { 'id' => String, 'displayName' => String, 'size' => Integer, 'displayDescription' => String, 'status' => String, 'snapshotId' => Fog::Nullable::String, 'availabilityZone' => String, 'attachments' => Array, 'volumeType' => Fog::Nullable::String, 'createdAt' => String, 'metadata' => Hash } tests('success') do tests('#create_volume').data_matches_schema({'volume' => @volume_format}) do Fog::Compute[:openstack].create_volume('loud', 'this is a loud volume', 3).body end tests('#list_volumes').data_matches_schema({'volumes' => [@volume_format]}) do Fog::Compute[:openstack].list_volumes.body end tests('#get_volume_detail').data_matches_schema({'volume' => @volume_format}) do volume_id = Fog::Compute[:openstack].volumes.all.first.id Fog::Compute[:openstack].get_volume_details(volume_id).body end tests('#delete_volume').succeeds do volume_id = Fog::Compute[:openstack].volumes.all.first.id Fog::Compute[:openstack].delete_volume(volume_id) end end end fog-1.19.0/tests/openstack/requests/compute/address_tests.rb0000644000004100000410000000307312261242552024265 0ustar www-datawww-dataShindo.tests('Fog::Compute[:openstack] | address requests', ['openstack']) do compute = Fog::Compute[:openstack] @server_id = compute.create_server("shindo_test_server", get_image_ref, get_flavor_ref).body['server']['id'] @address_format = { "instance_id" => NilClass, "ip" => String, "fixed_ip" => NilClass, "id" => Integer, "pool" => String } @address_pools_format = { "name" => String } tests('success') do tests('#allocate_address').formats({"floating_ip" => @address_format}) do data = compute.allocate_address.body @address_id = data['floating_ip']['id'] @address_ip = data['floating_ip']['ip'] data end tests('#list_all_addresses').formats({"floating_ips" => [@address_format]}) do compute.list_all_addresses.body end tests('#get_address(address_id)').formats({"floating_ip" => @address_format}) do compute.get_address(@address_id).body end tests('#list_address_pools').formats({"floating_ip_pools" => [@address_pools_format]}) do compute.list_address_pools.body end compute.servers.get(@server_id).wait_for { ready? } tests('#associate_address(server_id, ip_address)').succeeds do compute.associate_address(@server_id, @address_ip).body end tests('#disassociate_address(server_id, ip_address)').succeeds do compute.disassociate_address(@server_id, @address_ip).body end tests('#release_address(ip_address)').succeeds do compute.release_address(@address_id) end end compute.delete_server(@server_id) end fog-1.19.0/tests/openstack/requests/image/0000755000004100000410000000000012261242552020474 5ustar www-datawww-datafog-1.19.0/tests/openstack/requests/image/image_tests.rb0000644000004100000410000001046512261242552023333 0ustar www-datawww-dataShindo.tests('Fog::Image[:openstack] | image requests', ['openstack']) do openstack = Fog::Identity[:openstack] @image_attributes = { :name => 'new image', :owner => openstack.current_tenant['id'], :is_public => true, :copy_from => 'http://website.com/image.iso', :disk_format => 'iso', :properties => {:user_id => openstack.current_user['id'], :owner_id => openstack.current_tenant['id']}, :container_format => 'bare' } @image_format = { 'name' => String, 'container_format' => String, 'disk_format' => String, 'checksum' => String, 'id' => String, 'size' => Integer } @detailed_image_format = { 'id' => String, 'name' => String, 'size' => Integer, 'disk_format' => String, 'container_format' => String, 'checksum' => String, 'min_disk' => Integer, 'created_at' => String, 'deleted_at' => Fog::Nullable::String, 'updated_at' => String, 'deleted' => Fog::Boolean, 'protected' => Fog::Boolean, 'is_public' => Fog::Boolean, 'status' => String, 'min_ram' => Integer, 'owner' => Fog::Nullable::String, 'properties' => Hash } @image_meta_format ={ 'X-Image-Meta-Is_public'=>String, 'X-Image-Meta-Min_disk'=>Fog::Nullable::String, 'X-Image-Meta-Property-Ramdisk_id'=>Fog::Nullable::String, 'X-Image-Meta-Disk_format'=>Fog::Nullable::String, 'X-Image-Meta-Created_at'=>String, 'X-Image-Meta-Container_format'=>Fog::Nullable::String, 'Etag'=>String, 'Location'=>String, 'X-Image-Meta-Protected'=>String, 'Date'=>String, 'X-Image-Meta-Name'=>String, 'X-Image-Meta-Min_ram'=>String, 'Content-Type'=>String, 'X-Image-Meta-Updated_at'=>String, 'X-Image-Meta-Property-Kernel_id'=>Fog::Nullable::String, 'X-Image-Meta-Size'=>String, 'X-Image-Meta-Checksum'=>Fog::Nullable::String, 'X-Image-Meta-Deleted'=>String, 'Content-Length'=>String, 'X-Image-Meta-Status'=>String, 'X-Image-Meta-Owner'=>String, 'X-Image-Meta-Id'=>String } @image_members_format =[ {'can_share'=>Fog::Nullable::Boolean, 'member_id'=>String } ] tests('success') do tests('#list_public_images').data_matches_schema({'images' => [@image_format]}) do Fog::Image[:openstack].list_public_images.body end tests('#list_public_images_detailed').data_matches_schema({'images' => [@detailed_image_format]}) do Fog::Image[:openstack].list_public_images_detailed.body end tests('#create_image').data_matches_schema({'image' => @detailed_image_format}) do begin if Fog.mocking? image_attributes = @image_attributes else require 'tempfile' image_attributes = @image_attributes.dup image_attributes.delete(:copy_from) test_iso = Tempfile.new(['fog_test_iso', '.iso']) test_iso.write Fog::Mock.random_hex(32) test_iso.close image_attributes[:location] = test_iso.path end @instance = Fog::Image[:openstack].create_image(image_attributes).body ensure test_iso.delete if test_iso end end tests('#get_image').data_matches_schema(@image_meta_format) do Fog::Image[:openstack].get_image(@instance['image']['id']).headers end tests('#update_image').data_matches_schema(@detailed_image_format) do Fog::Image[:openstack].update_image({:id => @instance['image']['id'], :name => 'edit image'}).body['image'] end tests('#add_member_to_image').succeeds do Fog::Image[:openstack].add_member_to_image( @instance['image']['id'], @instance['image']['owner']) end tests('#get_image_members').succeeds do Fog::Image[:openstack].get_image_members(@instance['image']['id']) end tests('#get_shared_images').succeeds do Fog::Image[:openstack].get_shared_images(@instance['image']['owner']) end tests('#remove_member_from_image').succeeds do Fog::Image[:openstack].remove_member_from_image( @instance['image']['id'], @instance['image']['owner']) end tests('#delete_image').succeeds do Fog::Image[:openstack].delete_image(@instance['image']['id']) end end end fog-1.19.0/tests/openstack/volume_tests.rb0000644000004100000410000000100112261242552020605 0ustar www-datawww-dataShindo.tests('Fog::Volume[:openstack]', ['openstack', 'volume']) do volume = Fog::Volume[:openstack] tests("Volumes collection") do %w{ volumes }.each do |collection| test("it should respond to #{collection}") { volume.respond_to? collection } test("it should respond to #{collection}.all") { eval("volume.#{collection}").respond_to? 'all' } # not implemented #test("it should respond to #{collection}.get") { eval("volume.#{collection}").respond_to? 'get' } end end end fog-1.19.0/tests/openstack/models/0000755000004100000410000000000012261242552017022 5ustar www-datawww-datafog-1.19.0/tests/openstack/models/network/0000755000004100000410000000000012261242552020513 5ustar www-datawww-datafog-1.19.0/tests/openstack/models/network/port_tests.rb0000644000004100000410000000176012261242552023252 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | port", ['openstack']) do tests('success') do tests('#create').succeeds do @instance = Fog::Network[:openstack].ports.create(:name => 'port_name', :network_id => 'net_id', :fixed_ips => [], :mac_address => 'fa:16:3e:62:91:7f', :admin_state_up => true, :device_owner => 'device_owner', :device_id => 'device_id', :tenant_id => 'tenant_id') !@instance.id.nil? end tests('#update').succeeds do @instance.name = 'new_port_name' @instance.update end tests('#destroy').succeeds do @instance.destroy == true end end endfog-1.19.0/tests/openstack/models/network/lb_member_tests.rb0000644000004100000410000000163412261242552024212 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | lb_member", ['openstack']) do tests('success') do tests('#create').succeeds do @instance = Fog::Network[:openstack].lb_members.create(:pool_id => 'pool_id', :address => '10.0.0.1', :protocol_port => '80', :weight => 100, :admin_state_up => true, :tenant_id => 'tenant_id') !@instance.id.nil? end tests('#update').succeeds do @instance.pool_id = 'new_pool_id' @instance.weight = 50 @instance.admin_state_up = false @instance.update end tests('#destroy').succeeds do @instance.destroy == true end end endfog-1.19.0/tests/openstack/models/network/routers_tests.rb0000644000004100000410000000063012261242552023764 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | routers", ['openstack']) do @router = Fog::Network[:openstack].routers.create( :name => 'router_name', :admin_state_up => true ) @routers = Fog::Network[:openstack].routers tests('success') do tests('#all').succeeds do @routers.all end tests('#get').succeeds do @routers.get @router.id end end @router.destroy end fog-1.19.0/tests/openstack/models/network/networks_tests.rb0000644000004100000410000000114012261242552024132 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | networks", ['openstack']) do @network = Fog::Network[:openstack].networks.create(:name => 'net_name', :shared => false, :admin_state_up => true, :tenant_id => 'tenant_id') @networks = Fog::Network[:openstack].networks tests('success') do tests('#all').succeeds do @networks.all end tests('#get').succeeds do @networks.get @network.id end end @network.destroy endfog-1.19.0/tests/openstack/models/network/lb_pool_tests.rb0000644000004100000410000000354312261242552023715 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | lb_pool", ['openstack']) do tests('success') do before do @lb_health_monitor = Fog::Network[:openstack].lb_health_monitors.create(:type => 'PING', :delay => 1, :timeout => 5, :max_retries => 10) end after do @lb_health_monitor.destroy end tests('#create').succeeds do @instance = Fog::Network[:openstack].lb_pools.create(:subnet_id => 'subnet_id', :protocol => 'HTTP', :lb_method => 'ROUND_ROBIN', :name => 'test-pool', :description => 'Test Pool', :admin_state_up => true, :tenant_id => 'tenant_id') !@instance.id.nil? end tests('#update').succeeds do @instance.name = 'new-test-pool' @instance.description = 'New Test Pool' @instance.lb_method = 'LEAST_CONNECTIONS' @instance.admin_state_up = false @instance.update end tests('#stats').succeeds do @instance.stats !@instance.active_connections.nil? end tests('#associate_health_monitor').succeeds do @instance.associate_health_monitor(@lb_health_monitor.id) end tests('#disassociate_health_monitor').succeeds do @instance.disassociate_health_monitor(@lb_health_monitor.id) end tests('#destroy').succeeds do @instance.destroy == true end end endfog-1.19.0/tests/openstack/models/network/floating_ip_tests.rb0000644000004100000410000000100412261242552024550 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | floating_ip", ['openstack']) do tests('success') do tests('#create').succeeds do @instance = Fog::Network[:openstack].floating_ips.create(:floating_network_id => 'f0000000-0000-0000-0000-000000000000') !@instance.id.nil? end tests('#update').succeeds do @instance.port_id = 'p0000000-0000-0000-0000-000000000000' @instance.update end tests('#destroy').succeeds do @instance.destroy == true end end end fog-1.19.0/tests/openstack/models/network/floating_ips_tests.rb0000644000004100000410000000072112261242552024740 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | floating_ips", ['openstack']) do @floating_ip = Fog::Network[:openstack].floating_ips.create(:floating_network_id => 'f0000000-0000-0000-0000-000000000000') @floating_ips = Fog::Network[:openstack].floating_ips tests('success') do tests('#all').succeeds do @floating_ips.all end tests('#get').succeeds do @floating_ips.get @floating_ip.id end end @floating_ip.destroy end fog-1.19.0/tests/openstack/models/network/subnet_tests.rb0000644000004100000410000000221612261242552023563 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | subnet", ['openstack']) do tests('success') do tests('#create').succeeds do @instance = Fog::Network[:openstack].subnets.create(:name => 'subnet_name', :network_id => 'net_id', :cidr => '10.2.2.0/24', :ip_version => 4, :gateway_ip => '10.2.2.1', :allocation_pools => [], :dns_nameservers => [], :host_routes => [], :enable_dhcp => true, :tenant_id => 'tenant_id') !@instance.id.nil? end tests('#update').succeeds do @instance.name = 'new_subnet_name' @instance.update end tests('#destroy').succeeds do @instance.destroy == true end end endfog-1.19.0/tests/openstack/models/network/router_tests.rb0000644000004100000410000000163612261242552023610 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | router", ['openstack']) do tests('success') do tests('#create').succeeds do @instance = Fog::Network[:openstack].routers.create( :name => 'router_name', :admin_state_up => true ) !@instance.id.nil? end tests('#update') do test 'router name' do @instance.name = 'new_name' @instance.update.name == 'new_name' end # Needs code from issue #1598 #test 'external_gateway_info' do # net = Fog::Network[:openstack].networks.create( # :name => 'net_name', # :shared => false, # :admin_state_up => true, # :tenant_id => 'tenant_id', # :router_external => true, # ) # @instance.external_gateway_info = net # @instance.update #end end tests('#destroy').succeeds do @instance.destroy == true end end end fog-1.19.0/tests/openstack/models/network/lb_vips_tests.rb0000644000004100000410000000112312261242552023715 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | lb_vips", ['openstack']) do @lb_vip = Fog::Network[:openstack].lb_vips.create(:subnet_id => 'subnet_id', :pool_id => 'pool_id', :protocol => 'HTTP', :protocol_port => 80) @lb_vips = Fog::Network[:openstack].lb_vips tests('success') do tests('#all').succeeds do @lb_vips.all end tests('#get').succeeds do @lb_vips.get @lb_vip.id end end @lb_vip.destroy endfog-1.19.0/tests/openstack/models/network/lb_members_tests.rb0000644000004100000410000000117212261242552024372 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | lb_members", ['openstack']) do @lb_member = Fog::Network[:openstack].lb_members.create(:pool_id => 'pool_id', :address => '10.0.0.1', :protocol_port => '80', :weight => 100) @lb_members = Fog::Network[:openstack].lb_members tests('success') do tests('#all').succeeds do @lb_members.all end tests('#get').succeeds do @lb_members.get @lb_member.id end end @lb_member.destroy endfog-1.19.0/tests/openstack/models/network/lb_health_monitors_tests.rb0000644000004100000410000000133412261242552026137 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | lb_health_monitors", ['openstack']) do @lb_health_monitor = Fog::Network[:openstack].lb_health_monitors.create(:type => 'PING', :delay => 1, :timeout => 5, :max_retries => 10) @lb_health_monitors = Fog::Network[:openstack].lb_health_monitors tests('success') do tests('#all').succeeds do @lb_health_monitors.all end tests('#get').succeeds do @lb_health_monitors.get @lb_health_monitor.id end end @lb_health_monitor.destroy endfog-1.19.0/tests/openstack/models/network/network_tests.rb0000644000004100000410000000340012261242552023750 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | network", ['openstack']) do tests('success') do tests('#create').succeeds do @instance = Fog::Network[:openstack].networks.create(:name => 'net_name', :shared => false, :admin_state_up => true, :tenant_id => 'tenant_id') !@instance.id.nil? end tests('#create+extensions').succeeds do net = Fog::Network[:openstack].networks.create( :name => 'net_name', :shared => false, :admin_state_up => true, :tenant_id => 'tenant_id', :router_external => true, # local, gre, vlan. Depends on the provider. # May rise an exception if the network_type isn't valid: # QuantumError: "Invalid input for operation: provider:physical_network" :provider_network_type => 'gre', :provider_segmentation_id => 22 ) net.destroy net.provider_network_type == 'gre' end tests('have attributes') do attributes = [ :name, :subnets, :shared, :status, :admin_state_up, :tenant_id, :provider_network_type, :provider_physical_network, :provider_segmentation_id, :router_external ] tests("The network model should respond to") do attributes.each do |attribute| test("#{attribute}") { @instance.respond_to? attribute } end end end tests('#update').succeeds do @instance.name = 'new_net_name' @instance.update end tests('#destroy').succeeds do @instance.destroy == true end end end fog-1.19.0/tests/openstack/models/network/subnets_tests.rb0000644000004100000410000000203212261242552023742 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | subnets", ['openstack']) do @subnet = Fog::Network[:openstack].subnets.create(:name => 'subnet_name', :network_id => 'net_id', :cidr => '10.2.2.0/24', :ip_version => 4, :gateway_ip => '10.2.2.1', :allocation_pools => [], :dns_nameservers => [], :host_routes => [], :enable_dhcp => true, :tenant_id => 'tenant_id') @subnets = Fog::Network[:openstack].subnets tests('success') do tests('#all').succeeds do @subnets.all end tests('#get').succeeds do @subnets.get @subnet.id end end @subnet.destroy endfog-1.19.0/tests/openstack/models/network/lb_pools_tests.rb0000644000004100000410000000103412261242552024071 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | lb_pools", ['openstack']) do @lb_pool = Fog::Network[:openstack].lb_pools.create(:subnet_id => 'subnet_id', :protocol => 'HTTP', :lb_method => 'ROUND_ROBIN') @lb_pools = Fog::Network[:openstack].lb_pools tests('success') do tests('#all').succeeds do @lb_pools.all end tests('#get').succeeds do @lb_pools.get @lb_pool.id end end @lb_pool.destroy endfog-1.19.0/tests/openstack/models/network/lb_health_monitor_tests.rb0000644000004100000410000000355012261242552025756 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | lb_health_monitor", ['openstack']) do tests('success') do before do @lb_pool = Fog::Network[:openstack].lb_pools.create(:subnet_id => 'subnet_id', :protocol => 'HTTP', :lb_method => 'ROUND_ROBIN') end after do @lb_pool.destroy end tests('#create').succeeds do @instance = Fog::Network[:openstack].lb_health_monitors.create(:type => 'PING', :delay => 1, :timeout => 5, :max_retries => 10, :http_method => 'GET', :url_path => '/', :expected_codes => '200, 201', :admin_state_up => true, :tenant_id => 'tenant_id') !@instance.id.nil? end tests('#update').succeeds do @instance.delay = 5 @instance.timeout = 10 @instance.max_retries = 20 @instance.http_method = 'POST' @instance.url_path = '/varz' @instance.expected_codes = '200' @instance.admin_state_up = false @instance.update end tests('#associate_to_pool').succeeds do @instance.associate_to_pool(@lb_pool.id) end tests('#disassociate_from_pool').succeeds do @instance.disassociate_from_pool(@lb_pool.id) end tests('#destroy').succeeds do @instance.destroy == true end end endfog-1.19.0/tests/openstack/models/network/ports_tests.rb0000644000004100000410000000155612261242552023440 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | ports", ['openstack']) do @port = Fog::Network[:openstack].ports.create(:name => 'port_name', :network_id => 'net_id', :fixed_ips => [], :mac_address => 'fa:16:3e:62:91:7f', :admin_state_up => true, :device_owner => 'device_owner', :device_id => 'device_id', :tenant_id => 'tenant_id') @ports = Fog::Network[:openstack].ports tests('success') do tests('#all').succeeds do @ports.all end tests('#get').succeeds do @ports.get @port.id end end @port.destroy endfog-1.19.0/tests/openstack/models/network/lb_vip_tests.rb0000644000004100000410000000326612261242552023544 0ustar www-datawww-dataShindo.tests("Fog::Network[:openstack] | lb_vip", ['openstack']) do tests('success') do tests('#create').succeeds do @instance = Fog::Network[:openstack].lb_vips.create(:subnet_id => 'subnet_id', :pool_id => 'pool_id', :protocol => 'HTTP', :protocol_port => 80, :name => 'test-vip', :description => 'Test VIP', :address => '10.0.0.1', :session_persistence => { "cookie_name" => "COOKIE_NAME", "type" => "APP_COOKIE" }, :connection_limit => 10, :admin_state_up => true, :tenant_id => 'tenant_id') !@instance.id.nil? end tests('#update').succeeds do @instance.pool_id = 'new_pool_id', @instance.name = 'new-test-vip' @instance.description = 'New Test VIP' @instance.session_persistence = { "type" => "HTTP_COOKIE" } @instance.connection_limit = 5 @instance.admin_state_up = false @instance.update end tests('#destroy').succeeds do @instance.destroy == true end end endfog-1.19.0/tests/openstack/models/storage/0000755000004100000410000000000012261242552020466 5ustar www-datawww-datafog-1.19.0/tests/openstack/models/storage/file_tests.rb0000644000004100000410000001231712261242552023160 0ustar www-datawww-dataShindo.tests('Fog::OpenStack::Storage | file', ['openstack']) do pending if Fog.mocking? def object_attributes(file=@instance) @instance.service.head_object(@directory.key, file.key).headers end def object_meta_attributes @instance.service.head_object(@directory.key, @instance.key).headers.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)}" } @directory = Fog::Storage[:openstack]. directories. create(directory_attributes) model_tests(@directory.files, file_attributes.merge(:etag => 'foo'), Fog.mocking?) do tests('#save should not blow up with etag') do @instance.save end end model_tests(@directory.files, file_attributes, Fog.mocking?) do tests("#metadata should load empty metadata").returns({}) do @instance.metadata 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 end tests('#content_disposition') do before do @instance = @directory.files.create :key => 'meta-test', :body => lorem_file, :content_disposition => 'ho-ho-ho' end after do clear_metadata @instance.save end tests("sets Content-Disposition on create").returns("ho-ho-ho") do object_attributes(@instance)["Content-Disposition"] 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 @instance.metadata['foo-bar'] = 'baz' @instance.metadata[:'foo_bar'] = 'bref' tests("should only support one value per metadata key").returns('bref') 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 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 end @directory.destroy end fog-1.19.0/tests/openstack/models/identity/0000755000004100000410000000000012261242552020653 5ustar www-datawww-datafog-1.19.0/tests/openstack/models/identity/role_tests.rb0000644000004100000410000000147712261242552023374 0ustar www-datawww-dataShindo.tests("Fog::Identity[:openstack] | role", ['openstack']) do @instance = Fog::Identity[:openstack].roles.new({:name => 'Role Name', :user_id => 1, :role_id => 1}) @tenant = Fog::Identity[:openstack].tenants.create(:name => 'test_user') @user = Fog::Identity[:openstack].users.create(:name => 'test_user', :tenant_id => @tenant.id, :password => 'spoof') tests('success') do tests('#save').returns(true) do @instance.save end tests('#add_to_user(@user.id, @tenant.id)').returns(true) do @instance.add_to_user(@user.id, @tenant.id) end tests('#remove_to_user(@user.id, @tenant.id)').returns(true) do @instance.remove_to_user(@user.id, @tenant.id) end tests('#destroy').returns(true) do @instance.destroy end end @user.destroy @tenant.destroy end fog-1.19.0/tests/openstack/models/identity/tenants_tests.rb0000644000004100000410000000136512261242552024103 0ustar www-datawww-dataShindo.tests("Fog::Compute[:openstack] | tenants", ['openstack']) do @instance = Fog::Identity[:openstack].tenants.create(:name => 'test') tests('success') do tests('#find_by_id').succeeds do tenant = Fog::Identity[:openstack].tenants.find_by_id(@instance.id) tenant.id == @instance.id end tests('#destroy').succeeds do Fog::Identity[:openstack].tenants.destroy(@instance.id) end end tests('fails') do pending if Fog.mocking? tests('#find_by_id').raises(Fog::Identity::OpenStack::NotFound) do Fog::Identity[:openstack].tenants.find_by_id('fake') end tests('#destroy').raises(Fog::Identity::OpenStack::NotFound) do Fog::Identity[:openstack].tenants.destroy('fake') end end end fog-1.19.0/tests/openstack/models/identity/tenant_tests.rb0000644000004100000410000000136612261242552023721 0ustar www-datawww-dataShindo.tests("Fog::Identity[:openstack] | tenant", ['openstack']) do tests('success') do tests('#roles_for(0)').succeeds do instance = Fog::Identity[:openstack].tenants.first instance.roles_for(0) end tests('#users').succeeds do instance = Fog::Identity[:openstack].tenants.first instance.users.count != Fog::Identity[:openstack].users.count end end tests('CRUD') do tests('#create').succeeds do @instance = Fog::Identity[:openstack].tenants.create(:name => 'test') !@instance.id.nil? end tests('#update').succeeds do @instance.update(:name => 'test2') @instance.name == 'test2' end tests('#destroy').succeeds do @instance.destroy == true end end end fog-1.19.0/tests/openstack/models/identity/users_tests.rb0000644000004100000410000000167112261242552023570 0ustar www-datawww-dataShindo.tests("Fog::Identity[:openstack] | users", ['openstack']) do tenant_id = Fog::Identity[:openstack].list_tenants.body['tenants'].first['id'] @instance = Fog::Identity[:openstack].users.create({ :name => 'foobar', :email => 'foo@bar.com', :tenant_id => tenant_id, :password => 'spoof', :enabled => true }) tests('success') do tests('#find_by_id').succeeds do user = Fog::Identity[:openstack].users.find_by_id(@instance.id) user.id == @instance.id end tests('#destroy').succeeds do Fog::Identity[:openstack].users.destroy(@instance.id) end end tests('fails') do pending if Fog.mocking? tests('#find_by_id').raises(Fog::Identity::OpenStack::NotFound) do Fog::Identity[:openstack].users.find_by_id('fake') end tests('#destroy').raises(Fog::Identity::OpenStack::NotFound) do Fog::Identity[:openstack].users.destroy('fake') end end end fog-1.19.0/tests/openstack/models/identity/ec2_credential_tests.rb0000644000004100000410000000165612261242552025275 0ustar www-datawww-dataShindo.tests("Fog::Identity[:openstack] | ec2_credential", ['openstack']) do before do openstack = Fog::Identity[:openstack] tenant_id = openstack.list_tenants.body['tenants'].first['id'] @user = openstack.users.find { |user| user.name == 'foobar' } @user ||= openstack.users.create({ :name => 'foobar', :email => 'foo@bar.com', :tenant_id => tenant_id, :password => 'spoof', :enabled => true }) @ec2_credential = openstack.ec2_credentials.create({ :user_id => @user.id, :tenant_id => tenant_id, }) end after do @user.ec2_credentials.each do |ec2_credential| ec2_credential.destroy end @user.destroy end tests('success') do tests('#destroy').returns(true) do @ec2_credential.destroy end end tests('failure') do tests('#save').raises(Fog::Errors::Error) do @ec2_credential.save end end end fog-1.19.0/tests/openstack/models/identity/roles_tests.rb0000644000004100000410000000124012261242552023543 0ustar www-datawww-dataShindo.tests("Fog::Identity[:openstack] | roles", ['openstack']) do @tenant = Fog::Identity[:openstack].tenants.create(:name => 'test_user') @user = Fog::Identity[:openstack].users.create(:name => 'test_user', :tenant_id => @tenant.id, :password => 'spoof') @role = Fog::Identity[:openstack].roles(:user => @user, :tenant => @tenant).create(:name => 'test_role') @roles = Fog::Identity[:openstack].roles(:user => @user, :tenant => @tenant) tests('success') do tests('#all').succeeds do @roles.all end tests('#get').succeeds do @roles.get @roles.first.id end end @role.destroy @user.destroy @tenant.destroy end fog-1.19.0/tests/openstack/models/identity/ec2_credentials_tests.rb0000644000004100000410000000266012261242552025454 0ustar www-datawww-dataShindo.tests("Fog::Identity[:openstack] | ec2_credentials", ['openstack']) do before do openstack = Fog::Identity[:openstack] tenant_id = openstack.list_tenants.body['tenants'].first['id'] @user = openstack.users.find { |user| user.name == 'foobar' } @user ||= openstack.users.create({ :name => 'foobar', :email => 'foo@bar.com', :tenant_id => tenant_id, :password => 'spoof', :enabled => true }) @ec2_credential = openstack.ec2_credentials.create({ :user_id => @user.id, :tenant_id => tenant_id, }) end after do @user.ec2_credentials.each do |ec2_credential| ec2_credential.destroy end @user.destroy end tests('success') do tests('#find_by_access_key').succeeds do ec2_credential = @user.ec2_credentials.find_by_access_key(@ec2_credential.access) ec2_credential.access == @ec2_credential.access end tests('#create').succeeds do @user.ec2_credentials.create end tests('#destroy').succeeds do @user.ec2_credentials.destroy(@ec2_credential.access) end end tests('fails') do pending if Fog.mocking? tests('#find_by_access_key').raises(Fog::Identity::OpenStack::NotFound) do @user.ec2_credentials.find_by_access_key('fake') end tests('#destroy').raises(Fog::Identity::OpenStack::NotFound) do @user.ec2_credentials.destroy('fake') end end end fog-1.19.0/tests/openstack/models/identity/user_tests.rb0000644000004100000410000000211312261242552023375 0ustar www-datawww-dataShindo.tests("Fog::Identity[:openstack] | user", ['openstack']) do tenant_id = Fog::Identity[:openstack].list_tenants.body['tenants'].first['id'] @instance = Fog::Identity[:openstack].users.new({ :name => 'User Name', :email => 'test@fog.com', :tenant_id => tenant_id, :password => 'spoof', :enabled => true }) tests('success') do tests('#save').returns(true) do @instance.save end tests('#roles').succeeds do @instance.roles end tests('#update').returns(true) do @instance.update({:name => 'updatename', :email => 'new@email.com'}) end tests('#update_password').returns(true) do @instance.update_password('swordfish') end tests('#update_tenant').returns(true) do @instance.update_tenant(tenant_id) end tests('#update_enabled').returns(true) do @instance.update_enabled(true) end tests('#destroy').returns(true) do @instance.destroy end end tests('failure') do tests('#save').raises(Fog::Errors::Error) do @instance.save end end end fog-1.19.0/tests/openstack/models/compute/0000755000004100000410000000000012261242552020476 5ustar www-datawww-datafog-1.19.0/tests/openstack/models/compute/security_group_tests.rb0000644000004100000410000000362112261242552025332 0ustar www-datawww-dataShindo.tests("Fog::Compute[:openstack] | security_group", ['openstack']) do tests('success') do begin fog = Fog::Compute[:openstack] security_group = fog.security_groups.create( :name => 'my_group', :description => 'my group' ) tests('#create').succeeds do security_group = fog.security_groups.create( :name => 'my_group', :description => 'my group' ) returns('my_group') { security_group.name } returns('my group') { security_group.description } returns([]) { security_group.security_group_rules } returns(true) { security_group.tenant_id != nil } end tests('#rules').succeeds do tests("#create").succeeds do rules_count = security_group.security_group_rules.count rule = security_group.security_group_rules.create( :parent_group_id => security_group.id, :ip_protocol => 'tcp', :from_port => 1234, :to_port => 1234, :ip_range => { "cidr" => "0.0.0.0/0" } ) returns(true) { security_group.security_group_rules.count == (rules_count + 1) } security_group_rule = security_group.security_group_rules.detect { |r| r.id == rule.id } returns(true) { security_group_rule.attributes == rule.attributes } end tests("#destroy").succeeds do rule = security_group.security_group_rules.create( :parent_group_id => security_group.id, :ip_protocol => 'tcp', :from_port => 1234, :to_port => 1234, :ip_range => { "cidr" => "0.0.0.0/0" } ) rule.destroy returns(true) { rule.reload == nil } end end ensure security_group.destroy if security_group end end end fog-1.19.0/tests/openstack/models/compute/server_tests.rb0000644000004100000410000001156112261242552023557 0ustar www-datawww-dataShindo.tests("Fog::Compute[:openstack] | server", ['openstack']) do tests('success') do tests('#security_groups').succeeds do fog = Fog::Compute[:openstack] begin my_group = fog.security_groups.create(:name => 'my_group', :description => 'my group') flavor = fog.flavors.first.id image = fog.images.first.id server = fog.servers.new(:name => 'test server', :flavor_ref => flavor, :image_ref => image) server.security_groups = my_group server.save found_groups = server.security_groups returns(1) { found_groups.length } group = found_groups.first returns('my_group') { group.name } returns(server.service) { group.service } ensure unless Fog.mocking? then server.destroy if server begin fog.servers.get(server.id).wait_for do false end rescue Fog::Errors::Error # ignore, server went away end end my_group.destroy if my_group end end tests('#metadata').succeeds do fog = Fog::Compute[:openstack] begin flavor = fog.flavors.first.id image = fog.images.first.id server = fog.servers.new(:name => 'test server', :metadata => {"foo" => "bar"}, :flavor_ref => flavor, :image_ref => image) server.save returns(1) { server.metadata.length } server.metadata.each do |datum| datum.value = 'foo' datum.save datum.destroy end ensure unless Fog.mocking? then server.destroy if server begin fog.servers.get(server.id).wait_for do false end rescue Fog::Errors::Error # ignore, server went away end end end end tests('#resize').succeeds do fog = Fog::Compute[:openstack] begin flavor = fog.flavors.first.id image = fog.images.first.id server = fog.servers.new(:name => 'test server', :flavor_ref => flavor, :image_ref => image) server.save flavor_resize = fog.flavors[1].id server.resize(flavor_resize) server.wait_for { server.state == "VERIFY_RESIZE" } unless Fog.mocking? server.revert_resize server.wait_for { server.state == "ACTIVE" } unless Fog.mocking? server.resize(flavor_resize) server.wait_for { server.state == "VERIFY_RESIZE" } unless Fog.mocking? server.confirm_resize ensure unless Fog.mocking? then server.destroy if server begin fog.servers.get(server.id).wait_for do false end rescue Fog::Errors::Error # ignore, server went away end end end end tests('#volumes').succeeds do fog = Fog::Compute[:openstack] begin volume = fog.volumes.new(:name => 'test volume', :description => 'test volume', :size => 1) volume.save volume.wait_for { volume.status == 'available' } unless Fog.mocking? flavor = fog.flavors.first.id image = fog.images.first.id server = fog.servers.new(:name => 'test server', :flavor_ref => flavor, :image_ref => image) server.save server.wait_for { server.state == "ACTIVE" } unless Fog.mocking? server.attach_volume(volume.id, '/dev/vdc') volume.wait_for { volume.status == 'in-use' } unless Fog.mocking? found_volumes = server.volumes returns(1) { found_volumes.length } volume = found_volumes.first returns('test volume') { volume.name } found_attachments = server.volume_attachments returns(1) { found_attachments.length } attachment = found_attachments.first returns('/dev/vdc') { attachment['device'] } server.detach_volume(volume.id) volume.wait_for { volume.status == 'available' } unless Fog.mocking? found_volumes = server.volumes returns(0) { found_volumes.length } found_attachments = server.volume_attachments returns(0) { found_attachments.length } ensure unless Fog.mocking? then server.destroy if server volume.destroy if volume begin fog.servers.get(server.id).wait_for do false end fog.volumes.get(volume.id).wait_for do false end rescue Fog::Errors::Error # ignore, server went away end end end end end end fog-1.19.0/tests/openstack/models/compute/images_tests.rb0000644000004100000410000000040312261242552023507 0ustar www-datawww-dataShindo.tests("Fog::Compute[:openstack] | images collection", ['openstack']) do tests('success') do tests('#all').succeeds do fog = Fog::Compute[:openstack] test 'not nil' do fog.images.all.is_a? Array end end end end fog-1.19.0/tests/openstack/models/image/0000755000004100000410000000000012261242552020104 5ustar www-datawww-datafog-1.19.0/tests/openstack/models/image/image_tests.rb0000644000004100000410000000144312261242552022737 0ustar www-datawww-dataShindo.tests("Fog::Image[:openstack] | image", ['openstack']) do tests('success') do tests('#create').succeeds do @instance = Fog::Image[:openstack].images.create(:name => 'test image') !@instance.id.nil? end tests('#update').succeeds do @instance.name = 'edit test image' @instance.update @instance.name == 'edit test image' end tests('#get image metadata').succeeds do @instance.metadata end tests('#add member').succeeds do @instance.add_member(@instance.owner) end tests('#show members').succeeds do @instance.members end tests('#remove member').succeeds do @instance.remove_member(@instance.owner) end tests('#destroy').succeeds do @instance.destroy == true end end end fog-1.19.0/tests/openstack/models/image/images_tests.rb0000644000004100000410000000116312261242552023121 0ustar www-datawww-dataShindo.tests("Fog::Image[:openstack] | images", ['openstack']) do @instance = Fog::Image[:openstack].create_image({:name => "model test image"}).body tests('success') do tests('#find_by_id').succeeds do image = Fog::Image[:openstack].images.find_by_id(@instance['image']['id']) image.id == @instance['image']['id'] end tests('#get').succeeds do image = Fog::Image[:openstack].images.get(@instance['image']['id']) image.id == @instance['image']['id'] end tests('#destroy').succeeds do Fog::Image[:openstack].images.destroy(@instance['image']['id']) end end end fog-1.19.0/tests/openstack/storage_tests.rb0000644000004100000410000000101212261242552020744 0ustar www-datawww-dataShindo.tests('Fog::Storage[:openstack]', ['openstack', 'storage']) do storage = Fog::Storage[:openstack] original_path = storage.instance_variable_get :@path tests("account changes") do test("#change_account") do new_account = 'AUTH_1234567890' storage.change_account new_account storage.instance_variable_get(:@path) != original_path end test("#reset_account_name") do storage.reset_account_name storage.instance_variable_get(:@path) == original_path end end end fog-1.19.0/tests/openstack/version_tests.rb0000644000004100000410000000427612261242552021004 0ustar www-datawww-dataShindo.tests('OpenStack | versions', ['openstack']) do begin @old_mock_value = Excon.defaults[:mock] Excon.defaults[:mock] = true Excon.stubs.clear body = { "versions" => [ { "status" => "CURRENT", "id" => "v2.0", "links" => [ { "href" => "http://example:9292/v2/", "rel" => "self" } ] }, { "status" => "CURRENT", "id" => "v1.1", "links" => [ { "href" => "http://exampple:9292/v1/", "rel" => "self" } ] }, { "status" => "SUPPORTED", "id"=>"v1.0", "links" => [ { "href" => "http://example:9292/v1/", "rel" => "self" } ] } ] } tests("supported") do Excon.stub({ :method => 'GET' }, { :status => 300, :body => Fog::JSON.encode(body) }) returns("v1.1") do Fog::OpenStack.get_supported_version(/v1(\.(0|1))*/, URI('http://example/'), "authtoken") end end tests("unsupported") do Excon.stub({ :method => 'GET' }, { :status => 300, :body => Fog::JSON.encode(body) }) raises(Fog::OpenStack::Errors::ServiceUnavailable) do Fog::OpenStack.get_supported_version(/v3(\.(0|1))*/, URI('http://example/'), "authtoken") end end ensure Excon.stubs.clear Excon.defaults[:mock] = @old_mock_value end endfog-1.19.0/tests/core/0000755000004100000410000000000012261242552014500 5ustar www-datawww-datafog-1.19.0/tests/core/connection_tests.rb0000644000004100000410000000136012261242552020406 0ustar www-datawww-dataShindo.tests('Fog::Core::Connection', ['core']) do raises(ArgumentError, "raises ArgumentError when no arguments given") do Fog::Core::Connection.new end tests('new("http://example.com")') do @instance = Fog::Core::Connection.new("http://example.com") responds_to([:request, :reset]) tests('user agent').returns("fog/#{Fog::VERSION}") do @instance.instance_variable_get(:@excon).data[:headers]['User-Agent'] end end tests('new("http://example.com", true)') do Fog::Core::Connection.new("http://example.com", true) end tests('new("http://example.com", false, options")') do options = { :debug_response => false } Fog::Core::Connection.new("http://example.com", true, options) end end fog-1.19.0/tests/core/current_machine_tests.rb0000644000004100000410000000141612261242552021417 0ustar www-datawww-dataShindo.tests('Fog CurrentMachine', 'core') do pending unless Fog.mock? old_excon_defaults_mock = Excon.defaults[:mock] Excon.defaults[:mock] = true tests('ip_address') do tests('should be thread safe') do Excon.stub({:method => :get, :path => '/'}, {:body => ''}) (1..10).map { Thread.new { Fog::CurrentMachine.ip_address } }.each{ |t| t.join } end Fog::CurrentMachine.ip_address = nil Excon.stubs.clear tests('should remove trailing endline characters') do Excon.stub({:method => :get, :path => '/'}, {:body => "192.168.0.1\n"}) Fog::CurrentMachine.ip_address == '192.168.0.1' end end Fog::CurrentMachine.ip_address = nil Excon.stubs.clear Excon.defaults[:mock] = old_excon_defaults_mock end fog-1.19.0/tests/core/service_tests.rb0000644000004100000410000000116712261242552017714 0ustar www-datawww-dataShindo.tests('Fog::Service', ['core']) do class TestService < Fog::Service recognizes :generic_user, :generic_api_key class Real attr_reader :options def initialize(opts={}) @options = opts end end class Mock < Real end end tests('Properly passes headers') do user_agent = 'Generic Fog Client' params = { :generic_user => "bob", :generic_api_key => '1234', :connection_options => {:headers => { 'User-Agent' => user_agent }}} service = TestService.new(params) returns('User-Agent' => user_agent) { service.options[:connection_options][:headers] } end endfog-1.19.0/tests/core/wait_for_tests.rb0000644000004100000410000000046012261242552020061 0ustar www-datawww-dataShindo.tests('Fog#wait_for', 'core') do tests("success") do tests('Fog#wait_for').formats(:duration => Integer) do Fog.wait_for(1) { true } end end tests("failure") do tests('Fog#wait_for').raises(Fog::Errors::TimeoutError) do Fog.wait_for(2) { false } end end end fog-1.19.0/tests/core/uuid_tests.rb0000644000004100000410000000041012261242552017210 0ustar www-datawww-dataShindo.tests('Fog::UUID', 'core') do tests('supported?').succeeds do Fog::UUID.supported? == SecureRandom.respond_to?(:uuid) end tests('success').succeeds do Fog::UUID.uuid =~ /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ end endfog-1.19.0/tests/core/timeout_tests.rb0000644000004100000410000000027212261242552017736 0ustar www-datawww-dataShindo.tests('Fog#timeout', 'core') do tests('timeout').returns(600) do Fog.timeout end tests('timeout = 300').returns(300) do Fog.timeout = 300 Fog.timeout end end fog-1.19.0/tests/core/mocking_tests.rb0000644000004100000410000000351412261242552017701 0ustar www-datawww-dataShindo.tests('Fog mocking', 'core') do before do @fog_was_mocked = Fog.mock? Fog.unmock! if @fog_was_mocked end after do Fog.mock! if @fog_was_mocked end tests('Fog.mock!') do tests('Fog.mock!').returns(true) do Fog.mock! end tests('Fog.mock? without Fog.mock!').returns(false) do Fog.mock? end tests('Fog.mock? with Fog.mock!').returns(true) do Fog.mock! Fog.mock? end tests('Fog.mocking? without Fog.mock!').returns(false) do Fog.mocking? end tests('Fog.mocking? with Fog.mock!').returns(true) do Fog.mock! Fog.mocking? end end tests('Fog::Mock.delay') do tests('Fog::Mock.delay').returns(1, "defaults to 1") do Fog::Mock.delay end tests('Fog::Mock.delay = 2').returns(2, "changes Fog::Mock.delay to 2") do Fog::Mock.delay = 2 Fog::Mock.delay end tests('Fog::Mock.delay = 0').returns(0, "changes Fog::Mock.delay to 0") do Fog::Mock.delay = 0 Fog::Mock.delay end tests('Fog::Mock.delay = -1').raises(ArgumentError) do Fog::Mock.delay = -1 end end tests('Fog::Mock.random_ip') do tests('Fog::Mock.random_ip').returns(true, "default to ipv4") do IPAddr.new(Fog::Mock.random_ip).ipv4? end tests('Fog::Mock.random_ip').returns(true, "explicit ipv4") do IPAddr.new(Fog::Mock.random_ip({:version => :v4})).ipv4? end tests('Fog::Mock.random_ip({:version => :v6})').returns(true, "changes to ipv6") do IPAddr.new(Fog::Mock.random_ip({:version => :v6})).ipv6? end tests('Fog::Mock.random_ip({:version => :v5})').raises(ArgumentError) do IPAddr.new(Fog::Mock.random_ip({:version => :v5})).ipv4? end end tests('Fog::Mock.not_implemented').raises(Fog::Errors::MockNotImplemented) do Fog::Mock.not_implemented end end fog-1.19.0/tests/core/credential_tests.rb0000644000004100000410000000475012261242552020367 0ustar www-datawww-dataShindo.tests do before do @old_home = ENV['HOME'] @old_rc = ENV['FOG_RC'] @old_credential = ENV['FOG_CREDENTIAL'] @old_credentials = Fog.credentials Fog.instance_variable_set('@credential_path', nil) # kill memoization Fog.instance_variable_set('@credential', nil) # kill memoization end after do ENV['HOME'] = @old_home ENV['FOG_RC'] = @old_rc ENV['FOG_CREDENTIAL'] = @old_credential Fog.credentials = @old_credentials end tests('credential') do returns(:default, "is :default") { Fog.credential } returns(:foo, "can be set directly") do Fog.credential = "foo" Fog.credential end returns(:bar, "can be set with environment variable") do ENV["FOG_CREDENTIAL"] = "bar" Fog.credential end end tests('credentials_path') do returns('/rc/path', 'FOG_RC takes precedence over HOME') { ENV['HOME'] = '/home/path' ENV['FOG_RC'] = '/rc/path' } returns('/expanded/path', 'properly expands paths') { ENV['FOG_RC'] = '/expanded/subdirectory/../path' Fog.credentials_path } returns(File.join(ENV['HOME'], '.fog'), 'falls back to home path if FOG_RC not set') { ENV.delete('FOG_RC') Fog.credentials_path } returns(nil, 'ignores home path if it does not exist') { ENV.delete('FOG_RC') ENV['HOME'] = '/no/such/path' Fog.credentials_path } returns(nil, 'File.expand_path raises because of non-absolute path') { ENV.delete('FOG_RC') ENV['HOME'] = '.' if RUBY_PLATFORM == 'java' Fog::Logger.warning("Stubbing out non-absolute path credentials test due to JRuby bug: https://github.com/jruby/jruby/issues/1163") nil else Fog.credentials_path end } returns(nil, 'returns nil when neither FOG_RC or HOME are set') { ENV.delete('HOME') ENV.delete('FOG_RC') Fog.credentials_path } end tests('symbolize_credential?') do returns(true, "username") { Fog.symbolize_credential?(:username) } returns(false, "headers") { Fog.symbolize_credential?(:headers) } end tests('symbolize_credentials') do h = { "a" => 3, :something => 2, "connection_options" => {"val" => 5}, :headers => { 'User-Agent' => "my user agent" } } returns({ :a => 3, :something => 2, :connection_options => {:val => 5}, :headers => { 'User-Agent' => "my user agent" } }) { Fog.symbolize_credentials h } end end fog-1.19.0/tests/core/attribute_tests.rb0000644000004100000410000000361112261242552020253 0ustar www-datawww-dataclass FogAttributeTestModel < Fog::Model attribute :key, :aliases => 'keys', :squash => "id" attribute :time, :type => :time attribute :bool, :type => :boolean end Shindo.tests('Fog::Attributes', 'core') do @model = FogAttributeTestModel.new tests('squash') do tests('"keys" => {:id => "value"}').returns('value') do @model.merge_attributes("keys" => {:id => "value"}) @model.key end tests('"keys" => {"id" => "value"}').returns('value') do @model.merge_attributes("keys" => {'id' => "value"}) @model.key end tests('"keys" => {"id" => false}').returns(false) do @model.merge_attributes("keys" => {'id' => false }) @model.key end tests('"keys" => {:id => false}').returns(false) do @model.merge_attributes("keys" => {:id => false }) @model.key end end tests(':type => :time') do @time = Time.now tests(':time => nil').returns(nil) do @model.merge_attributes(:time => nil) @model.time end tests(':time => ""').returns('') do @model.merge_attributes(:time => '') @model.time end tests(':time => "#{@time.to_s}"').returns(Time.parse(@time.to_s)) do @model.merge_attributes(:time => @time.to_s) @model.time end end tests(':type => :boolean') do tests(':bool => "true"').returns(true) do @model.merge_attributes(:bool => 'true') @model.bool end tests(':bool => true').returns(true) do @model.merge_attributes(:bool => true) @model.bool end tests(':bool => "false"').returns(false) do @model.merge_attributes(:bool => 'false') @model.bool end tests(':bool => false').returns(false) do @model.merge_attributes(:bool => false) @model.bool end tests(':bool => "foo"').returns(nil) do @model.merge_attributes(:bool => "foo") @model.bool end end end fog-1.19.0/tests/core/parser_tests.rb0000644000004100000410000000430612261242552017546 0ustar www-datawww-dataShindo.tests('Fog::Parsers', 'core') do class TestParser < Fog::Parsers::Base def reset super reset_my_array end def reset_my_array @my_array = [] end def end_element(name) case name when 'key1', 'key2', 'key3', 'longText' @response[name] = value when 'myArray' @response[name] = @my_array reset_my_array when 'id' @my_array << value.to_i end end end @xml = %{ value1 value2 1 2 3 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis metus arcu, quis cursus turpis. Aliquam leo lacus, luctus vel iaculis id, posuere eu odio. Donec sodales, ante porta condimentum value3 } @xmlNS = %{ value1 value2 1 2 3 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis metus arcu, quis cursus turpis. Aliquam leo lacus, luctus vel iaculis id, posuere eu odio. Donec sodales, ante porta condimentum value3 } @response = { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'myArray' => [1,2,3], 'longText' => %{ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis metus arcu, quis cursus turpis. Aliquam leo lacus, luctus vel iaculis id, posuere eu odio. Donec sodales, ante porta condimentum } } tests('TestParser').returns(@response, "returns the response") do test_parser = TestParser.new Nokogiri::XML::SAX::Parser.new(test_parser).parse(@xml) test_parser.response end tests('TestParser for namespaces').returns(@response, "returns the response") do test_parser = TestParser.new Nokogiri::XML::SAX::Parser.new(test_parser).parse(@xmlNS) test_parser.response end end fog-1.19.0/tests/lorem.txt0000644000004100000410000000067612261242552015440 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-1.19.0/tests/vcloud/0000755000004100000410000000000012261242552015044 5ustar www-datawww-datafog-1.19.0/tests/vcloud/data/0000755000004100000410000000000012261242552015755 5ustar www-datawww-datafog-1.19.0/tests/vcloud/data/api_+_v1.0_+_network_+_10000644000004100000410000000405012261242552022043 0ustar www-datawww-data Some fancy Network false 192.168.0.1 255.255.255.0 172.0.0.2 172.0.0.190 192.168.0.101 192.168.0.150 192.168.0.1 natRouted false 3600 7200 192.168.0.151 192.168.0.254 true false portForwarding allowTraffic fog-1.19.0/tests/vcloud/data/api_+_vApp_+_vm-20000644000004100000410000003041612261242552020730 0ustar www-datawww-data vm-595 VIRTUAL_MACHINE Some VM Description Virtual hardware requirements Virtual Hardware Family 0 vm2 vmx-07 00:50:56:01:02:03 0 true Network1 PCNet32 ethernet adapter Network adapter 0 1 PCNet32 10 0 SCSI Controller SCSI Controller 0 2 lsilogicsas 6 0 Hard disk Hard disk 1 2000 2 17 1 Hard disk Hard disk 2 3000 2 17 0 IDE Controller IDE Controller 0 3 5 0 false CD/DVD Drive CD/DVD Drive 1 3002 3 15 hertz * 10^6 Number of Virtual CPUs 1 virtual CPU(s) 4 0 3 1 0 byte * 2^20 Memory Size 512 MB of memory 5 0 4 512 0 Specifies the operating system installed Red Hat Enterprise Linux 5 (64-bit) Specifies the available VM network connections 0 0 192.168.2.102 192.168.1.103 true 00:50:56:01:02:03 POOL 1 192.168.3.102 true 00:50:56:01:02:04 POOL Specifies Guest OS Customization Settings true false 2 false false true true password false vm2 vmware_RHEL5-U5-64-small_v02 fog-1.19.0/tests/vcloud/data/api_+_v1.0_+_vApp_+_vm-20000644000004100000410000003033312261242552021704 0ustar www-datawww-data vm-595 VIRTUAL_MACHINE Some VM Description Virtual hardware requirements Virtual Hardware Family 0 vm2 vmx-07 00:50:56:01:02:03 0 true Network1 PCNet32 ethernet adapter Network adapter 0 1 PCNet32 10 0 SCSI Controller SCSI Controller 0 2 lsilogicsas 6 0 Hard disk Hard disk 1 2000 2 17 1 Hard disk Hard disk 2 3000 2 17 0 IDE Controller IDE Controller 0 3 5 0 false CD/DVD Drive CD/DVD Drive 1 3002 3 15 hertz * 10^6 Number of Virtual CPUs 1 virtual CPU(s) 4 0 3 1 0 byte * 2^20 Memory Size 512 MB of memory 5 0 4 512 0 Specifies the operating system installed Red Hat Enterprise Linux 5 (64-bit) Specifies the available VM network connections 0 0 192.168.2.102 192.168.1.103 true 00:50:56:01:02:03 POOL 1 192.168.3.102 true 00:50:56:01:02:04 POOL Specifies Guest OS Customization Settings true false 2 false false true true password false vm2 vmware_RHEL5-U5-64-small_v02 fog-1.19.0/tests/vcloud/data/api_+_vdc_+_10000644000004100000410000001054712261242552020160 0ustar www-datawww-data resgroup-1 RESOURCE_POOL Some Description AllocationVApp MB 10240 102400 101650 0 MHz 20000 40000 2000 0 MB 1024 10240 8385 0 10 10 10 true fog-1.19.0/tests/vcloud/data/api_+_v1.0_+_vApp_+_vapp-10000644000004100000410000007367212261242552022244 0ustar www-datawww-data Some Description of a vApp Lease settings section 0 0 VApp startup section The list of logical networks The configuration parameters for logical networks Some Network Description false 192.168.2.1 255.255.255.0 192.168.2.1 192.168.2.101 192.168.2.150 192.168.2.101 192.168.2.1 192.168.2.102 natRouted false 7200 7200 true true ipTranslation allowTraffic automatic 192.168.1.102 vm1 0 automatic 192.168.1.103 vm2 0 true vm-595 VIRTUAL_MACHINE Virtual hardware requirements Virtual Hardware Family 0 vm2 vmx-07 00:50:56:01:02:03 0 true Network1 PCNet32 ethernet adapter Network adapter 0 1 PCNet32 10 0 SCSI Controller SCSI Controller 0 2 lsilogicsas 6 0 Hard disk Hard disk 1 2000 2 17 0 IDE Controller IDE Controller 0 3 5 0 false CD/DVD Drive CD/DVD Drive 1 3002 3 15 hertz * 10^6 Number of Virtual CPUs 1 virtual CPU(s) 4 0 3 1 0 byte * 2^20 Memory Size 512 MB of memory 5 0 4 512 0 Specifies the operating system installed Red Hat Enterprise Linux 5 (64-bit) Specifies the available VM network connections 0 0 192.168.2.102 192.168.1.103 true 00:50:56:01:00:03 POOL Specifies Guest OS Customization Settings true false 2 false false true true password false vm2 vmware_RHEL5-U5-64-small_v02 vm-594 VIRTUAL_MACHINE Virtual hardware requirements Virtual Hardware Family 0 vm1 vmx-07 00:50:56:01:02:04 0 true Network1 PCNet32 ethernet adapter Network adapter 0 1 PCNet32 10 0 SCSI Controller SCSI Controller 0 2 lsilogicsas 6 0 Hard disk Hard disk 1 2000 2 17 0 IDE Controller IDE Controller 0 3 5 0 false CD/DVD Drive CD/DVD Drive 1 3002 3 15 hertz * 10^6 Number of Virtual CPUs 1 virtual CPU(s) 4 0 3 1 0 byte * 2^20 Memory Size 512 MB of memory 5 0 4 512 0 Specifies the operating system installed Red Hat Enterprise Linux 5 (64-bit) Specifies the available VM network connections 0 0 192.168.2.101 192.168.1.102 true 00:50:56:01:02:04 POOL Specifies Guest OS Customization Settings true false 1 false false true true password false vm1 vmware_RHEL5-U5-64-small_v01 fog-1.19.0/tests/vcloud/data/api_+_v1.0_+_admin_+_network_+_20000644000004100000410000001264512261242552023437 0ustar www-datawww-data Internet Connection false 172.0.0.1 255.255.255.0 172.0.0.2 172.0.0.190 172.0.0.142 172.0.0.156 172.0.0.160 172.0.0.184 172.0.0.195 172.0.0.235 172.0.0.153 172.0.0.147 172.0.0.221 172.0.0.226 172.0.0.151 172.0.0.161 172.0.0.164 172.0.0.163 172.0.0.218 172.0.0.173 172.0.0.172 172.0.0.175 172.0.0.178 172.0.0.197 172.0.0.180 172.0.0.201 172.0.0.156 172.0.0.202 172.0.0.183 172.0.0.149 172.0.0.214 172.0.0.171 172.0.0.162 172.0.0.198 172.0.0.224 172.0.0.195 172.0.0.196 172.0.0.150 172.0.0.169 172.0.0.170 172.0.0.176 172.0.0.200 172.0.0.179 172.0.0.205 172.0.0.213 172.0.0.210 172.0.0.215 172.0.0.219 172.0.0.208 172.0.0.216 172.0.0.217 172.0.0.204 172.0.0.232 172.0.0.154 172.0.0.235 172.0.0.146 172.0.0.209 172.0.0.211 172.0.0.199 172.0.0.155 172.0.0.142 172.0.0.160 172.0.0.212 172.0.0.177 172.0.0.167 172.0.0.166 172.0.0.168 172.0.0.165 172.0.0.181 172.0.0.184 172.0.0.143 172.0.0.230 172.0.0.206 172.0.0.233 172.0.0.222 172.0.0.225 172.0.0.220 172.0.0.227 172.0.0.148 172.0.0.228 172.0.0.229 172.0.0.231 172.0.0.152 172.0.0.145 172.0.0.174 172.0.0.182 172.0.0.203 172.0.0.207 172.0.0.144 isolated NETWORK:dvportgroup-230 on com.vmware.vcloud.entity.vimserver:35935555 fog-1.19.0/tests/vcloud/data/api_+_v1.0_+_vApp_+_vm-10000644000004100000410000002660012261242552021705 0ustar www-datawww-data vm-594 VIRTUAL_MACHINE Virtual hardware requirements Virtual Hardware Family 0 vm1 vmx-07 00:50:56:01:02:04 0 true Network1 PCNet32 ethernet adapter Network adapter 0 1 PCNet32 10 0 SCSI Controller SCSI Controller 0 2 lsilogicsas 6 0 Hard disk Hard disk 1 2000 2 17 0 IDE Controller IDE Controller 0 3 5 0 false CD/DVD Drive CD/DVD Drive 1 3002 3 15 hertz * 10^6 Number of Virtual CPUs 1 virtual CPU(s) 4 0 3 1 0 byte * 2^20 Memory Size 512 MB of memory 5 0 4 512 0 Specifies the operating system installed Red Hat Enterprise Linux 5 (64-bit) Specifies the available VM network connections 0 0 192.168.2.101 192.168.1.102 true 00:50:56:01:02:04 POOL Specifies Guest OS Customization Settings true false 1 false false true true password false vm1 vmware_RHEL5-U5-64-small_v01 fog-1.19.0/tests/vcloud/data/api_+_org_+_0000644000004100000410000000110412261242552020077 0ustar www-datawww-data fog-1.19.0/tests/vcloud/data/api_+_org_+_10000644000004100000410000000354012261242552020166 0ustar www-datawww-data Some fancy Description My Full Name fog-1.19.0/tests/vcloud/data/api_+_network_+_10000644000004100000410000000410412261242552021065 0ustar www-datawww-data Some fancy Network false 192.168.0.1 255.255.255.0 172.0.0.2 172.0.0.190 192.168.0.101 192.168.0.150 192.168.0.1 natRouted false 3600 7200 192.168.0.151 192.168.0.254 true false portForwarding allowTraffic fog-1.19.0/tests/vcloud/data/api_+_v1.0_+_login0000644000004100000410000000111712261242552021031 0ustar www-datawww-data fog-1.19.0/tests/vcloud/data/api_+_v1.0_+_org_+_10000644000004100000410000000356712261242552021155 0ustar www-datawww-data Some fancy Description My Full Name fog-1.19.0/tests/vcloud/data/api_+_vApp_+_vapp-10000644000004100000410000007311612261242552021257 0ustar www-datawww-data Some Description of a vApp Lease settings section 0 0 VApp startup section The list of logical networks The configuration parameters for logical networks Some Network Description false 192.168.2.1 255.255.255.0 192.168.2.1 192.168.2.101 192.168.2.150 192.168.2.101 192.168.2.1 192.168.2.102 natRouted false 7200 7200 true true ipTranslation allowTraffic automatic 192.168.1.102 vm1 0 automatic 192.168.1.103 vm2 0 true vm-595 VIRTUAL_MACHINE Virtual hardware requirements Virtual Hardware Family 0 vm2 vmx-07 00:50:56:01:02:03 0 true Network1 PCNet32 ethernet adapter Network adapter 0 1 PCNet32 10 0 SCSI Controller SCSI Controller 0 2 lsilogicsas 6 0 Hard disk Hard disk 1 2000 2 17 0 IDE Controller IDE Controller 0 3 5 0 false CD/DVD Drive CD/DVD Drive 1 3002 3 15 hertz * 10^6 Number of Virtual CPUs 1 virtual CPU(s) 4 0 3 1 0 byte * 2^20 Memory Size 512 MB of memory 5 0 4 512 0 Specifies the operating system installed Red Hat Enterprise Linux 5 (64-bit) Specifies the available VM network connections 0 0 192.168.2.102 192.168.1.103 true 00:50:56:01:00:03 POOL Specifies Guest OS Customization Settings true false 2 false false true true password false vm2 vmware_RHEL5-U5-64-small_v02 vm-594 VIRTUAL_MACHINE Virtual hardware requirements Virtual Hardware Family 0 vm1 vmx-07 00:50:56:01:02:04 0 true Network1 PCNet32 ethernet adapter Network adapter 0 1 PCNet32 10 0 SCSI Controller SCSI Controller 0 2 lsilogicsas 6 0 Hard disk Hard disk 1 2000 2 17 0 IDE Controller IDE Controller 0 3 5 0 false CD/DVD Drive CD/DVD Drive 1 3002 3 15 hertz * 10^6 Number of Virtual CPUs 1 virtual CPU(s) 4 0 3 1 0 byte * 2^20 Memory Size 512 MB of memory 5 0 4 512 0 Specifies the operating system installed Red Hat Enterprise Linux 5 (64-bit) Specifies the available VM network connections 0 0 192.168.2.101 192.168.1.102 true 00:50:56:01:02:04 POOL Specifies Guest OS Customization Settings true false 1 false false true true password false vm1 vmware_RHEL5-U5-64-small_v01 fog-1.19.0/tests/vcloud/data/api_+_v1.0_+_vdc_+_10000644000004100000410000001065512261242552021136 0ustar www-datawww-data resgroup-1 RESOURCE_POOL Some Description AllocationVApp MB 10240 102400 101650 0 MHz 20000 40000 2000 0 MB 1024 10240 8385 0 10 10 10 true fog-1.19.0/tests/vcloud/data/api_+_admin_+_network_+_20000644000004100000410000001270512261242552022456 0ustar www-datawww-data Internet Connection false 172.0.0.1 255.255.255.0 172.0.0.2 172.0.0.190 172.0.0.142 172.0.0.156 172.0.0.160 172.0.0.184 172.0.0.195 172.0.0.235 172.0.0.153 172.0.0.147 172.0.0.221 172.0.0.226 172.0.0.151 172.0.0.161 172.0.0.164 172.0.0.163 172.0.0.218 172.0.0.173 172.0.0.172 172.0.0.175 172.0.0.178 172.0.0.197 172.0.0.180 172.0.0.201 172.0.0.156 172.0.0.202 172.0.0.183 172.0.0.149 172.0.0.214 172.0.0.171 172.0.0.162 172.0.0.198 172.0.0.224 172.0.0.195 172.0.0.196 172.0.0.150 172.0.0.169 172.0.0.170 172.0.0.176 172.0.0.200 172.0.0.179 172.0.0.205 172.0.0.213 172.0.0.210 172.0.0.215 172.0.0.219 172.0.0.208 172.0.0.216 172.0.0.217 172.0.0.204 172.0.0.232 172.0.0.154 172.0.0.235 172.0.0.146 172.0.0.209 172.0.0.211 172.0.0.199 172.0.0.155 172.0.0.142 172.0.0.160 172.0.0.212 172.0.0.177 172.0.0.167 172.0.0.166 172.0.0.168 172.0.0.165 172.0.0.181 172.0.0.184 172.0.0.143 172.0.0.230 172.0.0.206 172.0.0.233 172.0.0.222 172.0.0.225 172.0.0.220 172.0.0.227 172.0.0.148 172.0.0.228 172.0.0.229 172.0.0.231 172.0.0.152 172.0.0.145 172.0.0.174 172.0.0.182 172.0.0.203 172.0.0.207 172.0.0.144 isolated NETWORK:dvportgroup-230 on com.vmware.vcloud.entity.vimserver:35935555 fog-1.19.0/tests/vcloud/data/api_+_sessions0000644000004100000410000000175012261242552020614 0ustar www-datawww-data fog-1.19.0/tests/vcloud/data/api_+_v1.0_+_network_+_20000644000004100000410000000271612261242552022053 0ustar www-datawww-data Description false 192.168.251.254 255.255.255.0 192.168.251.254 192.168.251.101 192.168.251.200 isolated false 3600 7200 192.168.251.1 192.168.251.100 fog-1.19.0/tests/vcloud/requests/0000755000004100000410000000000012261242552016717 5ustar www-datawww-datafog-1.19.0/tests/vcloud/requests/compute/0000755000004100000410000000000012261242552020373 5ustar www-datawww-datafog-1.19.0/tests/vcloud/requests/compute/disk_configure_tests.rb0000644000004100000410000001134312261242552025137 0ustar www-datawww-databegin require 'rspec' require 'rspec/mocks' rescue LoadError require 'spec' require 'spec/mocks' end Shindo.tests("Vcloud::Compute | disk_requests", ['vcloud']) do @xmlns = { "xmlns" => "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData", "xmlns:vcloud" => "http://www.vmware.com/vcloud/v1" } def disk_hash [{:"rasd:AddressOnParent"=>"0", :"rasd:Description"=>"Hard disk", :"rasd:ElementName"=>"Hard disk 1", :"rasd:HostResource"=> {:vcloud_capacity=>"8192", :vcloud_busType=>"6", :vcloud_busSubType=>"lsilogic"}, :"rasd:InstanceID"=>"2000", :"rasd:Parent"=>"2", :"rasd:ResourceType"=>"17"}] end def nokogiri_load Nokogiri::XML(MockDiskResponse.new.body) end class MockDiskResponse def body < 0 SCSI Controller SCSI Controller 0 2 lsilogic 6 0 Hard disk Hard disk 1 2000 2 17 0 IDE Controller IDE Controller 0 3 5 EOF end end unless Fog.mocking? Vcloud[:compute].stub!(:request).and_return(MockDiskResponse.new) end tests("Call to generate config returns string").returns(true) do pending if Fog.mocking? Vcloud[:compute].generate_configure_vm_disks_request('http://blah', disk_hash).kind_of? String end tests("Call to generate config with no changes returns input data").returns(true) do pending if Fog.mocking? Nokogiri::XML(Vcloud[:compute].generate_configure_vm_disks_request('http://blah', disk_hash)).to_s == Nokogiri::XML(MockDiskResponse.new.body).to_s end tests("Call to generate config with no disks removes disk").returns(true) do pending if Fog.mocking? xml = Vcloud[:compute].generate_configure_vm_disks_request('http://blah', []) ng = Nokogiri::XML(xml) # Should have 2 controllers, but no disks. ng.xpath("//xmlns:ResourceType", @xmlns).size == 2 && ng.xpath("//xmlns:ResourceType[ .='17']", @xmlns).size == 0 end tests("Call to generate config adding a disk").returns(['4096', true, true]) do pending if Fog.mocking? disks = disk_hash disks << { :"rasd:AddressOnParent"=>"1", :"rasd:Description"=>"Hard disk", :"rasd:ElementName"=>"Hard disk 2", :"rasd:HostResource"=> {:vcloud_capacity=>"4096", :vcloud_busType=>"6", :vcloud_busSubType=>"lsilogic"}, :"rasd:InstanceID"=>"2000", :"rasd:Parent"=>"2", :"rasd:ResourceType"=>"17"} xml = Vcloud[:compute].generate_configure_vm_disks_request('http://blah', disks) ng = Nokogiri::XML(xml) [ # should be 4096mb ng.at("//xmlns:ResourceType[ .='17']/../xmlns:AddressOnParent[.='-1']/../xmlns:HostResource", @xmlns)["capacity"], # Should have 2 controllers, and 2 disks ng.xpath("//xmlns:ResourceType", @xmlns).size == 4, ng.xpath("//xmlns:ResourceType[ .='17']", @xmlns).size == 2 ] end unless Fog.mocking? Vcloud[:compute].unstub!(:request) end end fog-1.19.0/tests/vcloud/models/0000755000004100000410000000000012261242552016327 5ustar www-datawww-datafog-1.19.0/tests/vcloud/models/compute/0000755000004100000410000000000012261242552020003 5ustar www-datawww-datafog-1.19.0/tests/vcloud/models/compute/networks_tests.rb0000644000004100000410000000433312261242552023431 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/networks' Shindo.tests("Vcloud::Compute | networks", ['vcloud']) do Fog::Vcloud::Compute::SUPPORTED_VERSIONS.each do |version| tests("api version #{version}") do pending if Fog.mocking? tests("from an org perspective") do instance = Fog::Vcloud::Compute::Networks.new( :connection => Fog::Vcloud::Compute.new( :vcloud_host => 'vcloud.example.com', :vcloud_username => 'username', :vcloud_password => 'password', :vcloud_version => version ), :href => "https://vcloud.example.com/api#{version == '1.0' ? '/v1.0' : ''}/org/1" ) tests("collection") do returns(2) { instance.size } returns("https://vcloud.example.com/api#{version == '1.0' ? '/v1.0' : ''}/network/1") { instance.first.href } end end tests("from a vdc perspective") do instance = Fog::Vcloud::Compute::Networks.new( :connection => Fog::Vcloud::Compute.new( :vcloud_host => 'vcloud.example.com', :vcloud_username => 'username', :vcloud_password => 'password', :vcloud_version => version ), :href => "https://vcloud.example.com/api#{version == '1.0' ? '/v1.0' : ''}/vdc/1" ) tests("collection") do returns(2) { instance.size } returns("https://vcloud.example.com/api#{version == '1.0' ? '/v1.0' : ''}/network/1") { instance.first.href } end end tests("from a vapp perspective") do instance = Fog::Vcloud::Compute::Networks.new( :connection => Fog::Vcloud::Compute.new( :vcloud_host => 'vcloud.example.com', :vcloud_username => 'username', :vcloud_password => 'password', :vcloud_version => version ), :href => "https://vcloud.example.com/api#{version == '1.0' ? '/v1.0' : ''}/vApp/vapp-1" ) tests("collection") do returns(1) { instance.size } returns("https://vcloud.example.com/api#{version == '1.0' ? '/v1.0' : ''}/network/1") { instance.first.href } end end end end end fog-1.19.0/tests/vcloud/models/compute/vdcs_tests.rb0000644000004100000410000000156512261242552022520 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/vdcs' Shindo.tests("Vcloud::Compute | vdcs", ['vcloud']) do Fog::Vcloud::Compute::SUPPORTED_VERSIONS.each do |version| tests("api version #{version}") do pending if Fog.mocking? instance = Fog::Vcloud::Compute::Vdcs.new( :connection => Fog::Vcloud::Compute.new( :vcloud_host => 'vcloud.example.com', :vcloud_username => 'username', :vcloud_password => 'password', :vcloud_version => version), :href => "https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/org/1" ) tests("collection") do returns(1) { instance.size } returns("https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/vdc/1") { instance.first.href } end end end end fog-1.19.0/tests/vcloud/models/compute/helper.rb0000644000004100000410000000110612261242552021605 0ustar www-datawww-dataclass Vcloud module Compute module TestSupport if Fog.mocking? def self.template 'mock_template' end else def self.template template_name = ENV['VCLOUD_TEMPLATE'] raise "Specify VApp template name in VCLOUD_TEMPLATE env var" unless template_name template_res = Vcloud.catalogs.item_by_name template_name raise "URI Not found for specified template - check template name" unless template_res template_res.href end end end module Formats end end end fog-1.19.0/tests/vcloud/models/compute/server_tests.rb0000644000004100000410000001170512261242552023064 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/servers' Shindo.tests("Vcloud::Compute | server", ['vcloud']) do Fog::Vcloud::Compute::SUPPORTED_VERSIONS.each do |version| tests("api version #{version}") do pending if Fog.mocking? instance = Fog::Vcloud::Compute.new( :vcloud_host => 'vcloud.example.com', :vcloud_username => 'username', :vcloud_password => 'password', :vcloud_version => version ).get_server("https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/vApp/vm-2") instance.reload tests("#href").returns("https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/vApp/vm-2") { instance.href } tests("#name").returns("vm2") { instance.name } tests("#vapp").returns("vApp1") { instance.vapp.name } tests("#description").returns("Some VM Description") { instance.description } tests("#status").returns('8') { instance.status } tests("#deployed").returns(true) { instance.deployed } tests("#os_desc").returns("Red Hat Enterprise Linux 5 (64-bit)") { instance.os_desc } tests("#os_type").returns("rhel5_64Guest") { instance.os_type } tests("#computer_name").returns("vm2") { instance.computer_name } tests("cpu count").returns(1) { instance.cpus[:count] } tests("amount of memory").returns(512){ instance.memory[:amount] } tests("#disks") do tests("#size").returns(2){ instance.disks.size } tests("#number").returns(0){ instance.disks.first[:number] } tests("#size").returns(1600){ instance.disks.first[:size] } tests("#ElementName").returns("Hard disk 1"){ instance.disks.first[:disk_data][:'rasd:ElementName'] } tests("#InstanceID").returns("2000"){ instance.disks.first[:disk_data][:'rasd:InstanceID'] } end tests("#vapp_scoped_local_id").returns("vmware_RHEL5-U5-64-small_v02") { instance.vapp_scoped_local_id } tests("#friendly_status").returns('off') { instance.friendly_status } tests("#on?").returns(false) { instance.on? } tests("#off?").returns(true) { instance.off? } tests("#network_connections") do tests("#size").returns(2) { instance.network_connections.size } end end end #old tests tests("#server.new('#{Vcloud::Compute::TestSupport::template}')").returns(true) do pending if Fog.mocking? @svr = Vcloud.servers.create :catalog_item_uri => Vcloud::Compute::TestSupport::template, :name => 'fog_test_run', :password => 'password' print "Waiting for server to be ready" @svr.wait_for(1200) { print '.' ; ready? } puts "" @svr.ready? end tests("#svr.power_on()").returns(true) do pending if Fog.mocking? @svr.power_on @svr.wait_for { on? } @svr.wait_for { ready? } @svr.on? end tests("#svr.description(\"testing\")").returns("testing") do pending if Fog.mocking? @svr.wait_for { ready? } @svr.description = "testing" @svr.save @svr.wait_for { ready? } @svr.description end # Power off only stops the OS, doesn't free up resources. #undeploy is for this. tests("#svr.undeploy()").returns(true) do pending if Fog.mocking? @svr.undeploy @svr.wait_for { off? } @svr.wait_for { ready? } @svr.off? end tests("#svr.memory(384)").returns(384) do pending if Fog.mocking? raise 'Server template memory already 384m - change to something different' if @svr.memory[:amount] == 384 @svr.wait_for { ready? } @svr.memory = 384 @svr.save @svr.wait_for { ready? } # Can take a little while for the VM to know it has different ram, and not tied to a task.. (1..20).each do |i| break if @svr.reload.memory[:amount] == '384' sleep 1 end @svr.reload.memory[:amount] end tests("#svr.add_disk(4096)").returns([2, "4096"]) do pending if Fog.mocking? raise 'Server template already has two disks' if @svr.disks.size == 2 @svr.wait_for { ready? } @svr.add_disk(4096) @svr.save @svr.wait_for { ready? } # Can take a little while for the VM to know it has different ram, and not tied to a task.. (1..20).each do |i| break if @svr.reload.disks.size == 2 sleep 1 end [ @svr.disks.size, @svr.disks[1][:resource][:vcloud_capacity] ] end tests("#svr.delete_disk(1)").returns(1) do pending if Fog.mocking? raise "Server doesn't have two disks - did previous step fail? " if @svr.disks.size != 2 @svr.wait_for { ready? } sleep 5 # otherwise complains about being busy @svr.delete_disk 1 @svr.save @svr.wait_for { ready? } # Can take a little while for the VM to know it has different ram, and not tied to a task.. (1..20).each do |i| break if @svr.reload.disks.size == 1 sleep 1 end @svr.disks.size end tests("#svr.destroy").raises(Excon::Errors::Forbidden) do pending if Fog.mocking? @svr.destroy sleep 5 # allow cleanup.. Vcloud.servers.get(@svr.href) == nil end end fog-1.19.0/tests/vcloud/models/compute/organizations_tests.rb0000644000004100000410000000120612261242552024440 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/organizations' Shindo.tests("Vcloud::Compute | organizations", ['vcloud']) do Fog::Vcloud::Compute::SUPPORTED_VERSIONS.each do |version| tests("api version #{version}") do pending if Fog.mocking? instance = Fog::Vcloud::Compute.new(:vcloud_host => 'vcloud.example.com', :vcloud_username => 'username', :vcloud_password => 'password', :vcloud_version => version).organizations tests("collection") do returns(2) { instance.size } returns("https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/org/1") { instance.first.href } end end end end fog-1.19.0/tests/vcloud/models/compute/organization_tests.rb0000644000004100000410000000156012261242552024260 0ustar www-datawww-dataShindo.tests("Vcloud::Compute | organization", ['vcloud']) do Fog::Vcloud::Compute::SUPPORTED_VERSIONS.each do |version| tests("api version #{version}") do pending if Fog.mocking? instance = Fog::Vcloud::Compute.new( :vcloud_host => 'vcloud.example.com', :vcloud_username => 'username', :vcloud_password => 'password', :vcloud_version => version ).get_organization("https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/org/1") instance.reload tests("#href").returns("https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/org/1"){ instance.href } tests("#name").returns('Org1'){ instance.name } tests("#full_name").returns('My Full Name'){ instance.full_name } tests("#description").returns("Some fancy\n\nDescription"){ instance.description } end end end fog-1.19.0/tests/vcloud/models/compute/servers_tests.rb0000644000004100000410000000150512261242552023244 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/servers' Shindo.tests("Vcloud::Compute | servers", ['vcloud']) do Fog::Vcloud::Compute::SUPPORTED_VERSIONS.each do |version| tests("api version #{version}") do pending if Fog.mocking? instance = Fog::Vcloud::Compute::Servers.new( :connection => Fog::Vcloud::Compute.new( :vcloud_host => 'vcloud.example.com', :vcloud_username => 'username', :vcloud_password => 'password', :vcloud_version => version), :href => "https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/vApp/vapp-1" ) tests("collection") do returns(2) { instance.size } returns("https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/vApp/vm-2") { instance.first.href } end end end end fog-1.19.0/tests/vcloud/models/compute/conn_helper.rb0000644000004100000410000000076512261242552022634 0ustar www-datawww-datamodule Fog module Vcloud if false class Fog::Connection def request(params, &block) path = File.expand_path(File.join(File.dirname(__FILE__),'..','..','data',params[:path].gsub(/^\//,'').gsub('/','_+_'))) if File.exists?(path) body = File.read(path) else '' end Excon::Response.new( :body => body, :status => 200, :header => '') end end end end end fog-1.19.0/tests/vcloud/models/compute/network_tests.rb0000644000004100000410000000616412261242552023252 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/networks' Shindo.tests("Vcloud::Compute | network", ['vcloud']) do Fog::Vcloud::Compute::SUPPORTED_VERSIONS.each do |version| tests("api version #{version}") do pending if Fog.mocking? connection = Fog::Vcloud::Compute.new( :vcloud_host => 'vcloud.example.com', :vcloud_username => 'username', :vcloud_password => 'password', :vcloud_version => version ) tests("an org network") do instance = connection.get_network("https://vcloud.example.com/api#{version == '1.0' ? '/v1.0' : ''}/network/1") instance.reload tests("#href").returns("https://vcloud.example.com/api#{version == '1.0' ? '/v1.0' : ''}/network/1") { instance.href } tests("#name").returns("Network1") { instance.name } tests("#description").returns("Some fancy Network") { instance.description } tests("configuration") do tests("parent network").returns("ParentNetwork1") { instance.configuration[:ParentNetwork][:name]} tests("dns").returns("172.0.0.2") { instance.configuration[:IpScope][:Dns1]} tests("#fence_mode").returns("natRouted") { instance.configuration[:FenceMode] } tests("features") do tests("dhcp_service") do tests("#is_enabled").returns("false") { instance.configuration[:Features][:DhcpService][:IsEnabled] } tests("ip_range") do tests("#start_address").returns("192.168.0.151") { instance.configuration[:Features][:DhcpService][:IpRange][:StartAddress] } end end tests("firewall_server") do tests("is_enabled").returns("true"){ instance.configuration[:Features][:FirewallService][:IsEnabled] } end tests("nat_service") do tests("is_enabled").returns("false"){ instance.configuration[:Features][:NatService][:IsEnabled] } end end end tests("#parent_network") do tests("returned network name").returns("ParentNetwork1"){ p = instance.parent_network; p.name } end end tests("an external network") do instance = connection.get_network("https://vcloud.example.com/api#{version == '1.0' ? '/v1.0' : ''}/admin/network/2") instance.reload tests("#href").returns("https://vcloud.example.com/api#{version == '1.0' ? '/v1.0' : ''}/admin/network/2") { instance.href } tests("#name").returns("ParentNetwork1") { instance.name } tests("#description").returns("Internet Connection") { instance.description } tests("#provider_info").returns("NETWORK:dvportgroup-230 on com.vmware.vcloud.entity.vimserver:35935555") { instance.provider_info } tests("configuration") do tests("dns").returns("172.0.0.2") { instance.configuration[:IpScope][:Dns1]} tests("allocated addresses").returns("172.0.0.144") { instance.configuration[:IpScope][:AllocatedIpAddresses][:IpAddress].first } end tests("#parent_network").returns(nil){ instance.parent_network } end end end end fog-1.19.0/tests/vcloud/models/compute/vdc_tests.rb0000644000004100000410000000374712261242552022341 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/vdcs' require 'fog/vcloud/models/compute/vdc' Shindo.tests("Vcloud::Compute | vdc", ['vcloud']) do Fog::Vcloud::Compute::SUPPORTED_VERSIONS.each do |version| tests("api version #{version}") do pending if Fog.mocking? instance = Fog::Vcloud::Compute.new( :vcloud_host => 'vcloud.example.com', :vcloud_username => 'username', :vcloud_password => 'password', :vcloud_version => version ).get_vdc("https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/vdc/1") instance.reload tests("#href").returns("https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/vdc/1") { instance.href } tests("#name").returns("vDC1") { instance.name } tests('#organization').returns("Org1") { instance.organization.name } tests("#description").returns("Some Description") { instance.description } tests("#network_quota").returns(10) { instance.network_quota } tests("#nic_quota").returns(10) { instance.nic_quota } tests("#vm_quota").returns(10) { instance.vm_quota } tests("#is_enabled").returns(true) { instance.is_enabled } tests("#available_networks") do tests("#size").returns(2) { instance.available_networks.size } end tests("#storage_capacity") do tests("units").returns("MB") { instance.storage_capacity[:Units] } tests("allocated").returns("10240") { instance.storage_capacity[:Allocated] } end tests("#compute_capacity") do tests("cpu") do tests("allocated").returns("20000") { instance.compute_capacity[:Cpu][:Allocated] } tests("units").returns("MHz") { instance.compute_capacity[:Cpu][:Units] } end tests("memory") do tests("allocated").returns("1024") { instance.compute_capacity[:Memory][:Allocated] } tests("units").returns("MB") { instance.compute_capacity[:Memory][:Units] } end end end end end fog-1.19.0/tests/vcloud/models/compute/vapp_tests.rb0000644000004100000410000000254612261242552022527 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/vapps' require 'fog/vcloud/models/compute/vapp' Shindo.tests("Vcloud::Compute | vapp", ['vcloud']) do Fog::Vcloud::Compute::SUPPORTED_VERSIONS.each do |version| tests("api version #{version}") do pending if Fog.mocking? instance = Fog::Vcloud::Compute.new( :vcloud_host => 'vcloud.example.com', :vcloud_username => 'username', :vcloud_password => 'password', :vcloud_version => version ).get_vapp("https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/vApp/vapp-1") instance.reload tests("#href").returns("https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/vApp/vapp-1") { instance.href } tests("#name").returns("vApp1") { instance.name } tests("#vdc").returns("vDC1"){ instance.vdc.name } tests("#description").returns("Some Description of a vApp") { instance.description } tests("#status").returns('8') { instance.status } tests("#deployed").returns(true) { instance.deployed } tests("#children").returns(2) { instance.children.size } tests("#servers").returns(2) { instance.servers.size } tests("#friendly_status").returns('off') { instance.friendly_status } tests("#on?").returns(false) { instance.on? } tests("#off?").returns(true) { instance.off? } end end end fog-1.19.0/tests/vcloud/models/compute/vapps_tests.rb0000644000004100000410000000136612261242552022711 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/vapps' Shindo.tests("Vcloud::Compute | vapps", ['vcloud']) do Fog::Vcloud::Compute::SUPPORTED_VERSIONS.each do |version| tests("api version #{version}") do pending if Fog.mocking? instance = Fog::Vcloud::Compute::Vapps.new( :connection => Fog::Vcloud::Compute.new(:vcloud_host => 'vcloud.example.com', :vcloud_username => 'username', :vcloud_password => 'password'), :href => "https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/vdc/1" ) tests("collection") do returns(2) { instance.size } returns("https://vcloud.example.com/api#{(version == '1.0') ? '/v1.0' : ''}/vApp/vapp-1") { instance.first.href } end end end end fog-1.19.0/tests/go_grid/0000755000004100000410000000000012261242552015162 5ustar www-datawww-datafog-1.19.0/tests/go_grid/requests/0000755000004100000410000000000012261242552017035 5ustar www-datawww-datafog-1.19.0/tests/go_grid/requests/compute/0000755000004100000410000000000012261242552020511 5ustar www-datawww-datafog-1.19.0/tests/go_grid/requests/compute/image_tests.rb0000644000004100000410000000000012261242552023330 0ustar www-datawww-datafog-1.19.0/tests/dnsimple/0000755000004100000410000000000012261242552015363 5ustar www-datawww-datafog-1.19.0/tests/dnsimple/requests/0000755000004100000410000000000012261242552017236 5ustar www-datawww-datafog-1.19.0/tests/dnsimple/requests/dns/0000755000004100000410000000000012261242552020022 5ustar www-datawww-datafog-1.19.0/tests/dnsimple/requests/dns/dns_tests.rb0000644000004100000410000000577712261242552022375 0ustar www-datawww-dataShindo.tests('Fog::DNS[:dnsimple] | DNS requests', ['dnsimple', 'dns']) do @domain = nil @domain_count = 0 tests("success") do test("get current domain count") do response = Fog::DNS[:dnsimple].list_domains() if response.status == 200 @domain_count = response.body.size end response.status == 200 end test("create domain") do domain = generate_unique_domain response = Fog::DNS[:dnsimple].create_domain(domain) if response.status == 201 @domain = response.body["domain"] end response.status == 201 end test("get domain by id") do response = Fog::DNS[:dnsimple].get_domain(@domain["id"]) response.status == 200 end test("create an A resource record") do domain = @domain["name"] name = "www" type = "A" content = "1.2.3.4" response = Fog::DNS[:dnsimple].create_record(domain, name, type, content) if response.status == 201 @record = response.body["record"] end response.status == 201 end test("create a MX record") do domain = @domain["name"] name = "" type = "MX" content = "mail.#{domain}" options = { "ttl" => 60, "prio" => 10 } response = Fog::DNS[:dnsimple].create_record(domain, name, type, content, options) test "MX record creation returns 201" do response.status == 201 end options.each do |key, value| test("MX record has option #{key}") { value == response.body["record"][key.to_s] } end test "MX record is correct type" do response.body["record"]["record_type"] == "MX" end end test("get a record") do domain = @domain["name"] record_id = @record["id"] response = Fog::DNS[:dnsimple].get_record(domain, record_id) (response.status == 200) and (@record == response.body["record"]) end test("update a record") do domain = @domain["name"] record_id = @record["id"] options = { "content" => "2.3.4.5", "ttl" => 600 } response = Fog::DNS[:dnsimple].update_record(domain, record_id, options) response.status == 200 end test("list records") do response = Fog::DNS[:dnsimple].list_records(@domain["name"]) if response.status == 200 @records = response.body end test "list records returns all records for domain" do @records.reject { |record| record["record"]["system_record"] }.size == 2 end response.status == 200 end test("delete records") do domain = @domain["name"] result = true @records.each do |record| next if record["record"]["system_record"] response = Fog::DNS[:dnsimple].delete_record(domain, record["record"]["id"]) if response.status != 200 result = false break end end result end test("delete domain") do response = Fog::DNS[:dnsimple].delete_domain(@domain["name"]) response.status == 200 end end end fog-1.19.0/tests/vcloud_director/0000755000004100000410000000000012261242552016737 5ustar www-datawww-datafog-1.19.0/tests/vcloud_director/requests/0000755000004100000410000000000012261242552020612 5ustar www-datawww-datafog-1.19.0/tests/vcloud_director/requests/compute/0000755000004100000410000000000012261242552022266 5ustar www-datawww-datafog-1.19.0/tests/vcloud_director/requests/compute/vdc_storage_profile_tests.rb0000644000004100000410000000215412261242552030057 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | vdc_storage_profile requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new @org = VcloudDirector::Compute::Helper.current_org(@service) @vdc_id = VcloudDirector::Compute::Helper.first_vdc_id(@org) @vdc = @service.get_vdc(@vdc_id).body @vdc[:VdcStorageProfiles][:VdcStorageProfile].each do |storage_profile| @vdc_storage_profile_id = storage_profile[:href].split('/').last tests(storage_profile[:name]) do tests("#get_vdc_storage_class").data_matches_schema(VcloudDirector::Compute::Schema::VDC_STORAGE_PROFILE_TYPE) do @service.get_vdc_storage_class(@vdc_storage_profile_id).body end tests('#get_vdc_storage_class_metadata').data_matches_schema(VcloudDirector::Compute::Schema::METADATA_TYPE) do pending if Fog.mocking? @service.get_vdc_storage_class_metadata(@vdc_storage_profile_id).body end end end tests('Retrieve non-existent vDC storage profile').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_vdc_storage_class('00000000-0000-0000-0000-000000000000') end end fog-1.19.0/tests/vcloud_director/requests/compute/edge_gateway_tests.rb0000644000004100000410000001011312261242552026456 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | edge gateway requests', ['vclouddirector']) do FIREWALL_RULE_ID = '9999' @new_edge_gateway_configuration = { :FirewallService => { :IsEnabled => "true", :DefaultAction => "allow", :LogDefaultAction => "false", :FirewallRule => [ { :IsEnabled => "false", :MatchOnTranslate => "false", :Id => FIREWALL_RULE_ID, :Policy => "drop", :Description => "generated from edge_gateway_tests", :Protocols => { :Tcp => "true" }, :Port => "3412", :DestinationPortRange => "3412", :DestinationIp => "internal", :SourcePort => "3412", :SourceIp => "internal", :SourcePortRange => "3412", :EnableLogging => "false" } ] } } @service = Fog::Compute::VcloudDirector.new @org = VcloudDirector::Compute::Helper.current_org(@service) tests('Get first vDC with an EdgeGatewayRecord') do @org[:Link].each do |l| if l[:type] == 'application/vnd.vmware.vcloud.vdc+xml' id = l[:href].split('/').last edge_gateways = @service.get_org_vdc_gateways(id).body if edge_gateways && edge_gateways[:EdgeGatewayRecord].size >= 1 @vdc_id = id break end end end end tests('#get_org_vdc_gateways').data_matches_schema(VcloudDirector::Compute::Schema::QUERY_RESULT_RECORDS_TYPE) do begin @edge_gateways = @service.get_org_vdc_gateways(@vdc_id).body rescue Fog::Compute::VcloudDirector::Unauthorized # bug, may be localised retry end @edge_gateways end @edge_gateways[:EdgeGatewayRecord].each do |result| tests("each EdgeGatewayRecord"). data_matches_schema(VcloudDirector::Compute::Schema::QUERY_RESULT_EDGE_GATEWAY_RECORD_TYPE) do result end end tests('#get_edge_gateway').data_matches_schema(VcloudDirector::Compute::Schema::GATEWAY_TYPE) do @edge_gateway_id = @edge_gateways[:EdgeGatewayRecord].first[:href].split('/').last @original_gateway_conf = @service.get_edge_gateway(@edge_gateway_id).body end tests('#configure_edge_gateway_services') do rule = @original_gateway_conf[:Configuration][:EdgeGatewayServiceConfiguration][:FirewallService][:FirewallRule].find { |rule| rule[:Id] == FIREWALL_RULE_ID } raise('fail fast if our test firewall rule already exists - its likely left over from a broken test run') if rule response = @service.post_configure_edge_gateway_services(@edge_gateway_id, @new_edge_gateway_configuration) @service.process_task(response.body) tests('#check for new firewall rule').returns(@new_edge_gateway_configuration[:FirewallService][:FirewallRule]) do edge_gateway = @service.get_edge_gateway(@edge_gateway_id).body edge_gateway[:Configuration][:EdgeGatewayServiceConfiguration][:FirewallService][:FirewallRule] end tests('#remove the firewall rule added by test').returns(nil) do response = @service.post_configure_edge_gateway_services(@edge_gateway_id, @original_gateway_conf[:Configuration][:EdgeGatewayServiceConfiguration]) @service.process_task(response.body) edge_gateway = @service.get_edge_gateway(@edge_gateway_id).body edge_gateway[:Configuration][:EdgeGatewayServiceConfiguration][:FirewallService][:FirewallRule].find { |rule| rule[:Id] == FIREWALL_RULE_ID } end end tests('Retrieve non-existent edge gateway').raises(Fog::Compute::VcloudDirector::Forbidden) do begin @service.get_edge_gateway('00000000-0000-0000-0000-000000000000') rescue Fog::Compute::VcloudDirector::Unauthorized # bug, may be localised retry end end tests('Configure non-existent edge gateway').raises(Fog::Compute::VcloudDirector::Forbidden) do begin @service.post_configure_edge_gateway_services('00000000-0000-0000-0000-000000000000', {}) rescue Fog::Compute::VcloudDirector::Unauthorized # bug, may be localised retry end end end fog-1.19.0/tests/vcloud_director/requests/compute/task_tests.rb0000644000004100000410000000255512261242552025006 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | task requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new tests('error conditions') do tests('retrieve non-existent TasksList').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_task_list('00000000-0000-0000-0000-000000000000') end tests('retrieve non-existent Task').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_task('00000000-0000-0000-0000-000000000000') end tests('cancel non-existent Task').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.post_cancel_task('00000000-0000-0000-0000-000000000000') end end @org_id = VcloudDirector::Compute::Helper.current_org_id(@service) tests('#get_task_list').data_matches_schema(VcloudDirector::Compute::Schema::TASKS_LIST_TYPE) do session = @service.get_current_session.body org_href = session[:Link].detect {|l| l[:type] == 'application/vnd.vmware.vcloud.org+xml'}[:href] @org_uuid = org_href.split('/').last @tasks_list = @service.get_task_list(@org_uuid).body end tests('each task in the task list') do @tasks_list[:Task].each do |task| task_id = task[:href].split('/').last tests("#get_task(#{task_id}").data_matches_schema(VcloudDirector::Compute::Schema::TASK_TYPE) do @service.get_task(task_id).body end end end end fog-1.19.0/tests/vcloud_director/requests/compute/helper.rb0000644000004100000410000000151412261242552024073 0ustar www-datawww-dataclass VcloudDirector module Compute module Helper def self.test_name @test_name ||= 'fog-test-%x' % Time.now.to_i end def self.fixture(filename) File.join(File.expand_path('../../../fixtures', __FILE__), filename) end def self.current_org(service) service.get_organization(current_org_id(service)).body end def self.current_org_id(service) session = service.get_current_session.body link = session[:Link].detect do |l| l[:type] == 'application/vnd.vmware.vcloud.org+xml' end link[:href].split('/').last end def self.first_vdc_id(org) link = org[:Link].detect do |l| l[:type] == 'application/vnd.vmware.vcloud.vdc+xml' end link[:href].split('/').last end end end end fog-1.19.0/tests/vcloud_director/requests/compute/disk_tests.rb0000644000004100000410000001755512261242552025004 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | disk requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new @disk_name = VcloudDirector::Compute::Helper.test_name tests('error conditions') do tests('#post_upload_disk') do tests('Invalid size').raises(Fog::Compute::VcloudDirector::BadRequest) do @service.post_upload_disk('00000000-0000-0000-0000-000000000000', @disk_name, -1) end end tests('Upload to non-existent vDC').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.post_upload_disk('00000000-0000-0000-0000-000000000000', @disk_name, 0) end tests('Retrieve non-existent Disk').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_disk('00000000-0000-0000-0000-000000000000') end tests('Retrieve owner of non-existent Disk').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_disk_owner('00000000-0000-0000-0000-000000000000') end tests('Retrieve VM list for non-existent Disk').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_vms_disk_attached_to('00000000-0000-0000-0000-000000000000') end tests('Delete non-existent Disk').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.delete_disk('00000000-0000-0000-0000-000000000000') end end @org = VcloudDirector::Compute::Helper.current_org(@service) @size = 1024 tests('Upload and manipulate a disk') do tests('#post_upload_disk').data_matches_schema(VcloudDirector::Compute::Schema::DISK_TYPE) do @vdc_id = VcloudDirector::Compute::Helper.first_vdc_id(@org) @disk = @service.post_upload_disk(@vdc_id, @disk_name, @size).body end @service.process_task(@disk[:Tasks][:Task]) @disk_id = @disk[:href].split('/').last tests("#get_disk(#{@disk_id})").data_matches_schema(VcloudDirector::Compute::Schema::DISK_TYPE) do @disk = @service.get_disk(@disk_id).body end tests("disk[:name]").returns(@disk_name) { @disk[:name] } tests("disk[:size]").returns(@size) { @disk[:size].to_i } tests("#get_disk_owner(#{@disk_id})").data_matches_schema(VcloudDirector::Compute::Schema::OWNER_TYPE) do @owner = @service.get_disk_owner(@disk_id).body end tests("owner[:User][:name]").returns(@service.user_name) { @owner[:User][:name] } #tests("#put_disk(#{@disk_id})").data_matches_schema(VcloudDirector::Compute::Schema::TASK_TYPE) do # @disk_name += '-renamed' # @task = @service.put_disk(@disk_id, @disk_name).body #end #@service.process_task(@task) #tests("#get_disk(#{@disk_id})").data_matches_schema(VcloudDirector::Compute::Schema::DISK_TYPE) do # @disk = @service.get_disk(@disk_id).body #end #tests("disk[:name]").returns(@disk_name) { @disk[:name] } #tests("disk[:size]").returns(@size) { @disk[:size].to_i } # shouldn't change tests('disk metadata') do pending if Fog.mocking? tests("#put_disk_metadata_item_metadata(#{@disk_id})").data_matches_schema(VcloudDirector::Compute::Schema::TASK_TYPE) do @task = @service.put_disk_metadata_item_metadata(@disk_id, 'fog-test-key', 'fog-test-value').body end @service.process_task(@task) tests("#put_disk_metadata_item_metadata(#{@disk_id})") do tests("#put_disk_metadata_item_metadata(Boolean)").returns(true) do task = @service.put_disk_metadata_item_metadata(@disk_id, 'fog-test-boolean', true).body @service.process_task(task) end tests("#put_disk_metadata_item_metadata(DateTime)").returns(true) do task = @service.put_disk_metadata_item_metadata(@disk_id, 'fog-test-datetime', DateTime.now).body @service.process_task(task) end tests("#put_disk_metadata_item_metadata(Number)").returns(true) do task = @service.put_disk_metadata_item_metadata(@disk_id, 'fog-test-number', 111).body @service.process_task(task) end end tests("#post_update_disk_metadata(#{@disk_id})").data_matches_schema(VcloudDirector::Compute::Schema::TASK_TYPE) do metadata = { 'fog-test-key-update' => 'fog-test-value-update', 'fog-test-boolean-update' => false, 'fog-test-datetime-update' => DateTime.now, 'fog-test-number-update' => 222 } @task = @service.post_update_disk_metadata(@disk_id, metadata).body end @service.process_task(@task) tests("#get_disk_metadata(#{@disk_id})") do tests('response format').data_matches_schema(VcloudDirector::Compute::Schema::METADATA_TYPE) do @metadata = @service.get_disk_metadata(@disk_id).body end tests('TypedValue') do pending if @service.api_version.to_f < 5.1 tests('key').returns('MetadataStringValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-key'} entry[:TypedValue][:xsi_type] end tests('boolean').returns('MetadataBooleanValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-boolean'} entry[:TypedValue][:xsi_type] end tests('datetime').returns('MetadataDateTimeValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-datetime'} entry[:TypedValue][:xsi_type] end tests('number').returns('MetadataNumberValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-number'} entry[:TypedValue][:xsi_type] end tests('key-update').returns('MetadataStringValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-key-update'} entry[:TypedValue][:xsi_type] end tests('boolean-update').returns('MetadataBooleanValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-boolean-update'} entry[:TypedValue][:xsi_type] end tests('datetime-update').returns('MetadataDateTimeValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-datetime-update'} entry[:TypedValue][:xsi_type] end tests('number-update').returns('MetadataNumberValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-number-update'} entry[:TypedValue][:xsi_type] end end end end tests("#get_vms_disk_attached_to(#{@disk_id})").data_matches_schema(VcloudDirector::Compute::Schema::VMS_TYPE) do pending if Fog.mocking? @service.get_vms_disk_attached_to(@disk_id).body end tests("#delete_disk(#{@disk_id})").data_matches_schema(VcloudDirector::Compute::Schema::TASK_TYPE) do @task = @service.delete_disk(@disk_id).body end @service.process_task(@task) end tests('Disk no longer exists') do tests("#get_disk(#{@disk_id})").raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_disk(@disk_id) end tests("#get_disk_owner(#{@disk_id})").raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_disk_owner(@disk_id) end tests("#get_disk_metadata(#{@disk_id})").raises(Fog::Compute::VcloudDirector::Forbidden) do pending if Fog.mocking? @service.get_disk_metadata(@disk_id) end tests("#delete_disk(#{@disk_id})").raises(Fog::Compute::VcloudDirector::Forbidden) do @service.delete_disk(@disk_id) end end tests('#get_disks_from_query') do pending if Fog.mocking? %w[idrecords records references].each do |format| tests(":format => #{format}") do tests('#body').data_matches_schema(VcloudDirector::Compute::Schema::CONTAINER_TYPE) do @body = @service.get_disks_from_query(:format => format).body end key = (format == 'references') ? 'DiskReference' : 'DiskRecord' tests("#body.key?(:#{key})").returns(true) { @body.key?(key.to_sym) } end end end end fog-1.19.0/tests/vcloud_director/requests/compute/supported_systems_tests.rb0000644000004100000410000000056012261242552027652 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | supported_systems requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new if @service.api_version.to_f >= 5.1 tests('#get_supported_systems_info').formats(VcloudDirector::Compute::Schema::SUPPORTED_OPERATING_SYSTEMS_INFO_TYPE) do @service.get_supported_systems_info.body end end end fog-1.19.0/tests/vcloud_director/requests/compute/catalog_tests.rb0000644000004100000410000000323312261242552025450 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | catalog requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new @org = VcloudDirector::Compute::Helper.current_org(@service) tests('#get_catalog').data_matches_schema(VcloudDirector::Compute::Schema::CATALOG_TYPE) do link = @org[:Link].detect do |l| l[:rel] == 'down' && l[:type] == 'application/vnd.vmware.vcloud.catalog+xml' end @catalog_id = link[:href].split('/').last pending if Fog.mocking? @catalog = @service.get_catalog(@catalog_id).body end tests('#get_catalog_metadata').data_matches_schema(VcloudDirector::Compute::Schema::METADATA_TYPE) do pending if Fog.mocking? @service.get_catalog_metadata(@catalog_id).body end tests('#get_control_access_params_catalog').data_matches_schema(VcloudDirector::Compute::Schema::CONTROL_ACCESS_PARAMS_TYPE) do pending if Fog.mocking? @service.get_control_access_params_catalog(@org[:href].split('/').last, @catalog_id).body end tests('#get_catalogs_from_query') do pending if Fog.mocking? %w[idrecords records references].each do |format| tests(":format => #{format}") do tests('#body').data_matches_schema(VcloudDirector::Compute::Schema::CONTAINER_TYPE) do @body = @service.get_catalogs_from_query(:format => format).body end key = (format == 'references') ? 'CatalogReference' : 'CatalogRecord' tests("#body.key?(:#{key})").returns(true) { @body.key?(key.to_sym) } end end end tests('Retrieve non-existent Catalog').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_catalog('00000000-0000-0000-0000-000000000000') end end fog-1.19.0/tests/vcloud_director/requests/compute/versions_tests.rb0000644000004100000410000000064312261242552025710 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | versions requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new tests('#get_supported_versions').formats(VcloudDirector::Compute::Schema::SUPPORTED_VERSIONS_TYPE) do @versions = @service.get_supported_versions.body end tests('API 5.1 is supported').returns(true) do !!@versions[:VersionInfo].detect {|i| i[:Version] == '5.1'} end end fog-1.19.0/tests/vcloud_director/requests/compute/organization_tests.rb0000644000004100000410000000266612261242552026553 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | organization requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new tests('#get_organizations').data_matches_schema(VcloudDirector::Compute::Schema::ORG_LIST_TYPE) do @org_list = @service.get_organizations.body end tests('#get_organization').data_matches_schema(VcloudDirector::Compute::Schema::ORG_TYPE) do org = @org_list[:Org].detect {|o| o[:name] == @service.org_name} @org_uuid = org[:href].split('/').last @service.get_organization(@org_uuid).body end tests('#get_organization_metadata').data_matches_schema(VcloudDirector::Compute::Schema::METADATA_TYPE) do pending if Fog.mocking? @service.get_organization_metadata(@org_uuid).body end tests('#get_organizations_from_query') do pending if Fog.mocking? %w[idrecords records references].each do |format| tests(":format => #{format}") do tests('#body').data_matches_schema(VcloudDirector::Compute::Schema::CONTAINER_TYPE) do @body = @service.get_organizations_from_query(:format => format).body end key = (format == 'references') ? 'OrganizationReference' : 'OrganizationRecord' tests("#body.key?(:#{key})").returns(true) { @body.key?(key.to_sym) } end end end tests('retrieve non-existent Org').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_organization('00000000-0000-0000-0000-000000000000') end end fog-1.19.0/tests/vcloud_director/requests/compute/query_tests.rb0000644000004100000410000001022112261242552025176 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | query requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new tests('retrieve a summary list of all typed queries types') do tests('#get_execute_query') do @query_list = @service.get_execute_query.body tests(':type').returns('application/vnd.vmware.vcloud.query.queryList+xml') do @query_list[:type] end end end # for each queriable type, query and check that each available format # returns a result that matches the base schema # @query_list[:Link].select do |link| link[:rel] == 'down' end.sort_by do |link| [link[:name], link[:href]] end.each do |link| href = Nokogiri::XML.fragment(link[:href]) query = CGI.parse(URI.parse(href.text).query) type = query['type'].first format = query['format'].first next if %w[right role strandedUser].include?(type) tests("type => #{type}, format => #{format}") do pending if Fog.mocking? && (format != 'records' || type != 'orgVdcNetwork') tests("#get_execute_query").data_matches_schema(VcloudDirector::Compute::Schema::CONTAINER_TYPE) do @body = @service.get_execute_query(type, :format => format).body end tests("resource type").returns(link[:type]) { @body[:type] } unless ( type == 'event' || type == 'edgeGateway' ) records_key = @body.keys.detect {|key| key.to_s =~ /Record|Reference$/} if records = @body[records_key] records.first do |record| case format when 'records' tests("record is correct schema").data_matches_schema(VcloudDirector::Compute::Schema::REFERENCE_TYPE) do record end end end end end end end if Fog.mocking? tests('ensure Mock logic is sound') do tests('#get_execute_query') do tests('orgVdcNetwork') do output = @service.get_execute_query('orgVdcNetwork').body tests('all records').returns(@service.data[:networks].size) do output[:OrgVdcNetworkRecords].size end output = @service.get_execute_query('orgVdcNetwork', :filter => 'name==vDC1 backend network').body tests(':filter by name').returns(1) do output[:OrgVdcNetworkRecords].size end tests(':page option is ok if :page == 1').returns(@service.data[:networks].size) do output = @service.get_execute_query('orgVdcNetwork', :page => '1').body output[:OrgVdcNetworkRecords].size end tests('AND expression in :filter raises MockNotImplemented').raises(Fog::Errors::MockNotImplemented) do @service.get_execute_query('orgVdcNetwork', :filter => 'name==Default Network;thing==wibble') end tests('OR expression in :filter raises MockNotImplemented').raises(Fog::Errors::MockNotImplemented) do @service.get_execute_query('orgVdcNetwork', :filter => 'name==Default Network,thing==wibble') end tests('sortAsc option raises MockNotImplemented').raises(Fog::Errors::MockNotImplemented) do @service.get_execute_query('orgVdcNetwork', :sortAsc => 'name') end tests('sortDesc option raises MockNotImplemented').raises(Fog::Errors::MockNotImplemented) do @service.get_execute_query('orgVdcNetwork', :sortDesc => 'name') end tests('page option raises MockNotImplemented').raises(Fog::Errors::MockNotImplemented) do @service.get_execute_query('orgVdcNetwork', :page => '2') end tests('pageSize option raises MockNotImplemented').raises(Fog::Errors::MockNotImplemented) do @service.get_execute_query('orgVdcNetwork', :pageSize => '50') end tests('offset option raises MockNotImplemented').raises(Fog::Errors::MockNotImplemented) do @service.get_execute_query('orgVdcNetwork', :offset => '5') end tests('fields option raises MockNotImplemented').raises(Fog::Errors::MockNotImplemented) do @service.get_execute_query('orgVdcNetwork', :fields => 'name,thing') end end end end end end fog-1.19.0/tests/vcloud_director/requests/compute/session_tests.rb0000644000004100000410000000070612261242552025523 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | session requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new tests('#post_login_sessions').data_matches_schema(VcloudDirector::Compute::Schema::SESSION_TYPE) do pending @service.login.body # calls post_login_sessions end tests('#get_current_session').data_matches_schema(VcloudDirector::Compute::Schema::SESSION_TYPE) do @service.get_current_session.body end end fog-1.19.0/tests/vcloud_director/requests/compute/users_tests.rb0000644000004100000410000000120312261242552025172 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | users requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new tests('#get_users_from_query') do pending if Fog.mocking? %w[idrecords records references].each do |format| tests(":format => #{format}") do tests('#body').data_matches_schema(VcloudDirector::Compute::Schema::CONTAINER_TYPE) do @body = @service.get_users_from_query(:format => format).body end key = (format == 'references') ? 'UserReference' : 'UserRecord' tests("#body.key?(:#{key})").returns(true) { @body.key?(key.to_sym) } end end end end fog-1.19.0/tests/vcloud_director/requests/compute/admin_tests.rb0000644000004100000410000000073412261242552025131 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | admin requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new tests('#get_vcloud').data_matches_schema(VcloudDirector::Compute::Schema::VCLOUD_TYPE) do @service.get_vcloud.body end @org = VcloudDirector::Compute::Helper.current_org(@service) tests('#get_org_settings').returns(Hash) do pending if Fog.mocking? @service.get_org_settings(@org[:href].split('/').last).body.class end end fog-1.19.0/tests/vcloud_director/requests/compute/network_tests.rb0000644000004100000410000000672012261242552025533 0ustar www-datawww-data require 'pp' Shindo.tests('Compute::VcloudDirector | network requests', ['vclouddirector']) do GET_NETWORK_FORMAT = { :type => String, :name => String, :href => String, :id => String, :description => Fog::Nullable::String, :is_inherited => Fog::Boolean, :gateway => Fog::Nullable::String, :netmask => String, :dns1 => Fog::Nullable::String, :dns2 => Fog::Nullable::String, :dns_suffix => Fog::Nullable::String, :ip_ranges => [{ :start_address => String, :end_address => String }] } @service = Fog::Compute::VcloudDirector.new @org = VcloudDirector::Compute::Helper.current_org(@service) @created_net_id = nil tests('Create network in non-existent vDC').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.post_create_org_vdc_network('00000000-0000-0000-0000-000000000000', 'bob') end tests('Delete non-existent OrgNetwork').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.delete_network('00000000-0000-0000-0000-000000000000') end tests('Retrieve non-existent OrgNetwork').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_network('00000000-0000-0000-0000-000000000000') end tests('#get_network').data_matches_schema(GET_NETWORK_FORMAT) do link = @org[:Link].detect do |l| l[:rel] == 'down' && l[:type] == 'application/vnd.vmware.vcloud.orgNetwork+xml' end pending unless link # nothing to test here cannot continue @network_id = link[:href].split('/').last @service.get_network(@network_id).body end tests('#get_network_metadata').data_matches_schema(VcloudDirector::Compute::Schema::METADATA_TYPE) do pending if Fog.mocking? pending unless @network_id # nothing to test here cannot continue @service.get_network_metadata(@network_id).body end tests('#post_create_org_vdc_network') do pending unless Fog.mocking? link = @org[:Link].detect do |l| l[:rel] == 'down' && l[:type] == 'application/vnd.vmware.vcloud.vdc+xml' end vdc_id = link[:href].split('/').last name = VcloudDirector::Compute::Helper.test_name options = { :Description => "Testing post_create_org_vdc_network #{name}", :Configuration => { :IpScopes => { :IpScope => { :IsInherited => 'false', :Gateway => '198.51.100.1', :Netmask => '255.255.255.0', :Dns1 => '198.51.100.2', :Dns2 => '198.51.100.3', :DnsSuffix => 'example.com', :IpRanges => [ { :IpRange => { :StartAddress => '198.51.100.10', :EndAddress => '198.51.100.20' } }, { :IpRange => { :StartAddress => '198.51.100.30', :EndAddress => '198.51.100.40' } }, ] }, }, :FenceMode => 'isolated', } } body = @service.post_create_org_vdc_network(vdc_id, name, options).body @created_net_id = body[:href].split('/').last if body[:href] @service.process_task(body[:Tasks][:Task]) if body && body.key?(:Tasks) tests('fetched name matches created name').returns(name) do net = @service.get_network(@created_net_id).body net[:name] end end tests('#delete_network') do pending unless Fog.mocking? @delete_task = @service.delete_network(@created_net_id).body @service.process_task(@delete_task) tests('created network has been deleted').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_network(@created_net_id) end end end fog-1.19.0/tests/vcloud_director/requests/compute/media_tests.rb0000644000004100000410000002121312261242552025113 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | media requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new tests('error conditions') do tests('#post_upload_media') do tests('Invalid image_type').raises(Fog::Compute::VcloudDirector::BadRequest) do @service.post_upload_media('00000000-0000-0000-0000-000000000000', 'test.iso', 'isox', 0) end tests('Invalid size').raises(Fog::Compute::VcloudDirector::BadRequest) do @service.post_upload_media('00000000-0000-0000-0000-000000000000', 'test.iso', 'iso', -1) end end tests('Upload to non-existent vDC').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.post_upload_media('00000000-0000-0000-0000-000000000000', 'test.iso', 'iso', 0) end tests('Retrieve non-existent Media').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_media('00000000-0000-0000-0000-000000000000') end tests('Retrieve owner of non-existent Media').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_media_owner('00000000-0000-0000-0000-000000000000') end tests('Delete non-existent Media').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.delete_media('00000000-0000-0000-0000-000000000000') end end @org = VcloudDirector::Compute::Helper.current_org(@service) @media_name = VcloudDirector::Compute::Helper.test_name tests('Upload and manipulate a media object') do File.open(VcloudDirector::Compute::Helper.fixture('test.iso'), 'rb') do |iso| tests('#post_upload_media').data_matches_schema(VcloudDirector::Compute::Schema::MEDIA_TYPE) do @vdc_id = VcloudDirector::Compute::Helper.first_vdc_id(@org) @size = File.size(iso.path) @media = @service.post_upload_media(@vdc_id, @media_name, 'iso', @size).body end tests('media object has exactly one file').returns(true) do @media[:Files][:File].size == 1 end tests('media object file has an upload link').returns(true) do @link = @media[:Files][:File].first[:Link] @link[:rel] == 'upload:default' end unless Fog.mocking? headers = { 'Content-Length' => @size, 'Content-Type' => 'application/octet-stream', 'x-vcloud-authorization' => @service.vcloud_token } Excon.put( @link[:href], :body => iso.read, :expects => 200, :headers => headers ) end @service.process_task(@media[:Tasks][:Task]) @media_id = @media[:href].split('/').last tests("#get_media(#{@media_id})").data_matches_schema(VcloudDirector::Compute::Schema::MEDIA_TYPE) do @media = @service.get_media(@media_id).body end tests("media[:name]").returns(@media_name) { @media[:name] } tests("media[:imageType]").returns('iso') { @media[:imageType] } tests("media[:size]").returns(@size) { @media[:size].to_i } tests("#get_media_owner(#{@media_id})").data_matches_schema(VcloudDirector::Compute::Schema::OWNER_TYPE) do @owner = @service.get_media_owner(@media_id).body end tests("owner[:User][:name]").returns(@service.user_name) { @owner[:User][:name] } tests('media metadata') do pending if Fog.mocking? tests("#put_media_metadata_item_metadata(#{@media_id})").data_matches_schema(VcloudDirector::Compute::Schema::TASK_TYPE) do @task = @service.put_media_metadata_item_metadata(@media_id, 'fog-test-key', 'fog-test-value').body end @service.process_task(@task) tests("#put_media_metadata_item_metadata(#{@media_id})") do tests("#put_media_metadata_item_metadata(Boolean)").returns(true) do task = @service.put_media_metadata_item_metadata(@media_id, 'fog-test-boolean', true).body @service.process_task(task) end tests("#put_media_metadata_item_metadata(DateTime)").returns(true) do task = @service.put_media_metadata_item_metadata(@media_id, 'fog-test-datetime', DateTime.now).body @service.process_task(task) end tests("#put_media_metadata_item_metadata(Number)").returns(true) do task = @service.put_media_metadata_item_metadata(@media_id, 'fog-test-number', 111).body @service.process_task(task) end end tests("#post_update_media_metadata(#{@media_id})").data_matches_schema(VcloudDirector::Compute::Schema::TASK_TYPE) do metadata = { 'fog-test-key-update' => 'fog-test-value-update', 'fog-test-boolean-update' => false, 'fog-test-datetime-update' => DateTime.now, 'fog-test-number-update' => 222 } @task = @service.post_update_media_metadata(@media_id, metadata).body end @service.process_task(@task) tests("#get_media_metadata(#{@media_id})") do tests('response format').data_matches_schema(VcloudDirector::Compute::Schema::METADATA_TYPE) do @metadata = @service.get_media_metadata(@media_id).body end tests('TypedValue') do pending if @service.api_version.to_f < 5.1 tests('key').returns('MetadataStringValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-key'} entry[:TypedValue][:xsi_type] end tests('boolean').returns('MetadataBooleanValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-boolean'} entry[:TypedValue][:xsi_type] end tests('datetime').returns('MetadataDateTimeValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-datetime'} entry[:TypedValue][:xsi_type] end tests('number').returns('MetadataNumberValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-number'} entry[:TypedValue][:xsi_type] end tests('key-update').returns('MetadataStringValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-key-update'} entry[:TypedValue][:xsi_type] end tests('boolean-update').returns('MetadataBooleanValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-boolean-update'} entry[:TypedValue][:xsi_type] end tests('datetime-update').returns('MetadataDateTimeValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-datetime-update'} entry[:TypedValue][:xsi_type] end tests('number-update').returns('MetadataNumberValue') do entry = @metadata[:MetadataEntry].detect {|e| e[:Key] == 'fog-test-number-update'} entry[:TypedValue][:xsi_type] end end end end tests("#post_clone_media(#{@media_id})").data_matches_schema(VcloudDirector::Compute::Schema::MEDIA_TYPE) do @media = @service.post_clone_media(@vdc_id, @media_id, :IsSourceDelete => true).body end @service.process_task(@media[:Tasks][:Task]) @media_id = @media[:href].split('/').last tests("media[:name] starts '#{@media_name}-copy-'").returns(true) do !!(@media[:name] =~ /^#{@media_name}-copy-/) end tests("#delete_media(#{@media_id})").data_matches_schema(VcloudDirector::Compute::Schema::TASK_TYPE) do @task = @service.delete_media(@media_id).body end @service.process_task(@task) end end tests('Media item no longer exists') do tests("#get_media(#{@media_id})").raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_media(@media_id) end tests("#get_media_owner(#{@media_id})").raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_media_owner(@media_id) end tests("#get_media_metadata(#{@media_id})").raises(Fog::Compute::VcloudDirector::Forbidden) do pending if Fog.mocking? @service.get_media_metadata(@media_id) end tests("#delete_media(#{@media_id})").raises(Fog::Compute::VcloudDirector::Forbidden) do @service.delete_media(@media_id) end end tests('#get_medias_from_query') do pending if Fog.mocking? %w[idrecords records references].each do |format| tests(":format => #{format}") do tests('#body').data_matches_schema(VcloudDirector::Compute::Schema::CONTAINER_TYPE) do @body = @service.get_medias_from_query(:format => format).body end key = (format == 'references') ? 'MediaReference' : 'MediaRecord' tests("#body.key?(:#{key})").returns(true) { @body.key?(key.to_sym) } end end end end fog-1.19.0/tests/vcloud_director/requests/compute/schema_helper.rb0000644000004100000410000005110712261242552025416 0ustar www-datawww-dataclass VcloudDirector module Compute module Schema # Mapping of a content media type to a xsd complex type. MEDIA_TYPE_MAPPING_TYPE = { :MediaType => String, :ComplexTypeName => String, :SchemaLocation => String } # Information for one version of the API. VERSION_INFO_TYPE = { :Version => String, :LoginUrl => String, :MediaTypeMapping => [MEDIA_TYPE_MAPPING_TYPE] } # List all supported versions. SUPPORTED_VERSIONS_TYPE = { :VersionInfo => [VERSION_INFO_TYPE] } # The standard error message type used in the vCloud REST API. ERROR_TYPE = { :majorErrorCode => String, :message => String, :minorErrorCode => String, :stackTrace => Fog::Nullable::String, :vendorSpecificErrorCode => Fog::Nullable::String } # The base type for all objects in the vCloud model. Has an optional list # of links and href and type attributes. REFERENCE_TYPE = { :href => String, :id => Fog::Nullable::String, :name => Fog::Nullable::String, :type => Fog::Nullable::String } # Extends reference type by adding relation attribute. Defines a # hyper-link with a relationship, hyper-link reference, and an optional # MIME type. LINK_TYPE = REFERENCE_TYPE.merge({ :rel => String }) # Represents a reference to a resource. Contains an href attribute, a # resource status attribute, and optional name and type attributes. RESOURCE_REFERENCE_TYPE = REFERENCE_TYPE.merge({ :status => Fog::Nullable::String }) # The base type for all objects in the vCloud model. Has an optional list # of links and href and type attributes. RESOURCE_TYPE = { :href => Fog::Nullable::String, :type => Fog::Nullable::String, # :Link => [LINK_TYPE] -- FIXME: not required } # The base type for all resource types which contain an id attribute. IDENTIFIABLE_RESOURCE_TYPE = RESOURCE_TYPE.merge({ :id => Fog::Nullable::String, :operationKey => Fog::Nullable::String, }) # Basic entity type in the vCloud object model. Includes a name, an # optional description, and an optional list of links. ENTITY_TYPE = IDENTIFIABLE_RESOURCE_TYPE.merge({ :name => String }) # Represents a file to be transferred (uploaded or downloaded). FILE_TYPE = ENTITY_TYPE.merge({ :bytesTransfered => Fog::Nullable::String, :checksum => Fog::Nullable::String, # normalizedString :size => Fog::Nullable::String }) # Represents a list of files to be transferred (uploaded or downloaded). FILES_LIST_TYPE = { :File => [FILE_TYPE] } # Container for query result sets. CONTAINER_TYPE = RESOURCE_TYPE.merge({ :name => String, :page => String, :pageSize => String, :total => String }) # Represents an asynchronous operation in vCloud Director. TASK_TYPE = ENTITY_TYPE.merge({ :cancelRequested => Fog::Nullable::String, :endTime => Fog::Nullable::String, :expiryTime => String, :operation => Fog::Nullable::String, :operationName => Fog::Nullable::String, :serviceNamespace => Fog::Nullable::String, :startTime => Fog::Nullable::String, :status => String, # :Tasks => TASKS_IN_PROGRESS_TYPE, # not happening! :Owner => REFERENCE_TYPE, # :Error => ERROR_TYPE, :User => REFERENCE_TYPE, :Organization => REFERENCE_TYPE, :Progress => Fog::Nullable::String, # :Params => anyType, :Details => Fog::Nullable::String }) # A list of queued, running, or recently completed tasks. TASKS_IN_PROGRESS_TYPE = { :Task => [TASK_TYPE] } # Base type that represents a resource entity such as a vApp template or # virtual media. RESOURCE_ENTITY_TYPE = ENTITY_TYPE.merge({ :status => Fog::Nullable::String, :Description => Fog::Nullable::String, # :Tasks => TASKS_IN_PROGRESS_TYPE, # :Files => FILES_LIST_TYPE }) # Container for references to ResourceEntity objects in this vDC. RESOURCE_ENTITIES_TYPE = { :ResourceEntity => [RESOURCE_REFERENCE_TYPE] } # Represents a supported virtual hardware version. SUPPORTED_HARDWARE_VERSION_TYPE = String # Contains a list of VMware virtual hardware versions supported in this # vDC. SUPPORTED_HARDWARE_VERSIONS_TYPE = { :SupportedHardwareVersion => SUPPORTED_HARDWARE_VERSION_TYPE } # Represents a base type for VAppType and VmType. ABSTRACT_VAPP_TYPE = RESOURCE_ENTITY_TYPE.merge({ :deployed => String, :DateCreated => String }) VAPP_CHILDREN_TYPE = { #:VApp => ABSTRACT_VAPP_TYPE, :Vm => [ABSTRACT_VAPP_TYPE] } # Controls access to the resource. ACCESS_SETTING_TYPE = { :Subject => REFERENCE_TYPE, :AccessLevel => String } # A list of access settings for a resource. ACCESS_SETTINGS_TYPE = { :AccessSettingType => [ACCESS_SETTING_TYPE] } # Container for references to available organization vDC networks. AVAILABLE_NETWORKS_TYPE = { :Network => [REFERENCE_TYPE] } # Collection of supported hardware capabilities. CAPABILITIES_TYPE = { :SupportedHardwareVersions => SUPPORTED_HARDWARE_VERSIONS_TYPE } # Represents the capacity of a given resource. CAPACITY_TYPE = { :Units => String, :Allocated => Fog::Nullable::String, :Limit => String } # Represents a capacity and usage of a given resource. CAPACITY_WITH_USAGE_TYPE = CAPACITY_TYPE.merge({ :Reserved => String, :Used => Fog::Nullable::String, :Overhead => Fog::Nullable::String }) # Represents vDC compute capacity. COMPUTE_CAPACITY_TYPE = { :Cpu => CAPACITY_WITH_USAGE_TYPE, :Memory => CAPACITY_WITH_USAGE_TYPE } # Represents a guest customization settings. GUEST_CUSTOMIZATION_SECTION_TYPE = { # TODO: extends Section_Type :Enabled => Fog::Nullable::String, :ChangeSid => Fog::Nullable::String, :VirtualMachineId => Fog::Nullable::String, :JoinDomainEnabled => Fog::Nullable::String, :UseOrgSettings => Fog::Nullable::String, :DomainName => Fog::Nullable::String, :DomainUserName => Fog::Nullable::String, :DomainUserPassword => Fog::Nullable::String, :MachineObjectOU => Fog::Nullable::String, :AdminPasswordEnabled => Fog::Nullable::String, :AdminPasswordAuto => Fog::Nullable::String, :AdminPassword => Fog::Nullable::String, :ResetPasswordRequired => Fog::Nullable::String, :CustomizationScript => Fog::Nullable::String, :ComputerName => String, :Link => LINK_TYPE } # Represents the owner of this entity. OWNER_TYPE = RESOURCE_TYPE.merge({ :User => REFERENCE_TYPE }) # VMware Tools and other runtime information for this virtual machine. RUNTIME_INFO_SECTION_TYPE = { # TODO: extends Section_Type :VMWareTools => { :version => Fog::Nullable::String } } # Container for references to storage profiles associated with a vDC. VDC_STORAGE_PROFILES_TYPE = { :VdcStorageProfile => [REFERENCE_TYPE] } # Allows you to specify certain capabilities of this virtual machine. VM_CAPABILITIES_TYPE = RESOURCE_TYPE.merge({ :MemoryHotAddEnabled => String, :CpuHotAddEnabled => String }) # Represents the user view of a Catalog object. CATALOG_TYPE = ENTITY_TYPE.merge({ #:Owner => OWNER_TYPE, #:CatalogItems => CATALOG_ITEMS_TYPE, :IsPublished => String, :DateCreated => String }) # Specifies access controls for a resource. CONTROL_ACCESS_PARAMS_TYPE = { :IsSharedToEveryone => String, :EveryoneAccessLevel => Fog::Nullable::String, # :AccessSettings => ACCESS_SETTINGS_TYPE } # Represents a Media object. MEDIA_TYPE = RESOURCE_ENTITY_TYPE.merge({ :imageType => String, :size => String, :Owner => OWNER_TYPE, :VdcStorageProfile => REFERENCE_TYPE }) METADATA_TYPE = RESOURCE_TYPE.merge({ #:MetadataEntry => METADATA_ENTRY_TYPE }) # Represents a list of organizations. ORG_LIST_TYPE = RESOURCE_TYPE.merge({ :Org => [REFERENCE_TYPE] }) # Represents the user view of a vCloud Director organization. ORG_TYPE = ENTITY_TYPE.merge({ :Description => Fog::Nullable::String, :Tasks => TASKS_IN_PROGRESS_TYPE, :FullName => String, :IsEnabled => Fog::Nullable::String }) # Represents a vCloud Session. SESSION_TYPE = RESOURCE_TYPE.merge({ :org => String, :user => String, :Link => [LINK_TYPE] }) # A list of tasks. TASKS_LIST_TYPE = ENTITY_TYPE.merge({ #:Task => TASK_TYPE }) # Represents a vApp. VAPP_TYPE = ABSTRACT_VAPP_TYPE.merge({ :ovfDescriptorUploaded => String, :Owner => OWNER_TYPE, :InMaintenanceMode => String, :Children => VAPP_CHILDREN_TYPE }) # Represents the user view of an organization vDC. VDC_TYPE = ENTITY_TYPE.merge({ :status => Fog::Nullable::String, :AllocationModel => String, # :StorageCapacity => CAPACITY_WITH_USAGE_TYPE, :ComputeCapacity => COMPUTE_CAPACITY_TYPE, :ResourceEntities => RESOURCE_ENTITIES_TYPE, :AvailableNetworks => AVAILABLE_NETWORKS_TYPE, :Capabilities => CAPABILITIES_TYPE, :NicQuota => String, :NetworkQuota => String, :UsedNetworkCount => String, :VmQuota => Fog::Nullable::String, :IsEnabled => Fog::Nullable::String, :VdcStorageProfiles => VDC_STORAGE_PROFILES_TYPE # >= 5.1 }) # Represents a storage profile in an organization vDC. VDC_STORAGE_PROFILE_TYPE = ENTITY_TYPE.merge({ :Enabled => Fog::Nullable::String, :Units => String, :Limit => String, :Default => String }) # Information about an individual operating system. OPERATING_SYSTEM_INFO_TYPE = { :OperatingSystemId => String, :DefaultHardDiskAdapterType => String, :MinimumHardDiskSizeGigabytes => String, :MinimumMemoryMegabytes => String, :Name => String, :InternalName => String, :Supported => String, :x64 => String, :MaximumCpuCount => String, :MinimumHardwareVersion => String, :PersonalizationEnabled => String, :PersonalizationAuto => String, :SysprepPackagingSupported => String, :SupportsMemHotAdd => String, :cimOsId => String, :CimVersion => String, :SupportedForCreate => String } # Represents an operating system family. OPERATING_SYSTEM_FAMILY_INFO_TYPE = { :Name => String, :OperatingSystemFamilyId => String, :OperatingSystem => [OPERATING_SYSTEM_INFO_TYPE] } # Operating systems available for use on virtual machines owned by this # organization. SUPPORTED_OPERATING_SYSTEMS_INFO_TYPE = RESOURCE_TYPE.merge({ :OperatingSystemFamilyInfo => [OPERATING_SYSTEM_FAMILY_INFO_TYPE] }) # Container for query results in records format. # Combine with QUERY_RESULT_RECORD_TYPE subtypes to validate query results QUERY_RESULT_RECORDS_TYPE = CONTAINER_TYPE # Base type for a single record from query result in records format. # Subtypes define more specific elements. QUERY_RESULT_RECORD_TYPE = { :href => String, :id => Fog::Nullable::String, :type => Fog::Nullable::String } # Type for a single edgeGateway query result in records format. QUERY_RESULT_EDGE_GATEWAY_RECORD_TYPE = QUERY_RESULT_RECORD_TYPE.merge({ :gatewayStatus => String, :haStatus => String, :isBusy => String, :name => String, :numberOfExtNetworks => String, :numberOfOrgNetworks=> String, :vdc => String }) FIREWALL_RULE_TYPE__PROTOCOLS = { :Icmp => Fog::Nullable::String, :Asny => Fog::Nullable::String, :Other => Fog::Nullable::String } # Represents a firewall rule. FIREWALL_RULE_TYPE = { :Id => String, :IsEnabled => String, :MatchOnTranslate => Fog::Nullable::String, :Description => Fog::Nullable::String, :Policy => Fog::Nullable::String, :IcmpSubType => Fog::Nullable::String, :Port => Fog::Nullable::String, :DestinationPortRange => String, :SourcePort => Fog::Nullable::String, :SourcePortRange => String, :Direction => Fog::Nullable::String, :EnableLogging => Fog::Nullable::String, :Protocols => FIREWALL_RULE_TYPE__PROTOCOLS } # Represents a network firewall service. FIREWALL_SERVICE_TYPE = { :IsEnabled => String, :DefaultAction => String, :LogDefaultAction => String, #:FirewallRule => [FIREWALL_RULE_TYPE] # not required } #Represents the SNAT and DNAT rules. GATEWAY_NAT_RULE_TYPE = { :Interface => REFERENCE_TYPE, :OriginalIp => String, :OriginalPort => Fog::Nullable::String, :TranslatedIp => String, :TranslatedPort => Fog::Nullable::String, :Protocol => Fog::Nullable::String, :IcmpSubType => Fog::Nullable::String } #Represents a NAT rule. NAT_RULE_TYPE = { :Description => Fog::Nullable::String, :RuleType => String, :IsEnabled => String, :Id => String, :GatewayNatRule => GATEWAY_NAT_RULE_TYPE } # Represents a NAT network service. NAT_SERVICE_TYPE = { :IsEnabled => String, :NatType => Fog::Nullable::String, :Policy => Fog::Nullable::String, #:NatRule => [NAT_RULE_TYPE], # not required :ExternalIp => Fog::Nullable::String } # Represents a service port in a load balancer pool. LB_POOL_SERVICE_PORT_TYPE = { :IsEnabled => Fog::Nullable::String, :Protocol => String, :Algorithm => Fog::Nullable::String, :Port => String, :HealthCheckPort => String, #:HealthCheck => LBPoolHealthCheckType # not required } # Represents a member in a load balancer pool. LB_POOL_MEMBER_TYPE = { :IpAddress => String, :Weight => String, :ServicePort => [LB_POOL_SERVICE_PORT_TYPE] } # Represents a load balancer pool. LOAD_BALANCER_POOL_TYPE = { :Id => Fog::Nullable::String, :Name => String, :Description => Fog::Nullable::String, :ServicePort => [LB_POOL_SERVICE_PORT_TYPE], :Member => [LB_POOL_MEMBER_TYPE], :Operational => String, :ErrorDetails => Fog::Nullable::String } # Represents persistence type for a load balancer service profile. LB_PERSISTENCE_TYPE = { :Method => String, :CookieName => Fog::Nullable::String, :CookieMode => Fog::Nullable::String } # Represents service profile for a load balancing virtual server. LB_VIRTUAL_SERVER_SERVICE_PROFILE_TYPE = { :IsEnabled => String, :Protocol => String, :Port => String, :Persistence => LB_PERSISTENCE_TYPE } # Information about a vendor service template. This is optional. VENDOR_TEMPLATE_TYPE = { :Name => String, :Id => String } # Represents a load balancer virtual server. LOAD_BALANCER_VIRTUAL_SERVER_TYPE = { :IsEnabled => String, :Name => String, :Description => Fog::Nullable::String, :Interface => REFERENCE_TYPE, :IpAddress => String, :ServiceProfile => [LB_VIRTUAL_SERVER_SERVICE_PROFILE_TYPE], :Logging => String, :Pool => String, #:LoadBalancerTemplates => VENDOR_TEMPLATE_TYPE # not required } # Represents gateway load balancer service. LOAD_BALANCER_SERVICE_TYPE = { :Pool => LOAD_BALANCER_POOL_TYPE, :VirtualServer => LOAD_BALANCER_VIRTUAL_SERVER_TYPE, :IsEnabled => Fog::Nullable::String } # Represents Gateway DHCP service. GATEWAY_DHCP_SERVICE_TYPE = { :IsEnabled => String, #:Pool => DHCP_POOL_SERVICE_TYPE # not required } # Represents edge gateway services. GATEWAY_FEATURES_TYPE = { #:StaticRoutingService => STATIC_ROUTING_SERVICE_TYPE, #not required #:GatewayIpsecVpnService => GATEWAY_IPSEC_VPN_SERVICE_TYPE, #not required #:GatewayDhcpService => GATEWAY_DHCP_SERVICE_TYPE, #not required #:LoadBalancerService => LOAD_BALANCER_SERVICE_TYPE, #not required #:NatService => NAT_SERVICE_TYPE, #not required :FirewallService => FIREWALL_SERVICE_TYPE } # Represents a range of IP addresses, start and end inclusive. IP_RANGE_TYPE = { :StartAddress => String, :EndAddress => String } # Represents a list of IP ranges. IP_RANGES_TYPE = { :IpRange => [IP_RANGE_TYPE] } # Allows to chose which subnets a gateway can be part of SUBNET_PARTICIPATION_TYPE = { :Gateway => String, :Netmask => String, :IpAddress => String, :IpRanges => IP_RANGES_TYPE } # Gateway Interface configuration. GATEWAY_INTERFACE_TYPE = { :Name => String, :DisplayName => String, :Network => REFERENCE_TYPE, :InterfaceType => String, #:SubnetParticipation => [SUBNET_PARTICIPATION_TYPE], #bug in parser means list or hash :ApplyRateLimit => String, :InRateLimit => Fog::Nullable::String, :OutRateLimit => Fog::Nullable::String, :UseForDefaultRoute => String, } # A list of Gateway Interfaces. GATEWAY_INTERFACES_TYPE = { :GatewayInterface => [GATEWAY_INTERFACE_TYPE] } # Gateway Configuration. GATEWAY_CONFIGURATION_TYPE = { :BackwardCompatibilityMode => Fog::Nullable::String, :GatewayBackingConfig => String, :GatewayInterfaces => GATEWAY_INTERFACES_TYPE, :EdgeGatewayServiceConfiguration => GATEWAY_FEATURES_TYPE, :HaEnabled => Fog::Nullable::String, :UseDefaultRouteForDnsRelay => Fog::Nullable::String } # Represents a gateway. GATEWAY_TYPE = { :href => String, :type => String, :id => String, :operationKey => Fog::Nullable::String, :name => String, :status => Fog::Nullable::String, #:Link => LINK_TYPE, # not required :Description => Fog::Nullable::String, #:Tasks => TASKS_IN_PROGRESS_TYPE, # not required :Configuration => GATEWAY_CONFIGURATION_TYPE } ORGANIZATION_REFERENCE_TYPE = REFERENCE_TYPE PROVIDER_VDC_REFERENCE_TYPE = REFERENCE_TYPE RIGHT_REFERENCE_TYPE = REFERENCE_TYPE ROLE_REFERENCE_TYPE = REFERENCE_TYPE # Represents the admin view of this cloud. ORGANIZATION_REFERENCES_TYPE = { :OrganizationReference => [REFERENCE_TYPE] } # Container for references to Provider vDCs. PROVIDER_VDC_REFERENCES_TYPE = { :ProviderVdcReference => [PROVIDER_VDC_REFERENCE_TYPE] } # Container for references to rights. RIGHT_REFERENCES_TYPE = { :RightReference => [RIGHT_REFERENCE_TYPE] } # Container for references to roles. ROLE_REFERENCES_TYPE = { :RoleReference => [ROLE_REFERENCE_TYPE] } # Container for references to ExternalNetwork objects. NETWORKS_TYPE = { :Network => [REFERENCE_TYPE] } VCLOUD_TYPE = ENTITY_TYPE.merge({ :OrganizationReferences => ORGANIZATION_REFERENCES_TYPE, :ProviderVdcReferences => PROVIDER_VDC_REFERENCES_TYPE, :RightReferences => RIGHT_REFERENCES_TYPE, :RoleReferences => ROLE_REFERENCES_TYPE, :Networks => NETWORKS_TYPE }) # Represents a named disk. DISK_TYPE = RESOURCE_ENTITY_TYPE.merge({ :busSubType => Fog::Nullable::String, :busType => Fog::Nullable::String, :size => String, :StorageProfile => REFERENCE_TYPE, :Owner => OWNER_TYPE }) VMS_TYPE = RESOURCE_TYPE.merge({ :VmReference => [REFERENCE_TYPE] }) end end end fog-1.19.0/tests/vcloud_director/requests/compute/groups_tests.rb0000644000004100000410000000121012261242552025346 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | groups requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new tests('#get_groups_from_query') do pending if Fog.mocking? %w[idrecords records references].each do |format| tests(":format => #{format}") do tests('#body').data_matches_schema(VcloudDirector::Compute::Schema::CONTAINER_TYPE) do @body = @service.get_groups_from_query(:format => format).body end key = (format == 'references') ? 'GroupReference' : 'GroupRecord' tests("#body.key?(:#{key})").returns(true) { @body.key?(key.to_sym) } end end end end fog-1.19.0/tests/vcloud_director/requests/compute/vdc_tests.rb0000644000004100000410000000246712261242552024622 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | vdc requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new @org = VcloudDirector::Compute::Helper.current_org(@service) tests('#get_vdc').data_matches_schema(VcloudDirector::Compute::Schema::VDC_TYPE) do link = @org[:Link].detect do |l| l[:rel] == 'down' && l[:type] == 'application/vnd.vmware.vcloud.vdc+xml' end @vdc_id = link[:href].split('/').last @service.get_vdc(@vdc_id).body end tests('#get_vdc_metadata').data_matches_schema(VcloudDirector::Compute::Schema::METADATA_TYPE) do pending if Fog.mocking? @service.get_vdc_metadata(@vdc_id).body end tests('#get_vdcs_from_query') do pending if Fog.mocking? %w[idrecords records references].each do |format| tests(":format => #{format}") do tests('#body').data_matches_schema(VcloudDirector::Compute::Schema::CONTAINER_TYPE) do @body = @service.get_vdcs_from_query(:format => format).body end key = (format == 'references') ? 'OrgVdcReference' : 'OrgVdcRecord' tests("#body.key?(:#{key})").returns(true) { @body.key?(key.to_sym) } end end end tests('Retrieve non-existent vDC').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_vdc('00000000-0000-0000-0000-000000000000') end end fog-1.19.0/tests/vcloud_director/requests/compute/ovf_descriptor_tests.rb0000644000004100000410000000253112261242552027066 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | ovf requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new @org = VcloudDirector::Compute::Helper.current_org(@service) tests('Get first vDC') do session = @service.get_current_session.body link = @org[:Link].detect do |l| l[:type] == 'application/vnd.vmware.vcloud.vdc+xml' end @vdc = @service.get_vdc(link[:href].split('/').last).body end # 'Envelope' is the outer type of the parsed XML document. tests('#get_vapp_ovf_descriptor').returns('Envelope') do pending if Fog.mocking? link = @vdc[:ResourceEntities][:ResourceEntity].detect do |l| l[:type] == 'application/vnd.vmware.vcloud.vApp+xml' end pending if link.nil? body = @service.get_vapp_ovf_descriptor(link[:href].split('/').last).body Nokogiri::XML::Document.parse(body).children.first.name end # 'Envelope' is the outer type of the parsed XML document. tests('#get_vapp_template_ovf_descriptor').returns('Envelope') do pending if Fog.mocking? link = @vdc[:ResourceEntities][:ResourceEntity].detect do |l| l[:type] == 'application/vnd.vmware.vcloud.vAppTemplate+xml' end pending if link.nil? body = @service.get_vapp_template_ovf_descriptor(link[:href].split('/').last).body Nokogiri::XML::Document.parse(body).children.first.name end end fog-1.19.0/tests/vcloud_director/requests/compute/vapp_tests.rb0000644000004100000410000000720712261242552025011 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | vapp requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new @org = VcloudDirector::Compute::Helper.current_org(@service) tests('Each vDC') do @org[:Link].select do |l| l[:type] == 'application/vnd.vmware.vcloud.vdc+xml' end.each do |link| @vdc = @service.get_vdc(link[:href].split('/').last).body tests('Each vApp') do @vdc[:ResourceEntities][:ResourceEntity].select do |r| r[:type] == 'application/vnd.vmware.vcloud.vApp+xml' end.each do |v| @vapp_id = v[:href].split('/').last #tests("#get_vapp(#{@vapp_id})").data_matches_schema(VcloudDirector::Compute::Schema::VAPP_TYPE) do tests("#get_vapp(#{@vapp_id})").returns(Hash) do pending if Fog.mocking? @service.get_vapp(@vapp_id).body.class end tests("#get_lease_settings_section_vapp(#{@vapp_id})").returns(Hash) do pending if Fog.mocking? @service.get_lease_settings_section_vapp(@vapp_id).body.class end tests("#get_network_config_section_vapp(#{@vapp_id})").returns(Hash) do pending if Fog.mocking? @service.get_network_config_section_vapp(@vapp_id).body.class end tests("#get_network_section_vapp(#{@vapp_id})").returns(Hash) do pending if Fog.mocking? @service.get_network_section_vapp(@vapp_id).body.class end tests("#get_product_sections_vapp(#{@vapp_id})").returns(Hash) do pending if Fog.mocking? @service.get_product_sections_vapp(@vapp_id).body.class end tests("#get_startup_section(#{@vapp_id})").returns(Hash) do pending if Fog.mocking? @service.get_startup_section(@vapp_id).body.class end tests("#get_vapp_metadata(#{@vapp_id})").data_matches_schema(VcloudDirector::Compute::Schema::METADATA_TYPE) do pending if Fog.mocking? @service.get_vapp_metadata(@vapp_id).body end tests("#get_vapp_owner(#{@vapp_id})").data_matches_schema(VcloudDirector::Compute::Schema::OWNER_TYPE) do pending if Fog.mocking? @service.get_vapp_owner(@vapp_id).body end tests("#get_control_access_params_vapp(#{@vapp_id})").data_matches_schema(VcloudDirector::Compute::Schema::CONTROL_ACCESS_PARAMS_TYPE) do pending if Fog.mocking? @service.get_control_access_params_vapp(@vapp_id).body end end end end end tests('#get_vapps_in_lease_from_query') do pending if Fog.mocking? %w[idrecords records references].each do |format| tests(":format => #{format}") do tests('#body').data_matches_schema(VcloudDirector::Compute::Schema::CONTAINER_TYPE) do @body = @service.get_vapps_in_lease_from_query(:format => format).body end key = (format == 'references') ? 'VAppReference' : 'VAppRecord' tests("#body.key?(:#{key})").returns(true) { @body.key?(key.to_sym) } end end end tests('Retrieve non-existent vApp').raises(Fog::Compute::VcloudDirector::Forbidden) do pending if Fog.mocking? @service.get_vapp('00000000-0000-0000-0000-000000000000') end tests('Retrieve owner of non-existent vApp').raises(Fog::Compute::VcloudDirector::Forbidden) do pending if Fog.mocking? @service.get_vapp_owner('00000000-0000-0000-0000-000000000000') end tests('Delete non-existent vApp').raises(Fog::Compute::VcloudDirector::Forbidden) do pending if Fog.mocking? @service.delete_vapp('00000000-0000-0000-0000-000000000000') end end fog-1.19.0/tests/vcloud_director/requests/compute/vm_tests.rb0000644000004100000410000001301012261242552024452 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | vm requests', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new @org = VcloudDirector::Compute::Helper.current_org(@service) tests('Each vDC') do @org[:Link].select do |l| l[:type] == 'application/vnd.vmware.vcloud.vdc+xml' end.each do |link| @vdc = @service.get_vdc(link[:href].split('/').last).body tests('Each vApp') do @vdc[:ResourceEntities][:ResourceEntity].select do |r| r[:type] == 'application/vnd.vmware.vcloud.vApp+xml' end.each do |vapp| vapp_id = vapp[:href].split('/').last vapp = @service.get_vapp(vapp_id).body tests('Each VM') do vapp[:Children][:Vm].each do |vm| vm_id = vm[:href].split('/').last tests("#get_guest_customization_system_section_vapp(#{vm_id})").data_matches_schema(VcloudDirector::Compute::Schema::GUEST_CUSTOMIZATION_SECTION_TYPE) do pending if Fog.mocking? @service.get_guest_customization_system_section_vapp(vm_id).body end tests("#get_network_connection_system_section_vapp(#{vm_id})").returns(Hash) do pending if Fog.mocking? @service.get_network_connection_system_section_vapp(vm_id).body.class end tests("#get_operating_system_section(#{vm_id})").returns(Hash) do pending if Fog.mocking? @service.get_operating_system_section(vm_id).body.class end tests("#get_product_sections_vapp(#{vm_id})").returns(Hash) do pending if Fog.mocking? @service.get_product_sections_vapp(vm_id).body.class end tests("#get_runtime_info_section_type(#{vm_id})").data_matches_schema(VcloudDirector::Compute::Schema::RUNTIME_INFO_SECTION_TYPE) do pending if Fog.mocking? pending # fails if WMware Tools not installed @service.get_runtime_info_section_type(vm_id).body end tests("#get_snapshot_section(#{vm_id})").returns(Hash) do pending if Fog.mocking? @service.get_snapshot_section(vm_id).body.class end tests("#get_vm_capabilities(#{vm_id})").data_matches_schema(VcloudDirector::Compute::Schema::VM_CAPABILITIES_TYPE) do pending if Fog.mocking? @service.get_vm_capabilities(vm_id).body end tests("#get_virtual_hardware_section(#{vm_id})").returns(Hash) do pending if Fog.mocking? @section = @service.get_virtual_hardware_section(vm_id).body.class end tests("#get_cpu_rasd_item(#{vm_id})").returns(Hash) do pending if Fog.mocking? @service.get_cpu_rasd_item(vm_id).body.class end tests("#get_disks_rasd_items_list(#{vm_id})").returns(Hash) do pending if Fog.mocking? @service.get_disks_rasd_items_list(vm_id).body.class end tests("#get_media_drives_rasd_items_list(#{vm_id})").returns(Hash) do pending if Fog.mocking? @service.get_media_drives_rasd_items_list(vm_id).body.class end tests("#get_memory_rasd_item(#{vm_id})").returns(Hash) do pending if Fog.mocking? @service.get_memory_rasd_item(vm_id).body.class end tests("#get_network_cards_items_list(#{vm_id})").returns(Hash) do pending if Fog.mocking? @service.get_network_cards_items_list(vm_id).body.class end tests("#get_serial_ports_items_list(#{vm_id})").returns(Hash) do pending if Fog.mocking? @service.get_serial_ports_items_list(vm_id).body.class end tests("#get_vapp_metadata(#{vm_id})").data_matches_schema(VcloudDirector::Compute::Schema::METADATA_TYPE) do pending if Fog.mocking? @service.get_vapp_metadata(vm_id).body end tests("#post_acquire_ticket(#{vm_id})").data_matches_schema(VcloudDirector::Compute::Schema::METADATA_TYPE) do pending # result depends on power state @service.post_acquire_ticket(vm_id).body end end end end end end end tests('#get_vms_in_lease_from_query') do pending if Fog.mocking? %w[idrecords records references].each do |format| tests(":format => #{format}") do tests('#body').data_matches_schema(VcloudDirector::Compute::Schema::CONTAINER_TYPE) do @body = @service.get_vms_in_lease_from_query(:format => format).body end key = (format == 'references') ? 'VMReference' : 'VMRecord' tests("#body.key?(:#{key})").returns(true) { @body.key?(key.to_sym) } end end end #tests('Retrieve non-existent vApp').raises(Fog::Compute::VcloudDirector::Forbidden) do # pending if Fog.mocking? # @service.get_vapp('00000000-0000-0000-0000-000000000000') #end #tests('Retrieve owner of non-existent vApp').raises(Fog::Compute::VcloudDirector::Forbidden) do # pending if Fog.mocking? # @service.get_vapp_owner('00000000-0000-0000-0000-000000000000') #end #tests('Delete non-existent vApp').raises(Fog::Compute::VcloudDirector::Forbidden) do # pending if Fog.mocking? # @service.delete_vapp('00000000-0000-0000-0000-000000000000') #end end fog-1.19.0/tests/vcloud_director/fixtures/0000755000004100000410000000000012261242552020610 5ustar www-datawww-datafog-1.19.0/tests/vcloud_director/fixtures/test.iso0000644000004100000410000000001612261242552022300 0ustar www-datawww-dataNOT A REAL ISOfog-1.19.0/tests/vcloud_director/ensure_list_tests.rb0000644000004100000410000000505512261242552023047 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | ensure_list!', ['vclouddirector']) do # ensure list is not available in mocking mode unless Fog.mocking? @service = Fog::Compute::VcloudDirector.new tests('#ensure_list! for single key ensures our key has an array as a value') do tests('for key with a hash').returns(Array) do testdata = {:k => {:A => '1'}} @service.ensure_list!(testdata, :k) testdata[:k].class end tests('for key with empty array').returns(Array) do testdata = {:k => []} @service.ensure_list!(testdata, :k) testdata[:k].class end tests('for key with nothing').returns(Array) do testdata = {} @service.ensure_list!(testdata, :k) testdata[:k].class end tests('for key with non-empty array').returns(Array) do testdata = {:k => ['one', 'two']} @service.ensure_list!(testdata, :k) testdata[:k].class end end tests('#ensure_list! for nested keys ensures that the child key has an array as a value') do tests('with no key').returns(Array) do testdata = {} @service.ensure_list!(testdata, :keys, :key) testdata[:keys][:key].class end tests('with empty string').returns(Array) do testdata = {:keys => ''} @service.ensure_list!(testdata, :keys, :key) testdata[:keys][:key].class end tests('with nested hashes').returns(Array) do testdata = {:keys => {:key => {:a => '1'}}} @service.ensure_list!(testdata, :keys, :key) testdata[:keys][:key].class end end tests('#ensure_list! with parent and child keys does not effect existing data') do tests('for existing array').returns([:one, :two]) do testdata = {:keys => {:key => [:one, :two]}} @service.ensure_list!(testdata, :keys, :key) testdata[:keys][:key] end tests('for existing hash').returns([{:one => :two}]) do testdata = {:keys => {:key => {:one => :two}}} @service.ensure_list!(testdata, :keys, :key) testdata[:keys][:key] end end tests('#ensure_list! with single key does not effect existing data') do tests('for existing array').returns([:one, :two]) do testdata = {:k => [:one, :two]} @service.ensure_list!(testdata, :k) testdata[:k] end tests('for existing hash').returns([{:one => 'two'}]) do testdata = {:k => {:one => 'two'}} @service.ensure_list!(testdata, :k) testdata[:k] end end end end fog-1.19.0/tests/vcloud_director/models/0000755000004100000410000000000012261242552020222 5ustar www-datawww-datafog-1.19.0/tests/vcloud_director/models/compute/0000755000004100000410000000000012261242552021676 5ustar www-datawww-datafog-1.19.0/tests/vcloud_director/models/compute/vdcs_tests.rb0000644000004100000410000000325212261242552024406 0ustar www-datawww-datarequire File.expand_path(File.join(File.dirname(__FILE__), 'helper')) Shindo.tests("Compute::VcloudDirector | vdcs", ['vclouddirector', 'all']) do pending if Fog.mocking? tests("#There is one or more vdc").returns(true){ organization.vdcs.size >= 1 } vdcs = organization.vdcs vdc = vdcs.first tests("Compute::VcloudDirector | vdc") do tests("#id").returns(String) { vdc.id.class } tests("#name").returns(String) { vdc.name.class } tests("#href").returns(String) { vdc.href.class } tests("#type").returns("application/vnd.vmware.vcloud.vdc+xml") { vdc.type } end tests("Compute::VcloudDirector | vdc", ['lazy load attrs']) do vdc.lazy_load_attrs.each do |lazy_attr| tests("##{lazy_attr} is not loaded yet").returns(NonLoaded) { vdc.attributes[lazy_attr] } end end tests("Compute::VcloudDirector | vdc", ['load on demand']) do tests("#description is not loaded yet").returns(NonLoaded) { vdc.attributes[:description] } tests("#description is loaded on demand").returns(String) { vdc.description.class } tests("#description is now loaded").returns(true) { vdc.attributes[:description] != NonLoaded } end tests("Compute::VcloudDirector | vdc", ['lazy load attrs']) do lazy_attrs = vdc.lazy_load_attrs lazy_attrs.delete(:storage_capacity) if vcloud_director.api_version.to_f >= 5.1 lazy_attrs.each do |lazy_attr| tests("##{lazy_attr} is now loaded").returns(true) { vdc.attributes[lazy_attr] != NonLoaded } end end tests("Compute::VcloudDirector | vdc", ['get']) do tests("#get_by_name").returns(vdc.name) { vdcs.get_by_name(vdc.name).name } tests("#get").returns(vdc.id) { vdcs.get(vdc.id).id } end end fog-1.19.0/tests/vcloud_director/models/compute/helper.rb0000644000004100000410000000203012261242552023475 0ustar www-datawww-datarequire 'fog/vcloud_director/compute' def boolean?(item) [TrueClass, FalseClass].include?(item.class) end def vcloud_director @vcloud_director ||= Fog::Compute::VcloudDirector.new( :connection_options => { :ssl_verify_peer => false, :connect_timeout => 200, :read_timeout => 200 } ) end def organizations @organizations ||= vcloud_director.organizations end def organization @organization ||= organizations.get_by_name(vcloud_director.org_name) end def catalogs @catalogs ||= organization.catalogs end def catalog catalogs.first end def vdcs @vdcs ||= organization.vdcs end def vdc vdcs.first end def vapps @vapps ||= vdc.vapps end def vapp vapps.detect {|vapp| vapp.vms.size >= 1 } end def the_network @network ||= organization.networks.get_by_name(NETWORK_NAME) end def the_catalog @catalog ||= organization.catalogs.get_by_name(CATALOG_NAME) end def the_catalog_item return nil unless the_catalog @catalog_item ||= the_catalog.catalog_items.get_by_name(CATALOG_ITEM_NAME) end fog-1.19.0/tests/vcloud_director/models/compute/catalogs_tests.rb0000644000004100000410000000331412261242552025243 0ustar www-datawww-datarequire File.expand_path(File.join(File.dirname(__FILE__), 'helper')) Shindo.tests("Compute::VcloudDirector | catalogs", ['vclouddirector', 'all']) do pending if Fog.mocking? pending if organization.catalogs.empty? catalogs = organization.catalogs tests("#There is one or more catalog").returns(true) { catalogs.size >= 1 } catalog = catalogs.first tests("Compute::VcloudDirector | catalog") do tests("#id").returns(String){ catalog.id.class } tests("#name").returns(String){ catalog.name.class } tests("#href").returns(String){ catalog.href.class } tests("#type").returns("application/vnd.vmware.vcloud.catalog+xml"){ catalog.type } end tests("Compute::VcloudDirector | catalog", ['lazy load attrs']) do catalog.lazy_load_attrs.each do |lazy_attr| tests("##{lazy_attr} is not loaded yet").returns(NonLoaded) { catalog.attributes[lazy_attr] } end end tests("Compute::VcloudDirector | catalog", ['load on demand']) do tests("#description is not loaded yet").returns(NonLoaded) { catalog.attributes[:description] } tests("#description is loaded on demand").returns(String) { catalog.description.class } tests("#description is now loaded").returns(true) { catalog.attributes[:description] != NonLoaded } end tests("Compute::VcloudDirector | catalog", ['lazy load attrs']) do catalog.lazy_load_attrs.each do |lazy_attr| tests("##{lazy_attr} is now loaded").returns(true) { catalog.attributes[lazy_attr] != NonLoaded } end end tests("Compute::VcloudDirector | catalog", ['get']) do tests("#get_by_name").returns(catalog.name) { catalogs.get_by_name(catalog.name).name } tests("#get").returns(catalog.id) { catalogs.get(catalog.id).id } end end fog-1.19.0/tests/vcloud_director/models/compute/organizations_tests.rb0000644000004100000410000000141312261242552026333 0ustar www-datawww-datarequire File.expand_path(File.join(File.dirname(__FILE__), 'helper')) Shindo.tests("Compute::VcloudDirector | organizations", ['vclouddirector', 'all']) do organizations = vcloud_director.organizations tests("#There is at least one organization").returns(true) { organizations.size >= 1 } org = organizations.get_by_name(vcloud_director.org_name) tests("Compute::VcloudDirector | organization") do tests("#name").returns(String) { org.name.class } tests("#type").returns("application/vnd.vmware.vcloud.org+xml") { org.type } end tests("Compute::VcloudDirector | organization", ['get']) do tests("#get_by_name").returns(org.name) { organizations.get_by_name(org.name).name } tests("#get").returns(org.id) { organizations.get(org.id).id } end end fog-1.19.0/tests/vcloud_director/models/compute/vapp_life_cycle_tests.rb0000644000004100000410000001012712261242552026572 0ustar www-datawww-datarequire File.expand_path(File.join(File.dirname(__FILE__), 'helper')) VAPP_NAME = "shindo07" NETWORK_NAME = "DevOps - Dev Network Connection" NETWORK_MODE = "POOL" CATALOG_NAME = "Public VM Templates" CATALOG_ITEM_NAME = "DEVWEB" TAGS = { :company => "acme", :environment => "testing" } Shindo.tests("Compute::VcloudDirector | vapp", ['vclouddirector', 'creation']) do pending if Fog.mocking? pending # FIXME: vCloud environment needs to be set up in advance tests("#it creates a vApp from a catalog item").returns(true){ the_catalog_item.instantiate(VAPP_NAME, { :network_id => the_network.id, :network_name => NETWORK_NAME}) } vapp = vapps.get_by_name(VAPP_NAME) tests("#Finds the just created vApp").returns(VAPP_NAME) { vapp.name } tests("#it has one vm").returns(1) { vapp.vms.size} tests("Compute::VcloudDirector | vm", ['configuration']) do vm = vapp.vms.first tests("Compute::VcloudDirector | vm", ['network']) do network = vm.network network.network = NETWORK_NAME network.is_connected = true network.ip_address_allocation_mode = NETWORK_MODE tests("save network changes").returns(true){ network.save } network.reload tests("#network").returns(NETWORK_NAME) { network.network } tests("#is_connected").returns(true) { network.is_connected } tests("#ip_address_allocation_mode").returns(NETWORK_MODE) { network.ip_address_allocation_mode } end tests("Compute::VcloudDirector | vm", ['customization']) do customization = vm.customization customization.script = 'this is the user data' customization.enabled = true tests("save customization changes").returns(true){ customization.save } tests("#script").returns('this is the user data') { customization.script } tests("#enabled").returns(true) { customization.enabled } end tests("Compute::VcloudDirector | vm", ['doble the disk size']) do disk = vm.disks.get_by_name('Hard disk 1') tests("#disk_size").returns(Fixnum) { disk.capacity.class} new_size = disk.capacity * 2 disk.capacity = new_size disk.reload tests("#disk_size is now doubled").returns(new_size) { disk.capacity } end tests("Compute::VcloudDirector | vm", ['add a new disk']) do tests("hard disk 2 doesn't exist").returns(nil) { vm.disks.get_by_name('Hard disk 2') } tests("#create").returns(true) { vm.disks.create(1024) } tests("hard disk 2 exists").returns(1024) { vm.disks.get_by_name('Hard disk 2').capacity } tests("delete disk 2").returns(true) { vm.disks.get_by_name('Hard disk 2').destroy } tests("hard disk 2 doesn't exist anymore").returns(nil) { vm.disks.get_by_name('Hard disk 2') } end tests("Compute::VcloudDirector | vm", ['doble the memory size']) do tests("#memory").returns(Fixnum) { vm.memory.class} new_size = vm.memory * 2 vm.memory = new_size vm.reload tests("#memory is now doubled").returns(new_size) { vm.memory } end tests("Compute::VcloudDirector | vm", ['doble the cpu size']) do tests("#cpu").returns(Fixnum) { vm.cpu.class} new_size = vm.cpu * 2 vm.cpu = new_size vm.reload tests("#memory is now doubled").returns(new_size) { vm.cpu } end tests("Compute::VcloudDirector | vm", ['tags']) do TAGS.each_pair do |k,v| tests('create tag').returns(true) {vm.tags.create(k, v)} end tests('there are two tags').returns(2){ vm.tags.size } tests('#get_by_name').returns("acme"){ vm.tags.get_by_name('company').value } tests('#get_by_name').returns("testing"){ vm.tags.get_by_name('environment').value } tests('delete company').returns(true){ vm.tags.get_by_name('company').destroy } tests("company doesn't exists anymore").returns(nil){ vm.tags.get_by_name('company') } tests('there is only one tag').returns(1){ vm.tags.size } end tests("Compute::VcloudDirector | vm", ['power on']) do tests('#vm is off').returns("off"){ vm.status } tests('#power_on').returns(true){ vm.power_on } vm.reload tests('#vm is on').returns("on"){ vm.status } end end end fog-1.19.0/tests/vcloud_director/models/compute/catalog_items_tests.rb0000644000004100000410000000355112261242552026264 0ustar www-datawww-datarequire File.expand_path(File.join(File.dirname(__FILE__), 'helper')) Shindo.tests("Compute::VcloudDirector | catalog_items", ['vclouddirector', 'all']) do pending if Fog.mocking? pending if catalog.nil? catalog_items = catalog.catalog_items pending if catalog_items.empty? tests("#There is one or more catalog item").returns(true) { catalog_items.size >= 1 } catalog_item = catalog_items.first tests("Compute::VcloudDirector | catalog_item") do tests("#id").returns(String){ catalog_item.id.class } tests("#name").returns(String){ catalog_item.name.class } tests("#href").returns(String){ catalog_item.href.class } tests("#type").returns("application/vnd.vmware.vcloud.catalogItem+xml"){ catalog_item.type } end tests("Compute::VcloudDirector | catalog_item", ['lazy load attrs']) do catalog_item.lazy_load_attrs.each do |lazy_attr| tests("##{lazy_attr} is not loaded yet").returns(NonLoaded) { catalog_item.attributes[lazy_attr] } end end tests("Compute::VcloudDirector | catalog_item", ['load on demand']) do tests("#description is not loaded yet").returns(NonLoaded) { catalog_item.attributes[:description] } tests("#description is loaded on demand").returns(String) { catalog_item.description.class } tests("#description is now loaded").returns(true) { catalog_item.attributes[:description] != NonLoaded } end tests("Compute::VcloudDirector | catalog_item", ['lazy load attrs']) do catalog.lazy_load_attrs.each do |lazy_attr| tests("##{lazy_attr} is now loaded").returns(true) { catalog_item.attributes[lazy_attr] != NonLoaded } end end tests("Compute::VcloudDirector | catalog_item", ['get']) do tests("#get_by_name").returns(catalog_item.name) { catalog_items.get_by_name(catalog_item.name).name } tests("#get").returns(catalog_item.id) { catalog_items.get(catalog_item.id).id } end end fog-1.19.0/tests/vcloud_director/models/compute/vms_tests.rb0000644000004100000410000001067512261242552024263 0ustar www-datawww-datarequire File.expand_path(File.join(File.dirname(__FILE__), 'helper')) Shindo.tests("Compute::VcloudDirector | vms", ['vclouddirector', 'all']) do pending if Fog.mocking? vapp = vapps.detect {|v| v.vms.size >= 1} # we can't run these tests if there is no vapps with a vm in them pending unless vapp vms = vapp.vms vm = vms.first tests("Compute::VcloudDirector | vm") do tests("#model").returns(Fog::Compute::VcloudDirector::Vm){vm.class} tests("#id").returns(String){ vm.id.class } tests("#name").returns(String){ vm.name.class } tests("#href").returns(String){ vm.href.class } tests("#type").returns("application/vnd.vmware.vcloud.vm+xml"){ vm.type } tests("#vapp_id").returns(String){ vm.vapp_id.class } tests("#status").returns(String){ vm.status.class } tests("#operating_system").returns(String){ vm.operating_system.class } tests("#ip_address").returns(String){ vm.ip_address.class } tests("#cpu").returns(Fixnum){ vm.cpu.class } tests("#memory").returns(Fixnum){ vm.memory.class } tests("#hard_disks").returns(Array){ vm.hard_disks.class } end tests("Compute::VcloudDirector | vm", ['get']) do tests("#get_by_name").returns(vm.name) { vms.get_by_name(vm.name).name } tests("#get").returns(vm.id) { vms.get(vm.id).id } end tests("Compute::VcloudDirector | vm | disks") do tests("#collection").returns(Fog::Compute::VcloudDirector::Disks){ vm.disks.class } tests("#get_by_name").returns(Fog::Compute::VcloudDirector::Disk) { vm.disks.get_by_name("Hard disk 1").class } hard_disk = vm.disks.get_by_name("Hard disk 1") tests("#id").returns(2000){ hard_disk.id } tests("#name").returns("Hard disk 1"){ hard_disk.name } tests("#description").returns("Hard disk"){ hard_disk.description } tests("#resource_type").returns(17){ hard_disk.resource_type } tests("#address_on_parent").returns(0){ hard_disk.address_on_parent } tests("#parent").returns(2){ hard_disk.parent } tests("#capacity").returns(Fixnum){ hard_disk.capacity.class } tests("#bus_sub_type").returns(String){ hard_disk.bus_sub_type.class } tests("#bus_type").returns(6){ hard_disk.bus_type } end tests("Compute::VcloudDirector | vm | customization") do customization = vm.customization tests("#model").returns(Fog::Compute::VcloudDirector::VmCustomization){customization.class} tests("#id").returns(String){ customization.id.class } tests("#href").returns(String){ customization.href.class } tests("#type").returns("application/vnd.vmware.vcloud.guestCustomizationSection+xml"){ customization.type } tests("#virtual_machine_id").returns(String){ customization.virtual_machine_id.class } tests("#computer_name").returns(String){ customization.computer_name.class } tests("#enabled").returns(true){ boolean? customization.enabled } tests("#change_sid").returns(true){ boolean? customization.change_sid } tests("#join_domain_enabled").returns(true){ boolean? customization.join_domain_enabled } tests("#use_org_settings").returns(true){ boolean? customization.use_org_settings } tests("#admin_password_enabled").returns(true){ boolean? customization.admin_password_enabled } tests("#reset_password_required").returns(true){ boolean? customization.reset_password_required } end tests("Compute::VcloudDirector | vm | network") do network = vm.network tests("#model").returns(Fog::Compute::VcloudDirector::VmNetwork){network.class} tests("#id").returns(String){ network.id.class } tests("#href").returns(String){ network.href.class } tests("#type").returns("application/vnd.vmware.vcloud.networkConnectionSection+xml"){ network.type } tests("#info").returns(String){ network.info.class } tests("#primary_network_connection_index").returns(Fixnum){ network.primary_network_connection_index.class } tests("#network").returns(String){ network.network.class } tests("#network_connection_index").returns(Fixnum){ network.network_connection_index.class } tests("#mac_address").returns(String){ network.mac_address.class } tests("#ip_address_allocation_mode").returns(String){ network.ip_address_allocation_mode.class } tests("#needs_customization").returns(true){ boolean? network.needs_customization } tests("#is_connected").returns(true){ boolean? network.is_connected } end tests("Compute::VcloudDirector | vm | tags") do tags = vm.tags tests("#collection").returns(Fog::Compute::VcloudDirector::Tags){ tags.class } end end fog-1.19.0/tests/vcloud_director/models/compute/tasks_tests.rb0000644000004100000410000000207712261242552024600 0ustar www-datawww-datarequire File.expand_path(File.join(File.dirname(__FILE__), 'helper')) Shindo.tests('Compute::VcloudDirector | tasks', ['vclouddirector']) do pending if Fog.mocking? tasks = organization.tasks pending if tasks.empty? task = tasks.first tests('Compute::VcloudDirector | task') do tests('#href').returns(String) { task.href.class } tests('#type').returns('application/vnd.vmware.vcloud.task+xml') { task.type } tests('#id').returns(String) { task.id.class } tests('#name').returns(String) { task.name.class } tests('#status').returns(String) { task.status.class } tests('#end_time').returns(Fog::Time) { task.end_time.class } tests('#expiry_time').returns(Fog::Time) { task.expiry_time.class } tests('#operation').returns(String) { task.operation.class } tests('#operation_name').returns(String) { task.operation_name.class } end tests('Compute::VcloudDirector | task', ['get']) do tests('#get_by_name').returns(task.name) { tasks.get_by_name(task.name).name } tests('#get').returns(task.id) { tasks.get(task.id).id } end end fog-1.19.0/tests/vcloud_director/models/compute/media_tests.rb0000644000004100000410000000435012261242552024526 0ustar www-datawww-datarequire File.expand_path(File.join(File.dirname(__FILE__), 'helper')) Shindo.tests('Compute::VcloudDirector | media', ['vclouddirector']) do pending if Fog.mocking? medias = vdc.medias media_name = VcloudDirector::Compute::Helper.test_name tests('Compute::VcloudDirector | media', ['create']) do tests('#create').returns(Fog::Compute::VcloudDirector::Media) do File.open(VcloudDirector::Compute::Helper.fixture('test.iso'), 'rb') do |iso| medias.create(media_name, iso).class end end end media = medias.get_by_name(media_name) tests('Compute::VcloudDirector | media') do tests('#href').returns(String) { media.href.class } tests('#type').returns('application/vnd.vmware.vcloud.media+xml') { media.type } tests('#id').returns(String) { media.id.class } tests('#name').returns(String) { media.name.class } end tests('Compute::VcloudDirector | media', ['lazy load attrs']) do media.lazy_load_attrs.each do |lazy_attr| tests("##{lazy_attr} is not loaded yet").returns(NonLoaded) { media.attributes[lazy_attr] } end end tests('Compute::VcloudDirector | media', ['load on demand']) do tests('#description is not loaded yet').returns(NonLoaded) { media.attributes[:description] } tests('#description is loaded on demand').returns(String) { media.description.class } tests('#description is now loaded').returns(true) { media.attributes[:description] != NonLoaded } end tests('Compute::VcloudDirector | media', ['lazy load attrs']) do media.lazy_load_attrs.each do |lazy_attr| tests("##{lazy_attr} is now loaded").returns(true) { media.attributes[lazy_attr] != NonLoaded } end end tests('Compute::VcloudDirector | media' ['attributes']) do tests('#status').returns(Fixnum) { media.status.class } tests('#image_type').returns(String) { media.image_type.class } tests('#size').returns(Fixnum) { media.size.class } end tests('Compute::VcloudDirector | media', ['get']) do tests('#get_by_name').returns(media.name) { medias.get_by_name(media.name).name } tests('#get').returns(media.id) { medias.get(media.id).id } end tests('Compute::VcloudDirector | media', ['destroy']) do tests('#destroy').returns(true) { media.destroy } end end fog-1.19.0/tests/vcloud_director/models/compute/vapp_tests.rb0000644000004100000410000000312512261242552024414 0ustar www-datawww-datarequire File.expand_path(File.join(File.dirname(__FILE__), 'helper')) Shindo.tests("Compute::VcloudDirector | vapps", ['vclouddirector', 'all']) do pending if Fog.mocking? # unless there is atleast one vapp we cannot run these tests pending if vdc.vapps.empty? vapps = vdc.vapps vapp = vapps.first tests("Compute::VcloudDirector | vapp") do tests("#id").returns(String){ vapp.id.class } tests("#name").returns(String){ vapp.name.class } tests("#href").returns(String){ vapp.href.class } tests("#type").returns("application/vnd.vmware.vcloud.vApp+xml"){ vapp.type } end tests("Compute::VcloudDirector | vapp", ['lazy load attrs']) do vapp.lazy_load_attrs.each do |lazy_attr| tests("##{lazy_attr} is not loaded yet").returns(NonLoaded) { vapp.attributes[lazy_attr] } end end tests("Compute::VcloudDirector | vapp", ['load on demand']) do tests("#description is not loaded yet").returns(NonLoaded) { vapp.attributes[:description] } tests("#description is loaded on demand").returns(String) { vapp.description.class } tests("#description is now loaded").returns(true) { vapp.attributes[:description] != NonLoaded } end tests("Compute::VcloudDirector | vapp", ['lazy load attrs']) do vapp.lazy_load_attrs.each do |lazy_attr| tests("##{lazy_attr} is now loaded").returns(true) { vapp.attributes[lazy_attr] != NonLoaded } end end tests("Compute::VcloudDirector | vapp", ['get']) do tests("#get_by_name").returns(vapp.name) { vapps.get_by_name(vapp.name).name } tests("#get").returns(vapp.id) { vapps.get(vapp.id).id } end end fog-1.19.0/tests/ecloud/0000755000004100000410000000000012261242552015023 5ustar www-datawww-datafog-1.19.0/tests/ecloud/compute/0000755000004100000410000000000012261242552016477 5ustar www-datawww-datafog-1.19.0/tests/ecloud/compute/models/0000755000004100000410000000000012261242552017762 5ustar www-datawww-datafog-1.19.0/tests/ecloud/compute/models/environment_tests.rb0000644000004100000410000000147112261242552024100 0ustar www-datawww-dataprovider, config = :ecloud, compute_providers[:ecloud] Shindo.tests("Fog::Compute[:#{provider}] | environments", [provider.to_s]) do connection = Fog::Compute[provider] @organization = connection.organizations.first tests('#all').succeeds do returns(false) { @organization.environments.all.empty? } end tests('#get').succeeds do environment = @organization.environments.all.first fetched_environment = connection.environments.get(environment.href) returns(true) { !fetched_environment.nil? } end tests("#organization").succeeds do environment = @organization.environments.all.first returns(false, "returns an organization") { environment.organization.nil? } returns(true, "returns correct organization") { environment.organization.href == @organization.href } end end fog-1.19.0/tests/ecloud/compute/models/template_tests.rb0000644000004100000410000000131112261242552023340 0ustar www-datawww-dataprovider, config = :ecloud, compute_providers[:ecloud] Shindo.tests("Fog::Compute[:#{provider}] | templates", [provider.to_s]) do connection = Fog::Compute[provider] @organization = connection.organizations.first @environment = @organization.environments.find{|e| e.name == config[:server_attributes][:environment_name]} || @organization.environments.first @compute_pool = @environment.compute_pools.first tests('#all').succeeds do templates = @compute_pool.templates returns(false) { templates.empty? } end tests('#get').succeeds do templates = @compute_pool.templates template = templates.first returns(false) { @compute_pool.templates.get(template.href).nil? } end end fog-1.19.0/tests/ecloud/compute/models/server_tests.rb0000644000004100000410000001430012261242552023035 0ustar www-datawww-dataprovider, config = :ecloud, compute_providers[:ecloud] Shindo.tests("Fog::Compute[:#{provider}] | servers", [provider.to_s, "operations"]) do connection = Fog::Compute[provider] connection.base_path = '/cloudapi/spec' config[:server_attributes][:organization_uri] ? organization = connection.organizations.get("#{connection.base_path}#{config[:server_attributes][:organization_uri]}") : organization = connection.organizations.first environment = organization.environments.find{|e| e.name == config[:server_attributes][:environment_name]} || organization.environments.first public_ip = environment.public_ips.first compute_pool = environment.compute_pools.first image_href = Fog.credentials[:ecloud_image_href] || compute_pool.templates.first.href ssh_key = organization.admin.ssh_keys.detect { |key| key.name == "root" } || organization.admin.ssh_keys.first @network = environment.networks.first options = config[:server_attributes].merge(:network_uri => @network.href, :ssh_key_uri => ssh_key.href) #if Fog.credentials[:ecloud_ssh_key_id] # options = options.merge(:ssh_key_uri => "/cloudapi/ecloud/admin/sshkeys/#{Fog.credentials[:ecloud_ssh_key_id]}") #end tests('#create_server').succeeds do compute_pool.servers.create(image_href, options) end # Use the Living Specification, VM2 has valid power state to delete disks vm_uri = "#{connection.base_path}/virtualMachines/2" @server = compute_pool.servers.get(vm_uri) tests('#environment_has_a_row_and_group_with_the_right_names').succeeds do row = environment.rows.detect { |r| r.name == options[:row] } returns(false, "row is not nil") { row.nil? } group = row.groups.detect { |g| g.name == options[:group] } returns(false, "group is not nil") { group.nil? } server = group.servers.detect { |s| s.name == options[:name] } returns(false, "group has server") { server.nil? } end tests('#get_server_flavor').succeeds do @server.flavor_id == {:ram => 1024, :cpus => 2} end @hwc = @server.hardware_configuration tests('#add_disk_to_server').succeeds do @server.add_disk(25) end tests('#detach_disk_from_server').succeeds do server = connection.servers.get("#{connection.base_path}/virtualMachines/1") server.detach_disk(1) end @detached_disk = compute_pool.reload.detached_disks.first tests('#attach_disk_to_server').succeeds do server = connection.servers.get("#{connection.base_path}/virtualMachines/1") server.attach_disk(@detached_disk) end tests('#delete_disk').succeeds do @server.delete_disk(1) end @ip = @network.ips.reload.detect { |i| i.host.nil? && i.detected_on.nil? } tests('#add_ip_to_server').succeeds do @server.add_ip(:href => @network.href, :network_name => @network.name, :ip => @ip.name) end service_name = Fog.credentials[:ecloud_internet_service_name] || Fog::Mock.random_letters(6) service_port = Fog.credentials[:ecloud_internet_service_port] || Fog::Mock.random_numbers(3).to_i service_protocol = Fog.credentials[:ecloud_internet_service_protocol] tests('#create_internet_service').succeeds do @service = public_ip.internet_services.create(:name => service_name, :port => service_port, :protocol => service_protocol, :description => "", :enabled => true) returns(true, "is an internet service") { @service.is_a?(Fog::Compute::Ecloud::InternetService) } end @service = public_ip.internet_services.first @ip_address = @server.ips.first @ip = @server.ips.first.network.ips.detect { |i| i.name == @ip_address.address.name } @node = @service.nodes.create(:name => @server.name, :port => service_port, :ip_address => @ip.href, :description => "", :enabled => true) tests('#create_node_service').succeeds do returns(true, "is a node server") { @node.is_a?(Fog::Compute::Ecloud::Node) } end tests('#destroy_node_service').succeeds do @node.destroy end #tests('#delete_ip_from_server').succeeds do # @server.delete_ip(:href => @network.href, :network_name => @network.name, :ip => @ip.name) #end # NOTE(xtoddx): the Living Specification doesn't have any empty services #tests('#destroy_internet_service').succeeds do # @service.destroy #end @server_count = environment.servers.count tests('#destroy_server').succeeds do @server.destroy end @new_server_count = environment.servers.reload.count tests('#server_count_reduced').succeeds do returns(true, "server count is reduced") { @new_server_count < @server_count } end @row = environment.rows.detect { |r| r.name == options[:row] } @group = @row.groups.detect { |g| g.name == options[:group] } if @group.servers.empty? tests('#delete_group').succeeds do @group.destroy returns(true, "group no longer exists") { @group.reload.nil? } end end if @row.groups.reload.empty? tests("#delete_row").succeeds do @row.destroy returns(true, "row no longer exists") { @row.reload.nil? } end end end Shindo.tests("Fog::Compute[:#{provider}] | server", [provider.to_s, "attributes"]) do connection = Fog::Compute[provider] connection.base_path = '/cloudapi/spec' organization = connection.organizations.first environment = organization.environments.find{|e| e.name == config[:server_attributes][:environment_name]} || organization.environments.first public_ip = environment.public_ips.first compute_pool = environment.compute_pools.first image_href = Fog.credentials[:ecloud_image_href] || compute_pool.templates.first.href ssh_key = organization.admin.ssh_keys.detect { |key| key.name == "root" } @network = environment.networks.first options = config[:server_attributes].merge(:network_uri => @network.href, :ssh_key_uri => ssh_key.href) #if Fog.credentials[:ecloud_ssh_key_id] # options = options.merge(:ssh_key_uri => "/cloudapi/ecloud/admin/sshkeys/#{Fog.credentials[:ecloud_ssh_key_id]}") #end @server = compute_pool.servers.first || compute_pool.servers.create(image_href, options).tap{|s| s.wait_for { ready? }} tests('#ip_addresses').succeeds do returns(true, "is an array") { @server.ips.is_a?(Array) } returns(true, "contains an VirtualMachineAssignedIp") { @server.ips.all?{|ip| ip.is_a?(Fog::Compute::Ecloud::VirtualMachineAssignedIp) } } end end fog-1.19.0/tests/ecloud/compute/models/organization_tests.rb0000644000004100000410000000126412261242552024240 0ustar www-datawww-dataprovider, config = :ecloud, compute_providers[:ecloud] Shindo.tests("Fog::Compute[:#{provider}] | organizations", [provider.to_s]) do connection = Fog::Compute[provider] tests('#all').succeeds do returns(false) { connection.organizations.all.empty? } end tests('#get').succeeds do organization = connection.organizations.all.first fetched_organization = connection.organizations.get(organization.href) returns(true) { !fetched_organization.nil? } end tests("#admin").succeeds do organization = connection.organizations.all.first returns(true, "return AdminOrganization") { organization.admin.is_a?(Fog::Compute::Ecloud::AdminOrganization) } end end fog-1.19.0/tests/ecloud/compute/models/compute_pool_tests.rb0000644000004100000410000000111312261242552024232 0ustar www-datawww-dataprovider, config = :ecloud, compute_providers[:ecloud] Shindo.tests("Fog::Compute[:#{provider}] | compute_pools", [provider.to_s]) do connection = Fog::Compute[provider] @organization = connection.organizations.first @environment = @organization.environments.first tests('#all').succeeds do returns(false) { @environment.compute_pools.all.empty? } end tests('#get').succeeds do compute_pool = @environment.compute_pools.all.first fetched_compute_pool = connection.compute_pools.get(compute_pool.href) returns(true) { !fetched_compute_pool.nil? } end end fog-1.19.0/tests/ecloud/compute/models/ip_address_tests.rb0000644000004100000410000000113712261242552023650 0ustar www-datawww-dataprovider, config = :ecloud, compute_providers[:ecloud] Shindo.tests("Fog::Compute[:#{provider}] | ip_addresses", [provider.to_s]) do connection = Fog::Compute[provider] @organization = connection.organizations.first @environment = @organization.environments.first @network = @environment.networks.first @ip_addresses = @network.ips tests('#all').succeeds do returns(false) { @ip_addresses.all.empty? } end tests('#get').succeeds do address = @ip_addresses.first fetched_network = connection.ip_addresses.get(address.href) returns(false) { fetched_network.nil? } end end fog-1.19.0/tests/ecloud/compute/models/internet_service_tests.rb0000644000004100000410000000226012261242552025101 0ustar www-datawww-dataprovider, config = :ecloud, compute_providers[:ecloud] Shindo.tests("Fog::Compute[:#{provider}] | internet_services", [provider.to_s, "queries"]) do connection = Fog::Compute[provider] organization = connection.organizations.first environment = organization.environments.detect { |e| e.name == config[:ecloud_environment_name] } || organization.environments.first public_ips = environment.public_ips public_ip = public_ips.detect { |i| i.name == config[:ecloud_public_ip_name] } || public_ips.first @internet_services = public_ip.internet_services tests('#all').succeeds do returns(true, "is a collection") { @internet_services.is_a?(Fog::Compute::Ecloud::InternetServices) } if Fog.mocking? returns(false, "has services") { @internet_services.empty? } else true end end unless @internet_services.empty? tests('#get').succeeds do service = @internet_services.first fetched_service = connection.internet_services.get(service.href) returns(false, "service is not nil") { fetched_service.nil? } returns(true, "is an InternetService") { fetched_service.is_a?(Fog::Compute::Ecloud::InternetService) } end end end fog-1.19.0/tests/ecloud/compute/models/admin_organization_tests.rb0000644000004100000410000000114012261242552025401 0ustar www-datawww-dataprovider, config = :ecloud, compute_providers[:ecloud] Shindo.tests("Fog::Compute[:#{provider}] | admin_organizations", [provider.to_s]) do connection = Fog::Compute[provider] @organization = connection.organizations.first @admin_organization = @organization.admin tests('#get').succeeds do fetched_admin_organization = connection.get_admin_organization(@admin_organization.href) returns(true) { !fetched_admin_organization.nil? } end tests('#ssh_keys').succeeds do returns(true, "a list of SshKeys") { @admin_organization.ssh_keys.is_a?(Fog::Compute::Ecloud::SshKeys) } end end fog-1.19.0/tests/ecloud/compute/models/public_ip_tests.rb0000644000004100000410000000124312261242552023477 0ustar www-datawww-dataprovider, config = :ecloud, compute_providers[:ecloud] Shindo.tests("Fog::Compute[:#{provider}] | ip_addresses", [provider.to_s]) do connection = Fog::Compute[provider] @organization = connection.organizations.first @environment = @organization.environments.first @public_ips = @environment.public_ips tests('#all').succeeds do returns(false, "has ips") { @public_ips.all.empty? } end tests('#get').succeeds do address = @public_ips.first fetched_ip = connection.public_ips.get(address.href) returns(false, "ip is not nil") { fetched_ip.nil? } returns(true, "is a PublicIp") { fetched_ip.is_a?(Fog::Compute::Ecloud::PublicIp) } end end fog-1.19.0/tests/ecloud/compute/models/network_tests.rb0000644000004100000410000000104312261242552023220 0ustar www-datawww-dataprovider, config = :ecloud, compute_providers[:ecloud] Shindo.tests("Fog::Compute[:#{provider}] | networks", [provider.to_s]) do connection = Fog::Compute[provider] @organization = connection.organizations.first @environment = @organization.environments.first tests('#all').succeeds do returns(false) { @environment.networks.all.empty? } end tests('#get').succeeds do network = @environment.networks.all.first fetched_network = connection.networks.get(network.href) returns(true) { !fetched_network.nil? } end end fog-1.19.0/tests/ecloud/compute/models/operating_system_tests.rb0000644000004100000410000000154512261242552025132 0ustar www-datawww-dataprovider, config = :ecloud, compute_providers[:ecloud] Shindo.tests("Fog::Compute[:#{provider}] | operating_system", [provider.to_s]) do connection = Fog::Compute[provider] @organization = connection.organizations.first @environment = @organization.environments.find{|e| e.name == config[:server_attributes][:environment_name]} || @organization.environments.first @compute_pool = @environment.compute_pools.first tests('#all').succeeds do family = @compute_pool.operating_system_families.first operating_systems = family.operating_systems returns(false) { operating_systems.empty? } end tests('#get').succeeds do family = @compute_pool.operating_system_families.first operating_system = family.operating_systems.first returns(false) { family.operating_systems.get(operating_system.href).nil? } end end fog-1.19.0/tests/ecloud/compute/models/operating_system_families_tests.rb0000644000004100000410000000112712261242552026777 0ustar www-datawww-dataprovider, config = :ecloud, compute_providers[:ecloud] Shindo.tests("Fog::Compute[:#{provider}] | operating_system_families", [provider.to_s]) do connection = Fog::Compute[provider] @organization = connection.organizations.first @environment = @organization.environments.find{|e| e.name == config[:server_attributes][:environment_name]} || @organization.environments.first @compute_pool = @environment.compute_pools.first tests('#all').succeeds do operating_system_families = @compute_pool.operating_system_families returns(false) { operating_system_families.empty? } end end fog-1.19.0/tests/ecloud/compute/models/detached_disk_tests.rb0000644000004100000410000000200112261242552024275 0ustar www-datawww-dataprovider, config = :ecloud, compute_providers[:ecloud] Shindo.tests("Fog::Compute[:#{provider}] | detached_disks", [provider.to_s]) do connection = Fog::Compute[provider] @organization = connection.organizations.first @environment = @organization.environments.first @compute_pool = @environment.compute_pools.first @detached_disks = @compute_pool.detached_disks tests('#all').succeeds do if @detached_disks.is_a?(Fog::Compute::Ecloud::DetachedDisks) && @detached_disks.reload.empty? returns(true, "compute pool has no detached disks") { @detached_disks.all.empty? } else returns(false, "has detached disks") { @detached_disks.all.empty? } end end unless @detached_disks.empty? tests('#get') do disk = @detached_disks.first fetched_disk = connection.detached_disks.get(disk.href) returns(false, "disk is not nil") { fetched_disk.nil? } returns(true, "is a DetachedDisk") { fetched_disk.is_a?(Fog::Compute::Ecloud::DetachedDisk) } end end end fog-1.19.0/tests/ecloud/compute/models/ssh_key_tests.rb0000644000004100000410000000102612261242552023175 0ustar www-datawww-dataprovider, config = :ecloud, compute_providers[:ecloud] Shindo.tests("Fog::Compute[:#{provider}] | ssh_keys", [provider.to_s]) do connection = Fog::Compute[provider] @organization = connection.organizations.first @admin_organization = @organization.admin @admin_organization.reload @ssh_keys = @admin_organization.ssh_keys tests('#all').succeeds do returns(false) { @ssh_keys.empty? } end tests('#get').succeeds do ssh_key = @ssh_keys.first returns(false) { @ssh_keys.get(ssh_key.href).nil? } end end fog-1.19.0/tests/ibm/0000755000004100000410000000000012261242552014317 5ustar www-datawww-datafog-1.19.0/tests/ibm/requests/0000755000004100000410000000000012261242552016172 5ustar www-datawww-datafog-1.19.0/tests/ibm/requests/storage/0000755000004100000410000000000012261242552017636 5ustar www-datawww-datafog-1.19.0/tests/ibm/requests/storage/volume_tests.rb0000644000004100000410000000620712261242552022721 0ustar www-datawww-dataShindo.tests('Fog::Storage[:ibm] | volume requests', ['ibm']) do @volume_format = { "id" => String, "instanceId" => Fog::Nullable::String, "name" => String, "format" => String, "state" => Integer, "size" => String, "offeringId" => String, "owner" => String, "createdTime" => Integer, "location" => String, "productCodes" => Array, } @full_volume_format = @volume_format.merge({ "ioPrice" => { "rate" => Float, "unitOfMeasure" => String, "countryCode" => String, "effectiveDate" => Integer, "currencyCode" => String, "pricePerQuantity" => Integer, } }) @volumes_format = { 'volumes' => [ @volume_format ] } tests('success') do @volume_id = nil @name = "fog-test-volume" + Time.now.to_i.to_s(32) @format = "RAW" @location_id = "41" @size = "256" @offering_id = "20001208" @instance_id = nil @image_id = "20010001" @instance_type = "BRZ32.1/2048/60*175" # Instance-using tests are pending, so don't create the key now # @key_name = "fog-test-key-" + Time.now.to_i.to_s(32) # @key = Fog::Compute[:ibm].keys.create(:name => @key_name) tests("#create_volume('#{@name}', '#{@offering_id}', '#{@format}', '#{@location_id}', '#{@size}')").formats(@volume_format) do data = Fog::Storage[:ibm].create_volume(@name, @offering_id, @format, @location_id, @size).body @volume_id = data['id'] data end tests("#list_volumes").formats(@volumes_format) do Fog::Storage[:ibm].list_volumes.body end tests("#get_volume('#{@volume_id}')").formats(@full_volume_format) do Fog::Storage[:ibm].get_volume(@volume_id).body end # Tests which use this instance are pending # @instance_id = Fog::Compute[:ibm].create_instance( # 'fog-test-volume-instance-' + Time.now.to_i.to_s(32), # @image_id, # @instance_type, # @location_id, # :key_name => @key_name # ).body['instances'][0]['id'] tests("#attach_volume('#{@instance_id}','#{@volume_id}')") do pending # TODO: Add assertions for this whenever it is properly supported Fog::Compute[:ibm].modify_instance(@instance_id, 'type' => 'attach', 'volume_id' => @volume_id) end tests("#detach_volume('#{@instance_id}','#{@volume_id}')") do pending # TODO: Add assertions for this whenever it is properly supported Fog::Compute[:ibm].modify_instance(@instance_id, 'type' => 'attach', 'volume_id' => @volume_id) Fog::Compute[:ibm].delete_instance(@instance_id) end Fog::Storage[:ibm].volumes.get(@volume_id).wait_for(Fog::IBM.timeout) { ready? } tests("#delete_volume('#{@volume_id}')") do returns(true) { Fog::Storage[:ibm].delete_volume(@volume_id).body['success'] } end # See above # @server = Fog::Compute[:ibm].servers.get(@instance_id) # @server.wait_for(Fog::IBM.timeout) { ready? } # @server.destroy # @key.wait_for(Fog::IBM.timeout) { instance_ids.empty? } # @key.destroy end end fog-1.19.0/tests/ibm/requests/compute/0000755000004100000410000000000012261242552017646 5ustar www-datawww-datafog-1.19.0/tests/ibm/requests/compute/image_tests.rb0000644000004100000410000000615612261242552022507 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ibm] | image requests', ['ibm']) do @image_format = { 'state' => Integer, 'visibility' => String, 'platform' => String, 'owner' => String, 'architecture' => Fog::Nullable::String, 'createdTime' => Integer, 'location' => String, 'productCodes' => Array, 'name' => String, 'id' => String, 'description' => String, 'supportedInstanceTypes' => Array, 'manifest' => Fog::Nullable::String, 'documentation' => Fog::Nullable::String, } # TODO: Actually check this format @product_code_format = { 'detail' => String, 'label' => String, 'price' => @price_format, 'id' => String } # TODO: Actually check this format @price_format = { 'rate' => Float, 'unitOfMeasure' => String, 'effectiveDate' => Integer, 'currencyCode' => String, 'pricePerQuantity' => Integer } @images_format = { 'images' => [ @image_format ] } @create_image_format = { "name" => String, "createdTime" => Integer, "productCodes"=> Array, "id" => String, "description" => String, "visibility" => String, "state" => Integer } @instance_id = nil @name = "fog-test-image-instance-" + Time.now.to_i.to_s(32) @image_id = "20010001" @instance_type = "BRZ32.1/2048/60*175" @location = "41" @id = nil @cloned_id = nil @image_name = "fog test create image" @key_name = "fog-test-key-" + Time.now.to_i.to_s(32) @key = Fog::Compute[:ibm].keys.create(:name => @key_name) tests('success') do tests("#list_images").formats(@images_format) do Fog::Compute[:ibm].list_images.body end tests('#get_image').formats(@image_format) do Fog::Compute[:ibm].get_image("20010001").body end tests('#create_image').formats(@create_image_format) do response = Fog::Compute[:ibm].create_instance( @name, @image_id, @instance_type, @location, :key_name => @key_name ).body @instance_id = response['instances'][0]['id'] Fog::Compute[:ibm].servers.get(@instance_id).wait_for(Fog::IBM.timeout) { ready? } data = Fog::Compute[:ibm].create_image(@instance_id, @image_name, "").body @id = data['id'] data end tests('#clone_image') do clone_name = 'fog-test-clone-image-' + Time.now.to_i.to_s(32) data = Fog::Compute[:ibm].clone_image(@image_id, clone_name, clone_name).body @cloned_id = data['ImageID'] returns(String) { data['ImageID'].class } end tests('#delete_image') do pending returns(true) { Fog::Compute[:ibm].delete_image(@id).body['success'] } returns(true) { Fog::Compute[:ibm].delete_image(@cloned_id).body['success'] } end @server = Fog::Compute[:ibm].servers.get(@instance_id) @server.wait_for(Fog::IBM.timeout) { ready? } @server.destroy @key.wait_for(Fog::IBM.timeout) { instance_ids.empty? } @key.destroy end end fog-1.19.0/tests/ibm/requests/compute/key_tests.rb0000644000004100000410000000342712261242552022213 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ibm] | key requests', ['ibm']) do @key_format = { 'default' => Fog::Boolean, 'instanceIds' => Array, 'keyMaterial' => String, 'keyName' => String, 'lastModifiedTime' => Integer } @keys_format = { 'keys' => [ @key_format ] } tests('success') do @key_name = 'fog-test-key' + Time.now.to_i.to_s(32) @public_key = 'AAAAB3NzaC1yc2EAAAADAQABAAABAQCvVCQA6JWWCAwjUjXDFUH8wOm15slX+WJOYCPNNrW+xipvHq5zDOCnus0xfl/zjWLVDkIz+1ku0Qapd4Q2a+NyyyH09iRxmclQaZdNoj+l4RRL0TRzeJT+l9FU0e4eUYKylrEgQCkZPFVsgn8Vly9Nh/NRcBMA1BgLMiCMebPu3N3bZIVjUrVp8MB66hqAivA36zVQ4ogykTXO8XKG9Mth7yblLjcVyDq7tecSrvM/RAUkZp0Z6SHihQwdnJwqLTcBMXeV3N2VRF3TZWayOWFgTlr1M3ZL7HD3adjRFzY8lmzbOdL/L6BamwDL9nP6bnHeH5oDnUuOIsJng04BC9Ht' tests("#create_key('#{@key_name}')").formats(@key_format) do Fog::Compute[:ibm].create_key(@key_name + '-gen').body end tests("#create_key('#{@key_name}', '#{@public_key}')") do returns(true) { Fog::Compute[:ibm].create_key(@key_name, @public_key).body['success'] } end tests("#list_keys").formats(@keys_format) do Fog::Compute[:ibm].list_keys.body end tests("#get_key('#{@key_name}')").formats(@key_format) do Fog::Compute[:ibm].get_key(@key_name).body end tests("#set_default_key('#{@key_name}')") do returns(true) { Fog::Compute[:ibm].modify_key(@key_name, 'default' => true).body['success'] } end tests("#update_key('#{@key_name}', 'publicKey' => '#{@public_key}')") do returns(true) { Fog::Compute[:ibm].modify_key(@key_name, 'publicKey' => @public_key).body['success'] } end tests("#delete_key('#{@key_name}')") do returns(true) { Fog::Compute[:ibm].delete_key(@key_name).body['success'] } end end end fog-1.19.0/tests/ibm/requests/compute/vlan_tests.rb0000644000004100000410000000055212261242552022357 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ibm] | location requests', ['ibm']) do @vlan_format = { 'id' => String, 'name' => String, 'location' => String, } @vlans_format = { 'vlan' => [ @vlan_format ] } tests('success') do tests("#list_vlans").formats(@vlans_format) do Fog::Compute[:ibm].list_vlans.body end end end fog-1.19.0/tests/ibm/requests/compute/location_tests.rb0000644000004100000410000000115112261242552023223 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ibm] | location requests', ['ibm']) do @location_format = { 'state' => Integer, 'location' => String, 'capabilities' => Array, 'name' => String, 'id' => String, 'description' => String } @locations_format = { 'locations' => [ @location_format ] } tests('success') do tests("#list_locations").formats(@locations_format) do Fog::Compute[:ibm].list_locations.body end tests('#get_locations').formats(@location_format) do Fog::Compute[:ibm].get_location('41').body end end end fog-1.19.0/tests/ibm/requests/compute/address_tests.rb0000644000004100000410000000250412261242552023043 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ibm] | address requests', ['ibm']) do @address_format = { "state" => Integer, "offeringId"=> String, "location" => String, "ip" => String, "id" => String, "mode" => Integer, "hostname" => String, "type" => Integer, "instanceId" => Fog::Nullable::String, "vlan" => Fog::Nullable::String, } # create_address doesn't return mode, hostname or type attributes @create_address_format = @address_format.reject { |k,v| ["mode", "hostname", "type"].include? k } # list_address returns everything @list_address_format = { 'addresses' => [ @address_format ] } @address_id = nil @location_id = "41" @offering_id = "20001223" tests('success') do tests("#create_address('#{@location_id}')").formats(@create_address_format) do data = Fog::Compute[:ibm].create_address(@location_id, @offering_id).body @address_id = data['id'] data end tests("#list_addresses").formats(@list_address_format) do Fog::Compute[:ibm].list_addresses.body end tests("#delete_address('#{@address_id}')") do Fog::Compute[:ibm].addresses.get(@address_id).wait_for(Fog::IBM.timeout) { ready? } returns(true) { Fog::Compute[:ibm].delete_address(@address_id).body['success'] } end end end fog-1.19.0/tests/ibm/requests/compute/instance_tests.rb0000644000004100000410000000654112261242552023227 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ibm] | instance requests', ['ibm']) do @instance_format = { 'name' => String, 'location' => String, 'keyName' => String, 'primaryIP' => { 'vlan' => Fog::Nullable::String, 'type' => Integer, 'ip' => String, 'hostname' => String, }, 'productCodes' => Array, 'requestId' => String, 'imageId' => String, 'launchTime' => Integer, 'id' => String, 'ip' => Fog::Nullable::String, 'volumes' => Array, 'root-only' => Fog::Nullable::String, 'isMiniEphemeral' => Fog::Nullable::String, 'instanceType' => String, 'diskSize' => Fog::Nullable::String, 'requestName' => String, 'secondaryIP' => Array, 'status' => Integer, 'software' => Array, 'expirationTime'=> Integer, 'owner' => String, } @instances_format = { 'instances' => [ @instance_format ] } tests('success') do @instance_id = nil @name = "fog-test-instance-" + Time.now.to_i.to_s(32) @image_id = "20010001" @instance_type = "COP32.1/2048/60" @location = "41" @key_name = "fog-test-key-" + Time.now.to_i.to_s(32) @key = Fog::Compute[:ibm].keys.create(:name => @key_name) tests("#create_instance('#{@name}', '#{@image_id}', '#{@instance_type}', '#{@location}', :key_name => '#{@key_name}')").formats(@instances_format) do response = Fog::Compute[:ibm].create_instance(@name, @image_id, @instance_type, @location, :key_name => @key_name).body @instance_id = response['instances'][0]['id'] response end tests("#get_instance('#{@instance_id}')").formats(@instance_format) do response = Fog::Compute[:ibm].get_instance(@instance_id).body end Fog::Compute[:ibm].servers.get(@instance_id).wait_for(Fog::IBM.timeout) { ready? } tests("#list_instances").formats(@instances_format) do instances = Fog::Compute[:ibm].list_instances.body end tests("#modify_instance('#{@instance_id}', 'state' => 'restart')") do returns(true) { Fog::Compute[:ibm].modify_instance(@instance_id, 'state' => 'restart').body["success"] } end tests("#modify_instance('#{@instance_id}', 'name' => '#{@name} 2')") do returns(true) { Fog::Compute[:ibm].modify_instance(@instance_id, 'name' => @name + " 2").body["success"] } end @expiration_time = (Time.now.to_i + 10) * 1000 tests("#modify_instance('#{@instance_id}', 'expirationTime' => '#{@expiration_time}')") do returns(@expiration_time) { Fog::Compute[:ibm].modify_instance(@instance_id, 'expirationTime' => @expiration_time).body["expirationTime"] } end tests("#delete_instance('#{@instance_id}')") do if Fog::Compute[:ibm].servers.get(@instance_id).wait_for(Fog::IBM.timeout) { ready? } data = Fog::Compute[:ibm].delete_instance(@instance_id) else pending end end if @key.wait_for(Fog::IBM.timeout) { instance_ids.empty? } @key.destroy else pending end end tests('failures') do tests('#create_instance => 412') do raises(Excon::Errors::PreconditionFailed) do Fog::Compute[:ibm].create_instance("FAIL: 412", @image_id, @instance_type, @location, :key_name => "invalid") end end end end fog-1.19.0/tests/ibm/models/0000755000004100000410000000000012261242552015602 5ustar www-datawww-datafog-1.19.0/tests/ibm/models/storage/0000755000004100000410000000000012261242552017246 5ustar www-datawww-datafog-1.19.0/tests/ibm/models/storage/volume_tests.rb0000644000004100000410000000310012261242552022316 0ustar www-datawww-dataShindo.tests('Fog::Storage[:ibm] | volume', ['ibm']) do tests('success') do @volume = nil @volume_id = nil @name = "fog test volume" @format = "RAW" @location_id = "41" @size = "256" @offering_id = "20001208" tests('Fog::Storage::IBM::Volume.new') do @volume = Fog::Storage[:ibm].volumes.new( :name => @name, :format => @format, :location_id => @location_id, :size => @size, :offering_id => @offering_id ) returns(@name) { @volume.name } end tests('Fog::Storage::IBM::Volume#save') do returns(true) { @volume.save } returns(String) { @volume.id.class } @volume.wait_for(Fog::IBM.timeout) { ready? } @volume_id = @volume.id end tests("Fog::Storage::IBM::Volume#instance") do returns(nil) { @volume.instance } end tests("Fog::Storage::IBM::Volume#location_id") do returns(String) { @volume.location_id.class } end tests('Fog::Storage::IBM::Volume#id') do returns(@volume_id) { @volume.id } end tests('Fog::Storage::IBM::Volume#ready?') do # We do a "get" to advance the state if we are mocked. # TODO: Fix this for real connections Fog::Storage[:ibm].get_volume(@volume_id) returns(true) { @volume.ready? } end tests('Fog::Storage::IBM::Volume#state') do returns("Detached") { @volume.state } end tests('Fog::Storage::IBM::Volume#destroy') do returns(true) { @volume.destroy } end end end fog-1.19.0/tests/ibm/models/compute/0000755000004100000410000000000012261242552017256 5ustar www-datawww-datafog-1.19.0/tests/ibm/models/compute/keys_tests.rb0000644000004100000410000000167412261242552022010 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ibm] | keys', ['ibm']) do tests('success') do @key_name = 'fog-test-key' + Time.now.to_i.to_s(32) @key = nil tests("Fog::Compute[:ibm].keys.create(:name => '#{@key_name}')") do @key = Fog::Compute[:ibm].keys.create(:name => @key_name) returns(@key_name) { @key.name } end tests('Fog::Compute[:ibm].keys') do returns(true) { Fog::Compute[:ibm].keys.length > 0 } end tests("Fog::Compute[:ibm].keys.default = '#{@key_name}'") do returns(@key_name) { Fog::Compute[:ibm].keys.default = @key_name } end tests("Fog::Compute[:ibm].keys.default") do @key = Fog::Compute[:ibm].keys.get(@key_name) returns(@key.name) { Fog::Compute[:ibm].keys.default.name } end tests("Fog::Compute[:ibm].keys.get('#{@key_name}')") do key = Fog::Compute[:ibm].keys.get(@key_name) returns(@key_name) { key.name } end @key.destroy end end fog-1.19.0/tests/ibm/models/compute/image_tests.rb0000644000004100000410000000120412261242552022104 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ibm] | image', ['ibm']) do @image_id = '20010001' @clone_name = 'fog-test-clone-image-' + Time.now.to_i.to_s(32) tests('success') do tests("Fog::Compute[:ibm].images.get('#{@image_id}')") do @image = Fog::Compute[:ibm].images.get(@image_id) returns(@image_id) { @image.id } end tests("Fog::Compute::Image#clone") do clone_id = @image.clone(@clone_name, @clone_name) @clone = Fog::Compute[:ibm].images.get(clone_id) returns(@clone_name) { @clone.name } end tests("Fog::Compute::Image#destroy") do returns(true) { @clone.destroy } end end end fog-1.19.0/tests/ibm/models/compute/server_tests.rb0000644000004100000410000000506112261242552022335 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ibm] | server', ['ibm']) do tests('success') do # TODO: Fix this for non-mock tests @server = nil @instance_id = nil @name = "fog-test-instance-" + Time.now.to_i.to_s(32) @image_id = "20010001" @instance_type = "BRZ32.1/2048/60*175" @location_id = "41" @key_name = "fog-test-key-" + Time.now.to_i.to_s(32) @key = Fog::Compute[:ibm].keys.create(:name => @key_name) tests('Fog::Compute::IBM::Server.new') do @server = Fog::Compute[:ibm].servers.new( :name => @name, :image_id => @image_id, :instance_type => @instance_type, :location_id => @location, :key_name => @key_name ) returns(@name) { @server.name } end tests('Fog::Compute::IBM::Server#save') do returns(true) { @server.save } returns(String) { @server.id.class } @instance_id = @server.id end tests('Fog::Compute::IBM::Server#wait_for { ready? }') do @server = Fog::Compute[:ibm].servers.get(@instance_id) @server.wait_for(Fog::IBM.timeout) { ready? } end tests('Fog::Compute::IBM::Server#id') do returns(@instance_id) { @server.id } end tests('Fog::Compute::IBM::Server#ready?') do returns(true) { @server.ready? } end tests('Fog::Compute::IBM::Server#state') do returns("Active") { @server.state } end # TODO: make this work # tests('Fog::Compute::IBM::Server#reboot') do # returns(true) { @server.reboot } # end tests('Fog::Compute::IBM::Server#rename("name")') do name = @server.name + "-rename" returns(true) { @server.rename(name) } returns(name) { @server.name } end tests('Fog::Compute::IBM::Server#image') do returns(@image_id) { @server.image.id } end tests('Fog::Compute::IBM::Server#to_image') do body = @server.to_image(:name => @server.name) returns(@server.name) { body['name'] } image = Fog::Compute[:ibm].images.get(body['id']) image.wait_for(Fog::IBM.timeout) { ready? || state == 'New' } unless image.state == 'Capturing' returns(true) { Fog::Compute[:ibm].delete_image(image.id).body['success'] } end end tests('Fog::Compute::IBM::Server#expire_at') do returns(true) { @server.expire_at(Time.now + 60) } end tests('Fog::Compute::IBM::Server#destroy') do returns(true) { @server.destroy } end @key.wait_for(Fog::IBM.timeout) { instance_ids.empty? } @key.destroy end end fog-1.19.0/tests/ibm/models/compute/key_tests.rb0000644000004100000410000000103112261242552021610 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ibm] | key', ['ibm']) do tests('success') do @key_name = 'fog-test-key-' + Time.now.to_i.to_s(32) @key = nil tests("Fog::Compute::IBM::Key.create(:name => '#{@key_name}')") do @key = Fog::Compute[:ibm].keys.create(:name => @key_name) returns(@key_name) { @key.name } end tests("Fog::Compute::IBM::Key#instances") do returns([]) { @key.instances } end tests('Fog::Compute::IBM::Key#destroy') do returns(true) { @key.destroy } end end end fog-1.19.0/tests/ibm/models/compute/servers_tests.rb0000644000004100000410000000214712261242552022522 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ibm] | servers', ['ibm']) do tests('success') do @name = "fog-test-instance-" + Time.now.to_i.to_s(32) @image_id = "20010001" @instance_type = "BRZ32.1/2048/60*175" @location_id = "41" @key_name = "fog-test-key-" + Time.now.to_i.to_s(32) @key = Fog::Compute[:ibm].keys.create(:name => @key_name) @n_servers = Fog::Compute[:ibm].servers.length @instance_id = Fog::Compute[:ibm].create_instance(@name, @image_id, @instance_type, @location_id, :key_name => @key_name).body["instances"][0]["id"] tests('Fog::Compute[:ibm].servers') do returns(@n_servers + 1) { Fog::Compute[:ibm].servers.length } end tests('Fog::Compute[:ibm].servers.get("#{@instance_id}")') do @server = Fog::Compute[:ibm].servers.get(@instance_id) returns(@instance_id) { @server.id } end if @server.wait_for(Fog::IBM.timeout) { ready? } @server.destroy else pending end if @key.wait_for(Fog::IBM.timeout) { instance_ids.empty? } @key.destroy else pending end end end fog-1.19.0/tests/ibm/models/compute/locations_tests.rb0000644000004100000410000000065012261242552023021 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ibm] | locations', ['ibm']) do tests('success') do @location_id = '41' tests('Fog::Compute[:ibm].locations') do returns(true) { Fog::Compute[:ibm].locations.length > 0 } end tests('Fog::Compute[:ibm].locations.get("#{@location_id}")') do @location = Fog::Compute[:ibm].locations.get(@location_id) returns(@location_id) { @location.id } end end end fog-1.19.0/tests/ninefold/0000755000004100000410000000000012261242552015346 5ustar www-datawww-datafog-1.19.0/tests/ninefold/requests/0000755000004100000410000000000012261242552017221 5ustar www-datawww-datafog-1.19.0/tests/ninefold/requests/compute/0000755000004100000410000000000012261242552020675 5ustar www-datawww-datafog-1.19.0/tests/ninefold/requests/compute/helper.rb0000644000004100000410000003156512261242552022513 0ustar www-datawww-dataclass Ninefold module Compute module TestSupport # 1CPU, 1.7GB RAM, 160GB Storage SERVICE_OFFERING = 67 # alternate for testing - ALT_SERVICE_OFFERING = 68 # XEN Basic Ubuntu 10.04 Server x64 PV r2.0 TEMPLATE_ID = 421 # Sydney ZONE_ID = 1 # Max time to wait for job completion (2 mins) MAXWAIT = 2 * 60 ## Waits for a job, returning the completed jobs payload. ## Accepts an integer jobid, or a hash containing a jobid or id. def wait_for_job(job) job = job['jobid'] || job['id'] unless job.kind_of? Integer while Fog::Compute[:ninefold].query_async_job_result(:jobid => job)['jobstatus'] == 0 sleep 1 end Fog::Compute[:ninefold].query_async_job_result(:jobid => job) end module_function :wait_for_job end module Formats module Lists SERVICE_OFFERING = { "id" => Integer, "name" => String, "displaytext" => String, "cpunumber" => Integer, "cpuspeed" => Integer, "memory" => Integer, "created" => String, "storagetype" => String, "offerha" => Fog::Boolean, "domainid" => Integer, "domain" => String, "issystem" => Fog::Boolean, "limitcpuuse" => Fog::Boolean, "defaultuse" => Fog::Boolean } SERVICE_OFFERINGS = [Ninefold::Compute::Formats::Lists::SERVICE_OFFERING] ACCOUNTS = [{ "id"=>Integer, "name"=>String, "accounttype"=>Integer, "domainid"=>Integer, "domain"=>String, "receivedbytes"=>Integer, "sentbytes"=>Integer, "vmlimit"=>String, "vmtotal"=>Integer, "vmavailable"=>String, "iplimit"=>String, "iptotal"=>Integer, "ipavailable"=>String, "volumelimit"=>String, "volumetotal"=>Integer, "volumeavailable"=>String, "snapshotlimit"=>String, "snapshottotal"=>Integer, "snapshotavailable"=>String, "templatelimit"=>String, "templatetotal"=>Integer, "templateavailable"=>String, "vmstopped"=>Integer, "vmrunning"=>Integer, "state"=>String, "user"=> [{ "id"=>Integer, "username"=>String, "firstname"=>String, "lastname"=>String, "email"=>String, "created"=>String, "state"=>String, "account"=>String, "accounttype"=>Integer, "domainid"=>Integer, "domain"=>String, "apikey"=>String, "secretkey"=>String }] }] EVENTS = [{ "id"=>Integer, "username"=>String, "type"=>String, "level"=>String, "description"=>String, "account"=>String, "domainid"=>Integer, "domain"=>String, "created"=>String, "state"=>String, "parentid"=>Integer }] DISK_OFFERINGS = [{ "id"=>Integer, "domainid"=>Integer, "domain"=>String, "name"=>String, "displaytext"=>String, "disksize"=>Integer, "created"=>String, "iscustomized"=>Fog::Boolean, "tags"=>String }] CAPABILITIES = { "securitygroupsenabled" => Fog::Boolean, "cloudstackversion" => String, "userpublictemplateenabled" => Fog::Boolean } HYPERVISORS = [{ "name"=>String }] ZONES = [{ "allocationstate"=>String, "dhcpprovider"=>String, "id"=>Integer, "name"=>String, "networktype"=>String, "securitygroupsenabled"=>Fog::Boolean }] NETWORK_OFFERINGS = [{ "id"=>Integer, "name"=>String, "displaytext"=>String, "traffictype"=>String, "isdefault"=>Fog::Boolean, "specifyvlan"=>Fog::Boolean, "availability"=>String, "guestiptype"=>String, "networkrate"=>Integer }] RESOURCE_LIMITS = [{ "account"=>String, "domainid"=>Integer, "domain"=>String, "resourcetype"=>String, "max"=>Integer }] end module VirtualMachines VIRTUAL_MACHINE = { "id"=>Integer, "name"=>String, "displayname"=>String, "account"=>String, "domainid"=>Integer, "domain"=>String, "created"=>String, "state"=>String, "haenable"=>Fog::Boolean, "zoneid"=>Integer, "zonename"=>String, "templateid"=>Integer, "templatename"=>String, "templatedisplaytext"=>String, "passwordenabled"=>Fog::Boolean, "serviceofferingid"=>Integer, "serviceofferingname"=>String, "cpunumber"=>Integer, "cpuspeed"=>Integer, "memory"=>Integer, "guestosid"=>Integer, "rootdeviceid"=>Integer, "rootdevicetype"=>String, "nic"=>[{ "id"=>Integer, "networkid"=>Integer, "netmask"=>Fog::Nullable::String, "gateway"=>Fog::Nullable::String, "ipaddress"=>Fog::Nullable::String, "traffictype"=>String, "type"=>String, "isdefault"=>Fog::Boolean, }], "hypervisor"=>String, "cpuused"=>Fog::Nullable::String, "networkkbsread"=>Fog::Nullable::Integer, "networkkbswrite"=>Fog::Nullable::Integer } VIRTUAL_MACHINES = [VIRTUAL_MACHINE] end module Templates TEMPLATES = [{ "id"=>Integer, "name"=>String, "displaytext"=>String, "ispublic"=>Fog::Boolean, "created"=>String, "isready"=>Fog::Boolean, "passwordenabled"=>Fog::Boolean, "format"=>String, "isfeatured"=>Fog::Boolean, "crossZones"=>Fog::Boolean, "ostypeid"=>Integer, "ostypename"=>String, "account"=>String, "zoneid"=>Integer, "zonename"=>String, "size"=>Integer, "templatetype"=>String, "hypervisor"=>String, "domain"=>String, "domainid"=>Integer, "isextractable"=>Fog::Boolean, }] end module Jobs JOB = { "jobid"=>Integer, "accountid"=>Integer, "userid"=>Integer, "cmd"=>String, "jobstatus"=>Integer, "jobprocstatus"=>Integer, "jobresultcode"=>Integer, "jobresult"=>Hash, "created"=>String } JOBS = [JOB] JOB_QUERY = { "jobid"=>Integer, "jobstatus"=>Integer, "jobprocstatus"=>Integer, "jobresultcode"=>Integer, "jobresulttype"=>String, "jobresult"=>Hash } end module Networks NETWORKS=[{"id"=>Integer, "name"=>String, "displaytext"=>String, "broadcastdomaintype"=>String, "traffictype"=>String, "zoneid"=>Integer, "networkofferingid"=>Integer, "networkofferingname"=>String, "networkofferingdisplaytext"=>String, "networkofferingavailability"=>String, "isshared"=>Fog::Boolean, "issystem"=>Fog::Boolean, "state"=>String, "related"=>Integer, "broadcasturi"=>Fog::Nullable::String, "dns1"=>String, "dns2"=>String, "type"=>String, "account"=>String, "domainid"=>Integer, "domain"=>String, "isdefault"=>Fog::Boolean, "service"=>Array, "networkdomain"=>Fog::Nullable::String, "securitygroupenabled"=>Fog::Boolean, "netmask"=>Fog::Nullable::String, "startip"=>Fog::Nullable::String, "endip"=>Fog::Nullable::String, "gateway"=>Fog::Nullable::String, "vlan"=>Fog::Nullable::String }] end module Addresses ADDRESS = { "id"=>Integer, "ipaddress"=>String, "allocated"=>String, "zoneid"=>Integer, "zonename"=>String, "issourcenat"=>Fog::Boolean, "account"=>String, "domainid"=>Integer, "domain"=>String, "forvirtualnetwork"=>Fog::Boolean, "isstaticnat"=>Fog::Boolean, "associatednetworkid"=>Integer, "networkid"=>Integer, "state"=>String, "virtualmachineid"=>Fog::Nullable::Integer, "virtualmachinename"=>Fog::Nullable::String } ADDRESSES = [ADDRESS] DISASSOC_ADDRESS = {"jobid"=>Integer} end module Nat ENABLE_NAT_RESPONSE = { 'success' => String } DISABLE_NAT_RESPONSE = { 'success' => Fog::Boolean } DELETE_RULE_RESPONSE = { 'success' => Fog::Boolean } FORWARDING_RULE = { "id"=>Integer, "protocol"=>String, "virtualmachineid"=>Integer, "virtualmachinename"=>String, "ipaddressid"=>Integer, "ipaddress"=>String, "startport"=>Integer, "endport"=>Integer, "state"=>String } FORWARDING_RULES = [FORWARDING_RULE] end module LoadBalancers CREATE_LOAD_BALANCER_RULE_RESPONSE = { "id"=>Integer, "account"=>String, "algorithm"=>String, "cidrlist"=>String, "domain"=>String, "domainid"=>Integer, "name"=>String, "privateport"=>String, "publicip"=>String, "publicipid"=>Integer, "publicport"=>String, "state"=>String, "zoneid"=>Integer } ASSIGN_LOAD_BALANCER_RULE_RESPONSE = { "success"=>Fog::Boolean } LIST_LOAD_BALANCER_RULES_RESPONSE = { "id"=>Integer, "name"=>String, "publicipid"=>Integer, "publicip"=>String, "publicport"=>String, "privateport"=>String, "algorithm"=>String, "cidrlist"=>String, "account"=>String, "domainid"=>Integer, "domain"=>String, "state"=>String, "zoneid"=>Integer } UPDATE_LOAD_BALANCER_RULE_RESPONSE = { "id"=>Integer, "name"=>String, "publicipid"=>Integer, "publicip"=>String, "publicport"=>String, "privateport"=>String, "algorithm"=>String, "cidrlist"=>String, "account"=>String, "domainid"=>Integer, "domain"=>String, "state"=>String, "zoneid"=>Integer } REMOVE_FROM_LOAD_BALANCER_RULE_RESPONSE = { "success"=>Fog::Boolean } end end end end fog-1.19.0/tests/ninefold/requests/compute/async_job_tests.rb0000644000004100000410000000162112261242552024413 0ustar www-datawww-data# This will fail until there are jobs in the system. Shindo.tests('Fog::Compute[:ninefold] | async job requests', ['ninefold']) do tests('success') do tests("#list_async_jobs()").formats(Ninefold::Compute::Formats::Jobs::JOBS) do pending if Fog.mocking? jobs = Fog::Compute[:ninefold].list_async_jobs() unless jobs[0] raise "No async jobs in system yet - create a VM through web UI to create" end @jobid = jobs[0]['jobid'] jobs end tests("#query_async_job_result()").formats(Ninefold::Compute::Formats::Jobs::JOB_QUERY) do pending if Fog.mocking? Fog::Compute[:ninefold].query_async_job_result(:jobid => @jobid) end end tests('failure') do #tests("#deploy_virtual_machine()").raises(Excon::Errors::HTTPStatusError) do # pending if Fog.mocking? # Fog::Compute[:ninefold].deploy_virtual_machine #end end end fog-1.19.0/tests/ninefold/requests/compute/template_tests.rb0000644000004100000410000000102012261242552024250 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ninefold] | template requests', ['ninefold']) do tests('success') do tests("#list_templates()").formats(Ninefold::Compute::Formats::Templates::TEMPLATES) do pending if Fog.mocking? Fog::Compute[:ninefold].list_templates(:templatefilter => 'executable') end end tests('failure') do #tests("#deploy_virtual_machine()").raises(Excon::Errors::HTTPStatusError) do # pending if Fog.mocking? # Fog::Compute[:ninefold].deploy_virtual_machine #end end end fog-1.19.0/tests/ninefold/requests/compute/nat_tests.rb0000644000004100000410000000732412261242552023234 0ustar www-datawww-data## Note: # If needed, these tests will create a new VM and public IP address. Because this is expensive, you # can optionally specify VM_ID and IP_ID as environment variables, and we will use those. Note: # The IP must not already have static nat enabled or any port mappings. Shindo.tests('Fog::Compute[:ninefold] | nat requests', ['ninefold']) do if ENV['VM_ID'] && ENV['IP_ID'] @ipid, @vmid = ENV['IP_ID'], ENV['VM_ID'] elsif !Fog.mock? begin # Create a VM to work with networks = Fog::Compute[:ninefold].list_networks vm_job = Fog::Compute[:ninefold].deploy_virtual_machine(:serviceofferingid => Ninefold::Compute::TestSupport::SERVICE_OFFERING, :templateid => Ninefold::Compute::TestSupport::TEMPLATE_ID, :zoneid => Ninefold::Compute::TestSupport::ZONE_ID, :networkids => networks[0]['id']) @vm = Ninefold::Compute::TestSupport.wait_for_job(vm_job)['jobresult']['virtualmachine'] @vmid = @vm['id'] # Allocate a public IP to work with ip_job = Fog::Compute[:ninefold].associate_ip_address(:zoneid => Ninefold::Compute::TestSupport::ZONE_ID) @ip = Ninefold::Compute::TestSupport.wait_for_job(ip_job)['jobresult']['ipaddress'] @ipid = @ip['id'] rescue => e puts "*** CREATING VM OR IP FAILED - PLEASE TEST AND CORRECT THIS FIRST" raise e end end tests('success') do tests("#enable_static_nat()").formats(Ninefold::Compute::Formats::Nat::ENABLE_NAT_RESPONSE) do pending if Fog.mocking? Fog::Compute[:ninefold].enable_static_nat(:ipaddressid => @ipid, :virtualmachineid => @vmid) end tests("#create_ip_forwarding_rule()").formats(Ninefold::Compute::Formats::Nat::FORWARDING_RULE) do pending if Fog.mocking? job = Fog::Compute[:ninefold].create_ip_forwarding_rule(:ipaddressid => @ipid, :protocol => 'TCP', :startport => 22) result = Ninefold::Compute::TestSupport.wait_for_job(job)['jobresult']['ipforwardingrule'] @fwd_rule_id = result['id'] result end tests("#list_ip_forwarding_rules()").formats(Ninefold::Compute::Formats::Nat::FORWARDING_RULES) do pending if Fog.mocking? Fog::Compute[:ninefold].list_ip_forwarding_rules end tests("#delete_ip_forwarding_rule()").formats(Ninefold::Compute::Formats::Nat::DELETE_RULE_RESPONSE) do pending if Fog.mocking? job = Fog::Compute[:ninefold].delete_ip_forwarding_rule(:id => @fwd_rule_id) Ninefold::Compute::TestSupport.wait_for_job(job)['jobresult'] end tests("#disable_static_nat()").formats(Ninefold::Compute::Formats::Nat::DISABLE_NAT_RESPONSE) do pending if Fog.mocking? job = Fog::Compute[:ninefold].disable_static_nat(:ipaddressid => @ipid) Ninefold::Compute::TestSupport.wait_for_job(job)['jobresult'] end end tests('failure') do tests("#associate_ip_address()").raises(Excon::Errors::HTTPStatusError) do pending if Fog.mocking? Fog::Compute[:ninefold].associate_ip_address end end unless ENV['VM_ID'] && ENV['IP_ID'] || Fog.mock? begin # Kill test VM vm_job = Fog::Compute[:ninefold].destroy_virtual_machine(:id => @vmid) Ninefold::Compute::TestSupport.wait_for_job(vm_job) # Disassociate public IP ip_job = Fog::Compute[:ninefold].disassociate_ip_address(:id => @ipid) Ninefold::Compute::TestSupport.wait_for_job(ip_job) rescue => e puts "*** DESTROYING VM OR IP FAILED - PLEASE TEST AND CORRECT THIS FIRST" raise e end end end fog-1.19.0/tests/ninefold/requests/compute/virtual_machine_tests.rb0000644000004100000410000000610612261242552025621 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ninefold] | server requests', ['ninefold']) do tests('success') do tests("#deploy_virtual_machine()").formats(Ninefold::Compute::Formats::VirtualMachines::VIRTUAL_MACHINE) do pending if Fog.mocking? networks = Fog::Compute[:ninefold].list_networks unless networks[0] raise "No networks, ensure a network has been created by deploying a VM from the web UI and verify list_networks test" end newvm = Fog::Compute[:ninefold].deploy_virtual_machine(:serviceofferingid => Ninefold::Compute::TestSupport::SERVICE_OFFERING, :templateid => Ninefold::Compute::TestSupport::TEMPLATE_ID, :zoneid => Ninefold::Compute::TestSupport::ZONE_ID, :networkids => networks[0]['id']) # wait for deployment, stash the job id. @newvmid = newvm['id'] Ninefold::Compute::TestSupport.wait_for_job(newvm['jobid'])['jobresult']['virtualmachine'] end tests("#list_virtual_machines()").formats(Ninefold::Compute::Formats::VirtualMachines::VIRTUAL_MACHINES) do pending if Fog.mocking? Fog::Compute[:ninefold].list_virtual_machines end tests("#reboot_virtual_machine()").formats(Ninefold::Compute::Formats::VirtualMachines::VIRTUAL_MACHINE) do pending if Fog.mocking? job = Fog::Compute[:ninefold].reboot_virtual_machine(:id => @newvmid) Ninefold::Compute::TestSupport.wait_for_job(job)['jobresult']['virtualmachine'] end tests("#stop_virtual_machine()").formats(Ninefold::Compute::Formats::VirtualMachines::VIRTUAL_MACHINE) do pending if Fog.mocking? job = Fog::Compute[:ninefold].stop_virtual_machine(:id => @newvmid) Ninefold::Compute::TestSupport.wait_for_job(job)['jobresult']['virtualmachine'] end tests("#change_service_for_virtual_machine()").formats(Ninefold::Compute::Formats::VirtualMachines::VIRTUAL_MACHINE) do pending if Fog.mocking? Fog::Compute[:ninefold].change_service_for_virtual_machine(:id => @newvmid, :serviceofferingid => Ninefold::Compute::TestSupport::ALT_SERVICE_OFFERING) end tests("#start_virtual_machine()").formats(Ninefold::Compute::Formats::VirtualMachines::VIRTUAL_MACHINE) do pending if Fog.mocking? job = Fog::Compute[:ninefold].start_virtual_machine(:id => @newvmid) Ninefold::Compute::TestSupport.wait_for_job(job)['jobresult']['virtualmachine'] end tests("#destroy_virtual_machine()").formats(Ninefold::Compute::Formats::VirtualMachines::VIRTUAL_MACHINE) do pending if Fog.mocking? job = Fog::Compute[:ninefold].destroy_virtual_machine(:id => @newvmid) Ninefold::Compute::TestSupport.wait_for_job(job)['jobresult']['virtualmachine'] end end tests('failure') do tests("#deploy_virtual_machine()").raises(Excon::Errors::HTTPStatusError) do pending if Fog.mocking? Fog::Compute[:ninefold].deploy_virtual_machine end end end fog-1.19.0/tests/ninefold/requests/compute/list_tests.rb0000644000004100000410000000334312261242552023422 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ninefold] | list only requests', ['ninefold']) do tests('success') do tests("#list_accounts()").formats(Ninefold::Compute::Formats::Lists::ACCOUNTS) do pending if Fog.mocking? Fog::Compute[:ninefold].list_accounts end tests("#list_events()").formats(Ninefold::Compute::Formats::Lists::EVENTS) do pending if Fog.mocking? Fog::Compute[:ninefold].list_events end tests("#list_service_offerings()").formats(Ninefold::Compute::Formats::Lists::SERVICE_OFFERINGS) do pending if Fog.mocking? Fog::Compute[:ninefold].list_service_offerings end tests("#list_disk_offerings()").formats(Ninefold::Compute::Formats::Lists::DISK_OFFERINGS) do pending if Fog.mocking? Fog::Compute[:ninefold].list_disk_offerings end tests("#list_capabilities()").formats(Ninefold::Compute::Formats::Lists::CAPABILITIES) do pending if Fog.mocking? Fog::Compute[:ninefold].list_capabilities end tests("#list_hypervisors()").formats(Ninefold::Compute::Formats::Lists::HYPERVISORS) do pending if Fog.mocking? Fog::Compute[:ninefold].list_hypervisors end tests("#list_zones()").formats(Ninefold::Compute::Formats::Lists::ZONES) do pending if Fog.mocking? Fog::Compute[:ninefold].list_zones end tests("#list_network_offerings()").formats(Ninefold::Compute::Formats::Lists::NETWORK_OFFERINGS) do pending if Fog.mocking? Fog::Compute[:ninefold].list_network_offerings end tests("#list_resource_limits()").formats(Ninefold::Compute::Formats::Lists::RESOURCE_LIMITS) do pending if Fog.mocking? Fog::Compute[:ninefold].list_resource_limits end end tests('failure') do end end fog-1.19.0/tests/ninefold/requests/compute/network_tests.rb0000644000004100000410000000075412261242552024143 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ninefold] | network requests', ['ninefold']) do tests('success') do tests("#list_networks()").formats(Ninefold::Compute::Formats::Networks::NETWORKS) do pending if Fog.mocking? Fog::Compute[:ninefold].list_networks() end end tests('failure') do #tests("#deploy_virtual_machine()").raises(Excon::Errors::HTTPStatusError) do # pending if Fog.mocking? # Fog::Compute[:ninefold].deploy_virtual_machine #end end end fog-1.19.0/tests/ninefold/requests/compute/address_tests.rb0000644000004100000410000000263612261242552024100 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ninefold] | address requests', ['ninefold']) do tests('success') do tests("#associate_ip_address()").formats(Ninefold::Compute::Formats::Addresses::ADDRESS) do pending if Fog.mocking? job = newaddress = Fog::Compute[:ninefold].associate_ip_address(:zoneid => Ninefold::Compute::TestSupport::ZONE_ID) while Fog::Compute[:ninefold].query_async_job_result(:jobid => job['jobid'])['jobstatus'] == 0 sleep 1 end result = Fog::Compute[:ninefold].query_async_job_result(:jobid => job['jobid'])['jobresult']['ipaddress'] @newaddressid = result['id'] result end tests("#list_public_ip_addresses()").formats(Ninefold::Compute::Formats::Addresses::ADDRESSES) do pending if Fog.mocking? result = Fog::Compute[:ninefold].list_public_ip_addresses result end tests("#disassociate_ip_address()").formats(Ninefold::Compute::Formats::Addresses::DISASSOC_ADDRESS) do pending if Fog.mocking? job = Fog::Compute[:ninefold].disassociate_ip_address(:id => @newaddressid) while Fog::Compute[:ninefold].query_async_job_result(:jobid => job['jobid'])['jobstatus'] == 0 sleep 1 end job end end tests('failure') do tests("#associate_ip_address()").raises(Excon::Errors::HTTPStatusError) do pending if Fog.mocking? Fog::Compute[:ninefold].associate_ip_address end end end fog-1.19.0/tests/ninefold/requests/compute/load_balancer_tests.rb0000644000004100000410000000616212261242552025217 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ninefold] | load balancers', ['ninefold']) do # NOTE: all of these tests require you to have a vm built with a public IP address. tests('success') do before do @compute = Fog::Compute[:ninefold] unless Fog.mocking? @public_ip_id = @compute.list_public_ip_addresses.first['id'] @server_id = @compute.servers.all.first.id @create_load_balancer = @compute.create_load_balancer_rule(:algorithm => 'roundrobin', :name => 'test', :privateport => 1000, :publicport => 2000, :publicipid => @public_ip_id) end end after do unless Fog.mocking? delete = @compute.delete_load_balancer_ruler(:id => @create_load_balancer['id']) Ninefold::Compute::TestSupport.wait_for_job(delete['jobid']) end end tests("#create_load_balancer_rule()").formats(Ninefold::Compute::Formats::LoadBalancers::CREATE_LOAD_BALANCER_RULE_RESPONSE) do pending if Fog.mocking? result = Ninefold::Compute::TestSupport.wait_for_job(@create_load_balancer['jobid']) result['jobresult']['loadbalancer'] end tests("#assign_to_load_balancer_rule()").formats(Ninefold::Compute::Formats::LoadBalancers::ASSIGN_LOAD_BALANCER_RULE_RESPONSE) do pending if Fog.mocking? assign_load_balancer = @compute.assign_to_load_balancer_rule(:id => @create_load_balancer['id'], :virtualmachineids => @server_id) result = Ninefold::Compute::TestSupport.wait_for_job(assign_load_balancer['jobid']) result['jobresult'] end tests("#list_to_load_balancer_rules()").formats(Ninefold::Compute::Formats::LoadBalancers::LIST_LOAD_BALANCER_RULES_RESPONSE) do pending if Fog.mocking? list_load_balancer_rules = @compute.list_load_balancer_rules list_load_balancer_rules['loadbalancerrule'].first end tests("#update_to_load_balancer_rule()").formats(Ninefold::Compute::Formats::LoadBalancers::UPDATE_LOAD_BALANCER_RULE_RESPONSE) do pending if Fog.mocking? update_load_balancer = @compute.update_load_balancer_rule(:id => @create_load_balancer['id'], :algorithm => 'source') result = Ninefold::Compute::TestSupport.wait_for_job(update_load_balancer['jobid']) result['jobresult']['loadbalancer'] end tests('with assigned to load balancer rule') do before do unless Fog.mocking? assign_load_balancer = @compute.assign_to_load_balancer_rule(:id => @create_load_balancer['id'], :virtualmachineids => @server_id) result = Ninefold::Compute::TestSupport.wait_for_job(assign_load_balancer['jobid']) end end tests("#remove_from_load_balancer_rule()").formats(Ninefold::Compute::Formats::LoadBalancers::REMOVE_FROM_LOAD_BALANCER_RULE_RESPONSE) do pending if Fog.mocking? remove = @compute.remove_from_load_balancer_rule(:id => @create_load_balancer['id'], :virtualmachineids => @server_id) result = Ninefold::Compute::TestSupport.wait_for_job(remove['jobid']) result['jobresult'] end end end end fog-1.19.0/tests/ninefold/models/0000755000004100000410000000000012261242552016631 5ustar www-datawww-datafog-1.19.0/tests/ninefold/models/storage/0000755000004100000410000000000012261242552020275 5ustar www-datawww-datafog-1.19.0/tests/ninefold/models/storage/file_update_tests.rb0000644000004100000410000000075212261242552024331 0ustar www-datawww-dataShindo.tests("Storage[:ninefold] | nested directories", ['ninefold']) do unless Fog.mocking? @directory = Fog::Storage[:ninefold].directories.create(:key => 'updatefiletests') end ninefold = Fog::Storage[:ninefold] tests("update a file").succeeds do pending if Fog.mocking? file = @directory.files.create(:key => 'lorem.txt', :body => lorem_file) file.body = "xxxxxx" file.save end unless Fog.mocking? @directory.destroy(:recursive => true) end endfog-1.19.0/tests/ninefold/models/storage/nested_directories_tests.rb0000644000004100000410000000137212261242552025725 0ustar www-datawww-dataShindo.tests("Storage[:ninefold] | nested directories", ['ninefold']) do ninefold = Fog::Storage[:ninefold] tests("create a directory with a / character").succeeds do pending if Fog.mocking? ninefold.directories.create(:key => 'sub/path') end tests("List of top directory returns sub dir").returns(1) do pending if Fog.mocking? ninefold.directories.get('sub').directories.count end tests("create a directory in a sub dir").returns('sub/path/newdir/') do pending if Fog.mocking? ninefold.directories.get('sub/path').directories.create(:key => 'newdir').identity end tests("Recursively destroy parent dir").succeeds do pending if Fog.mocking? ninefold.directories.get('sub').destroy(:recursive => true) end endfog-1.19.0/tests/dynect/0000755000004100000410000000000012261242552015036 5ustar www-datawww-datafog-1.19.0/tests/dynect/requests/0000755000004100000410000000000012261242552016711 5ustar www-datawww-datafog-1.19.0/tests/dynect/requests/dns/0000755000004100000410000000000012261242552017475 5ustar www-datawww-datafog-1.19.0/tests/dynect/requests/dns/dns_tests.rb0000644000004100000410000002411112261242552022027 0ustar www-datawww-dataShindo.tests('Dynect::dns | DNS requests', ['dynect', 'dns']) do shared_format = { 'job_id' => Integer, 'msgs' => [{ 'ERR_CD' => Fog::Nullable::String, 'INFO' => String, 'LVL' => String, 'SOURCE' => String }], 'status' => String } tests "success" do @dns = Fog::DNS[:dynect] @domain = generate_unique_domain @fqdn = "www.#{@domain}" post_session_format = shared_format.merge({ 'data' => { 'token' => String, 'version' => String } }) tests("post_session").formats(post_session_format) do @dns.post_session.body end post_zone_format = shared_format.merge({ 'data' => { 'serial' => Integer, 'zone' => String, 'zone_type' => String, 'serial_style' => String } }) tests("post_zone('netops@#{@domain}', 3600, '#{@domain}')").formats(post_zone_format) do @dns.post_zone("netops@#{@domain}", 3600, @domain).body end get_zones_format = shared_format.merge({ 'data' => [String] }) tests("get_zone").formats(get_zones_format) do @dns.get_zone.body end get_zone_format = shared_format.merge({ 'data' => { "serial" => Integer, "serial_style" => String, "zone" => String, "zone_type" => String } }) tests("get_zone('zone' => '#{@domain}')").formats(get_zone_format) do @dns.get_zone('zone' => @domain).body end post_record_format = shared_format.merge({ 'data' => { 'fqdn' => String, 'rdata' => { 'address' => String }, 'record_id' => Integer, 'record_type' => String, 'ttl' => Integer, 'zone' => String } }) tests("post_record('A', '#{@domain}', '#{@fqdn}', 'address' => '1.2.3.4')").formats(post_record_format) do @dns.post_record('A', @domain, @fqdn, {'address' => '1.2.3.4'}).body end put_record_format = shared_format.merge({ 'data' => { 'fqdn' => String, 'ARecords' => [ { 'rdata' => { 'address' => String } } ], 'record_id' => Integer, 'record_type' => String, 'ttl' => Integer, 'zone' => String } }) tests("put_record('A', '#{@domain}', '#{@fqdn}', 'address' => '1.2.3.4')").formats(post_record_format) do @dns.put_record('A', @domain, @fqdn, {'address' => '1.2.3.4'}).body end publish_zone_format = shared_format.merge({ 'data' => { 'serial' => Integer, 'serial_style' => String, 'zone' => String, 'zone_type' => String } }) tests("put_zone('#{@domain}', 'publish' => true)").formats(publish_zone_format) do @dns.put_zone(@domain, 'publish' => true).body end freeze_zone_format = shared_format.merge({ 'data' => {} }) tests("put_zone('#{@domain}', 'freeze' => true)").formats(freeze_zone_format) do @dns.put_zone(@domain, 'freeze' => true).body end thaw_zone_format = shared_format.merge({ 'data' => {} }) tests("put_zone('#{@domain}', 'thaw' => true)").formats(thaw_zone_format) do @dns.put_zone(@domain, 'thaw' => true).body end get_node_list_format = shared_format.merge({ 'data' => [String] }) tests("get_node_list('#{@domain}')").formats(get_node_list_format) do @dns.get_node_list(@domain).body end get_all_records_format = shared_format.merge({ 'data' => [String] }) tests("get_all_records('#{@domain}')").formats(get_all_records_format) do @dns.get_all_records(@domain).body end get_records_format = shared_format.merge({ 'data' => [String] }) tests("get_record('A', '#{@domain}', '#{@fqdn}')").formats(get_records_format) do data = @dns.get_record('A', @domain, @fqdn).body @record_id = data['data'].first.split('/').last data end sleep 5 unless Fog.mocking? @dns.post_record('CNAME', @domain, "cname.#{@fqdn}", {'cname' => "#{@fqdn}."}) tests("get_record('ANY', '#{@domain}', 'cname.#{@fqdn}')").formats(get_records_format) do @dns.get_record('ANY', @domain, "cname.#{@fqdn}").body end get_record_format = shared_format.merge({ 'data' => { 'zone' => String, 'ttl' => Integer, 'fqdn' => String, 'record_type' => String, 'rdata' => { 'address' => String }, 'record_id' => Integer } }) tests("get_record('A', '#{@domain}', '#{@fqdn}', 'record_id' => '#{@record_id}')").formats(get_record_format) do @dns.get_record('A', @domain, @fqdn, 'record_id' => @record_id).body end delete_record_format = shared_format.merge({ 'data' => {} }) tests("delete_record('A', '#{@domain}', '#{@fqdn}', '#{@record_id}')").formats(delete_record_format) do @dns.delete_record('A', @domain, "#{@fqdn}", @record_id).body end delete_zone_format = shared_format.merge({ 'data' => {} }) sleep 5 unless Fog.mocking? tests("delete_zone('#{@domain}')").formats(delete_zone_format) do @dns.delete_zone(@domain).body end tests("job handling") do pending unless Fog.mocking? old_mock_value = Excon.defaults[:mock] Excon.stubs.clear tests("returns final response from a complete job").returns({"status" => "success"}) do begin Excon.defaults[:mock] = true Excon.stub({:method => :post, :path => "/REST/Session"}, {:body=>"{\"status\": \"success\", \"data\": {\"token\": \"foobar\", \"version\": \"2.3.1\"}, \"job_id\": 150583906, \"msgs\": [{\"INFO\": \"login: Login successful\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}", :headers=>{"Content-Type"=>"application/json"}, :status=>200}) Excon.stub({:method => :get, :path => "/REST/Zone/example.com"}, {:status => 307, :body => '/REST/Job/150576635', :headers => {'Content-Type' => 'text/html', 'Location' => '/REST/Job/150576635'}}) Excon.stub({:method => :get, :path => "/REST/Job/150576635"}, {:status => 307, :body => '{"status":"success"}', :headers => {'Content-Type' => 'application/json'}}) Fog::DNS::Dynect::Real.new.request(:method => :get, :path => "Zone/example.com").body ensure Excon.stubs.clear Excon.defaults[:mock] = old_mock_value end end tests("passes expects through when polling a job").returns({"status" => "success"}) do begin Excon.defaults[:mock] = true Excon.stub({:method => :post, :path => "/REST/Session"}, {:body=>"{\"status\": \"success\", \"data\": {\"token\": \"foobar\", \"version\": \"2.3.1\"}, \"job_id\": 150583906, \"msgs\": [{\"INFO\": \"login: Login successful\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}", :headers=>{"Content-Type"=>"application/json"}, :status=>200}) Excon.stub({:method => :get, :path => "/REST/Zone/example.com"}, {:status => 307, :body => '/REST/Job/150576635', :headers => {'Content-Type' => 'text/html', 'Location' => '/REST/Job/150576635'}}) Excon.stub({:method => :get, :path => "/REST/Job/150576635"}, {:status => 404, :body => '{"status":"success"}', :headers => {'Content-Type' => 'application/json'}}) Fog::DNS::Dynect::Real.new.request(:method => :get, :expects => 404, :path => "Zone/example.com").body ensure Excon.stubs.clear Excon.defaults[:mock] = old_mock_value end end end end tests('failure') do tests("#auth_token with expired credentials").raises(Excon::Errors::BadRequest) do pending if Fog.mocking? @dns = Fog::DNS[:dynect] @dns.instance_variable_get(:@connection).stub(:request) { raise Excon::Errors::BadRequest.new('Expected(200) <=> Actual(400 Bad Request) request => {:headers=>{"Content-Type"=>"application/json", "API-Version"=>"2.3.1", "Auth-Token"=>"auth-token", "Host"=>"api2.dynect.net:443", "Content-Length"=>0}, :host=>"api2.dynect.net", :mock=>nil, :path=>"/REST/CNAMERecord/domain.com/www.domain.com", :port=>"443", :query=>nil, :scheme=>"https", :expects=>200, :method=>:get} response => #"nginx/0.7.67", "Date"=>"Thu, 08 Sep 2011 20:04:21 GMT", "Content-Type"=>"application/json", "Transfer-Encoding"=>"chunked", "Connection"=>"keep-alive"}, @status=400>') } @dns.instance_variable_get(:@connection).should_receive(:request).exactly(2).times @dns.auth_token end tests("#auth_token with inactivity logout").raises(Excon::Errors::BadRequest) do pending if Fog.mocking? @dns = Fog::DNS[:dynect] @dns.instance_variable_get(:@connection).stub(:request) { raise Excon::Errors::BadRequest.new('Expected(200) <=> Actual(400 Bad Request) request => {:headers=>{"Content-Type"=>"application/json", "API-Version"=>"2.3.1", "Auth-Token"=>"auth-token", "Host"=>"api2.dynect.net:443", "Content-Length"=>0}, :host=>"api2.dynect.net", :mock=>nil, :path=>"/REST/CNAMERecord/domain.com/www.domain.com", :port=>"443", :query=>nil, :scheme=>"https", :expects=>200, :method=>:get} response => #"nginx/0.7.67", "Date"=>"Thu, 08 Sep 2011 20:04:21 GMT", "Content-Type"=>"application/json", "Transfer-Encoding"=>"chunked", "Connection"=>"keep-alive"}, @status=400>') } @dns.instance_variable_get(:@connection).should_receive(:request).exactly(2).times @dns.auth_token end end end fog-1.19.0/tests/atmos/0000755000004100000410000000000012261242552014673 5ustar www-datawww-datafog-1.19.0/tests/atmos/models/0000755000004100000410000000000012261242552016156 5ustar www-datawww-datafog-1.19.0/tests/atmos/models/storage/0000755000004100000410000000000012261242552017622 5ustar www-datawww-datafog-1.19.0/tests/atmos/models/storage/file_update_tests.rb0000644000004100000410000000073412261242552023656 0ustar www-datawww-dataShindo.tests("Storage[:atmos] | nested directories", ['atmos']) do unless Fog.mocking? @directory = Fog::Storage[:atmos].directories.create(:key => 'updatefiletests') end atmos = Fog::Storage[:atmos] tests("update a file").succeeds do pending if Fog.mocking? file = @directory.files.create(:key => 'lorem.txt', :body => lorem_file) file.body = "xxxxxx" file.save end unless Fog.mocking? @directory.destroy(:recursive => true) end end fog-1.19.0/tests/atmos/models/storage/nested_directories_tests.rb0000644000004100000410000000134312261242552025250 0ustar www-datawww-dataShindo.tests("Storage[:atmos] | nested directories", ['atmos']) do atmos = Fog::Storage[:atmos] tests("create a directory with a / character").succeeds do pending if Fog.mocking? atmos.directories.create(:key => 'sub/path') end tests("List of top directory returns sub dir").returns(1) do pending if Fog.mocking? atmos.directories.get('sub').directories.count end tests("create a directory in a sub dir").returns('sub/path/newdir/') do pending if Fog.mocking? atmos.directories.get('sub/path').directories.create(:key => 'newdir').identity end tests("Recursively destroy parent dir").succeeds do pending if Fog.mocking? atmos.directories.get('sub').destroy(:recursive => true) end end fog-1.19.0/tests/ovirt/0000755000004100000410000000000012261242552014713 5ustar www-datawww-datafog-1.19.0/tests/ovirt/requests/0000755000004100000410000000000012261242552016566 5ustar www-datawww-datafog-1.19.0/tests/ovirt/requests/compute/0000755000004100000410000000000012261242552020242 5ustar www-datawww-datafog-1.19.0/tests/ovirt/requests/compute/list_storage_domains_tests.rb0000644000004100000410000000065612261242552026231 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ovirt] | storage_domains request', ['ovirt']) do compute = Fog::Compute[:ovirt] tests("When listing all storage_domains") do response = compute.storage_domains tests("The response data format ...") do test("it should be a kind of Array") { response.kind_of? Array } test("be a kind of OVIRT::StorageDomain") { response.first.kind_of? OVIRT::StorageDomain } end end end fog-1.19.0/tests/ovirt/requests/compute/update_vm_tests.rb0000644000004100000410000000116712261242552024002 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ovirt] | vm_update request', ['ovirt']) do compute = Fog::Compute[:ovirt] if compute.servers.all(:search => 'fog-*').empty? compute.create_vm(:name => 'fog-'+Time.now.to_i.to_s, :cluster_name => 'Default') end vm = compute.servers.all(:search => 'fog-*').last tests('The response should') do response = compute.update_vm(:id => vm.id, :name => vm.name + 'updated') test("be a kind of OVIRT::VM") { response.kind_of? OVIRT::VM} end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when id option is missing') { compute.update_vm } end end fog-1.19.0/tests/ovirt/requests/compute/create_vm_tests.rb0000644000004100000410000000176612261242552023770 0ustar www-datawww-dataShindo.tests("Fog::Compute[:ovirt] | vm_create request", 'ovirt') do compute = Fog::Compute[:ovirt] name_base = Time.now.to_i tests("Create VM") do response = compute.create_vm(:name => 'fog-'+name_base.to_s, :cluster_name => 'Default') test("should be a kind of OVIRT::VM") { response.kind_of? OVIRT::VM} end tests("Create VM from template (clone)") do response = compute.create_vm(:name => 'fog-'+(name_base+ 1).to_s, :template_name => 'hwp_small', :cluster_name => 'Default') test("should be a kind of OVIRT::VM") { response.kind_of? OVIRT::VM} end tests("Fail Creating VM") do begin response = compute.create_vm(:name => 'fog-'+name_base.to_s, :cluster_name => 'Default') test("should be a kind of OVIRT::VM") { response.kind_of? OVIRT::VM} #mock never raise exceptions rescue => e #should raise vm name already exist exception. test("error should be a kind of OVIRT::OvirtException") { e.kind_of? OVIRT::OvirtException} end end end fog-1.19.0/tests/ovirt/requests/compute/destroy_vm_tests.rb0000644000004100000410000000112312261242552024201 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ovirt] | vm_destroy request', ['ovirt']) do compute = Fog::Compute[:ovirt] if compute.servers.all(:search => 'fog-*').empty? compute.create_vm(:name => 'fog-'+Time.now.to_i.to_s, :cluster_name => 'Default') end vm_id = compute.servers.all(:search => 'fog-*').last.id tests('The response should') do response = compute.destroy_vm(:id => vm_id) test('be a success') { response ? true: false } end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when id option is missing') { compute.destroy_vm } end end fog-1.19.0/tests/ovirt/requests/compute/list_quotas_tests.rb0000644000004100000410000000046212261242552024362 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ovirt] | quotas request', ['ovirt']) do compute = Fog::Compute[:ovirt] tests("When listing all quotas") do response = compute.quotas tests("The response data format ...") do test("it should be a kind of Array") { response.kind_of? Array } end end end fog-1.19.0/tests/ovirt/requests/compute/list_datacenters_tests.rb0000644000004100000410000000060212261242552025337 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ovirt] | datacenters request', ['ovirt']) do compute = Fog::Compute[:ovirt] tests("When listing all datacenters") do response = compute.datacenters tests("The response data format ...") do test("it should be a kind of Array") { response.kind_of? Array } test("be a kind of Hash") { response.first.kind_of? Hash } end end end fog-1.19.0/tests/ovirt/compute_tests.rb0000644000004100000410000000160212261242552020135 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ovirt]', ['ovirt']) do compute = Fog::Compute[:ovirt] tests("Compute attributes") do %w{ ovirt_attrs }.each do |attr| test("it should respond to #{attr}") { compute.respond_to? attr } end end tests("Compute collections") do %w{ servers templates clusters interfaces }.each do |collection| test("it should respond to #{collection}") { compute.respond_to? collection } end end tests("Compute requests") do %w{ add_interface create_vm datacenters destroy_interface destroy_vm get_cluster get_template get_virtual_machine list_clusters list_networks list_template_interfaces list_templates list_virtual_machines list_vm_interfaces storage_domains update_interface update_vm vm_action }.each do |collection| test("it should respond to #{collection}") { compute.respond_to? collection } end end end fog-1.19.0/tests/ovirt/models/0000755000004100000410000000000012261242552016176 5ustar www-datawww-datafog-1.19.0/tests/ovirt/models/compute/0000755000004100000410000000000012261242552017652 5ustar www-datawww-datafog-1.19.0/tests/ovirt/models/compute/clusters_tests.rb0000644000004100000410000000043112261242552023263 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ovirt] | clusters collection', ['ovirt']) do clusters = Fog::Compute[:ovirt].clusters tests('The clusters collection') do test('should be a kind of Fog::Compute::Ovirt::Clusters') { clusters.kind_of? Fog::Compute::Ovirt::Clusters } end end fog-1.19.0/tests/ovirt/models/compute/template_tests.rb0000644000004100000410000000160212261242552023233 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ovirt] | template model', ['ovirt']) do templates = Fog::Compute[:ovirt].templates template = templates.last tests('The template model should') do tests('have the action') do test('reload') { template.respond_to? 'reload' } end tests('have attributes') do model_attribute_hash = template.attributes attributes = [ :id, :name] tests("The template model should respond to") do attributes.each do |attribute| test("#{attribute}") { template.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::Ovirt::Template') { template.kind_of? Fog::Compute::Ovirt::Template } end end fog-1.19.0/tests/ovirt/models/compute/server_tests.rb0000644000004100000410000000274612261242552022740 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ovirt] | server model', ['ovirt']) do servers = Fog::Compute[:ovirt].servers server = servers.last tests('The server model should') do tests('have the action') do test('reload') { server.respond_to? 'reload' } %w{ start stop destroy reboot suspend }.each do |action| test(action) { server.respond_to? action } end %w{ start reboot suspend stop }.each do |action| test("#{action} returns successfully") { begin server.send(action.to_sym) ? true : false rescue OVIRT::OvirtException #ovirt exceptions are acceptable for the above actions. true end } end end tests('have attributes') do model_attribute_hash = server.attributes attributes = [ :id, :name, :description, :profile, :display, :creation_time, :os, :status, :cores, :memory, :cluster, :template] tests("The server model should respond to") do attributes.each do |attribute| test("#{attribute}") { server.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::Ovirt::Server') { server.kind_of? Fog::Compute::Ovirt::Server } end end fog-1.19.0/tests/ovirt/models/compute/interface_tests.rb0000644000004100000410000000163612261242552023367 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ovirt] | interface model', ['ovirt']) do interfaces = Fog::Compute[:ovirt].servers.last.interfaces interface = interfaces.last tests('The interface model should') do tests('have the action') do test('reload') { interface.respond_to? 'reload' } end tests('have attributes') do model_attribute_hash = interface.attributes attributes = [ :id, :name, :network] tests("The interface model should respond to") do attributes.each do |attribute| test("#{attribute}") { interface.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::Ovirt::Interface') { interface.kind_of? Fog::Compute::Ovirt::Interface } end end fog-1.19.0/tests/ovirt/models/compute/servers_tests.rb0000644000004100000410000000102212261242552023105 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ovirt] | servers collection', ['ovirt']) do servers = Fog::Compute[:ovirt].servers tests('The servers collection') do test('should not be empty') { not servers.empty? } test('should be a kind of Fog::Compute::Ovirt::Servers') { servers.kind_of? Fog::Compute::Ovirt::Servers } tests('should be able to reload itself').succeeds { servers.reload } tests('should be able to get a model') do tests('by instance uuid').succeeds { servers.get servers.first.id } end end end fog-1.19.0/tests/ovirt/models/compute/cluster_tests.rb0000644000004100000410000000173112261242552023104 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ovirt] | cluster model', ['ovirt']) do clusters = Fog::Compute[:ovirt].clusters cluster = clusters.last tests('The cluster model should') do tests('have the action') do test('reload') { cluster.respond_to? 'reload' } %w{ networks }.each do |action| test(action) { cluster.respond_to? action } end end tests('have attributes') do model_attribute_hash = cluster.attributes attributes = [ :id, :name] tests("The cluster model should respond to") do attributes.each do |attribute| test("#{attribute}") { cluster.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::Ovirt::Cluster') { cluster.kind_of? Fog::Compute::Ovirt::Cluster } end end fog-1.19.0/tests/ovirt/models/compute/templates_tests.rb0000644000004100000410000000044012261242552023415 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ovirt] | templates collection', ['ovirt']) do templates = Fog::Compute[:ovirt].templates tests('The templates collection') do test('should be a kind of Fog::Compute::Ovirt::Templates') { templates.kind_of? Fog::Compute::Ovirt::Templates } end end fog-1.19.0/tests/ovirt/models/compute/interfaces_tests.rb0000644000004100000410000000044712261242552023551 0ustar www-datawww-dataShindo.tests('Fog::Compute[:ovirt] | interfaces collection', ['ovirt']) do interfaces = Fog::Compute[:ovirt].interfaces tests('The interfaces collection') do test('should be a kind of Fog::Compute::Ovirt::Interfaces') { interfaces.kind_of? Fog::Compute::Ovirt::Interfaces } end end fog-1.19.0/tests/internet_archive/0000755000004100000410000000000012261242552017101 5ustar www-datawww-datafog-1.19.0/tests/internet_archive/signaturev4_tests.rb0000644000004100000410000000521612261242552023127 0ustar www-datawww-data# encoding: utf-8 Shindo.tests('InternetArchive | signaturev4', ['internet_archive']) do # These testcases are from http://docs.amazonwebservices.com/general/latest/gr/signature-v4-test-suite.html @signer = Fog::InternetArchive::SignatureV4.new('AKIDEXAMPLE', 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', 'us-east-1','host') Fog::Time.now = ::Time.utc(2011,9,9,23,36,0) tests('get-vanilla') do returns(@signer.sign({:headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/'}, Fog::Time.now)) do 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=b27ccfbfa7df52a200ff74193ca6e32d4b48b8856fab7ebf1c595d0670a7e470' end end tests('get-vanilla-query-order-key with symbol keys') do returns(@signer.sign({:query => {:'a' => 'foo', :'b' => 'foo'}, :headers => {:'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/'}, Fog::Time.now)) do 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=0dc122f3b28b831ab48ba65cb47300de53fbe91b577fe113edac383730254a3b' end end tests('get-vanilla-query-order-key') do returns(@signer.sign({:query => {'a' => 'foo', 'b' => 'foo'}, :headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/'}, Fog::Time.now)) do 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=0dc122f3b28b831ab48ba65cb47300de53fbe91b577fe113edac383730254a3b' end end tests('get-unreserved') do returns(@signer.sign({:headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/-._~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'}, Fog::Time.now)) do 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=830cc36d03f0f84e6ee4953fbe701c1c8b71a0372c63af9255aa364dd183281e' end end tests('post-x-www-form-urlencoded-parameter') do returns(@signer.sign({:headers => {'Content-type' => 'application/x-www-form-urlencoded; charset=utf8', 'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :post, :path => '/', :body => 'foo=bar'}, Fog::Time.now)) do 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=content-type;date;host, Signature=b105eb10c6d318d2294de9d49dd8b031b55e3c3fe139f2e637da70511e9e7b71' end end Fog::Time.now = ::Time.now endfog-1.19.0/tests/internet_archive/requests/0000755000004100000410000000000012261242552020754 5ustar www-datawww-datafog-1.19.0/tests/internet_archive/requests/storage/0000755000004100000410000000000012261242552022420 5ustar www-datawww-datafog-1.19.0/tests/internet_archive/requests/storage/multipart_upload_tests.rb0000644000004100000410000001111512261242552027553 0ustar www-datawww-dataShindo.tests('Fog::Storage[:internetarchive] | multipart upload requests', ["internet_archive"]) do @directory = Fog::Storage[:internetarchive].directories.create(:key => "fogmultipartuploadtests-#{rand(65536)}") tests('success') do @initiate_multipart_upload_format = { 'Bucket' => String, 'Key' => String, 'UploadId' => String } tests("#initiate_multipart_upload('#{@directory.identity}')", 'fog_multipart_upload').formats(@initiate_multipart_upload_format) do pending if Fog.mocking? data = Fog::Storage[:internetarchive].initiate_multipart_upload(@directory.identity, 'fog_multipart_upload').body @upload_id = data['UploadId'] data end @list_multipart_uploads_format = { 'Bucket' => String, 'IsTruncated' => Fog::Boolean, 'MaxUploads' => Integer, 'KeyMarker' => NilClass, 'NextKeyMarker' => String, 'NextUploadIdMarker' => Fog::Nullable::String, 'Upload' => [{ 'Initiated' => Time, 'Initiator' => { 'DisplayName' => String, 'ID' => String }, 'Key' => String, 'Owner' => { 'DisplayName' => String, 'ID' => String }, 'StorageClass' => String, 'UploadId' => String }], 'UploadIdMarker' => NilClass, } tests("#list_multipart_uploads('#{@directory.identity})").formats(@list_multipart_uploads_format) do pending if Fog.mocking? Fog::Storage[:internetarchive].list_multipart_uploads(@directory.identity).body end @parts = [] tests("#upload_part('#{@directory.identity}', 'fog_multipart_upload', '#{@upload_id}', 1, ('x' * 6 * 1024 * 1024))").succeeds do pending if Fog.mocking? data = Fog::Storage[:internetarchive].upload_part(@directory.identity, 'fog_multipart_upload', @upload_id, 1, ('x' * 6 * 1024 * 1024)) @parts << data.headers['ETag'] end @list_parts_format = { 'Bucket' => String, 'Initiator' => { 'DisplayName' => String, 'ID' => String }, 'IsTruncated' => Fog::Boolean, 'Key' => String, 'MaxParts' => Integer, 'NextPartNumberMarker' => String, 'Part' => [{ 'ETag' => String, 'LastModified' => Time, 'PartNumber' => Integer, 'Size' => Integer }], 'PartNumberMarker' => String, 'StorageClass' => String, 'UploadId' => String } tests("#list_parts('#{@directory.identity}', 'fog_multipart_upload', '#{@upload_id}')").formats(@list_parts_format) do pending if Fog.mocking? Fog::Storage[:internetarchive].list_parts(@directory.identity, 'fog_multipart_upload', @upload_id).body end if !Fog.mocking? @parts << Fog::Storage[:internetarchive].upload_part(@directory.identity, 'fog_multipart_upload', @upload_id, 2, ('x' * 4 * 1024 * 1024)).headers['ETag'] end @complete_multipart_upload_format = { 'Bucket' => String, 'ETag' => String, 'Key' => String, 'Location' => String } tests("#complete_multipart_upload('#{@directory.identity}', 'fog_multipart_upload', '#{@upload_id}', #{@parts.inspect})").formats(@complete_multipart_upload_format) do pending if Fog.mocking? Fog::Storage[:internetarchive].complete_multipart_upload(@directory.identity, 'fog_multipart_upload', @upload_id, @parts).body end tests("#get_object('#{@directory.identity}', 'fog_multipart_upload').body").succeeds do pending if Fog.mocking? Fog::Storage[:internetarchive].get_object(@directory.identity, 'fog_multipart_upload').body == ('x' * 10 * 1024 * 1024) end if !Fog.mocking? @directory.files.new(:key => 'fog_multipart_upload').destroy end if !Fog.mocking? @upload_id = Fog::Storage[:internetarchive].initiate_multipart_upload(@directory.identity, 'fog_multipart_abort').body['UploadId'] end tests("#abort_multipart_upload('#{@directory.identity}', 'fog_multipart_abort', '#{@upload_id}')").succeeds do pending if Fog.mocking? Fog::Storage[:internetarchive].abort_multipart_upload(@directory.identity, 'fog_multipart_abort', @upload_id) end end tests('failure') do tests("initiate_multipart_upload") tests("list_multipart_uploads") tests("upload_part") tests("list_parts") tests("complete_multipart_upload") tests("abort_multipart_upload") end @directory.destroy end fog-1.19.0/tests/internet_archive/requests/storage/object_tests.rb0000644000004100000410000001646712261242552025453 0ustar www-datawww-dataShindo.tests('InternetArchive::Storage | object requests', ['internet_archive']) do @directory = Fog::Storage[:internetarchive].directories.create(:key => 'fogobjecttests-' + Time.now.to_i.to_s(32)) @ia_owner = Fog::Storage[:internetarchive].get_bucket_acl(@directory.key).body['Owner'] tests('success') do @multiple_delete_format = { 'DeleteResult' => [{ 'Deleted' => { 'Key' => String } }] } tests("#put_object('#{@directory.identity}', 'fog_object', lorem_file)").succeeds do Fog::Storage[:internetarchive].put_object(@directory.identity, 'fog_object', lorem_file) end tests("#copy_object('#{@directory.identity}', 'fog_object', '#{@directory.identity}', 'fog_other_object')").succeeds do Fog::Storage[:internetarchive].copy_object(@directory.identity, 'fog_object', @directory.identity, 'fog_other_object') end @directory.files.get('fog_other_object').destroy tests("#get_object('#{@directory.identity}', 'fog_object')").returns(lorem_file.read) do Fog::Storage[:internetarchive].get_object(@directory.identity, 'fog_object').body end tests("#get_object('#{@directory.identity}', 'fog_object', &block)").returns(lorem_file.read) do data = '' Fog::Storage[:internetarchive].get_object(@directory.identity, 'fog_object') do |chunk, remaining_bytes, total_bytes| data << chunk end data end tests("#get_object('#{@directory.identity}', 'fog_object', {'Range' => 'bytes=0-20'})").returns(lorem_file.read[0..20]) do Fog::Storage[:internetarchive].get_object(@directory.identity, 'fog_object', {'Range' => 'bytes=0-20'}).body end tests("#get_object('#{@directory.identity}', 'fog_object', {'Range' => 'bytes=0-0'})").returns(lorem_file.read[0..0]) do Fog::Storage[:internetarchive].get_object(@directory.identity, 'fog_object', {'Range' => 'bytes=0-0'}).body end tests("#head_object('#{@directory.identity}', 'fog_object')").succeeds do Fog::Storage[:internetarchive].head_object(@directory.identity, 'fog_object') end tests("#put_object_acl('#{@directory.identity}', 'fog_object', 'private')").succeeds do Fog::Storage[:internetarchive].put_object_acl(@directory.identity, 'fog_object', 'private') end acl = { 'Owner' => @ia_owner, 'AccessControlList' => [ { 'Grantee' => @ia_owner, 'Permission' => "FULL_CONTROL" } ]} tests("#put_object_acl('#{@directory.identity}', 'fog_object', hash with id)").returns(acl) do Fog::Storage[:internetarchive].put_object_acl(@directory.identity, 'fog_object', acl) Fog::Storage[:internetarchive].get_object_acl(@directory.identity, 'fog_object').body end tests("#put_object_acl('#{@directory.identity}', 'fog_object', hash with email)").returns({ 'Owner' => @ia_owner, 'AccessControlList' => [ { 'Grantee' => { 'ID' => 'f62f0218873cfa5d56ae9429ae75a592fec4fd22a5f24a20b1038a7db9a8f150', 'DisplayName' => 'mtd' }, 'Permission' => "FULL_CONTROL" } ]}) do pending if Fog.mocking? Fog::Storage[:internetarchive].put_object_acl(@directory.identity, 'fog_object', { 'Owner' => @ia_owner, 'AccessControlList' => [ { 'Grantee' => { 'EmailAddress' => 'mtd@amazon.com' }, 'Permission' => "FULL_CONTROL" } ]}) Fog::Storage[:internetarchive].get_object_acl(@directory.identity, 'fog_object').body end acl = { 'Owner' => @ia_owner, 'AccessControlList' => [ { 'Grantee' => { 'URI' => 'http://acs.amazonaws.com/groups/global/AllUsers' }, 'Permission' => "FULL_CONTROL" } ]} tests("#put_object_acl('#{@directory.identity}', 'fog_object', hash with uri)").returns(acl) do Fog::Storage[:internetarchive].put_object_acl(@directory.identity, 'fog_object', acl) Fog::Storage[:internetarchive].get_object_acl(@directory.identity, 'fog_object').body end tests("#delete_object('#{@directory.identity}', 'fog_object')").succeeds do Fog::Storage[:internetarchive].delete_object(@directory.identity, 'fog_object') end tests("#get_object_http_url('#{@directory.identity}', 'fog_object', expiration timestamp)").returns(true) do object_url = Fog::Storage[:internetarchive].get_object_http_url(@directory.identity, 'fog_object', (Time.now + 60)) puts "get_object_http_url object_url: #{object_url}" (object_url =~ /http:\/\/#{Regexp.quote(@directory.identity)}\.s3\.us\.archive\.org\/fog_object/) != nil end tests("delete_multiple_objects('#{@directory.identity}', ['fog_object', 'fog_other_object'])").formats(@multiple_delete_format) do Fog::Storage[:internetarchive].delete_multiple_objects(@directory.identity, ['fog_object', 'fog_other_object']).body end end tests('failure') do tests("#put_object('fognonbucket', 'fog_non_object', lorem_file)").raises(Excon::Errors::NotFound) do Fog::Storage[:internetarchive].put_object('fognonbucket', 'fog_non_object', lorem_file) end tests("#copy_object('fognonbucket', 'fog_object', '#{@directory.identity}', 'fog_other_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:internetarchive].copy_object('fognonbucket', 'fog_object', @directory.identity, 'fog_other_object') end tests("#copy_object('#{@directory.identity}', 'fog_non_object', '#{@directory.identity}', 'fog_other_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:internetarchive].copy_object(@directory.identity, 'fog_non_object', @directory.identity, 'fog_other_object') end tests("#copy_object('#{@directory.identity}', 'fog_object', 'fognonbucket', 'fog_other_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:internetarchive].copy_object(@directory.identity, 'fog_object', 'fognonbucket', 'fog_other_object') end tests("#get_object('fognonbucket', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:internetarchive].get_object('fognonbucket', 'fog_non_object') end tests("#get_object('#{@directory.identity}', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:internetarchive].get_object(@directory.identity, 'fog_non_object') end tests("#head_object('fognonbucket', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:internetarchive].head_object('fognonbucket', 'fog_non_object') end tests("#head_object('#{@directory.identity}', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:internetarchive].head_object(@directory.identity, 'fog_non_object') end tests("#delete_object('fognonbucket', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:internetarchive].delete_object('fognonbucket', 'fog_non_object') end tests("#delete_multiple_objects('fognonbucket', ['fog_non_object'])").raises(Excon::Errors::NotFound) do pending if Fog.mocking? Fog::Storage[:internetarchive].delete_multiple_objects('fognonbucket', ['fog_non_object']) end tests("#put_object_acl('#{@directory.identity}', 'fog_object', 'invalid')").raises(Excon::Errors::BadRequest) do Fog::Storage[:internetarchive].put_object_acl('#{@directory.identity}', 'fog_object', 'invalid') end end @directory.destroy end fog-1.19.0/tests/internet_archive/requests/storage/acl_utils_tests.rb0000644000004100000410000002315412261242552026153 0ustar www-datawww-datarequire 'fog/internet_archive/requests/storage/acl_utils' Shindo.tests('Fog::Storage::InternetArchive | ACL utils', ["internet_archive"]) do tests(".hash_to_acl") do tests(".hash_to_acl({}) at xpath //AccessControlPolicy").returns("", "has an empty AccessControlPolicy") do xml = Fog::Storage::InternetArchive.hash_to_acl({}) Nokogiri::XML(xml).xpath("//AccessControlPolicy").first.content.chomp end tests(".hash_to_acl({}) at xpath //AccessControlPolicy/Owner").returns(nil, "does not have an Owner element") do xml = Fog::Storage::InternetArchive.hash_to_acl({}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner").first end tests(".hash_to_acl('Owner' => {}) at xpath //AccessControlPolicy/Owner").returns(nil, "does not have an Owner element") do xml = Fog::Storage::InternetArchive.hash_to_acl('Owner' => {}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner").first end tests(".hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'}) at xpath //AccessControlPolicy/Owner/ID").returns("abcdef0123456789", "returns the Owner ID") do xml = Fog::Storage::InternetArchive.hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/ID").first.content end tests(".hash_to_acl('Owner' => {'DisplayName' => 'bob'}) at xpath //AccessControlPolicy/Owner/ID").returns(nil, "does not have an Owner ID element") do xml = Fog::Storage::InternetArchive.hash_to_acl('Owner' => {'DisplayName' => 'bob'}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/ID").first end tests(".hash_to_acl('Owner' => {'DisplayName' => 'bob'}) at xpath //AccessControlPolicy/Owner/DisplayName").returns("bob", "returns the Owner DisplayName") do xml = Fog::Storage::InternetArchive.hash_to_acl('Owner' => {'DisplayName' => 'bob'}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/DisplayName").first.content end tests(".hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'}) at xpath //AccessControlPolicy/Owner/DisplayName").returns(nil, "does not have an Owner DisplayName element") do xml = Fog::Storage::InternetArchive.hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/DisplayName").first end tests(".hash_to_acl({}) at xpath //AccessControlPolicy/AccessControlList").returns(nil, "has no AccessControlList") do xml = Fog::Storage::InternetArchive.hash_to_acl({}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlPolicy").first end acl = { 'AccessControlList' => [ { 'Grantee' => { 'ID' => 'abcdef0123456789', 'DisplayName' => 'bob' }, 'Permission' => 'READ' } ] } tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee").returns("CanonicalUser", "has an xsi:type of CanonicalUser") do xml = Fog::Storage::InternetArchive.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee").first.attributes["type"].value end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/ID").returns("abcdef0123456789", "returns the Grantee ID") do xml = Fog::Storage::InternetArchive.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/ID").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/DisplayName").returns("bob", "returns the Grantee DisplayName") do xml = Fog::Storage::InternetArchive.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/DisplayName").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Permission").returns("READ", "returns the Grantee Permission") do xml = Fog::Storage::InternetArchive.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Permission").first.content end acl = { 'AccessControlList' => [ { 'Grantee' => { 'EmailAddress' => 'user@example.com' }, 'Permission' => 'FULL_CONTROL' } ] } tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee").returns("AmazonCustomerByEmail", "has an xsi:type of AmazonCustomerByEmail") do xml = Fog::Storage::InternetArchive.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee").first.attributes["type"].value end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").returns("user@example.com", "returns the Grantee EmailAddress") do xml = Fog::Storage::InternetArchive.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Permission").returns("FULL_CONTROL", "returns the Grantee Permission") do xml = Fog::Storage::InternetArchive.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Permission").first.content end acl = { 'AccessControlList' => [ { 'Grantee' => { 'URI' => 'http://acs.amazonaws.com/groups/global/AllUsers' }, 'Permission' => 'WRITE' } ] } tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee").returns("Group", "has an xsi:type of Group") do xml = Fog::Storage::InternetArchive.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee").first.attributes["type"].value end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/URI").returns("http://acs.amazonaws.com/groups/global/AllUsers", "returns the Grantee URI") do xml = Fog::Storage::InternetArchive.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/URI").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Permission").returns("WRITE", "returns the Grantee Permission") do xml = Fog::Storage::InternetArchive.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Permission").first.content end acl = { 'AccessControlList' => [ { 'Grantee' => { 'ID' => 'abcdef0123456789', 'DisplayName' => 'bob' }, 'Permission' => 'READ' }, { 'Grantee' => { 'EmailAddress' => 'user@example.com' }, 'Permission' => 'FULL_CONTROL' }, { 'Grantee' => { 'URI' => 'http://acs.amazonaws.com/groups/global/AllUsers' }, 'Permission' => 'WRITE' } ] } tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant").returns(3, "has three elements") do xml = Fog::Storage::InternetArchive.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant").size end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/ID").returns("abcdef0123456789", "returns the first Grant's Grantee ID") do xml = Fog::Storage::InternetArchive.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/ID").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").returns("user@example.com", "returns the second Grant's Grantee EmailAddress") do xml = Fog::Storage::InternetArchive.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/URI").returns("http://acs.amazonaws.com/groups/global/AllUsers", "returns the third Grant's Grantee URI") do xml = Fog::Storage::InternetArchive.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/URI").first.content end end tests(".acl_to_hash") do acl_xml = <<-XML 2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0 me 2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0 me FULL_CONTROL XML tests(".acl_to_hash(#{acl_xml.inspect})").returns({ "Owner" => { "DisplayName" => "me", "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0" }, "AccessControlList" => [{ "Grantee" => { "DisplayName" => "me", "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0" }, "Permission" => "FULL_CONTROL" }] }, 'returns hash of ACL XML') do Fog::Storage::InternetArchive.acl_to_hash(acl_xml) end end end fog-1.19.0/tests/internet_archive/requests/storage/cors_utils_tests.rb0000644000004100000410000001214412261242552026357 0ustar www-datawww-datarequire 'fog/internet_archive/requests/storage/cors_utils' Shindo.tests('Fog::Storage::InternetArchive | CORS utils', ["internet_archive"]) do tests(".hash_to_cors") do tests(".hash_to_cors({}) at xpath //CORSConfiguration").returns("", "has an empty CORSConfiguration") do xml = Fog::Storage::InternetArchive.hash_to_cors({}) Nokogiri::XML(xml).xpath("//CORSConfiguration").first.content.chomp end tests(".hash_to_cors({}) at xpath //CORSConfiguration/CORSRule").returns(nil, "has no CORSRules") do xml = Fog::Storage::InternetArchive.hash_to_cors({}) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule").first end cors = { 'CORSConfiguration' => [ { 'AllowedOrigin' => ['origin_123', 'origin_456'], 'AllowedMethod' => ['GET', 'POST'], 'AllowedHeader' => ['Accept', 'Content-Type'], 'ID' => 'blah-888', 'MaxAgeSeconds' => 2500, 'ExposeHeader' => ['x-some-header', 'x-other-header'] } ] } tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedOrigin").returns("origin_123", "returns the CORSRule AllowedOrigin") do xml = Fog::Storage::InternetArchive.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedOrigin")[0].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedOrigin").returns("origin_456", "returns the CORSRule AllowedOrigin") do xml = Fog::Storage::InternetArchive.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedOrigin")[1].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedMethod").returns("GET", "returns the CORSRule AllowedMethod") do xml = Fog::Storage::InternetArchive.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedMethod")[0].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedMethod").returns("POST", "returns the CORSRule AllowedMethod") do xml = Fog::Storage::InternetArchive.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedMethod")[1].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedHeader").returns("Accept", "returns the CORSRule AllowedHeader") do xml = Fog::Storage::InternetArchive.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedHeader")[0].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedHeader").returns("Content-Type", "returns the CORSRule AllowedHeader") do xml = Fog::Storage::InternetArchive.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedHeader")[1].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/ID").returns("blah-888", "returns the CORSRule ID") do xml = Fog::Storage::InternetArchive.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/ID")[0].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/MaxAgeSeconds").returns("2500", "returns the CORSRule MaxAgeSeconds") do xml = Fog::Storage::InternetArchive.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/MaxAgeSeconds")[0].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/ExposeHeader").returns("x-some-header", "returns the CORSRule ExposeHeader") do xml = Fog::Storage::InternetArchive.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/ExposeHeader")[0].content end tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/ExposeHeader").returns("x-other-header", "returns the CORSRule ExposeHeader") do xml = Fog::Storage::InternetArchive.hash_to_cors(cors) Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/ExposeHeader")[1].content end end tests(".cors_to_hash") do cors_xml = <<-XML http://www.example.com http://www.example2.com Content-Length X-Foobar PUT GET 3000 x-amz-server-side-encryption x-amz-balls XML tests(".cors_to_hash(#{cors_xml.inspect})").returns({ "CORSConfiguration" => [{ "AllowedOrigin" => ["http://www.example.com", "http://www.example2.com"], "AllowedHeader" => ["Content-Length", "X-Foobar"], "AllowedMethod" => ["PUT", "GET"], "MaxAgeSeconds" => 3000, "ExposeHeader" => ["x-amz-server-side-encryption", "x-amz-balls"] }] }, 'returns hash of CORS XML') do Fog::Storage::InternetArchive.cors_to_hash(cors_xml) end end end fog-1.19.0/tests/internet_archive/requests/storage/bucket_tests.rb0000644000004100000410000003042312261242552025446 0ustar www-datawww-dataShindo.tests('Fog::Storage[:internetarchive] | bucket requests', ["internet_archive"]) do @ia_bucket_name = 'fogbuckettests-' + Time.now.to_i.to_s(32) tests('success') do @bucket_format = { 'CommonPrefixes' => [], 'IsTruncated' => Fog::Boolean, 'Marker' => NilClass, 'MaxKeys' => Integer, 'Name' => String, 'Prefix' => NilClass, 'Contents' => [{ 'ETag' => String, 'Key' => String, 'LastModified' => Time, 'Owner' => { 'DisplayName' => String, 'ID' => String }, 'Size' => Integer }] } @bucket_lifecycle_format = { 'Rules' => [{ 'ID' => String, 'Prefix' => Fog::Nullable::String, 'Enabled' => Fog::Boolean, 'Expiration' => Fog::Nullable::Hash, 'Transition' => Fog::Nullable::Hash }] } @service_format = { 'Buckets' => [{ 'CreationDate' => Time, 'Name' => String, }], 'Owner' => { 'DisplayName' => String, 'ID' => String } } tests("#put_bucket('#{@ia_bucket_name}')").succeeds do Fog::Storage[:internetarchive].put_bucket(@ia_bucket_name) @aws_owner = Fog::Storage[:internetarchive].get_bucket_acl(Fog::Storage[:internetarchive].directories.first.key).body['Owner'] end tests("#get_service").formats(@service_format) do Fog::Storage[:internetarchive].get_service.body end dirs = Fog::Storage[:internetarchive].directories.get(@ia_bucket_name) file = Fog::Storage[:internetarchive].directories.get(@ia_bucket_name).files.create(:body => 'y', :key => 'x') tests("#get_bucket('#{@ia_bucket_name}')").formats(@bucket_format) do Fog::Storage[:internetarchive].get_bucket(@ia_bucket_name).body end file.destroy file1 = Fog::Storage[:internetarchive].directories.get(@ia_bucket_name).files.create(:body => 'a', :key => 'a/a1/file1') file2 = Fog::Storage[:internetarchive].directories.get(@ia_bucket_name).files.create(:body => 'ab', :key => 'a/file2') file3 = Fog::Storage[:internetarchive].directories.get(@ia_bucket_name).files.create(:body => 'abc', :key => 'b/file3') file4 = Fog::Storage[:internetarchive].directories.get(@ia_bucket_name).files.create(:body => 'abcd', :key => 'file4') tests("#get_bucket('#{@ia_bucket_name}')") do before do @bucket = Fog::Storage[:internetarchive].get_bucket(@ia_bucket_name) end tests(".body['Contents'].map{|n| n['Key']}").returns(["a/a1/file1", "a/file2", "b/file3", "file4"]) do @bucket.body['Contents'].map{|n| n['Key']} end tests(".body['Contents'].map{|n| n['Size']}").returns([1, 2, 3, 4]) do @bucket.body['Contents'].map{|n| n['Size']} end tests(".body['CommonPrefixes']").returns([]) do @bucket.body['CommonPrefixes'] end end tests("#get_bucket('#{@ia_bucket_name}', 'delimiter' => '/')") do before do @bucket = Fog::Storage[:internetarchive].get_bucket(@ia_bucket_name, 'delimiter' => '/') end tests(".body['Contents'].map{|n| n['Key']}").returns(['file4']) do @bucket.body['Contents'].map{|n| n['Key']} end tests(".body['CommonPrefixes']").returns(['a/', 'b/']) do @bucket.body['CommonPrefixes'] end end tests("#get_bucket('#{@ia_bucket_name}', 'delimiter' => '/', 'prefix' => 'a/')") do before do @bucket = Fog::Storage[:internetarchive].get_bucket(@ia_bucket_name, 'delimiter' => '/', 'prefix' => 'a/') end tests(".body['Contents'].map{|n| n['Key']}").returns(['a/file2']) do @bucket.body['Contents'].map{|n| n['Key']} end tests(".body['CommonPrefixes']").returns(['a/a1/']) do @bucket.body['CommonPrefixes'] end end file1.destroy; file2.destroy; file3.destroy; file4.destroy tests("#get_bucket_location('#{@ia_bucket_name}')").formats('LocationConstraint' => NilClass) do Fog::Storage[:internetarchive].get_bucket_location(@ia_bucket_name).body end tests("#get_request_payment('#{@ia_bucket_name}')").formats('Payer' => String) do Fog::Storage[:internetarchive].get_request_payment(@ia_bucket_name).body end tests("#put_request_payment('#{@ia_bucket_name}', 'Requester')").succeeds do Fog::Storage[:internetarchive].put_request_payment(@ia_bucket_name, 'Requester') end tests("#put_bucket_website('#{@ia_bucket_name}', 'index.html')").succeeds do Fog::Storage[:internetarchive].put_bucket_website(@ia_bucket_name, 'index.html') end tests("#put_bucket_acl('#{@ia_bucket_name}', 'private')").succeeds do Fog::Storage[:internetarchive].put_bucket_acl(@ia_bucket_name, 'private') end acl = { 'Owner' => @aws_owner, 'AccessControlList' => [ { 'Grantee' => @aws_owner, 'Permission' => "FULL_CONTROL" } ] } tests("#put_bucket_acl('#{@ia_bucket_name}', hash with id)").returns(acl) do Fog::Storage[:internetarchive].put_bucket_acl(@ia_bucket_name, acl) Fog::Storage[:internetarchive].get_bucket_acl(@ia_bucket_name).body end tests("#put_bucket_acl('#{@ia_bucket_name}', hash with email)").returns({ 'Owner' => @aws_owner, 'AccessControlList' => [ { 'Grantee' => { 'ID' => 'f62f0218873cfa5d56ae9429ae75a592fec4fd22a5f24a20b1038a7db9a8f150', 'DisplayName' => 'mtd' }, 'Permission' => "FULL_CONTROL" } ] }) do pending if Fog.mocking? Fog::Storage[:internetarchive].put_bucket_acl(@ia_bucket_name, { 'Owner' => @aws_owner, 'AccessControlList' => [ { 'Grantee' => { 'EmailAddress' => 'mtd@amazon.com' }, 'Permission' => "FULL_CONTROL" } ] }) Fog::Storage[:internetarchive].get_bucket_acl(@ia_bucket_name).body end acl = { 'Owner' => @aws_owner, 'AccessControlList' => [ { 'Grantee' => { 'URI' => 'http://acs.amazonaws.com/groups/global/AllUsers' }, 'Permission' => "FULL_CONTROL" } ] } tests("#put_bucket_acl('#{@ia_bucket_name}', hash with uri)").returns(acl) do Fog::Storage[:internetarchive].put_bucket_acl(@ia_bucket_name, acl) Fog::Storage[:internetarchive].get_bucket_acl(@ia_bucket_name).body end tests("#delete_bucket_website('#{@ia_bucket_name}')").succeeds do pending if Fog.mocking? Fog::Storage[:internetarchive].delete_bucket_website(@ia_bucket_name) end tests('bucket lifecycle') do pending if Fog.mocking? lifecycle = {'Rules' => [{'ID' => 'test rule', 'Prefix' => '/prefix', 'Enabled' => true, 'Days' => 42}]} tests('non-existant bucket') do tests('#put_bucket_lifecycle').returns([404, 'NoSuchBucket']) do begin Fog::Storage[:internetarchive].put_bucket_lifecycle('fognonbucket', lifecycle) rescue Excon::Errors::NotFound => e [e.response.status, e.response.body.match(%r{(.*)})[1]] end end tests('#get_bucket_lifecycle').returns([404, 'NoSuchBucket']) do begin Fog::Storage[:internetarchive].get_bucket_lifecycle('fognonbucket') rescue Excon::Errors::NotFound => e [e.response.status, e.response.body.match(%r{(.*)})[1]] end end tests('#delete_bucket_lifecycle').returns([404, 'NoSuchBucket']) do begin Fog::Storage[:internetarchive].delete_bucket_lifecycle('fognonbucket') rescue Excon::Errors::NotFound => e [e.response.status, e.response.body.match(%r{(.*)})[1]] end end end tests('no lifecycle') do tests('#get_bucket_lifecycle').returns([404, 'NoSuchLifecycleConfiguration']) do begin Fog::Storage[:internetarchive].get_bucket_lifecycle(@ia_bucket_name) rescue Excon::Errors::NotFound => e [e.response.status, e.response.body.match(%r{(.*)})[1]] end end tests('#delete_bucket_lifecycle').succeeds do Fog::Storage[:internetarchive].delete_bucket_lifecycle(@ia_bucket_name) end end tests('create').succeeds do Fog::Storage[:internetarchive].put_bucket_lifecycle(@ia_bucket_name, lifecycle) end tests('read').formats(@bucket_lifecycle_format) do Fog::Storage[:internetarchive].get_bucket_lifecycle(@ia_bucket_name).body end lifecycle = { 'Rules' => 5.upto(6).map { |i| {'ID' => "rule\##{i}", 'Prefix' => i.to_s, 'Enabled' => true, 'Days' => i} } } lifecycle_return = { 'Rules' => 5.upto(6).map { |i| {'ID' => "rule\##{i}", 'Prefix' => i.to_s, 'Enabled' => true, 'Expiration' => {'Days' => i}} } } tests('update').returns(lifecycle_return) do Fog::Storage[:internetarchive].put_bucket_lifecycle(@ia_bucket_name, lifecycle) Fog::Storage[:internetarchive].get_bucket_lifecycle(@ia_bucket_name).body end lifecycle = {'Rules' => [{'ID' => 'test rule', 'Prefix' => '/prefix', 'Enabled' => true, 'Expiration' => {'Date' => '2012-12-31T00:00:00.000Z'}}]} tests('date').returns(lifecycle) do Fog::Storage[:internetarchive].put_bucket_lifecycle(@ia_bucket_name, lifecycle) Fog::Storage[:internetarchive].get_bucket_lifecycle(@ia_bucket_name).body end tests('delete').succeeds do Fog::Storage[:internetarchive].delete_bucket_lifecycle(@ia_bucket_name) end tests('read').returns([404, 'NoSuchLifecycleConfiguration']) do begin Fog::Storage[:internetarchive].get_bucket_lifecycle(@ia_bucket_name) rescue Excon::Errors::NotFound => e [e.response.status, e.response.body.match(%r{(.*)})[1]] end end end tests("put_bucket_cors('#{@ia_bucket_name}', cors)").succeeds do cors = {'CORSConfiguration' => [ { 'AllowedOrigin' => 'http://localhost:3000', 'AllowedMethod' => ['POST', 'GET'], 'AllowedHeader' => '*', 'MaxAgeSeconds' => 3000 } ] } Fog::Storage[:internetarchive].put_bucket_cors(@ia_bucket_name, cors) end tests("#delete_bucket('#{@ia_bucket_name}')").succeeds do Fog::Storage[:internetarchive].delete_bucket(@ia_bucket_name) end end # tests('failure') do # tests("#delete_bucket('fognonbucket')").raises(Excon::Errors::NotFound) do # Fog::Storage[:internetarchive].delete_bucket('fognonbucket') # end # @fognonempty = "fognonempty-#{rand(65536)}" # @bucket = Fog::Storage[:internetarchive].directories.create(:key => "fognonempty-#{rand(65536)}") # @file = @bucket.files.create(:key => 'foo', :body => 'bar') # tests("#delete_bucket('fognonempty')").raises(Excon::Errors::Conflict) do # Fog::Storage[:internetarchive].delete_bucket('fognonempty') # end # @file.destroy # @bucket.destroy # tests("#get_bucket('fognonbucket')").raises(Excon::Errors::NotFound) do # Fog::Storage[:internetarchive].get_bucket('fognonbucket') # end # tests("#get_bucket_location('fognonbucket')").raises(Excon::Errors::NotFound) do # Fog::Storage[:internetarchive].get_bucket_location('fognonbucket') # end # tests("#get_request_payment('fognonbucket')").raises(Excon::Errors::NotFound) do # Fog::Storage[:internetarchive].get_request_payment('fognonbucket') # end # tests("#put_request_payment('fognonbucket', 'Requester')").raises(Excon::Errors::NotFound) do # Fog::Storage[:internetarchive].put_request_payment('fognonbucket', 'Requester') # end # tests("#put_bucket_acl('fognonbucket', 'invalid')").raises(Excon::Errors::BadRequest) do # Fog::Storage[:internetarchive].put_bucket_acl('fognonbucket', 'invalid') # end # tests("#put_bucket_website('fognonbucket', 'index.html')").raises(Excon::Errors::NotFound) do # Fog::Storage[:internetarchive].put_bucket_website('fognonbucket', 'index.html') # end # end # don't keep the bucket around # Fog::Storage[:internetarchive].delete_bucket(@ia_bucket_name) rescue nil end fog-1.19.0/tests/internet_archive/models/0000755000004100000410000000000012261242552020364 5ustar www-datawww-datafog-1.19.0/tests/internet_archive/models/storage/0000755000004100000410000000000012261242552022030 5ustar www-datawww-datafog-1.19.0/tests/internet_archive/models/storage/file_tests.rb0000644000004100000410000000306712261242552024524 0ustar www-datawww-dataShindo.tests("Storage[:internet_archive] | file", ["internet_archive"]) do # Fog.mock! require 'tempfile' file_attributes = { :key => 'fog_file_tests', :body => lorem_file, :public => true, :auto_make_bucket => 1, } directory_attributes = { # Add a random suffix to prevent collision :key => "fogfilestests-#{rand(65536)}", :collections => ['test_collection'] } @directory = Fog::Storage[:internetarchive].directories.create(directory_attributes) model_tests(@directory.files, file_attributes, Fog.mocking?) do tests("#set_metadata_array_headers") do @instance.collections = ['test_collection', 'opensource'] @options = {} @instance.set_metadata_array_headers(:collections, @options) tests("#set_metadata_array_headers should set options").returns(true) do @options['x-archive-meta01-collection'] == 'opensource' && @options['x-archive-meta02-collection'] == 'test_collection' end end end model_tests(@directory.files, file_attributes, Fog.mocking?) do tests("multipart upload") do pending if Fog.mocking? # A 6MB file @large_file = Tempfile.new("fog-test-ia-s3-multipart") 6.times { @large_file.write("x" * (1024**2)) } @large_file.rewind tests("#save(:multipart_chunk_size => 5242880)").succeeds do @directory.files.create(:key => 'multipart-upload', :body => @large_file, :multipart_chunk_size => 5242880) end @large_file.close end end # @directory.versions.each(&:destroy) @directory.destroy end fog-1.19.0/tests/internet_archive/models/storage/directory_tests.rb0000644000004100000410000000225712261242552025611 0ustar www-datawww-dataShindo.tests("Storage[:internet_archive] | directory", ["internet_archive"]) do directory_attributes = { :key => "fogdirectorytests-#{rand(65536)}", :collections => ['test_collection'] } tests('success') do params = directory_attributes mocks_implemented = Fog.mocking? collection = Fog::Storage[:internetarchive].directories @instance = collection.new(params) tests("#save").succeeds do pending if Fog.mocking? && !mocks_implemented @instance.save end tests("#public_url").returns("http://archive.org/details/#{directory_attributes[:key]}") do @instance.public_url end end tests("#set_metadata_array_headers") do params = directory_attributes collection = Fog::Storage[:internetarchive].directories @instance = collection.new(params) @instance.collections = ['test_collection', 'opensource'] @options = {} @instance.set_metadata_array_headers(:collections, @options) tests("#set_metadata_array_headers should set options").returns(true) do @options['x-archive-meta01-collection'] == 'opensource' && @options['x-archive-meta02-collection'] == 'test_collection' end end end fog-1.19.0/tests/internet_archive/models/storage/files_tests.rb0000644000004100000410000000365212261242552024707 0ustar www-datawww-dataShindo.tests("Storage[:internet_archive] | files", ["internet_archive"]) do file_attributes = { :key => 'fog_file_tests', :body => lorem_file, :public => true, :auto_make_bucket => 1, :collections => ['test_collection'] } directory_attributes = { :key => "fogfilestests-#{rand(65536)}" } @directory = Fog::Storage[:internetarchive].directories.create(directory_attributes) # @directory.versioning = true model_tests(@directory.files, file_attributes, Fog.mocking?) do @instance # v2 = @directory.connection.put_object(@directory.key, @instance.key, 'version 2 content').headers['x-amz-version-id'] # v3 = @directory.connection.delete_object(@directory.key, @instance.key).headers['x-amz-version-id'] # v4 = @directory.connection.put_object(@directory.key, @instance.key, 'version 3 content').headers['x-amz-version-id'] # tests("#get") do # tests("#get without version fetches the latest version").returns(v4) do # @directory.files.get(@instance.key).version # end # tests("#get with version fetches that exact version").returns(v2) do # @directory.files.get(@instance.key, 'versionId' => v2).version # end # tests("#get with a deleted version returns nil").returns(nil) do # @directory.files.get(@instance.key, 'versionId' => v3) # end # end # tests("#head") do # tests("#head without version fetches the latest version").returns(v4) do # @directory.files.head(@instance.key).version # end # tests("#head with version fetches that exact version").returns(v2) do # @directory.files.head(@instance.key, 'versionId' => v2).version # end # tests("#head with a deleted version returns nil").returns(nil) do # @directory.files.head(@instance.key, 'versionId' => v3) # end # end end # @directory.versions.each(&:destroy) # @directory.destroy end fog-1.19.0/tests/internet_archive/models/storage/url_tests.rb0000644000004100000410000000146412261242552024406 0ustar www-datawww-data# encoding: utf-8 Shindo.tests('InternetArchive | url', ["internet_archive"]) do @expires = Time.utc(2013,1,1).utc.to_i @storage = Fog::Storage.new( :provider => 'InternetArchive', :ia_access_key_id => '123', :ia_secret_access_key => 'abc', :region => 'us-east-1' ) @file = @storage.directories.new(:key => 'fognonbucket').files.new(:key => 'test.txt') if Fog.mock? signature = Fog::Storage::InternetArchive.new.signature(nil) else signature = 'tajHIhKHAdFYsigmzybCpaq8N0Q%3D' end tests('#url w/ response-cache-control').returns( "http://fognonbucket.s3.us.archive.org/test.txt?response-cache-control=No-cache&AWSAccessKeyId=123&Signature=#{signature}&Expires=1356998400" ) do @file.url(@expires, :query => { 'response-cache-control' => 'No-cache' }) end end fog-1.19.0/tests/internet_archive/signed_params_tests.rb0000644000004100000410000000032012261242552023457 0ustar www-datawww-data# encoding: utf-8 Shindo.tests('InternetArchive | signed_params', ['internet_archive']) do returns( Fog::InternetArchive.escape( "'Stöp!' said Fred_-~." ) ) { "%27St%C3%B6p%21%27%20said%20Fred_-~." } end fog-1.19.0/tests/watchr.rb0000644000004100000410000000070712261242552015371 0ustar www-datawww-dataENV['FOG_MOCK'] ||= 'true' ENV['AUTOTEST'] = 'true' ENV['WATCHR'] = '1' def file2shindo(file) result = file.sub('lib/fog/', 'tests/').gsub(/\.rb$/, '_tests.rb') end def run_shindo_test(file) if File.exist? file system("shindont #{file}") else puts "FIXME: No test #{file} [#{Time.now}]" end end watch( 'tests/.*_tests\.rb' ) do |md| run_shindo_test(md[0]) end watch( 'lib/.*\.rb' ) do |md| run_shindo_test(file2shindo(md[0])) end fog-1.19.0/tests/vsphere/0000755000004100000410000000000012261242552015224 5ustar www-datawww-datafog-1.19.0/tests/vsphere/requests/0000755000004100000410000000000012261242552017077 5ustar www-datawww-datafog-1.19.0/tests/vsphere/requests/compute/0000755000004100000410000000000012261242552020553 5ustar www-datawww-datafog-1.19.0/tests/vsphere/requests/compute/vm_reboot_tests.rb0000644000004100000410000000177012261242552024323 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere] | vm_reboot request', ['vsphere']) do compute = Fog::Compute[:vsphere] powered_on_vm = '5032c8a5-9c5e-ba7a-3804-832a03e16381' tests('The response should') do response = compute.vm_reboot('instance_uuid' => powered_on_vm) test('be a kind of Hash') { response.kind_of? Hash } test('should have a task_state key') { response.has_key? 'task_state' } test('should have a reboot_type key') { response.has_key? 'reboot_type' } end # When forcing the shutdown, we expect the result to be { true => 'reset_power', false => 'reboot_guest'}.each do |force, expected| tests("When force => #{force}") do response = compute.vm_reboot('instance_uuid' => powered_on_vm, 'force' => force) test("should return reboot_type of #{expected}") { response['reboot_type'] == expected } end end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when instance_uuid option is missing') { compute.vm_reboot } end end fog-1.19.0/tests/vsphere/requests/compute/set_vm_customvalue_tests.rb0000644000004100000410000000146312261242552026252 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere] | set_vm_customvalue request', ['vsphere']) do compute = Fog::Compute[:vsphere] instance_uuid = '50137835-88a1-436e-768e-9b2677076e67' custom_key = nil custom_value = nil tests('The response should') do response = compute.set_vm_customvalue(instance_uuid, custom_key, custom_value) test('be nil') { response.nil? } end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when instance_uuid option is missing') { compute.set_vm_customvalue } raises(ArgumentError, 'raises ArgumentError when custom_key option is missing') { compute.set_vm_customvalue(instance_uuid) } raises(ArgumentError, 'raises ArgumentError when custom_value option is missing') { compute.set_vm_customvalue(instance_uuid, custom_key) } end end fog-1.19.0/tests/vsphere/requests/compute/vm_migrate_tests.rb0000644000004100000410000000107212261242552024454 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere] | vm_migrate request', ['vsphere']) do compute = Fog::Compute[:vsphere] powered_on_vm = '50137835-88a1-436e-768e-9b2677076e67' tests('The response should') do response = compute.vm_migrate('instance_uuid' => powered_on_vm) test('be a kind of Hash') { response.kind_of? Hash } test('should have a task_state key') { response.has_key? 'task_state' } end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when instance_uuid option is missing') { compute.vm_migrate } end end fog-1.19.0/tests/vsphere/requests/compute/vm_config_vnc_tests.rb0000644000004100000410000000133512261242552025141 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere] | vm_config_vnc request', ['vsphere']) do compute = Fog::Compute[:vsphere] reconfig_target = '50137835-88a1-436e-768e-9b2677076e67' vnc_spec = {:port => '5900', :password => 'ssaaa', :enabled => 'true'} tests('The response should') do response = compute.vm_config_vnc('instance_uuid' => reconfig_target).merge(vnc_spec) test('be a kind of Hash') { response.kind_of? Hash } test('should have a task_state key') { response.has_key? 'task_state' } end tests('VNC attrs response should') do response = compute.vm_get_vnc(reconfig_target) test('be a kind of Hash') { response.kind_of? Hash } test('should have a port key') { response.has_key? :port } end end fog-1.19.0/tests/vsphere/requests/compute/vm_reconfig_hardware_tests.rb0000644000004100000410000000155412261242552026502 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere] | vm_reconfig_hardware request', ['vsphere']) do compute = Fog::Compute[:vsphere] reconfig_target = '50137835-88a1-436e-768e-9b2677076e67' reconfig_spec = {'guestId' => 'rhel5_64Guest'} tests('The response should') do response = compute.vm_reconfig_hardware('instance_uuid' => reconfig_target, 'hardware_spec' => reconfig_spec) test('be a kind of Hash') { response.kind_of? Hash } test('should have a task_state key') { response.has_key? 'task_state' } end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when instance_uuid option is missing') { compute.vm_reconfig_hardware('hardware_spec' => reconfig_spec) } raises(ArgumentError, 'raises ArgumentError when hardware_spec option is missing') { compute.vm_reconfig_hardware('instance_uuid' => reconfig_target) } end end fog-1.19.0/tests/vsphere/requests/compute/vm_clone_tests.rb0000644000004100000410000000470112261242552024126 0ustar www-datawww-dataShindo.tests("Fog::Compute[:vsphere] | vm_clone request", 'vsphere') do # require 'guid' compute = Fog::Compute[:vsphere] response = nil response_linked = nil template = "rhel64" datacenter = "Solutions" tests("Standard Clone | The return value should") do servers_size = compute.servers.size response = compute.vm_clone('datacenter' => datacenter, 'template_path' => template, 'name' => 'cloning_vm', 'wait' => true) test("be a kind of Hash") { response.kind_of? Hash } %w{ vm_ref new_vm task_ref }.each do |key| test("have a #{key} key") { response.has_key? key } end test("creates a new server") { compute.servers.size == servers_size+1 } test("new server name is set") { compute.get_virtual_machine(response['new_vm']['id'])['name'] == 'cloning_vm' } end tests("Standard Clone setting ram and cpu | The return value should") do servers_size = compute.servers.size response = compute.vm_clone('datacenter' => datacenter, 'template_path' => template, 'name' => 'cloning_vm', 'memoryMB' => '8192', 'numCPUs' => '8', 'wait' => true) test("be a kind of Hash") { response.kind_of? Hash } %w{ vm_ref new_vm task_ref }.each do |key| test("have a #{key} key") { response.has_key? key } end test("creates a new server") { compute.servers.size == servers_size+1 } test("new server name is set") { compute.get_virtual_machine(response['new_vm']['id'])['name'] == 'cloning_vm' } end tests("Linked Clone | The return value should") do servers_size = compute.servers.size response = compute.vm_clone('datacenter' => datacenter, 'template_path' => template, 'name' => 'cloning_vm_linked', 'wait' => 1, 'linked_clone' => true) test("be a kind of Hash") { response.kind_of? Hash } %w{ vm_ref new_vm task_ref }.each do |key| test("have a #{key} key") { response.has_key? key } end test("creates a new server") { compute.servers.size == servers_size+1 } test("new server name is set") { compute.get_virtual_machine(response['new_vm']['id'])['name'] == 'cloning_vm_linked' } end tests("When invalid input is presented") do raises(ArgumentError, 'it should raise ArgumentError') { compute.vm_clone(:foo => 1) } raises(Fog::Compute::Vsphere::NotFound, 'it should raise Fog::Compute::Vsphere::NotFound when the UUID is not a string') do pending # require 'guid' compute.vm_clone('instance_uuid' => Guid.from_s(template), 'name' => 'jefftestfoo') end end end fog-1.19.0/tests/vsphere/requests/compute/vm_reconfig_cpus_tests.rb0000644000004100000410000000144412261242552025655 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere] | vm_reconfig_cpus request', ['vsphere']) do compute = Fog::Compute[:vsphere] reconfig_target = '50137835-88a1-436e-768e-9b2677076e67' reconfig_spec = 2 tests('The response should') do response = compute.vm_reconfig_cpus('instance_uuid' => reconfig_target, 'cpus' => reconfig_spec) test('be a kind of Hash') { response.kind_of? Hash } test('should have a task_state key') { response.has_key? 'task_state' } end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when instance_uuid option is missing') { compute.vm_reconfig_cpus('cpus' => reconfig_spec) } raises(ArgumentError, 'raises ArgumentError when cpus option is missing') { compute.vm_reconfig_cpus('instance_uuid' => reconfig_target) } end end fog-1.19.0/tests/vsphere/requests/compute/vm_power_off_tests.rb0000644000004100000410000000202112261242552025005 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere] | vm_power_off request', ['vsphere']) do compute = Fog::Compute[:vsphere] powered_on_vm = '5032c8a5-9c5e-ba7a-3804-832a03e16381' tests('The response should') do response = compute.vm_power_off('instance_uuid' => powered_on_vm) test('be a kind of Hash') { response.kind_of? Hash } test('should have a task_state key') { response.has_key? 'task_state' } test('should have a power_off_type key') { response.has_key? 'power_off_type' } end # When forcing the shutdown, we expect the result to be { true => 'cut_power', false => 'shutdown_guest'}.each do |force, expected| tests("When 'force' => #{force}") do response = compute.vm_power_off('instance_uuid' => powered_on_vm, 'force' => force) test('should retur power_off_type of #{expected}') { response['power_off_type'] == expected } end end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when instance_uuid option is missing') { compute.vm_power_off } end end fog-1.19.0/tests/vsphere/requests/compute/vm_power_on_tests.rb0000644000004100000410000000103312261242552024651 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere] | vm_power_on request', ['vsphere']) do compute = Fog::Compute[:vsphere] powered_off_vm = nil tests('The response should') do response = compute.vm_power_on('instance_uuid' => powered_off_vm) test('be a kind of Hash') { response.kind_of? Hash } test('should have a task_state key') { response.has_key? 'task_state' } end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when instance_uuid option is missing') { compute.vm_power_on } end end fog-1.19.0/tests/vsphere/requests/compute/vm_destroy_tests.rb0000644000004100000410000000106112261242552024513 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere] | vm_destroy request', ['vsphere']) do compute = Fog::Compute[:vsphere] booted_vm = '5032c8a5-9c5e-ba7a-3804-832a03e16381' tests('The response should') do response = compute.vm_destroy('instance_uuid' => booted_vm) test('be a kind of Hash') { response.kind_of? Hash } test('should have a task_state key') { response.has_key? 'task_state' } end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when instance_uuid option is missing') { compute.vm_destroy } end end fog-1.19.0/tests/vsphere/requests/compute/list_virtual_machines_tests.rb0000644000004100000410000000225512261242552026716 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere] | list_virtual_machines request', ['vsphere']) do tests("When listing all machines") do response = Fog::Compute[:vsphere].list_virtual_machines tests("The response data format ...") do test("be a kind of Hash") { response.kind_of? Array } end end tests("When providing an instance_uuid") do # pending unless Fog.mock? tests("that does exist") do uuid = "5029c440-85ee-c2a1-e9dd-b63e39364603" response = Fog::Compute[:vsphere].list_virtual_machines({'instance_uuid' => uuid}) tests("The response should") do test("contain one vm") { response.length == 1 } test("contain that is an attribute hash") { response[0].kind_of? Hash } test("find jefftest") { response.first['name'] == 'jefftest' } end end tests("that does not exist or is a template") do %w{ does-not-exist-and-is-not-a-uuid 50323f93-6835-1178-8b8f-9e2109890e1a }.each do |uuid| response = Fog::Compute[:vsphere].list_virtual_machines({'instance_uuid' => uuid}) tests("The response should") do test("be empty") { response.empty? } end end end end end fog-1.19.0/tests/vsphere/requests/compute/current_time_tests.rb0000644000004100000410000000064712261242552025031 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere] | current_time request', ['vsphere']) do compute = Fog::Compute[:vsphere] tests('The response should') do response = compute.current_time test('be a kind of Hash') { response.kind_of? Hash } test('have a current_time key') { response.has_key? 'current_time' } test('have a current_time key with a Time value') { response['current_time'].kind_of? Time } end end fog-1.19.0/tests/vsphere/requests/compute/vm_reconfig_memory_tests.rb0000644000004100000410000000146512261242552026216 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere] | vm_reconfig_memory request', ['vsphere']) do compute = Fog::Compute[:vsphere] reconfig_target = '50137835-88a1-436e-768e-9b2677076e67' reconfig_spec = 4096 tests('The response should') do response = compute.vm_reconfig_memory('instance_uuid' => reconfig_target, 'memory' => reconfig_spec) test('be a kind of Hash') { response.kind_of? Hash } test('should have a task_state key') { response.has_key? 'task_state' } end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when instance_uuid option is missing') { compute.vm_reconfig_memory('memory' => reconfig_spec) } raises(ArgumentError, 'raises ArgumentError when memory option is missing') { compute.vm_reconfig_memory('instance_uuid' => reconfig_target) } end end fog-1.19.0/tests/vsphere/compute_tests.rb0000644000004100000410000000316612261242552020455 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere]', ['vsphere']) do compute = Fog::Compute[:vsphere] tests("| convert_vm_mob_ref_to_attr_hash") do # Mock the RbVmomi::VIM::ManagedObject class class MockManagedObject attr_reader :parent, :_ref def initialize @parent = @_ref = 'vm-123' end def collect! *pathSet { '_ref' => 'vm-123', 'name' => 'fakevm' } end end fake_vm_mob_ref = MockManagedObject.new tests("When converting an incomplete vm object") do test("it should return a Hash") do compute.send(:convert_vm_mob_ref_to_attr_hash, fake_vm_mob_ref).kind_of? Hash end tests("The converted Hash should") do attr_hash = compute.send(:convert_vm_mob_ref_to_attr_hash, fake_vm_mob_ref) test("have a name") { attr_hash['name'] == 'fakevm' } test("have a mo_ref") {attr_hash['mo_ref'] == 'vm-123' } test("have an id") { attr_hash['id'] == 'vm-123' } test("not have a instance_uuid") { attr_hash['instance_uuid'].nil? } end end tests("When passed a nil object") do attr_hash = compute.send :convert_vm_mob_ref_to_attr_hash, nil test("it should return a nil object") do attr_hash.nil? end end end tests("Compute attributes") do %w{ vsphere_is_vcenter vsphere_rev vsphere_username vsphere_server }.each do |attr| test("it should respond to #{attr}") { compute.respond_to? attr } end end tests("Compute collections") do %w{ servers }.each do |collection| test("it should respond to #{collection}") { compute.respond_to? collection } end end end fog-1.19.0/tests/vsphere/models/0000755000004100000410000000000012261242552016507 5ustar www-datawww-datafog-1.19.0/tests/vsphere/models/compute/0000755000004100000410000000000012261242552020163 5ustar www-datawww-datafog-1.19.0/tests/vsphere/models/compute/server_tests.rb0000644000004100000410000000252012261242552023237 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere] | server model', ['vsphere']) do servers = Fog::Compute[:vsphere].servers server = servers.last tests('The server model should') do tests('have the action') do test('reload') { server.respond_to? 'reload' } %w{ stop start destroy reboot }.each do |action| test(action) { server.respond_to? action } test("#{action} returns successfully") { server.send(action.to_sym) ? true : false } end end tests('have attributes') do model_attribute_hash = server.attributes attributes = [ :id, :instance_uuid, :uuid, :power_state, :tools_state, :mo_ref, :tools_version, :hostname, :mac_addresses, :operatingsystem, :connection_state, :hypervisor, :name, :public_ip_address] tests("The server model should respond to") do attributes.each do |attribute| test("#{attribute}") { server.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::Vsphere::Server') { server.kind_of? Fog::Compute::Vsphere::Server } end end fog-1.19.0/tests/vsphere/models/compute/servers_tests.rb0000644000004100000410000000117712261242552023431 0ustar www-datawww-dataShindo.tests('Fog::Compute[:vsphere] | servers collection', ['vsphere']) do servers = Fog::Compute[:vsphere].servers tests('The servers collection') do test('should not be empty') { not servers.empty? } test('should be a kind of Fog::Compute::Vsphere::Servers') { servers.kind_of? Fog::Compute::Vsphere::Servers } tests('should be able to reload itself').succeeds { servers.reload } tests('should be able to get a model') do tests('by managed object reference').succeeds { servers.get 'vm-715' } tests('by instance uuid').succeeds { servers.get '5032c8a5-9c5e-ba7a-3804-832a03e16381' } end end end fog-1.19.0/tests/dns/0000755000004100000410000000000012261242552014334 5ustar www-datawww-datafog-1.19.0/tests/dns/helper.rb0000644000004100000410000000204312261242552016137 0ustar www-datawww-datadef dns_providers { :aws => { :mocked => false }, :bluebox => { :mocked => false, :zone_attributes => { :ttl => 60 } }, :dnsimple => { :mocked => false }, :dnsmadeeasy => { :mocked => false }, :dynect => { :mocked => false, :zone_attributes => { :email => 'fog@example.com' } }, :linode => { :mocked => false, :zone_attributes => { :email => 'fog@example.com' } }, :zerigo => { :mocked => false }, :rackspace => { :mocked => false, :zone_attributes => { :email => 'fog@example.com' } } } end def generate_unique_domain( with_trailing_dot = false) #get time (with 1/100th of sec accuracy) #want unique domain name and if provider is fast, this can be called more than once per second time= (Time.now.to_f * 100).to_i domain = 'test-' + time.to_s + '.com' if with_trailing_dot domain+= '.' end domain end fog-1.19.0/tests/dns/models/0000755000004100000410000000000012261242552015617 5ustar www-datawww-datafog-1.19.0/tests/dns/models/zones_tests.rb0000644000004100000410000000064512261242552020531 0ustar www-datawww-datafor provider, config in dns_providers # FIXME: delay/timing breaks things :( next if [:dnsmadeeasy].include?(provider) domain_name = uniq_id + '.com' Shindo.tests("Fog::DNS[:#{provider}] | zones", [provider.to_s]) do zone_attributes = { :domain => domain_name }.merge!(config[:zone_attributes] || {}) collection_tests(Fog::DNS[provider].zones, zone_attributes, config[:mocked]) end end fog-1.19.0/tests/dns/models/zone_tests.rb0000644000004100000410000000063712261242552020347 0ustar www-datawww-datafor provider, config in dns_providers # FIXME: delay/timing breaks things :( next if [:dnsmadeeasy].include?(provider) domain_name = uniq_id + '.com' Shindo.tests("Fog::DNS[:#{provider}] | zone", [provider.to_s]) do zone_attributes = { :domain => domain_name }.merge!(config[:zone_attributes] || {}) model_tests(Fog::DNS[provider].zones, zone_attributes, config[:mocked]) end end fog-1.19.0/tests/dns/models/records_tests.rb0000644000004100000410000000131412261242552021026 0ustar www-datawww-datafor provider, config in dns_providers # FIXME: delay/timing breaks things :( next if [:dnsmadeeasy].include?(provider) domain_name = uniq_id + '.com' Shindo.tests("Fog::DNS[:#{provider}] | records", [provider.to_s]) do record_attributes = { :name => 'www.' + domain_name, :type => 'A', :value => '1.2.3.4' }.merge!(config[:record_attributes] || {}) if !Fog.mocking? || config[:mocked] zone_attributes = { :domain => domain_name }.merge(config[:zone_attributes] || {}) @zone = Fog::DNS[provider].zones.create(zone_attributes) collection_tests(@zone.records, record_attributes, config[:mocked]) @zone.destroy end end end fog-1.19.0/tests/dns/models/record_tests.rb0000644000004100000410000000234212261242552020645 0ustar www-datawww-datafor provider, config in dns_providers # FIXME: delay/timing breaks things :( next if [:dnsmadeeasy].include?(provider) domain_name = uniq_id + '.com' Shindo.tests("Fog::DNS[:#{provider}] | record", [provider.to_s]) do a_record_attributes = { :name => 'a.' + domain_name, :type => 'A', :value => '1.2.3.4' }.merge!(config[:record_attributes] || {}) aaaa_record_attributes = { :name => 'aaaa.' + domain_name, :type => 'AAAA', :value => '2001:0db8:0000:0000:0000:ff00:0042:8329' }.merge!(config[:record_attributes] || {}) cname_record_attributes = { :name => 'cname.' + domain_name, :type => 'CNAME', :value => 'real.' + domain_name }.merge!(config[:record_attributes] || {}) if !Fog.mocking? || config[:mocked] zone_attributes = { :domain => domain_name }.merge(config[:zone_attributes] || {}) @zone = Fog::DNS[provider].zones.create(zone_attributes) model_tests(@zone.records, a_record_attributes, config[:mocked]) model_tests(@zone.records, aaaa_record_attributes, config[:mocked]) model_tests(@zone.records, cname_record_attributes, config[:mocked]) @zone.destroy end end end fog-1.19.0/tests/joyent/0000755000004100000410000000000012261242552015060 5ustar www-datawww-datafog-1.19.0/tests/joyent/requests/0000755000004100000410000000000012261242552016733 5ustar www-datawww-datafog-1.19.0/tests/joyent/requests/compute/0000755000004100000410000000000012261242552020407 5ustar www-datawww-datafog-1.19.0/tests/joyent/requests/compute/keys_tests.rb0000644000004100000410000000275512261242552023142 0ustar www-datawww-dataShindo.tests("Fog::Compute[:joyent] | key requests", ['joyent']) do @key_format = { "name" => String, "key" => String, "created" => Time, "updated" => Time } before do # # Clear out all the test keys on the account in prep for test # Fog::Compute[:joyent].list_keys.body.each do |key| if key["name"] =~ /^fog-test/ Fog::Compute[:joyent].delete_key(key["name"]) end end @test_key_name = "fog-test-#{Time.now.utc.to_i}" Fog::Compute[:joyent].create_key( :name => @test_key_name, :key => "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDWxSNYngOTeu0pYd+2tpfYGISuMfMUNGyAIh4yRprAbacVddRq4Nyr12vDklzaRTzgd9PgX/82JMb4RARbVTtUKXJXmaBLvg2epGM+ScanZIitzL53whJrlGx+7nT+TnRdkB1XG7uIf2EpTQBaKrT4iG0magCXh5bmOqCyWte2gV8fArMg5bZclUT1p2E7qEW0htaLOiMSyGkjBlxb6vYQCA/Pa8VWETHehIF46S942gCj0aaL81gTocfyTm5/F+AgvUAsjHzRVkB/Dlhwq7Q7sK+4iAhlKPYMflkKC8r+nF0/LL9S3lllLZvbkEWJfEqlMCAbgmjTpYlBzQEqf/eN" ) end tests("#list_keys").formats(@key_format) do Fog::Compute[:joyent].list_keys.body.first end tests("#get_key").formats(@key_format) do Fog::Compute[:joyent].get_key(@test_key_name).body end tests("#delete_key") do returns(204 , "returns status code 204") do Fog::Compute[:joyent].delete_key(@test_key_name).status end raises(Excon::Errors::NotFound, "when a key no longer exists") do Fog::Compute[:joyent].delete_key(@test_key_name) Fog::Compute[:joyent].delete_key(@test_key_name) end end end fog-1.19.0/tests/joyent/requests/compute/networks_tests.rb0000644000004100000410000000177012261242552024037 0ustar www-datawww-dataShindo.tests("Fog::Compute[:joyent] | network requests", ["joyent"]) do @provider = Fog::Compute[:joyent] @network_format = { "id" => String, "name" => String, "public" => Fog::Boolean } if Fog.mock? @networks = Fog::Compute[:joyent].data[:networks] = { "193d6804-256c-4e89-a4cd-46f045959993" => { "id" => "193d6804-256c-4e89-a4cd-46f045959993", "name" => "Joyent-SDC-Private", "public" => false }, "1e7bb0e1-25a9-43b6-bb19-f79ae9540b39" => { "id" => "1e7bb0e1-25a9-43b6-bb19-f79ae9540b39", "name" => "Joyent-SDC-Public", "public" => true } } end tests("#list_networks") do if Fog.mock? returns(@networks.length, "correct number of networks") do @provider.list_networks.body.length end end returns(Array, "returns an Array of networks") do @provider.list_networks.body.class end formats([@network_format]) do @provider.list_networks.body end end end fog-1.19.0/tests/joyent/requests/compute/datasets_tests.rb0000644000004100000410000000324012261242552023765 0ustar www-datawww-dataShindo.tests("Fog::Compute[:joyent] | dataset requests", ["joyent"]) do @dataset_format = { "description" => String, "requirements" => { "max_memory" => Integer, "min_memory" => Integer }, "name" => String, "version" => String, "os" => String, "id" => String, "urn" => String, "default" => Fog::Boolean, "type" => String, "created" => Time, } if Fog.mock? Fog::Compute[:joyent].data[:datasets] = { "33904834-1f01-49d3-bed3-b642e158c375" => { "id" => "33904834-1f01-49d3-bed3-b642e158c375", "urn" => "sdc:sdc:zeus-simple-lb-200mbps:1.1.1", "name" => "zeus-simple-lb-200mbps", "os" => "smartos", "type" => "smartmachine", "description" => "Zeus Simple Load Balancer 200 Mbps SmartMachine", "default" => false, "requirements" => { "max_memory" => 32768, "min_memory" => 4096 }, "version" => "1.1.1", "created" => Time.parse("2011-09-15T07:39:13+00:00") }, "3fcf35d2-dd79-11e0-bdcd-b3c7ac8aeea6" => { "id" => "3fcf35d2-dd79-11e0-bdcd-b3c7ac8aeea6", "urn" => "sdc:sdc:mysql:1.4.1", "name" => "mysql", "os" => "smartos", "type" => "smartmachine", "description" => "MySQL SmartMachine", "default" => false, "requirements" => { "max_memory" => 32768, "min_memory" => 4096 }, "version" => "1.4.1", "created" => Time.parse("2011-09-15T05:01:34+00:00") } } end tests("#list_datasets") do formats(@dataset_format) do Fog::Compute[:joyent].list_datasets.body.first end end end fog-1.19.0/tests/joyent/requests/compute/machines_tests.rb0000644000004100000410000000323012261242552023743 0ustar www-datawww-dataShindo.tests("Fog::Compute[:joyent] | machine requests", ["joyent"]) do @machine_format = { "id" => String, "name" => String, "type" => String, "state" => String, "dataset" => String, "memory" => Integer, "disk" => Integer, "ips" => Array, "metadata" => Hash, "created" => Time, "updated" => Time } if Fog.mock? @machines = Fog::Compute[:joyent].data[:machines] = { "15080eca-3786-4bb8-a4d0-f43e1981cd72" => { "id" => "15080eca-3786-4bb8-a4d0-f43e1981cd72", "name" => "getting-started", "type" => "smartmachine", "state" => "running", "dataset" => "sdc:sdc:smartos:1.3.15", "memory" => 256, "disk" => 5120, "ips" => ["10.88.88.50"], "metadata" => {}, "created" => Time.parse("2011-06-03T00:02:31+00:00"), "updated" => Time.parse("2011-06-03T00:02:31+00:00") } } end @provider = Fog::Compute[:joyent] # # https://us-west-1.api.joyentcloud.com/docs#ListMachines # tests("#list_machines") do if Fog.mock? returns(@machines.length, "correct number of machines") do @provider.list_machines.body.length end end returns(Array, "returns an Array of machines") do @provider.list_machines.body.class end formats([@machine_format]) do @provider.list_machines.body end end # https://us-west-1.api.joyentcloud.com/docs#GetMachine tests("#get_machine") do machines = @provider.list_machines.body unless machines.empty? formats(@machine_format) do id = machines.first["id"] @provider.get_machine(id).body end end end end fog-1.19.0/tests/joyent/requests/compute/packages_tests.rb0000644000004100000410000000276712261242552023750 0ustar www-datawww-dataShindo.tests("Fog::Compute[:joyent] | package requests", ["joyent"]) do @package_format = { 'name' => String, 'vcpus' => Integer, 'memory' => Integer, 'disk' => Integer, 'swap' => Integer, 'default' => Fog::Boolean } if Fog.mock? @data = Fog::Compute[:joyent].data @data[:packages] = { "regular_128" => { "name" => "regular_128", "memory" => 128, "disk" => 5120, "vcpus" => 1, "swap" => 256, "default" => true }, "regular_256" => { "name" => "regular_256", "memory" => 256, "disk" => 5120, "vcpus" => 1, "swap" => 512, "default" => false }, "regular_512" => { "name" => "regular_512", "memory" => 512, "disk" => 10240, "vcpus" => 1, "swap" => 1024, "default" => false } } end tests("#list_packages") do formats([@package_format]) do Fog::Compute[:joyent].list_packages.body end end if Fog.mock? tests("#list_packages") do actual = @data[:packages].values.length returns(actual, "has correct number of packages") do Fog::Compute[:joyent].list_packages.body.length end end end tests("#get_package") do pkgid = if Fog.mock? @data[:packages].keys.first else Fog::Compute[:joyent].list_packages.body.first["name"] end formats(@package_format) do Fog::Compute[:joyent].get_package(pkgid).body end end end fog-1.19.0/tests/xenserver/0000755000004100000410000000000012261242552015571 5ustar www-datawww-datafog-1.19.0/tests/xenserver/helper.rb0000644000004100000410000000145512261242552017402 0ustar www-datawww-datadef test_template_name ENV['FOG_XENSERVER_TEMPLATE'] || 'squeeze-test' end def test_ephemeral_vm_name 'fog-test-server-shindo' end def valid_ref?(ref) (ref =~ /OpaqueRef:/) and \ (ref != "OpaqueRef:NULL" ) end def create_ephemeral_vm Fog::Compute[:xenserver].servers.create(:name => test_ephemeral_vm_name, :template_name => test_template_name) end def create_ephemeral_server create_ephemeral_vm end def destroy_ephemeral_servers servers = Fog::Compute[:xenserver].servers # Teardown cleanup (servers.all :name_matches => test_ephemeral_vm_name).each do |s| s.destroy end (servers.templates.find_all { |t| t.name == test_ephemeral_vm_name}).each do |s| s.destroy end end def destroy_ephemeral_vms destroy_ephemeral_servers end fog-1.19.0/tests/xenserver/README0000644000004100000410000000124712261242552016455 0ustar www-datawww-data# Running the XenServer tests. Tweak the helper.rb file in tests/xenserver/helper.rb to fit your needs. Fog credentials in $HOME/.fog file are used to run the tests. In particular: :default: :xenserver_url: xenserver-test :xenserver_username: root :xenserver_password: secret We need a working template named squeeze-test available in the XenServer to perform the tests. Change the template name to fit your needs or create a working template named squeeze-test. The tests creates a few VMs during the flight. Make sure you have enough RAM and Storage available in the hypervisor. Run the XenServer provider tests issuing: shindo tests/xenserver fog-1.19.0/tests/xenserver/requests/0000755000004100000410000000000012261242552017444 5ustar www-datawww-datafog-1.19.0/tests/xenserver/requests/compute/0000755000004100000410000000000012261242552021120 5ustar www-datawww-datafog-1.19.0/tests/xenserver/requests/compute/create_sr_tests.rb0000644000004100000410000000317412261242552024643 0ustar www-datawww-data# # @rubiojr # # Testing this requires a very specific setup: # # I use VirtualBox to virtualize XenServer/XCP and create the XenServer VM using # two virtual disks under the same SATA controller. One of the virtual disks # will be /dev/sdb, used to perform the tests. # Shindo.tests('Fog::Compute[:xenserver] | create_sr request', ['xenserver']) do compute = Fog::Compute[:xenserver] tests('#create_sr "FOG TEST SR" with device /dev/sdb') do test('create an EXT SR') do ref = compute.create_sr compute.hosts.first.reference, 'FOG TEST SR', 'ext', '', { :device => '/dev/sdb' }, '0', 'user', false, {} valid_ref? ref end raises(Fog::XenServer::RequestFailed, 'raise when device in use') do ref = compute.create_sr compute.hosts.first.reference, 'FOG TEST SR', 'ext', '', { :device => '/dev/sdb' }, '0', 'user', false, {} valid_ref? ref end end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when arguments missing') { compute.create_sr } end # Clean-up compute.storage_repositories.each do |sr| next unless sr.name == 'FOG TEST SR' sr.pbds.each { |pbd| pbd.unplug } sr.destroy end end fog-1.19.0/tests/xenserver/requests/compute/create_network_tests.rb0000644000004100000410000000115112261242552025701 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | create_network request', ['xenserver']) do compute = Fog::Compute[:xenserver] tests('success') do test('#create_network') do @ref = compute.create_network 'test-net' !(compute.networks.find { |n| n.reference == @ref }).nil? end test('#create_network with description') do # Destroy previously created network compute.networks.get(@ref).destroy @ref = compute.create_network 'test-net', :description => 'foo' !(compute.networks.find { |n| n.description == 'foo' }).nil? end end compute.destroy_network @ref end fog-1.19.0/tests/xenserver/requests/compute/create_vlan_tests.rb0000644000004100000410000000175112261242552025156 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | create_vlan request', ['xenserver']) do compute = Fog::Compute[:xenserver] tests('success') do test('#create_vlan') do @net = compute.networks.create :name => 'test-net' # try to use a bonded interface first @pif = compute.pifs.find { |p| p.device == 'bond0' and p.vlan == "-1" } unless @pif @pif = compute.pifs.find { |p| p.device == 'eth0' and p.vlan == "-1" } end @ref = compute.create_vlan @pif.reference, 1499, @net.reference @ref.start_with? "OpaqueRef" end end tests('failure') do test('#create_vlan duplicated') do raises = false # Try to create a VLAN with a duplicated tag begin @ref = compute.create_vlan @pif.reference, 1499, @net.reference rescue Fog::XenServer::RequestFailed => e raises = true if (e.message =~ /NETWORK_ALREADY_CONNECTED/) end raises end end compute.destroy_vlan @ref @net.destroy end fog-1.19.0/tests/xenserver/requests/compute/disable_host_tests.rb0000644000004100000410000000052312261242552025327 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | disable_host request', ['xenserver']) do compute = Fog::Compute[:xenserver] host = compute.hosts.first tests('#disable_host') do test('disables the host') do compute.disable_host host.reference host.reload !host.enabled end end # Cleanup host.enable end fog-1.19.0/tests/xenserver/requests/compute/destroy_network_tests.rb0000644000004100000410000000053012261242552026127 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | destroy_network request', ['xenserver']) do compute = Fog::Compute[:xenserver] tests('success') do test('#destroy_network') do @ref = compute.create_network 'test-net' compute.destroy_network @ref (compute.networks.find { |n| n.reference == @ref }).nil? end end end fog-1.19.0/tests/xenserver/requests/compute/create_vdi_tests.rb0000644000004100000410000000461612261242552025003 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | create_vdi request', ['xenserver']) do compute = Fog::Compute[:xenserver] sr = compute.storage_repositories.find { |sr| sr.name == 'Local storage' } tests('create_vdi should') do raises(ArgumentError, 'raise ArgumentError if virtual_size is no specified') do ref = compute.create_vdi( { :storage_repository => sr, :name => 'foovdi', :type => 'system', :read_only => false, :sharable => false, :other_config => {} } ) end raises(ArgumentError, 'raise ArgumentError if type is no specified') do ref = compute.create_vdi( { :storage_repository => sr, :name => 'foovdi', :virtual_size => '8589934592', :read_only => false, :sharable => false, :other_config => {} } ) valid_ref? ref end raises(ArgumentError, 'raise ArgumentError if read_only is no specified') do ref = compute.create_vdi( { :storage_repository => sr, :name => 'foovdi', :virtual_size => '8589934592', :type => 'system', :sharable => false, :other_config => {} } ) valid_ref? ref end raises(ArgumentError, 'raise ArgumentError if sharable is no specified') do ref = compute.create_vdi( { :storage_repository => sr, :name => 'foovdi', :virtual_size => '8589934592', :type => 'system', :read_only => false, :other_config => {} } ) valid_ref? ref end raises(ArgumentError, 'raise ArgumentError if other_config is no specified') do ref = compute.create_vdi( { :storage_repository => sr, :name => 'foovdi', :virtual_size => '8589934592', :type => 'system', :read_only => false, :sharable => false, } ) valid_ref? ref end test('create a VDI') do ref = compute.create_vdi( { :storage_repository => sr, :name => 'foovdi', :virtual_size => '8589934592', :type => 'system', :read_only => false, :sharable => false, :other_config => {} } ) valid_ref? ref end end compute.vdis.each { |vdi| vdi.destroy if vdi.name == 'foovdi' } tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when vm_ref,net_ref missing') { compute.create_vdi } end end fog-1.19.0/tests/xenserver/requests/compute/destroy_sr_tests.rb0000644000004100000410000000261712261242552025072 0ustar www-datawww-data# # @rubiojr # # Testing this requires a very specific setup: # # I use VirtualBox to virtualize XenServer/XCP and create the XenServer VM using # two virtual disks under the same SATA controller. One of the virtual disks # will be /dev/sdb, used to perform the tests. # Shindo.tests('Fog::Compute[:xenserver] | destroy_sr request', ['xenserver']) do compute = Fog::Compute[:xenserver] # We need the SR available for this to work, so create it first ref = compute.create_sr compute.hosts.first.reference, 'FOG TEST SR', 'ext', '', { :device => '/dev/sdb' }, '0', 'user', false, {} tests('#destroy_sr') do test('destroyed "FOG TEST SR"') do compute.storage_repositories.each do |sr| next unless sr.name == 'FOG TEST SR' sr.pbds.each { |pbd| pbd.unplug } end compute.destroy_sr ref (compute.storage_repositories.find { |sr| sr.name == 'FOG TEST SR' }).nil? end raises(Fog::XenServer::RequestFailed, 'raises HandleInvalid trying to destroy it twice') do compute.destroy_sr ref end end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when arguments missing') \ { compute.destroy_sr } end end fog-1.19.0/tests/xenserver/requests/compute/create_vif_tests.rb0000644000004100000410000000553212261242552025003 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | create_vif request', ['xenserver']) do compute = Fog::Compute[:xenserver] servers = compute.servers # pre-flight cleanup (servers.all :name_matches => test_ephemeral_vm_name).each do |s| s.destroy end tests('create_vif should') do vm_ref = compute.create_server test_ephemeral_vm_name, test_template_name ref = compute.create_vif vm_ref, compute.networks.first.reference s = servers.get vm_ref test('return a valid reference') do if (ref != "OpaqueRef:NULL") and (ref.split("1") != "NULL") true else false end end test('add the VIF to the server') do !(s.vifs.find { |vif| vif.reference == ref }).nil? end raises(ArgumentError, 'raise ArgumentError when vm_ref nil') do ref = compute.create_vif nil, compute.networks.first.reference end raises(ArgumentError, 'raise ArgumentError when network_ref nil') do ref = compute.create_vif vm_ref, nil end test('create a VIF with device number 9') do ref = compute.create_vif vm_ref, compute.networks.first.reference, 9 s.reload (compute.vifs.get(ref).device == 9.to_s) and \ !(s.vifs.find { |vif| vif.reference == ref }).nil? end end tests('create_vif_custom should') do vm_ref = compute.create_server test_ephemeral_vm_name, test_template_name network_ref = compute.networks.first.reference conf = { 'MAC_autogenerated' => 'True', 'VM' => vm_ref, 'network' => network_ref, 'MAC' => '', 'device' => '4', 'MTU' => '0', 'other_config' => {}, 'qos_algorithm_type' => 'ratelimit', 'qos_algorithm_params' => {} } ref = compute.create_vif_custom conf s = servers.get vm_ref test('return a valid reference') do if (ref != "OpaqueRef:NULL") and (ref.split("1") != "NULL") true else false end end test('add the VIF to the server') do !(s.vifs.find { |vif| vif.reference == ref }).nil? end raises(ArgumentError, 'raise ArgumentError when conf is not a Hash') do conf['device'] = '5' ref = compute.create_vif_custom 'foobar' end test('create a VIF with device number 9') do conf['device'] = '9' ref = compute.create_vif_custom conf s.reload (compute.vifs.get(ref).device == 9.to_s) and \ !(s.vifs.find { |vif| vif.reference == ref }).nil? end test('create a VIF with MAC 11:22:33:44:55:66') do conf['MAC_autogenerated'] = 'False' conf['MAC'] = '11:22:33:44:55:66' conf['device'] = '6' ref = compute.create_vif_custom conf vif = compute.vifs.get ref vif.mac == '11:22:33:44:55:66' end end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when vm_ref,net_ref missing') { compute.create_vif } end end fog-1.19.0/tests/xenserver/requests/compute/set_attribute_tests.rb0000644000004100000410000000500112261242552025541 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | set_attribute request', ['xenserver']) do # Setup cleanup destroy_ephemeral_servers connection = Fog::Compute[:xenserver] servers = connection.servers server = create_ephemeral_server tests('Setting an attribute with set_attribute should') do test('set the PV_bootloader attr to foobar') do response = connection.set_attribute('VM', server.reference, 'PV_bootloader', 'foobar') server.reload server.pv_bootloader == 'foobar' end test('set the PV-bootloader attr to stuff') do response = connection.set_attribute('VM', server.reference, 'PV-bootloader', 'stuff') server.reload server.pv_bootloader == 'stuff' end test('set the other_config attr { "foo" => "bar", :stuff => "crap" }') do response = connection.set_attribute('VM', server.reference, 'other_config', { "foo" => "bar", :stuff => 'crap' }) server.reload (server.other_config['foo'] == 'bar') and \ (server.other_config['stuff'] == 'crap') end test('set the multiple valued attribute memory_limits }') do server = create_ephemeral_server server.stop 'hard' server.wait_for { not running? } response = connection.set_attribute('VM', server.reference, 'memory_limits', '1073741824', '1073741824', '1073741824', '1073741824' ) server.reload (server.memory_dynamic_max == "1073741824") and \ (server.memory_dynamic_min == "1073741824") and \ (server.memory_static_max == "1073741824") and \ (server.memory_static_min == "1073741824") server.start end test('set an array valued attribute') do server = create_ephemeral_server response = connection.set_attribute('VM', server.reference, 'tags', ['foo','bar'] ) server.reload server.tags.include?('foo') and server.tags.include?('bar') end end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when ref,attr,value missing') { connection.get_record } end # Teardown cleanup destroy_ephemeral_servers end fog-1.19.0/tests/xenserver/requests/compute/unplug_pbd_tests.rb0000644000004100000410000000261112261242552025026 0ustar www-datawww-data# # @rubiojr # # Testing this requires a very specific setup: # # I use VirtualBox to virtualize XenServer/XCP and create the XenServer VM using # two virtual disks under the same SATA controller. One of the virtual disks # will be /dev/sdb, used to perform the tests. # Shindo.tests('Fog::Compute[:xenserver] | unplug_pbd request', ['xenserver']) do compute = Fog::Compute[:xenserver] # Creating a new SR automatically plugs the PBD # We need the SR available for this to work, so create it first ref = compute.create_sr compute.hosts.first.reference, 'FOG TEST SR', 'ext', '', { :device => '/dev/sdb' }, '0', 'user', false, {} tests('#unplug_pbd') do test('unplugged') do sr = compute.storage_repositories.find { |sr| sr.name == 'FOG TEST SR' } pbd = sr.pbds.first compute.unplug_pbd pbd.reference pbd.reload pbd.currently_attached == false end end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when arguments missing') \ { compute.unplug_pbd } end # Clean-up compute.storage_repositories.each do |sr| next unless sr.name == 'FOG TEST SR' sr.pbds.each { |pbd| pbd.unplug } sr.destroy end end fog-1.19.0/tests/xenserver/requests/compute/clone_server_tests.rb0000644000004100000410000000222712261242552025360 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | clone_server request', ['xenserver']) do compute = Fog::Compute[:xenserver] servers = compute.servers (servers.all :name_matches => test_ephemeral_vm_name).each do |s| s.destroy end tests('clone_server should') do raises(ArgumentError, 'raise exception when template nil') do compute.clone_server 'fooserver', nil end raises(ArgumentError, 'raise exception when name nil') do compute.clone_server nil, 'fooref' end compute.default_template = test_template_name tmpl = compute.default_template test('accept a string template ref') do ref = compute.clone_server test_ephemeral_vm_name, tmpl.reference (ref =~ /OpaqueRef:/) == 0 and !(servers.custom_templates.find { |s| s.reference == ref }).nil? end test('accept a Server object') do ref = compute.clone_server test_ephemeral_vm_name, tmpl (ref =~ /OpaqueRef:/) == 0 and !(servers.custom_templates.find { |s| s.reference == ref }).nil? end end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when ref,class missing') { compute.clone_server } end end fog-1.19.0/tests/xenserver/requests/compute/enable_host_tests.rb0000644000004100000410000000051612261242552025154 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | enable_host request', ['xenserver']) do compute = Fog::Compute[:xenserver] host = compute.hosts.first tests('#enable_host') do test('enables the host') do compute.enable_host host.reference host.reload host.enabled end end # Cleanup host.enable end fog-1.19.0/tests/xenserver/requests/compute/destroy_vlan_tests.rb0000644000004100000410000000173412261242552025405 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | destroy_vlan request', ['xenserver']) do compute = Fog::Compute[:xenserver] tests('success') do test('#destroy_vlan') do @net = compute.networks.create :name => 'test-net' # try to use a bonded interface first @pif = compute.pifs.find { |p| p.device == 'bond0' and p.vlan == "-1" } unless @pif @pif = compute.pifs.find { |p| p.device == 'eth0' and p.vlan == "-1" } end @ref = compute.create_vlan @pif.reference, 1499, @net.reference compute.destroy_vlan @ref (compute.vlans.reload.find { |v| v.reference == @ref }).nil? end end tests('failure') do test('#destroy_vlan invalid') do raises = false # Try to create a VLAN with a duplicated tag begin compute.destroy_vlan @ref rescue Fog::XenServer::RequestFailed => e raises = true if (e.message =~ /HANDLE_INVALID/) end raises end end @net.destroy end fog-1.19.0/tests/xenserver/requests/compute/destroy_vdi_tests.rb0000644000004100000410000000135712261242552025230 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | destroy_vdi request', ['xenserver']) do compute = Fog::Compute[:xenserver] sr = compute.storage_repositories.find { |sr| sr.name == 'Local storage' } tests('destroy_vdi should') do ref = compute.create_vdi( { :storage_repository => sr, :name => 'foovdi', :virtual_size => '8589934592', :type => 'system', :read_only => false, :sharable => false, :other_config => {} } ) raises(Fog::XenServer::RequestFailed, 'destroy it') do compute.destroy_vdi ref compute.vdis.get ref end end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when vm_ref,net_ref missing') { compute.destroy_vdi } end end fog-1.19.0/tests/xenserver/requests/compute/get_record_tests.rb0000644000004100000410000000071412261242552025006 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | get_record request', ['xenserver']) do compute = Fog::Compute[:xenserver] vm_ref = 'alksjdfoiuoiwueroiwe' tests('The response should') do raises(Fog::XenServer::RequestFailed, 'when ref invalid') do response = compute.get_record(vm_ref, 'VM') end end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when ref,class missing') { compute.get_record } end end fog-1.19.0/tests/xenserver/requests/compute/create_server_tests.rb0000644000004100000410000000747712261242552025537 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | create_server request', ['xenserver']) do compute = Fog::Compute[:xenserver] servers = compute.servers # pre-flight cleanup (servers.all :name_matches => test_ephemeral_vm_name).each do |s| s.destroy end (servers.templates.find_all { |t| t.name == test_ephemeral_vm_name}).each do |s| s.destroy end tests('create_server should') do raises(StandardError, 'raise exception when template nil') do compute.create_server 'fooserver', nil end ref = compute.create_server test_ephemeral_vm_name, test_template_name test('return a valid reference') do if (ref != "OpaqueRef:NULL") and (ref.split("1") != "NULL") true else false end end end tests('get_vm_by_name should') do test('return a valid OpaqueRef') do (compute.get_vm_by_name(test_template_name) =~ /OpaqueRef:/) and \ (compute.get_vm_by_name(test_template_name) != "OpaqueRef:NULL" ) end returns(nil, 'return nil if VM does not exist') { compute.get_vm_by_name('sdfsdf') } end tests('create_server_raw should') do raises(ArgumentError, 'raise exception when name_label nil') do compute.create_server_raw end test('create a server') do ref = compute.create_server_raw( { :name_label => test_ephemeral_vm_name, :affinity => compute.hosts.first } ) valid_ref? ref end test('create a server with name foobar') do ref = compute.create_server_raw( { :name_label => test_ephemeral_vm_name, :affinity => compute.hosts.first } ) (compute.servers.get ref).name == test_ephemeral_vm_name end test('set the PV_bootloader attribute to eliloader') do ref = compute.create_server_raw( { :name_label => test_ephemeral_vm_name, :affinity => compute.hosts.first, :PV_bootloader => 'eliloader', } ) (compute.servers.get ref).pv_bootloader == 'eliloader' end test('set the :pv_bootloader attribute to eliloader') do ref = compute.create_server_raw( { :name_label => test_ephemeral_vm_name, :affinity => compute.hosts.first, :pv_bootloader => 'eliloader', } ) (compute.servers.get ref).pv_bootloader == 'eliloader' end test('set the "vcpus_attribute" to 1') do ref = compute.create_server_raw( { :name_label => test_ephemeral_vm_name, :affinity => compute.hosts.first, 'vcpus_max' => '1', } ) (compute.servers.get ref).vcpus_max == '1' end tests('set lowercase hash attributes') do %w{ VCPUs_params HVM_boot_params }.each do |a| test("set the :#{a} to { :foo => 'bar' }") do ref = compute.create_server_raw( { :name_label => test_ephemeral_vm_name, :affinity => compute.hosts.first, a.downcase.to_sym => {:foo => :bar}, } ) eval "(compute.servers.get ref).#{a.to_s.downcase}['foo'] == 'bar'" end end %w{ VCPUs_at_startup VCPUs_max PV_bootloader_args PV_bootloader PV_kernel PV_ramdisk PV_legacy_args }.each do |a| test("set the :#{a} to 1") do ref = compute.create_server_raw( { :name_label => test_ephemeral_vm_name, :affinity => compute.hosts.first, a.downcase.to_sym => '1', } ) eval "(compute.servers.get ref).#{a.to_s.downcase} == '1'" end end end end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when ref,class missing') { compute.create_server } end end fog-1.19.0/tests/xenserver/xenserver_tests.rb0000644000004100000410000000167212261242552021367 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver]', ['xenserver']) do tests("Login") do raises(Fog::XenServer::InvalidLogin, 'raises error when invalid password') do conn = Fog::Compute.new({ :provider => 'XenServer', :xenserver_url => 'xenserver-test', :xenserver_username => 'root', :xenserver_password => 'asdfsadf' }) end raises(Fog::XenServer::InvalidLogin, 'raises error when invalid user') do conn = Fog::Compute.new({ :provider => 'XenServer', :xenserver_url => 'xenserver-test', :xenserver_username => 'rootffff', :xenserver_password => 'changeme' }) end raises(SocketError, 'raises error when invalid host') do conn = Fog::Compute.new({ :provider => 'XenServer', :xenserver_url => 'xenserver-testlakjsdflkj', :xenserver_username => 'root', :xenserver_password => 'changeme' }) end end end fog-1.19.0/tests/xenserver/compute_tests.rb0000644000004100000410000000416212261242552021017 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver]', ['xenserver']) do compute = Fog::Compute[:xenserver] tests("Compute attributes") do %w{ default_template }.each do |attr| test("it should respond to #{attr}") { compute.respond_to? attr } end end tests("Compute collections") do %w{ pifs vifs hosts storage_repositories servers networks vbds vdis pools consoles}.each do |collection| test("it should respond to #{collection}") { compute.respond_to? collection } test("it should respond to #{collection}.all") { eval("compute.#{collection}").respond_to? 'all' } test("it should respond to #{collection}.get") { eval("compute.#{collection}").respond_to? 'get' } end # This will fail if there are no PIFs # (not sure if that's gonna be a real scenario though) tests("PIFs collection") do test("should have at least one PIF") { compute.pifs.size >= 1 } end # This will fail if there are no VIFs # (not sure if that's gonna be a real scenario though) tests("VIFs collection") do test("should have at least one VIF") { compute.vifs.size >= 1 } end # This will fail if there are no VIFs # (not sure if that's gonna be a real scenario though) tests("Networks collection") do test("should have at least one Network") { compute.networks.size >= 1 } tests("each network should be a Fog::Compute::XenServer::Network") do ok = true compute.networks.each { |n| ok = false if n.kind_of? Fog::Compute::XenServer::Network } end end end tests "Default template" do test("it should NOT have a default template") { compute.default_template.nil? } # This template exists in our XenServer compute.default_template = 'squeeze-test' test("it should have a default template if template exists") { compute.default_template.name == 'squeeze-test' } test("it should be a Fog::Compute::XenServer::Server") { compute.default_template.is_a? Fog::Compute::XenServer::Server } test("it should return nil when not found") do compute.default_template = 'asdfasdfasfdwe' compute.default_template.nil? end end end fog-1.19.0/tests/xenserver/models/0000755000004100000410000000000012261242552017054 5ustar www-datawww-datafog-1.19.0/tests/xenserver/models/compute/0000755000004100000410000000000012261242552020530 5ustar www-datawww-datafog-1.19.0/tests/xenserver/models/compute/networks_tests.rb0000644000004100000410000000120312261242552024147 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | Networks collection', ['xenserver']) do conn = Fog::Compute[:xenserver] tests('The networks collection') do networks = conn.networks.all test('should not be empty') { !networks.empty? } test('should be a kind of Fog::Compute::XenServer::Networks') { networks.kind_of? Fog::Compute::XenServer::Networks } tests('should be able to reload itself').succeeds { networks.reload } tests('should be able to get a model') do tests('by reference').succeeds { networks.get(networks.first.reference).is_a? Fog::Compute::XenServer::Network } end end end fog-1.19.0/tests/xenserver/models/compute/host_metrics_tests.rb0000644000004100000410000000261212261242552025003 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | HostMetrics model', ['xenserver']) do host = Fog::Compute[:xenserver].hosts.first tests('The HostMetrics model should') do tests('have attributes') do model_attribute_hash = host.metrics.attributes attributes = [ :reference, :uuid, :memory_free, :memory_total, :other_config, :last_updated ] tests("The HostMetrics model should respond to") do attributes.each do |attribute| test("#{attribute}") { host.metrics.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::XenServer::HostMetrics') do host.metrics.kind_of? Fog::Compute::XenServer::HostMetrics end test("have a last_updated Time property") { host.metrics.last_updated.kind_of? Time } test("return a valid memory_free ammount") do (host.metrics.memory_free =~ /^\d+$/) == 0 end test("have memory_free > 0") { host.metrics.memory_free.to_i > 0 } test("return a valid memory_total ammount") do (host.metrics.memory_total =~ /^\d+$/) == 0 end test("have memory_total > 0") { host.metrics.memory_total.to_i > 0 } end end fog-1.19.0/tests/xenserver/models/compute/vlans_tests.rb0000644000004100000410000000164112261242552023424 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | Vlans collection', ['xenserver']) do service = Fog::Compute[:xenserver] tests('The Vlans collection') do test('should not be empty') { !service.vlans.empty? } test('should be a kind of Fog::Compute::XenServer::Vlans') do service.vlans.kind_of? Fog::Compute::XenServer::Vlans end tests('should be able to reload itself').succeeds { service.vlans.reload } tests('should be able to get a model') do tests('by reference').succeeds { service.vlans.get(service.vlans.first.reference).is_a? \ Fog::Compute::XenServer::VLAN } end end tests('failures') do test 'with an invalid reference' do raises = false begin service.vlans.get('OpaqueRef:foo') rescue Fog::XenServer::RequestFailed => e raises = true if e.message =~ /HANDLE_INVALID/ end raises end end end fog-1.19.0/tests/xenserver/models/compute/server_tests.rb0000644000004100000410000001335412261242552023613 0ustar www-datawww-data Shindo.tests('Fog::Compute[:xenserver] | server model', ['xenserver']) do connection = Fog::Compute[:xenserver] servers = connection.servers # pre-flight cleanup (servers.all :name_matches => test_ephemeral_vm_name).each do |s| s.destroy end (servers.templates.find_all { |t| t.name == test_ephemeral_vm_name}).each do |s| s.destroy end server = Fog::Compute[:xenserver].servers.create(:name => test_ephemeral_vm_name, :template_name => test_template_name) server.reload tests('The server model should') do tests('have the action') do test('reload') { server.respond_to? 'reload' } %w{ affinity set_attribute refresh stop clean_shutdown hard_shutdown start destroy reboot hard_reboot clean_reboot }.each do |action| test(action) { server.respond_to? action } #test("#{action} returns successfully") { server.send(action.to_sym) ? true : false } end end tests('have attributes') do model_attribute_hash = server.attributes attributes = [ :reference, :uuid, :is_a_template, :__affinity, :allowed_operations, :__consoles, :domarch, :domid, :__guest_metrics, :is_a_snapshot, :is_a_template, :is_control_domain, :memory_dynamic_max, :memory_dynamic_min, :memory_static_max, :memory_static_min, :memory_target, :metrics, :name_description, :other_config, :power_state, :pv_args, :__resident_on, :__vbds, :__vifs, :vcpus_params, :vcpus_at_startup, :vcpus_max, :hvm_boot_policy, :hvm_boot_params, :pci_bus, :pv_kernel, :pv_ramdisk, :pv_legacy_args, :pv_bootloader_args, :snapshots ] tests("The server model should respond to") do attributes.each do |attribute| test("#{attribute}") { server.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::XenServer::Server') { server.kind_of? Fog::Compute::XenServer::Server } #test('return a Fog::Compute::XenServer::Host affinity') { server.affinity.kind_of? Fog::Compute::XenServer::Host } end tests("Creating a server") do tests("it should create a server") do s = nil test("named #{test_ephemeral_vm_name}") do s = servers.create(:name => test_ephemeral_vm_name, :template_name => test_template_name) servers.get(s.reference).name == test_ephemeral_vm_name end test("and destroy it afterwards") { s.destroy } end tests("it should create a server") do s = nil # The template has 2 VIFs already, we add 2 more test("with 4 NICs") do s = servers.create(:name => test_ephemeral_vm_name, :template_name => test_template_name, :networks => [connection.default_network, connection.default_network]) s.reload s.networks.size == 4 end test("and destroy it afterwards") { s.destroy } end end tests("A real server should") do tests("return valid vbds") do test("as an array") { server.vbds.kind_of? Array } server.vbds.each { |i| test("and each VBD should be a Fog::Compute::XenServer::VBD") { i.kind_of? Fog::Compute::XenServer::VBD } } end tests('return valid consoles') do test('as an array') { server.consoles.kind_of? Array } server.consoles.each { |i| test('and each Console should be a Fog::Compute::XenServer::Console') { i.kind_of? Fog::Compute::XenServer::Console } } end test("have 0 or more networks") { server.networks.kind_of? Array } tests("have networks if networks > 0") do if server.networks.size > 0 server.networks.each do |n| test("and network is of type Fog::Compute::XenServer::Network") do n.kind_of? Fog::Compute::XenServer::Network end end end end test("reside on a Fog::Compute::XenServer::Host") { server.resident_on.kind_of? Fog::Compute::XenServer::Host } #test("have Fog::Compute::XenServer::GuestMetrics") { server.guest_metrics.kind_of? Fog::Compute::XenServer::GuestMetrics } test("be able to refresh itself") { server.refresh } test("always stop when I say stop('hard')") do server.stop 'hard' end # shutdown is async apparently, we wait test("not be running when it's stopped") do server.wait_for { !server.running? } true end test("do nothing when I say stop('hard') but it's not running") do server.stop('hard') == false end test("always start when I say start") do server.start end # start is async apparently, we wait test("be running if I started the server") do server.wait_for { server.running? } true end test("set attribute PV_bootloader to supergrub") do server.set_attribute 'PV_bootloader', 'supergrub' server.reload server.pv_bootloader == 'supergrub' end tests("Creating a snapshot") do snap_ref = server.snapshot('newsnapshot') tests("it should create a snapshot") do snap_ref = server.snapshot('newsnapshot') servers.get(snap_ref).reference == snap_ref end test("and destroy it afterwards") { servers.get(snap_ref).destroy } end test("be able to be destroyed!") do server.destroy servers.get_by_name('fog-test-server-shindo') == nil end end end fog-1.19.0/tests/xenserver/models/compute/pool_tests.rb0000644000004100000410000000333512261242552023254 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | Pool model', ['xenserver']) do pools = Fog::Compute[:xenserver].pools pool = pools.first tests('The Pool model should') do tests('have the action') do test('reload') { pool.respond_to? 'reload' } end tests('have attributes') do model_attribute_hash = pool.attributes attributes = [ :reference, :uuid, :name, :description, :__default_sr, :__master, :tags, :restrictions, :ha_enabled, :vswitch_controller, :__suspend_image_sr ] tests("The Pool model should respond to") do attributes.each do |attribute| test("#{attribute}") { pool.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::XenServer::Pool') { pool.kind_of? Fog::Compute::XenServer::Pool} end tests("A real Pool should") do tests("return a valid default_storage_repository") do test("should be a Fog::Compute::XenServer::StorageRepository") { pool.default_storage_repository.kind_of? Fog::Compute::XenServer::StorageRepository } end tests("return valid Host as the master") do test("should be a Fog::Compute::XenServer::Host") { pool.master.kind_of? Fog::Compute::XenServer::Host } end test("be able to be configured as a valid suspend_image_sr") do pool.suspend_image_sr = pool.default_storage_repository pool.reload pool.suspend_image_sr.reference == pool.default_storage_repository.reference end end end fog-1.19.0/tests/xenserver/models/compute/vbd_tests.rb0000644000004100000410000000612712261242552023060 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | VBD model', ['xenserver']) do vbds = Fog::Compute[:xenserver].vbds vbd = vbds.first servers = Fog::Compute[:xenserver].servers server = create_ephemeral_vm tests('The VBD model should') do tests('have the action') do test('reload') { vbd.respond_to? 'reload' } test('eject') { vbd.respond_to? 'eject' } test('insert') { vbd.respond_to? 'insert' } test('unplug') { vbd.respond_to? 'unplug' } test('unplug_force') { vbd.respond_to? 'unplug_force' } end tests('have attributes') do model_attribute_hash = vbd.attributes attributes = [ :reference, :uuid, :currently_attached, :__vdi, :__vm, :device, :status_detail, :type, :allowed_operations, :current_operations, :status_code, :storage_lock, :mode, :runtime_properties, :unpluggable, :userdevice, :bootable, :empty, :__metrics ] tests("The VBD model should respond to") do attributes.each do |attribute| test("#{attribute}") { vbd.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::XenServer::VBD') { vbd.kind_of? Fog::Compute::XenServer::VBD} end tests("A real VBD should") do test("have a valid OpaqueRef") do puts vbd.reference (vbd.reference =~ /OpaqueRef:/).eql?(0) and \ vbd.reference != "OpaqueRef:NULL" end tests("belong to a VM when attached") do vbds.each do |vbd| test("#{vbd.uuid}") do if vbd.currently_attached (vbd.__vm =~ /OpaqueRef/).eql?(0) and \ vbd.__vm != "OpaqueRef:NULL" else true end end end end vbds.each do |vbd| test("return a Fog::Compute::XenServer::VDI when type Disk") do if vbd.type == 'Disk' vbd.vdi.kind_of? Fog::Compute::XenServer::VDI else true end end test("return a nil VDI when type CD") do if vbd.type == 'CD' vbd.vdi.nil? else true end end test("return a VbdMetrics object when attached") do if vbd.currently_attached vbd.metrics.kind_of? Fog::Compute::XenServer::VbdMetrics else vbd.metrics.nil? end end end tests("return valid Server") do test("should be a Fog::Compute::XenServer::Server") { vbd.server.kind_of? Fog::Compute::XenServer::Server } end test("be able to be unplugged when type is CD") do if vbd.type == "CD" vbd.unpluggable == true else vbd.unpluggable == false end end end tests("VBD Metrics should") do test("have a last_updated Time property") { server.vbds.first.metrics.last_updated.kind_of? Time } end destroy_ephemeral_servers end fog-1.19.0/tests/xenserver/models/compute/pbd_tests.rb0000644000004100000410000000461412261242552023051 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | PBD model', ['xenserver']) do pbds = Fog::Compute[:xenserver].pbds pbd = pbds.first tests('The PBD model should') do tests('have the action') do test('reload') { pbd.respond_to? 'reload' } test('unplug') { pbd.respond_to? 'reload' } end tests('have attributes') do model_attribute_hash = pbd.attributes attributes = [ :reference, :uuid, :__host, :__sr, :currently_attached ] tests("The PBD model should respond to") do attributes.each do |attribute| test("#{attribute}") { pbd.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::XenServer::PBD') { pbd.kind_of? Fog::Compute::XenServer::PBD} end tests("A real PBD should") do tests("return valid host") do test("should be a Fog::Compute::XenServer::Host") { pbd.host.kind_of? Fog::Compute::XenServer::Host } end tests("return valid storage repository") do test("should be a Fog::Compute::XenServer::StorageRepository") { pbd.storage_repository.kind_of? Fog::Compute::XenServer::StorageRepository } end # FIXME: find a better way (faster, lighter) to tests this tests("be plugged or unplugged") do compute = Fog::Compute[:xenserver] # Create a storage repository only to tests PBD.unplug ref = compute.create_sr compute.hosts.first.reference, 'FOG TEST SR', 'ext', '', { :device => '/dev/sdb' }, '0', 'user', false, {} sr = compute.storage_repositories.find { |sr| sr.name == 'FOG TEST SR' } pbd = sr.pbds.first test('plugged') do pbd.currently_attached == true end pbd.unplug pbd.reload test('unplugged') do pbd.currently_attached == false end # Clean-up compute.storage_repositories.each do |sr| next unless sr.name == 'FOG TEST SR' sr.pbds.each { |pbd| pbd.unplug } sr.destroy end end end end fog-1.19.0/tests/xenserver/models/compute/storage_repositories_tests.rb0000644000004100000410000000205612261242552026555 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | StorageRepositories collection', ['xenserver']) do conn = Fog::Compute[:xenserver] tests('The storage_repositories collection') do storage_repositories = conn.storage_repositories.all test('should not be empty') { !storage_repositories.empty? } test('should be a kind of Fog::Compute::XenServer::StorageRepositories') { storage_repositories.kind_of? Fog::Compute::XenServer::StorageRepositories } tests('should be an array of Fog::Compute::XenServer::StorageRepository') do storage_repositories.each do |p| test("#{p.uuid} is a Fog::Compute::XenServer::StorageRepository") { p.is_a? Fog::Compute::XenServer::StorageRepository } end end tests('should be able to reload itself').succeeds { storage_repositories.reload } tests('should be able to get a model') do tests('by reference').succeeds { storage_repositories.get(storage_repositories.first.reference).is_a? Fog::Compute::XenServer::StorageRepository } end end end fog-1.19.0/tests/xenserver/models/compute/servers_tests.rb0000644000004100000410000000613712261242552023777 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | servers collection', ['xenserver']) do conn = Fog::Compute[:xenserver] destroy_ephemeral_servers servers = conn.servers templates = conn.servers.templates tests('The servers collection') do servers = conn.servers.all test('should be empty') do servers.empty? end server = conn.servers.create(:name => test_ephemeral_vm_name, :template_name => test_template_name) test('should NOT be empty') do servers.reload !servers.empty? end server.destroy test('should be a kind of Fog::Compute::XenServer::Servers') { servers.kind_of? Fog::Compute::XenServer::Servers } test('should be a kind of Fog::Compute::XenServer::Servers') { servers.kind_of? Fog::Compute::XenServer::Servers } tests('should have Fog::Compute::XenServer::Servers inside') do conn.servers.each do |s| test { s.kind_of? Fog::Compute::XenServer::Server } end end test("should return a list of templates") do templates.kind_of? Array end tests("The servers template list should") do test("should include only templates in servers.templates") do ok = true templates.each { |t| ok = false if !t.is_a_template } ok end test("include a #{test_template_name} template in custom_templates") do found = false servers.custom_templates.each do |s| found = (s.name == test_template_name) end found end test("NOT include a #{test_template_name} template in built-in templates") do found = false servers.builtin_templates.each do |s| found = (s.name != test_template_name) end found end # This may fail in other test scenarios with more than one built-in template # present test("include only one custom template") { servers.custom_templates.size == 1 } tests("not include built-in templates in custom_templates") do servers.custom_templates.each do |s| test("#{s.name} is NOT a built-in template") {s.allowed_operations.include?('destroy') } end end test("include more than one built-in templates") { servers.builtin_templates.size >= 1 } tests("not include real servers") do servers.builtin_templates.each do |s| test("#{s.name} is not a real server") { s.is_a_template } end end end tests('should be able to reload itself').succeeds { servers.reload } tests('should be able to get a model') do server = conn.servers.create(:name => test_ephemeral_vm_name, :template_name => test_template_name) test('by name') { servers.get_by_name(test_ephemeral_vm_name).kind_of? Fog::Compute::XenServer::Server } test('by instance uuid') { servers.get_by_uuid(server.uuid).kind_of? Fog::Compute::XenServer::Server } test('by instance reference') { servers.get(server.reference).kind_of? Fog::Compute::XenServer::Server } server.destroy end end # Teardown cleaup destroy_ephemeral_servers end fog-1.19.0/tests/xenserver/models/compute/storage_repository_tests.rb0000644000004100000410000001000312261242552026234 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | StorageRepository model', ['xenserver']) do storage_repositories = Fog::Compute[:xenserver].storage_repositories storage_repository = storage_repositories.first conn = Fog::Compute[:xenserver] tests('The StorageRepository model should') do tests('have the action') do test('reload') { storage_repository.respond_to? 'reload' } test('destroy') { storage_repository.respond_to? 'destroy' } test('scan') { storage_repository.respond_to? 'scan' } test('save') { storage_repository.respond_to? 'save' } end tests('have attributes') do model_attribute_hash = storage_repository.attributes attributes = [ :reference, :name, :uuid, :description, :uuid, :allowed_operations, :current_operations, :content_type, :other_config, :__pbds, :shared, :type, :tags, :__vdis, :physical_size, :physical_utilisation, :virtual_allocation, :sm_config ] tests("The StorageRepository model should respond to") do attributes.each do |attribute| test("#{attribute}") { storage_repository.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::XenServer::StorageRepository') { storage_repository.kind_of? Fog::Compute::XenServer::StorageRepository } end tests("A real StorageRepository should") do tests("return a valid list of VDIs") do storage_repository.vdis.each do |vdi| test("where #{vdi.uuid} is a Fog::Compute::XenServer::VDI") { vdi.is_a? Fog::Compute::XenServer::VDI } end end tests("return a valid list of PBDs") do storage_repository.pbds.each do |pbd| test("where #{pbd.uuid} is a Fog::Compute::XenServer::PBD") { pbd.is_a? Fog::Compute::XenServer::PBD } end end end tests('#save should') do sr = nil test('save with required attributes') do sr = conn.storage_repositories.create :name => 'FOG TEST SR', :host => conn.hosts.first, :type => 'ext', :device_config => { :device => '/dev/sdb' } !(conn.storage_repositories.find { |sr| sr.name == 'FOG TEST SR' }).nil? end # Cleanup sr.pbds.each { |pbd| pbd.unplug } sr.destroy test('save with additional attributes') do sr = conn.storage_repositories.create :name => 'FOG TEST SR', :host => conn.hosts.first, :type => 'ext', :content_type => 'user', :device_config => { :device => '/dev/sdb' }, :shared => false !(conn.storage_repositories.find { |sr| sr.name == 'FOG TEST SR' }).nil? end # Cleanup sr.pbds.each { |pbd| pbd.unplug } sr.destroy test('return sane defaults') do sr = conn.storage_repositories.create :name => 'FOG TEST SR', :host => conn.hosts.first, :type => 'ext', :device_config => { :device => '/dev/sdb' } sr.reload (sr.content_type == 'user') and \ (sr.shared == false) and (sr.sm_config.is_a? Hash) and \ (sr.description == '') end end tests('#destroy should') do test('destroy existing FOG TEST SR') do sr = (conn.storage_repositories.find { |sr| sr.name == 'FOG TEST SR' }) sr.pbds.each { |pbd| pbd.unplug } sr.destroy (conn.storage_repositories.find { |sr| sr.name == 'FOG TEST SR' }).nil? end end end fog-1.19.0/tests/xenserver/models/compute/vbds_tests.rb0000644000004100000410000000112312261242552023232 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | VBDs collection', ['xenserver']) do conn = Fog::Compute[:xenserver] tests('The vbds collection') do vbds = conn.vbds.all test('should not be empty') { !vbds.empty? } test('should be a kind of Fog::Compute::XenServer::Vbds') { vbds.kind_of? Fog::Compute::XenServer::Vbds } tests('should be able to reload itself').succeeds { vbds.reload } tests('should be able to get a model') do tests('by reference').succeeds { vbds.get(vbds.first.reference).is_a? Fog::Compute::XenServer::VBD } end end end fog-1.19.0/tests/xenserver/models/compute/vlan_tests.rb0000644000004100000410000000412312261242552023237 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | VLAN model', ['xenserver']) do service = Fog::Compute[:xenserver] vlans = service.vlans vlan = vlans.first tests('The VLAN model should') do tests('have the action') do %w{ reload destroy save untagged_pif tagged_pif }.each do |action| test(action) { vlan.respond_to? action } end end tests('have attributes') do model_attribute_hash = vlan.attributes attributes = [ :reference, :uuid, :__untagged_pif, :__tagged_pif, :tag ] tests("The VLAN model should respond to") do attributes.each do |attribute| test("#{attribute}") { vlan.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::XenServer::VLAN') { vlan.kind_of? Fog::Compute::XenServer::VLAN} end tests("#save") do test 'should create a VLAN' do @net = service.networks.create :name => 'test-net' # try to use a bonded interface first pif = service.pifs.find { |p| p.device == 'bond0' and p.vlan == "-1" } unless pif pif = compute.pifs.find { |p| p.device == 'eth0' and p.vlan == "-1" } end @vlan = vlans.create :tag => 1499, :pif => pif, :network => @net @vlan.is_a? Fog::Compute::XenServer::VLAN end test 'VLAN ID should be 1449' do @vlan.tag == 1499 end end tests("#destroy") do test 'should destroy the network' do @vlan.destroy @net.destroy (vlans.reload.find { |v| v.reference == @vlan.reference }).nil? end end tests("#tagged_pif") do test 'should return a PIF' do vlans.find.first.tagged_pif.is_a? Fog::Compute::XenServer::PIF end end tests("#untagged_pif") do test 'should return a PIF' do vlans.find.first.untagged_pif.is_a? Fog::Compute::XenServer::PIF end end end fog-1.19.0/tests/xenserver/models/compute/pools_tests.rb0000644000004100000410000000151112261242552023431 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | Pools collection', ['xenserver']) do conn = Fog::Compute[:xenserver] tests('The pools collection') do pools = conn.pools.all test('should not be empty') { !pools.empty? } test('should be a kind of Fog::Compute::XenServer::Pools') { pools.kind_of? Fog::Compute::XenServer::Pools } tests('should be an array of Fog::Compute::XenServer::Pool') do pools.each do |p| test("#{p.uuid} is a Fog::Compute::XenServer::Pool") { p.is_a? Fog::Compute::XenServer::Pool } end end tests('should be able to reload itself').succeeds { pools.reload } tests('should be able to get a model') do tests('by reference').succeeds { pools.get(pools.first.reference).is_a? Fog::Compute::XenServer::Pool } end end end fog-1.19.0/tests/xenserver/models/compute/consoles_test.rb0000644000004100000410000000117012261242552023740 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | console collection', ['xenserver']) do conn = Fog::Compute[:xenserver] tests('The console collection') do consoles = conn.consoles.all test('should not be empty') { !consoles.empty? } test('should be a kind of Fog::Compute::XenServer::Consoles') { consoles.kind_of? Fog::Compute::XenServer::Consoles } tests('should be able to reload itself').succeeds { consoles.reload } tests('should be able to get a model') do tests('by reference').succeeds { consoles.get(hosts.first.reference).is_a? Fog::Compute::XenServer::Console } end end end fog-1.19.0/tests/xenserver/models/compute/host_cpu_tests.rb0000644000004100000410000000266112261242552024130 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | HostCpu model', ['xenserver']) do host = Fog::Compute[:xenserver].hosts.first host_cpu = host.host_cpus.first tests('The HostCpu model should') do tests('have attributes') do model_attribute_hash = host_cpu.attributes attributes = [ :reference, :uuid, :family, :flags, :__host, :model_name, :model, :number, :other_config, :speed, :stepping, :utilisation, :vendor ] tests("The HostCpu model should respond to") do attributes.each do |attribute| test("#{attribute}") { host_cpu.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::XenServer::HostCpu') do host_cpu.kind_of? Fog::Compute::XenServer::HostCpu end test("return a valid host") do host_cpu.host.kind_of? Fog::Compute::XenServer::Host end test("have a valid vendor string") do host_cpu.vendor.kind_of? String end test("have a valid other_config") do host_cpu.other_config.kind_of? Hash end test("have a valid utilisation attribute") do host_cpu.utilisation.kind_of? Float end end end fog-1.19.0/tests/xenserver/models/compute/network_tests.rb0000644000004100000410000000437312261242552023777 0ustar www-datawww-dataShindo.tests('Fog::Compute[:network] | network model', ['xenserver']) do networks = Fog::Compute[:xenserver].networks network = networks.first tests('The network model should') do tests('have the action') do %w{ reload refresh destroy save vifs pifs }.each do |action| test(action) { network.respond_to? action } #test("#{action} returns successfully") { server.send(action.to_sym) ? true : false } end end tests('have attributes') do model_attribute_hash = network.attributes attributes = [ :reference, :uuid, :__vifs, :tags, :mtu, :bridge, :name, :other_config, :__pifs, :allowed_operations, :current_operations, :blobs ] tests("The network model should respond to") do attributes.each do |attribute| test("#{attribute}") { network.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::XenServer::Network') { network.kind_of? Fog::Compute::XenServer::Network } end tests("A real network should") do tests("return valid vifs") do test("as an array") { network.vifs.kind_of? Array } network.vifs.each { |i| test("and each VIF should be a Fog::Compute::XenServer::VIF") { i.kind_of? Fog::Compute::XenServer::VIF } } end tests("return valid PIFs") do networks.each do |network| test("as an array") { network.pifs.kind_of? Array } network.pifs.each { |i| test("and each PIF should be a Fog::Compute::XenServer::PIF") { i.kind_of? Fog::Compute::XenServer::PIF} } end end test("be able to refresh itself") { network.refresh } end tests("#save") do test 'should create a network' do @net = networks.create :name => 'foo-net' @net.is_a? Fog::Compute::XenServer::Network end end tests("#destroy") do test 'should destroy the network' do @net.destroy (networks.find { |n| n.reference == @net.reference }).nil? end end end fog-1.19.0/tests/xenserver/models/compute/pifs_tests.rb0000644000004100000410000000112312261242552023235 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | PIFs collection', ['xenserver']) do conn = Fog::Compute[:xenserver] tests('The pifs collection') do pifs = conn.pifs.all test('should not be empty') { !pifs.empty? } test('should be a kind of Fog::Compute::XenServer::Pifs') { pifs.kind_of? Fog::Compute::XenServer::Pifs } tests('should be able to reload itself').succeeds { pifs.reload } tests('should be able to get a model') do tests('by reference').succeeds { pifs.get(pifs.first.reference).is_a? Fog::Compute::XenServer::PIF } end end end fog-1.19.0/tests/xenserver/models/compute/pif_tests.rb0000644000004100000410000000277612261242552023071 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | PIF model', ['xenserver']) do pifs = Fog::Compute[:xenserver].pifs pif = pifs.first tests('The PIF model should') do tests('have the action') do test('reload') { pif.respond_to? 'reload' } end tests('have attributes') do model_attribute_hash = pif.attributes attributes = [ :reference, :uuid, :physical, :mac, :currently_attached, :device, :metrics, :dns, :gateway, :ip, :ip_configuration_mode, :mtu, :__network, :netmask, :management, :vlan, :other_config, :__host ] tests("The PIF model should respond to") do attributes.each do |attribute| test("#{attribute}") { pif.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::XenServer::PIF') { pif.kind_of? Fog::Compute::XenServer::PIF} end tests("A real PIF should") do tests("return a valid network") do test("should be a Fog::Compute::XenServer::Network") { pif.network.kind_of? Fog::Compute::XenServer::Network } end tests("return valid host") do test("should be a Fog::Compute::XenServer::Host") { pif.host.kind_of? Fog::Compute::XenServer::Host } end end end fog-1.19.0/tests/xenserver/models/compute/console_test.rb0000644000004100000410000000202612261242552023556 0ustar www-datawww-data Shindo.tests('Fog::Compute[:xenserver] | console model', ['xenserver']) do consoles = Fog::Compute[:xenserver].consoles console = consoles.first tests('The console model should') do tests('have attributes') do model_attribute_hash = console.attributes attributes = [ :reference, :location, :protocol, :uuid, :__vm ] tests("The console model should respond to") do attributes.each do |attribute| test("#{attribute}") { console.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::XenServer::Console') { console.kind_of? Fog::Compute::XenServer::Console } end tests('A real console should') do tests('return valid vm') do test('object') { console.vm.kind_of? Fog::Compute::XenServer::Server } end end end fog-1.19.0/tests/xenserver/models/compute/hosts_tests.rb0000644000004100000410000000113712261242552023441 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | hosts collection', ['xenserver']) do conn = Fog::Compute[:xenserver] tests('The hosts collection') do hosts = conn.hosts.all test('should not be empty') { !hosts.empty? } test('should be a kind of Fog::Compute::XenServer::Hosts') { hosts.kind_of? Fog::Compute::XenServer::Hosts } tests('should be able to reload itself').succeeds { hosts.reload } tests('should be able to get a model') do tests('by reference').succeeds { hosts.get(hosts.first.reference).is_a? Fog::Compute::XenServer::Host } end end end fog-1.19.0/tests/xenserver/models/compute/host_tests.rb0000644000004100000410000000537512261242552023266 0ustar www-datawww-data Shindo.tests('Fog::Compute[:xenserver] | host model', ['xenserver']) do hosts = Fog::Compute[:xenserver].hosts host = hosts.first tests('The host model should') do tests('have the action') do test('reload') { host.respond_to? 'reload' } test('shutdown') { host.respond_to? 'shutdown' } test('disable') { host.respond_to? 'disable' } test('reboot') { host.respond_to? 'reboot' } end tests('have attributes') do model_attribute_hash = host.attributes attributes = [ :reference, :uuid, :name, :address, :allowed_operations, :enabled, :hostname, :__metrics, :name_description, :other_config, :__pbds, :__pifs, :__resident_vms, :__host_cpus, :edition, :software_version ] tests("The host model should respond to") do attributes.each do |attribute| test("#{attribute}") { host.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::XenServer::Host') { host.kind_of? Fog::Compute::XenServer::Host } end tests("A real host should") do tests("return valid PIFs") do test("as an array") { host.pifs.kind_of? Array } host.pifs.each { |i| test("and each PIF should be a Fog::Compute::XenServer::PIF") { i.kind_of? Fog::Compute::XenServer::PIF} } end tests("return valid PBDs") do test("as an array") { host.pbds.kind_of? Array } host.pbds.each { |i| test("and each PBD should be a Fog::Compute::XenServer::PBD") { i.kind_of? Fog::Compute::XenServer::PBD} } end tests("return valid resident servers") do test("as an array") { host.resident_servers.kind_of? Array } host.resident_servers.each { |i| test("and each Server should be a Fog::Compute::XenServer::Server") { i.kind_of? Fog::Compute::XenServer::Server} } end tests("return valid HostMetrics") do test("object") { host.metrics.kind_of? Fog::Compute::XenServer::HostMetrics } end tests('be able to be') do test('disable') do host.disable host.reload host.enabled == false end test('enabled') do host.enable host.reload host.enabled end end tests('return a list of HostCpu') do test('as an Array') do host.host_cpus.kind_of? Array end test('with one element at least') do host.host_cpus.first.kind_of? Fog::Compute::XenServer::HostCpu end end end end fog-1.19.0/tests/xenserver/models/compute/vif_tests.rb0000644000004100000410000000272712261242552023073 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | VIF model', ['xenserver']) do vifs = Fog::Compute[:xenserver].vifs vif = vifs.first tests('The VIF model should') do tests('have the action') do test('reload save destroy network server') { vif.respond_to? 'reload' } end tests('have attributes') do model_attribute_hash = vif.attributes attributes = [ :reference, :mac, :uuid, :allowed_operations, :currently_attached, :device, :mac_autogenerated, :metrics, :mtu, :__network, :status_code, :status_detail, :__vm ] tests("The VIF model should respond to") do attributes.each do |attribute| test("#{attribute}") { vif.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::XenServer::VIF') { vif.kind_of? Fog::Compute::XenServer::VIF} end tests("A real VIF should") do tests("return a valid network") do test("should be a Fog::Compute::XenServer::Network") { vif.network.kind_of? Fog::Compute::XenServer::Network } end tests("return valid VIF") do test("should be a Fog::Compute::XenServer::Server") { vif.server.kind_of? Fog::Compute::XenServer::Server } end end end fog-1.19.0/tests/xenserver/models/compute/pbds_tests.rb0000644000004100000410000000112312261242552023224 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | pbds collection', ['xenserver']) do conn = Fog::Compute[:xenserver] tests('The pbds collection') do pbds = conn.pbds.all test('should not be empty') { !pbds.empty? } test('should be a kind of Fog::Compute::XenServer::Pbds') { pbds.kind_of? Fog::Compute::XenServer::Pbds } tests('should be able to reload itself').succeeds { pbds.reload } tests('should be able to get a model') do tests('by reference').succeeds { pbds.get(pbds.first.reference).is_a? Fog::Compute::XenServer::PBD } end end end fog-1.19.0/tests/xenserver/models/compute/vifs_tests.rb0000644000004100000410000000112312261242552023243 0ustar www-datawww-dataShindo.tests('Fog::Compute[:xenserver] | VIFs collection', ['xenserver']) do conn = Fog::Compute[:xenserver] tests('The vifs collection') do vifs = conn.vifs.all test('should not be empty') { !vifs.empty? } test('should be a kind of Fog::Compute::XenServer::Vifs') { vifs.kind_of? Fog::Compute::XenServer::Vifs } tests('should be able to reload itself').succeeds { vifs.reload } tests('should be able to get a model') do tests('by reference').succeeds { vifs.get(vifs.first.reference).is_a? Fog::Compute::XenServer::VIF } end end end fog-1.19.0/tests/google/0000755000004100000410000000000012261242552015024 5ustar www-datawww-datafog-1.19.0/tests/google/requests/0000755000004100000410000000000012261242552016677 5ustar www-datawww-datafog-1.19.0/tests/google/requests/storage/0000755000004100000410000000000012261242552020343 5ustar www-datawww-datafog-1.19.0/tests/google/requests/storage/object_tests.rb0000644000004100000410000000655312261242552023371 0ustar www-datawww-dataShindo.tests('Fog::Storage[:google] | object requests', ["google"]) do @directory = Fog::Storage[:google].directories.create(:key => 'fogobjecttests') tests('success') do tests("#put_object('#{@directory.identity}', 'fog_object', lorem_file)").succeeds do Fog::Storage[:google].put_object(@directory.identity, 'fog_object', lorem_file) end tests("#copy_object('#{@directory.identity}', 'fog_object', '#{@directory.identity}', 'fog_other_object')").succeeds do Fog::Storage[:google].copy_object(@directory.identity, 'fog_object', @directory.identity, 'fog_other_object') end @directory.files.get('fog_other_object').destroy tests("#get_object('#{@directory.identity}', 'fog_object')").returns(lorem_file.read) do Fog::Storage[:google].get_object(@directory.identity, 'fog_object').body end tests("#get_object('#{@directory.identity}', 'fog_object', &block)").returns(lorem_file.read) do data = '' Fog::Storage[:google].get_object(@directory.identity, 'fog_object') do |chunk, remaining_bytes, total_bytes| data << chunk end data end tests("#head_object('#{@directory.identity}', 'fog_object')").succeeds do Fog::Storage[:google].head_object(@directory.identity, 'fog_object') end tests("#delete_object('#{@directory.identity}', 'fog_object')").succeeds do Fog::Storage[:google].delete_object(@directory.identity, 'fog_object') end end tests('failure') do tests("#put_object('fognonbucket', 'fog_non_object', lorem_file)").raises(Excon::Errors::NotFound) do Fog::Storage[:google].put_object('fognonbucket', 'fog_non_object', lorem_file) end tests("#copy_object('fognonbucket', 'fog_object', '#{@directory.identity}', 'fog_other_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].copy_object('fognonbucket', 'fog_object', @directory.identity, 'fog_other_object') end tests("#copy_object('#{@directory.identity}', 'fog_non_object', '#{@directory.identity}', 'fog_other_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].copy_object(@directory.identity, 'fog_non_object', @directory.identity, 'fog_other_object') end tests("#copy_object('#{@directory.identity}', 'fog_object', 'fognonbucket', 'fog_other_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].copy_object(@directory.identity, 'fog_object', 'fognonbucket', 'fog_other_object') end tests("#get_object('fognonbucket', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].get_object('fognonbucket', 'fog_non_object') end tests("#get_object('#{@directory.identity}', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].get_object(@directory.identity, 'fog_non_object') end tests("#head_object('fognonbucket', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].head_object('fognonbucket', 'fog_non_object') end tests("#head_object('#{@directory.identity}', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].head_object(@directory.identity, 'fog_non_object') end tests("#delete_object('fognonbucket', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].delete_object('fognonbucket', 'fog_non_object') end end @directory.destroy end fog-1.19.0/tests/google/requests/storage/bucket_tests.rb0000644000004100000410000000377112261242552023377 0ustar www-datawww-dataShindo.tests('Fog::Storage[:google] | bucket requests', ["google"]) do tests('success') do @bucket_format = { 'CommonPrefixes' => [], 'IsTruncated' => Fog::Boolean, 'Marker' => NilClass, 'Name' => String, 'Prefix' => NilClass, 'Contents' => [{ 'ETag' => String, 'Key' => String, 'LastModified' => Time, 'Owner' => { 'DisplayName' => String, 'ID' => String }, 'Size' => Integer }] } @service_format = { 'Buckets' => [{ 'CreationDate' => Time, 'Name' => String, }], 'Owner' => { 'ID' => String } } tests("#put_bucket('fogbuckettests')").succeeds do Fog::Storage[:google].put_bucket('fogbuckettests') end tests("#get_service").formats(@service_format) do Fog::Storage[:google].get_service.body end file = Fog::Storage[:google].directories.get('fogbuckettests').files.create(:body => 'y', :key => 'x') tests("#get_bucket('fogbuckettests)").formats(@bucket_format) do Fog::Storage[:google].get_bucket('fogbuckettests').body end file.destroy tests("#delete_bucket('fogbuckettests')").succeeds do Fog::Storage[:google].delete_bucket('fogbuckettests') end end tests('failure') do tests("#delete_bucket('fognonbucket')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].delete_bucket('fognonbucket') end @bucket = Fog::Storage[:google].directories.create(:key => 'fognonempty') @file = @bucket.files.create(:key => 'foo', :body => 'bar') tests("#delete_bucket('fognonempty')").raises(Excon::Errors::Conflict) do Fog::Storage[:google].delete_bucket('fognonempty') end @file.destroy @bucket.destroy tests("#get_bucket('fognonbucket')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].get_bucket('fognonbucket') end end end fog-1.19.0/tests/google/requests/compute/0000755000004100000410000000000012261242552020353 5ustar www-datawww-datafog-1.19.0/tests/google/requests/compute/firewall_tests.rb0000644000004100000410000000372412261242552023735 0ustar www-datawww-dataShindo.tests('Fog::Compute[:google] | firewall requests', ['google']) do pending if Fog.mocking? @google = Fog::Compute[:google] @insert_firewall_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'name' => String, 'targetLink' => String, 'status' => String, 'user' => String, 'progress' => Integer, 'insertTime' => String, 'startTime' => String, 'operationType' => String } @get_firewall_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'creationTimestamp' => DateTime, 'name' => String, 'network' => String, 'sourceRanges' => [], 'allowed' => [], } @delete_firewall_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'name' => String, 'targetLink' => String, 'status' => String, 'user' => String, 'progress' => Integer, 'targetId' => String, 'insertTime' => String, 'startTime' => String, 'operationType' => String } @list_firewalls_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'items' => [] } tests('success') do firewall_name = 'new-firewall-test' source_range = [ '10.0.0.0/8' ] allowed = [{ "IPProtocol" => "tcp", "ports" => [ "1-65535" ] }, { "IPProtocol" => "udp", "ports" => [ "1-65535" ] }, { "IPProtocol" => "icmp" }] tests("#insert_firewall").formats(@insert_firewall_format) do @google.insert_firewall(firewall_name, source_range, allowed).body end # TODO: Get better matching for firewall responses. tests("#get_firewall").succeeds do @google.get_firewall(firewall_name) end tests("#list_firewalls").succeeds do @google.list_firewalls end tests("#delete_firewall").formats(@delete_firewall_format) do @google.delete_firewall(firewall_name).body end end end fog-1.19.0/tests/google/requests/compute/disk_tests.rb0000644000004100000410000000407112261242552023056 0ustar www-datawww-dataShindo.tests('Fog::Compute[:google] | disk requests', ['google']) do @google = Fog::Compute[:google] @insert_disk_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'name' => String, 'targetLink' => String, 'status' => String, 'user' => String, 'progress' => Integer, 'zone' => String, 'insertTime' => String, 'startTime' => String, 'operationType' => String } @get_disk_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'creationTimestamp' => String, 'name' => String, 'zone' => String, 'status' => String, 'sizeGb' => String } @delete_disk_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'name' => String, 'targetLink' => String, 'targetId' => String, 'status' => String, 'user' => String, 'progress' => Integer, 'insertTime' => String, 'zone' => String, 'startTime' => String, 'operationType' => String } @list_disks_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'items' => [{ 'kind'=> String, 'id'=> String, 'creationTimestamp'=>String, 'selfLink'=>String, 'name'=> String, 'sizeGb'=> String, 'zone'=> String, 'status'=>String, }] } tests('success') do disk_name = 'new-disk-test' disk_size = '2' zone_name = 'us-central1-a' image_name = 'centos-6-v20130813' # These will all fail if errors happen on insert tests("#insert_disk").formats(@insert_disk_format) do @google.insert_disk(disk_name, zone_name, image_name).body end tests("#get_disk").formats(@get_disk_format) do @google.get_disk(disk_name, zone_name).body end tests("#list_disks").formats(@list_disks_format) do @google.list_disks(zone_name).body end tests("#delete_disk").formats(@delete_disk_format) do @google.delete_disk(disk_name, zone_name).body end end end fog-1.19.0/tests/google/requests/compute/image_tests.rb0000644000004100000410000000372512261242552023213 0ustar www-datawww-dataShindo.tests('Fog::Compute[:google] | image requests', ['google']) do @google = Fog::Compute[:google] @insert_image_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'name' => String, 'targetLink' => String, 'status' => String, 'user' => String, 'progress' => Integer, 'insertTime' => String, 'startTime' => String, 'operationType' => String } @get_image_format = { 'kind' => String, 'id' => String, 'creationTimestamp' => String, 'selfLink' => String, 'name' => String, 'description' => String, 'sourceType' => String, 'preferredKernel' => String, 'rawDisk' => { 'containerType' => String, 'source' => String } } @delete_image_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'name' => String, 'targetLink' => String, 'status' => String, 'user' => String, 'progress' => Integer, 'insertTime' => String, 'startTime' => String, 'operationType' => String } @list_images_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'items' => [@get_image_format] } tests('success') do image_name = 'test-image' source = 'https://www.google.com/images/srpr/logo4w.png' tests("#insert_image").formats(@insert_image_format) do pending if Fog.mocking? @google.insert_image(image_name, source).body end tests("#get_image").formats(@get_image_format) do pending if Fog.mocking? @google.insert_image(image_name, source) @google.get_image(image_name).body end tests("#list_images").formats(@list_images_format) do @google.list_images.body end tests("#delete_image").formats(@delete_image_format) do pending if Fog.mocking? @google.insert_image(image_name, source) @google.delete_image(image_name).body end end end fog-1.19.0/tests/google/requests/compute/server_tests.rb0000644000004100000410000000377512261242552023444 0ustar www-datawww-dataShindo.tests('Fog::Compute[:google] | server requests', ['google']) do @google = Fog::Compute[:google] @insert_server_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'name' => String, 'targetLink' => String, 'user' => String, 'startTime' => String, 'insertTime' => String, 'operationType' => String, 'status' => String, 'progress' => Integer } @get_server_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'creationTimestamp' => String, 'name' => String, 'image' => String, 'machineType' => String, 'status' => String, 'zone' => String, 'disks' => [], 'networkInterfaces' => [] } @delete_server_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'name' => String, 'targetLink' => String, 'status' => String, 'user' => String, 'targetId' => String, 'progress' => Integer, 'insertTime' => String, 'startTime' => String, 'operationType' => String } @list_servers_format = { 'kind' => String, 'id' => String, 'selfLink' => String, } tests('success') do server_name = 'new-server-test' image_name = "centos-6-v20130813" machine_type = "n1-standard-1" zone_name = "us-central1-a" tests("#insert_server").formats(@insert_server_format) do @google.insert_server( server_name, zone_name, { 'image' => image_name, 'machineType' => machine_type } ).body end tests("#list_servers").formats(@list_servers_format) do @google.list_servers(zone_name).body end # Both of these tests require the server to be there... #tests("#get_server").formats(@get_server_format) do # @google.get_server(server_name, zone_name).body #end #tests("#delete_server").formats(@delete_server_format) do # @google.delete_server(server_name, zone_name).body #end end end fog-1.19.0/tests/google/requests/compute/operation_tests.rb0000644000004100000410000000122612261242552024123 0ustar www-datawww-dataShindo.tests('Fog::Compute[:google] | operation requests', ['google']) do pending if Fog.mocking? @google = Fog::Compute[:google] tests('success') do # We are not testing the format here because operation formats are pretty # extensive based on what has happened to you account, ever. # https://developers.google.com/compute/docs/reference/latest/globalOperations#resource tests("#list_global_operations").succeeds do @google.list_global_operations end tests("#list_zone_operations").succeeds do zone_name = @google.list_zones.body["items"][0]["name"] @google.list_zone_operations(zone_name) end end end fog-1.19.0/tests/google/requests/compute/network_tests.rb0000644000004100000410000000335212261242552023616 0ustar www-datawww-dataShindo.tests('Fog::Compute[:google] | network requests', ['google']) do pending if Fog.mocking? @google = Fog::Compute[:google] @insert_network_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'name' => String, 'targetLink' => String, 'status' => String, 'user' => String, 'progress' => Integer, 'insertTime' => String, 'startTime' => String, 'operationType' => String } @get_network_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'creationTimestamp' => String, 'name' => String, 'IPv4Range' => String, 'gatewayIPv4' => String } @delete_network_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'name' => String, 'targetLink' => String, 'targetId' => String, 'status' => String, 'user' => String, 'progress' => Integer, 'insertTime' => String, 'startTime' => String, 'operationType' => String } @list_networks_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'items' => [@get_network_format] } tests('success') do network_name = 'new-network-test' ip_range = '192.168.0.0/16' tests("#insert_network").formats(@insert_network_format) do @google.insert_network(network_name, ip_range).body end tests("#get_network").formats(@get_network_format) do @google.get_network(network_name).body end tests("#list_networks").formats(@list_networks_format) do @google.list_networks.body end tests("#delete_network").formats(@delete_network_format) do @google.delete_network(network_name).body end end end fog-1.19.0/tests/google/requests/compute/zone_tests.rb0000644000004100000410000000162712261242552023103 0ustar www-datawww-dataShindo.tests('Fog::Compute[:google] | zone requests', ['google']) do @google = Fog::Compute[:google] @get_zone_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'creationTimestamp' => String, 'name' => String, 'description' => String, 'status' => String, 'maintenanceWindows' => Fog::Nullable::Array, 'quotas' => [{ 'metric' => String, 'limit' => Float, 'usage' => Float}, ], } @list_zones_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'items' => [@get_zone_format] } tests('success') do tests("#get_zone").formats(@get_zone_format) do zone_name = @google.list_zones.body["items"][0]["name"] @google.get_zone(zone_name).body end tests("#list_zones").formats(@list_zones_format) do @google.list_zones.body end end end fog-1.19.0/tests/google/models/0000755000004100000410000000000012261242552016307 5ustar www-datawww-datafog-1.19.0/tests/google/models/compute/0000755000004100000410000000000012261242552017763 5ustar www-datawww-datafog-1.19.0/tests/google/models/compute/disk_tests.rb0000644000004100000410000000025412261242552022465 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | disk model", ['google']) do model_tests(Fog::Compute[:google].disks, {:name => 'fogdiskname', :zone_name => 'us-central1-a'}) end fog-1.19.0/tests/google/models/compute/server_tests.rb0000644000004100000410000000142512261242552023042 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | server model", ['google']) do model_tests(Fog::Compute[:google].disks, {:name => 'fogservername', :zone_name => 'us-central1-a', :machine_type => 'n1-standard-1'}) tests('servers') do @instance = nil test('#bootstrap') do attributes = Fog.mocking? ? {:public_key_path => nil, :private_key_path => nil} : {} @instance = Fog::Compute[:google].servers.bootstrap(attributes) @instance.ready? end test('#sshable?') do @instance.wait_for { sshable? } @instance.sshable? end test('#ssh') do pending if Fog.mocking? @instance.ssh("uname") == "Linux" end test('#destroy') do response = @instance.destroy response.body['operationType'] == 'delete' end end end fog-1.19.0/tests/google/models/compute/disks_tests.rb0000644000004100000410000000025412261242552022650 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | disks", ['google']) do collection_tests(Fog::Compute[:google].disks, {:name => 'fogdiskname', :zone_name => 'us-central1-a'}) end fog-1.19.0/tests/google/models/compute/servers_tests.rb0000644000004100000410000000032412261242552023222 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | servers", ['google']) do collection_tests(Fog::Compute[:google].servers, {:name => 'fogservername', :zone_name => 'us-central1-a', :machine_type => 'n1-standard-1'}) end fog-1.19.0/tests/dnsmadeeasy/0000755000004100000410000000000012261242552016045 5ustar www-datawww-datafog-1.19.0/tests/dnsmadeeasy/requests/0000755000004100000410000000000012261242552017720 5ustar www-datawww-datafog-1.19.0/tests/dnsmadeeasy/requests/dns/0000755000004100000410000000000012261242552020504 5ustar www-datawww-datafog-1.19.0/tests/dnsmadeeasy/requests/dns/dns_tests.rb0000644000004100000410000000650412261242552023044 0ustar www-datawww-dataShindo.tests('Fog::DNS[:dnsmadeeasy] | DNS requests', ['dnsmadeeasy', 'dns']) do @domain = '' @domain_count = 0 tests("success") do test("get current domain count") do pending if Fog.mocking? response = Fog::DNS[:dnsmadeeasy].list_domains() if response.status == 200 @domain_count = response.body['list'].size end response.status == 200 end test("create domain") do pending if Fog.mocking? domain = generate_unique_domain response = Fog::DNS[:dnsmadeeasy].create_domain(domain) if response.status == 201 @domain = response.body end response.status == 201 end test("get domain by name") do pending if Fog.mocking? response = Fog::DNS[:dnsmadeeasy].get_domain(@domain["name"]) response.status == 200 end test("create an A resource record") do pending if Fog.mocking? domain = @domain["name"] name = "www" type = "A" data = "1.2.3.4" response = Fog::DNS[:dnsmadeeasy].create_record(domain, name, type, data) if response.status == 201 @record = response.body end response.status == 201 end test("create a MX record") do pending if Fog.mocking? domain = @domain["name"] name = "" type = "MX" data = "10 mail.#{domain}" options = { :ttl => 60 } response = Fog::DNS[:dnsmadeeasy].create_record(domain, name, type, data, options) response.status == 201 end test("update a record") do pending if Fog.mocking? domain = @domain["name"] record_id = @record["id"] options = {:name => '', :type => 'A', :data => "2.3.4.5", :ttl => 600} response = Fog::DNS[:dnsmadeeasy].update_record(domain, record_id, options) response.status == 200 end test("get record - check ip/ttl") do pending if Fog.mocking? response = Fog::DNS[:dnsmadeeasy].get_record(@domain["name"], @record['id']) record = response.body result = false if response.status == 200 && record['data'] == '2.3.4.5' && record['ttl'] == 600 result = true end result end test("list records") do pending if Fog.mocking? response = Fog::DNS[:dnsmadeeasy].list_records(@domain["name"]) if response.status == 200 @records = response.body end (response.status == 200) and (response.body.size == 2) end test("delete records") do pending if Fog.mocking? domain = @domain["name"] result = true @records.each do |record| response = Fog::DNS[:dnsmadeeasy].delete_record(domain, record["id"]) if(response.status != 200) result = false break end end result end test("delete domain") do pending if Fog.mocking? puts "DNS Made Easy - Sleeping for 10 seconds, otherwise test fails because DNS Made Easy queues requests, it still might fail if DNS Made Easy is busy! MOCK IT!" puts "THIS MOST LIKELY WILL FAIL ON LIVE because it can take while for DNS Made Easy to create a domain/zone, changing the host to api.sandbox.dnsmadeeasy.com should make it work" sleep 10 response = Fog::DNS[:dnsmadeeasy].delete_domain(@domain["name"]) response.status == 200 end end tests( 'failure') do end end fog-1.19.0/tests/glesys/0000755000004100000410000000000012261242552015056 5ustar www-datawww-datafog-1.19.0/tests/glesys/requests/0000755000004100000410000000000012261242552016731 5ustar www-datawww-datafog-1.19.0/tests/glesys/requests/compute/0000755000004100000410000000000012261242552020405 5ustar www-datawww-datafog-1.19.0/tests/glesys/requests/compute/helper.rb0000644000004100000410000001657412261242552022226 0ustar www-datawww-dataclass Glesys module Compute module Formats module Servers LIST = { 'debug' => { 'input' => Array }, 'servers' => [{ 'serverid' => String, 'hostname' => String, 'datacenter' => String, 'platform' => String }], 'status' => { 'timestamp' => String, 'code' => Integer, 'text' => String } } DETAILS = { 'debug' => { 'input' => { 'serverid' => Fog::Nullable::String } }, 'server' => { 'managedhosting' => String, 'cost' => { 'amount' => Float, 'timeperiod' => String, 'currency' => String }, 'serverid' => String, 'datacenter' => String, 'memorysize' => Integer, 'cpucores' => Integer, 'transfer' => Integer, 'templatename' => String, 'iplist' => [{ 'cost' => Integer, 'version' => Fog::Nullable::Integer, 'ipaddress' => Fog::Nullable::String, 'currency' => String }], 'description' => String, 'hostname' => String, 'disksize' => Integer, 'platform' => String, 'state' => Fog::Nullable::String }, 'status' => { 'timestamp' => String, 'code' => Integer, 'text' => String } } STOP = DETAILS.merge( 'debug' => { 'input' => { 'serverid' => Fog::Nullable::String, 'type' => String } } ) CREATE = DETAILS.merge( 'debug' => { 'input' => { 'serverid' => Fog::Nullable::String, 'hostname' => String, 'rootpassword' => String, 'datacenter' => String, 'platform' => String, 'templatename' => String, 'disksize' => String, 'memorysize' => String, 'cpucores' => String, 'transfer' => String, 'description' => String } } ) STATUS = { 'debug' => { 'input' => { 'serverid' => String } }, 'server' => { 'memory' => { 'usage' => Fog::Nullable::Integer, 'max' => Fog::Nullable::Integer, 'unit' => Fog::Nullable::String }, 'transfer' => { 'usage' => Fog::Nullable::Integer, 'max' => Fog::Nullable::Integer, 'unit' => Fog::Nullable::String }, 'disk' => { 'usage' => Fog::Nullable::Integer, 'max' => Fog::Nullable::Integer, 'unit' => Fog::Nullable::String }, 'state' => String, 'transfer' => { 'usage' => Fog::Nullable::Integer, 'max' => Fog::Nullable::Integer, 'unit' => Fog::Nullable::String }, 'cpu' => { 'usage' => Fog::Nullable::Integer, 'max' => Fog::Nullable::Integer, 'unit' => Fog::Nullable::String }, 'uptime' => { 'current' => Fog::Nullable::Integer, 'unit' => String }, 'warnings' => Array }, 'status' => { 'timestamp' => String, 'code' => Integer, 'text' => String } } DESTROY = { 'debug' => { 'input' => { 'serverid' => String, 'keepip' => String } }, 'status' => { 'timestamp' => String, 'code' => Integer, 'text' => String } } end module Ips IPLIST = { 'debug' => { 'input' => [] }, 'iplist' => [{ 'cost' => { 'amount' => Integer, 'timeperiod' => String, 'currency' => String }, 'netmask' => Fog::Nullable::String, 'broadcast' => Fog::Nullable::String, 'gateway' => Fog::Nullable::String, 'nameservers' => Array, 'datacenter' => String, 'serverid' => Fog::Nullable::String, 'platform' => String, 'ipaddress' => String, 'ipversion' => Integer, 'ptr' => String, 'reserved' => String }], 'status' => { 'timestamp' => String, 'code' => Integer, 'text' => String } } IPLIST_ALL = { 'debug' => { 'input' => { 'datacenter' => String, 'ipversion' => String, 'platform' => String } }, 'iplist' => { 'ipversion' => Integer, 'datacenter' => String, 'platform' => String, "ipaddresses" => Array }, 'status' => { 'timestamp' => String, 'code' => Integer, 'text' => String }, } IPLIST_CATCH_RELEASE = { 'debug' => { 'input' => { 'ipaddress' => String, } }, 'details' => { 'cost' => { 'amount' => Integer, 'timeperiod' => String, 'currency' => String }, 'ipaddress' => String, 'netmask' => String, 'broadcast' => String, 'gateway' => String, 'nameservers' => Array, 'datacenter' => String, 'serverid' => Fog::Nullable::String, 'platform' => String, 'ipaddress' => String, 'ipversion' => Integer, 'ptr' => String, 'reserved' => String }, 'status' => { 'timestamp' => String, 'code' => Integer, 'text' => String } } end module Templates LIST = { 'debug' => { 'input' => [] }, 'templates' => { 'Xen' => [{ 'name' => String, 'operatingsystem' => String, 'minimummemorysize' => Integer, 'minimumdisksize' => Integer, 'platform' => String }], 'OpenVZ' => [{ 'name' => String, 'operatingsystem' => String, 'minimummemorysize' => Integer, 'minimumdisksize' => Integer, 'platform' => String }] }, 'status' => { 'timestamp' => String, 'code' => Integer, 'text' => String } } end end end end fog-1.19.0/tests/glesys/requests/compute/template_tests.rb0000644000004100000410000000044212261242552023767 0ustar www-datawww-dataShindo.tests('Fog::Compute[:glesys] | template requests', ['glesys']) do tests('success') do tests("#template_list()").formats(Glesys::Compute::Formats::Templates::LIST) do pending if Fog.mocking? Fog::Compute[:glesys].template_list.body['response'] end end end fog-1.19.0/tests/glesys/requests/compute/server_tests.rb0000644000004100000410000001044512261242552023466 0ustar www-datawww-dataShindo.tests('Fog::Compute[:glesys] | server requests', ['glesys']) do @serverid = nil @hostname = "fog-#{Time.now.to_i}" @create = ":hostname => #@hostname, :rootpassword => 'pw#{Time.now.to_i}', "+ ":datacenter => 'Falkenberg', :platform => 'Xen', :templatename => 'Debian-6 x64', "+ ":disksize => '10', :memorysize => '512', :cpucores => '1', :transfer => '500'" @create_vz = ":hostname => #@hostname, :rootpassword => 'pw#{Time.now.to_i}', "+ ":datacenter => 'Stockholm', :platform => 'OpenVZ', :templatename => 'Debian 6.0 64-bit', "+ ":disksize => '10', :memorysize => '256', :cpucores => '2', :transfer => '500'" tests('success') do tests("#list_servers()").formats(Glesys::Compute::Formats::Servers::LIST) do pending if Fog.mocking? Fog::Compute[:glesys].list_servers.body['response'] end tests("#create(#{@create})").formats(Glesys::Compute::Formats::Servers::CREATE) do pending if Fog.mocking? vm = Fog::Compute[:glesys].create( :hostname => @hostname, :rootpassword => "pw#{Time.now.to_i}", :datacenter => "Falkenberg", :platform => "Xen", :templatename => "Debian-6 x64", :disksize => "10", :memorysize => "512", :cpucores => "1", :transfer => "500" ) @serverid = vm.body['response']['server']['serverid'] vm.body['response'] end unless Fog.mocking? Fog::Compute[:glesys].servers.get(@serverid).wait_for { ready? } end tests("#server_details(#{@serverid})").formats(Glesys::Compute::Formats::Servers::DETAILS) do pending if Fog.mocking? Fog::Compute[:glesys].server_details(@serverid).body['response'] end tests("#server_status(#{@serverid})").formats(Glesys::Compute::Formats::Servers::STATUS) do pending if Fog.mocking? Fog::Compute[:glesys].server_status(@serverid).body['response'] end tests("#stop(:serverid => #{@serverid})").formats(Glesys::Compute::Formats::Servers::STOP) do pending if Fog.mocking? Fog::Compute[:glesys].stop(:serverid => @serverid).body['response'] end # Wait for stopped unless Fog.mocking? pending if Fog.mocking? s = Fog::Compute[:glesys].servers.get(@serverid) s.wait_for { s.state == 'stopped' } end tests("#start(:serverid => #{@serverid})").formats(Glesys::Compute::Formats::Servers::DETAILS) do pending if Fog.mocking? Fog::Compute[:glesys].start(:serverid => @serverid).body['response'] end # Wait for started unless Fog.mocking? Fog::Compute[:glesys].servers.get(@serverid).wait_for { ready? } end tests("#destroy(:serverid => #{@serverid})").formats(Glesys::Compute::Formats::Servers::DESTROY) do pending if Fog.mocking? Fog::Compute[:glesys].destroy(:serverid => @serverid).body['response'] end # Test of OpenVZ tests("#create(#{@create_vz})").formats(Glesys::Compute::Formats::Servers::CREATE) do pending if Fog.mocking? vm = Fog::Compute[:glesys].create( :hostname => @hostname, :rootpassword => "pw#{Time.now.to_i}", :datacenter => "Stockholm", :platform => "OpenVZ", :templatename => "Debian 6.0 64-bit", :disksize => "10", :memorysize => "256", :cpucores => "2", :transfer => "500" ) @serverid = vm.body['response']['server']['serverid'] vm.body['response'] end tests("#server_details(#{@serverid})").formats(Glesys::Compute::Formats::Servers::DETAILS) do pending if Fog.mocking? Fog::Compute[:glesys].server_details(@serverid).body['response'] end unless Fog.mocking? Fog::Compute[:glesys].servers.get(@serverid).wait_for { ready? } end tests("#destroy(:serverid => #{@serverid})").formats(Glesys::Compute::Formats::Servers::DESTROY) do pending if Fog.mocking? Fog::Compute[:glesys].destroy(:serverid => @serverid).body['response'] end end tests('failure') do tests("#create(:hostname => 0)").raises(Excon::Errors::HTTPStatusError) do pending if Fog.mocking? Fog::Compute[:glesys].create(:hostname => 0) end end end fog-1.19.0/tests/glesys/requests/compute/ip_tests.rb0000644000004100000410000000346612261242552022575 0ustar www-datawww-dataShindo.tests('Fog::Compute[:glesys] | ip requests', ['glesys']) do @free_ip = nil @ips = nil tests('success') do tests("#ip_list_own()").formats(Glesys::Compute::Formats::Ips::IPLIST) do pending if Fog.mocking? Fog::Compute[:glesys].ip_list_own.body['response'] end tests("#ip_list_free(:datacenter => 'Falkenberg, :platform => 'Xen', :ipversion => 4)" ).formats(Glesys::Compute::Formats::Ips::IPLIST_ALL) do pending if Fog.mocking? ips = Fog::Compute[:glesys].ip_list_free( :datacenter => "Falkenberg", :platform => "Xen", :ipversion => 4 ) @free_ip = ips.body['response']['iplist']['ipaddresses'].first ips.body['response'] end tests("#ip_take(:datacenter => 'Falkenberg', :platform => 'Xen', :ipversion => 4, :ipaddress => #{@free_ip})" ).formats(Glesys::Compute::Formats::Ips::IPLIST_CATCH_RELEASE) do pending if Fog.mocking? Fog::Compute[:glesys].ip_take( :datacenter => "Falkenberg", :platform => "Xen", :ipversion => 4, :ipaddress => @free_ip ).body['response'] end tests("#ip_release(:ipaddress => '#{@free_ip}', :ipversion => 4)" ).formats(Glesys::Compute::Formats::Ips::IPLIST_CATCH_RELEASE) do pending if Fog.mocking? Fog::Compute[:glesys].ip_release( :ipaddress => @free_ip, :ipversion => 4 ).body['response'] end # ip_details() # ip_add() # ip_remove() end tests('failure') do tests("#ip_take_argument_error()").raises(Excon::Errors::HTTPStatusError) do pending if Fog.mocking? ip = Fog::Compute[:glesys].ips.new( :datacenter => "Falkenberg", :platform => "Xen", :version => 4, :ip => "127.0.0.1" ) ip.take end end end fog-1.19.0/tests/storm_on_demand/0000755000004100000410000000000012261242552016720 5ustar www-datawww-datafog-1.19.0/tests/storm_on_demand/requests/0000755000004100000410000000000012261242552020573 5ustar www-datawww-datafog-1.19.0/tests/storm_on_demand/requests/compute/0000755000004100000410000000000012261242552022247 5ustar www-datawww-datafog-1.19.0/tests/storm_on_demand/requests/compute/server_tests.rb0000644000004100000410000000376012261242552025332 0ustar www-datawww-dataShindo.tests('Fog::Compute[:stormondemand] | server requests', ['stormondemand']) do @server_format = { 'uniq_id' => String, 'accnt' => String, 'backup_enabled' => String, 'backup_plan' => String, 'backup_size' => String, 'backup_quota' => String, 'bandwidth_quota' => Integer, 'config_description' => String, 'config_id' => String, 'domain' => String, 'ip' => String, 'ip_count' => String, 'subaccnt' => String, 'template' => String, 'template_description' => String, 'manage_level' => String, 'zone' => Hash, 'active' => Integer, 'create_date' => String } @servers_format = { 'items' => [@server_format] } tests('success') do @uniq_id = nil @name = "fog-test#{Time.now.to_i}.com" tests("#create_server(:backup_enabled => 0, :config_id => 114, :domain => '#{@name}', :template => 'CENTOSUNMANAGED', :ip_count => 1, :password => 'B92bxfijsdK3!')").formats(@server_format) do pending if Fog.mocking? data = Fog::Compute[:stormondemand].create_server(:backup_enabled => 0, :config_id => 114, :domain => @name, :template => 'CENTOSUNMANAGED', :ip_count => 1, :password => 'B92bxfijsdK3!').body @uniq_id = data['uniq_id'] data end tests('#list_servers').formats(@servers_format) do pending if Fog.mocking? Fog::Compute[:stormondemand].list_servers.body end unless Fog.mocking? Fog::Compute[:stormondemand].servers.get(@uniq_id).wait_for { ready? } end tests("#delete_server(:uniq_id => #{@uniq_id})").succeeds do pending if Fog.mocking? Fog::Compute[:stormondemand].delete_server(:uniq_id => @uniq_id) end end tests('failure') do tests('#delete_server(0)').raises(Fog::Compute::StormOnDemand::Error) do pending if Fog.mocking? Fog::Compute[:stormondemand].delete_server(:uniq_id => 'XXXXXX') end end end fog-1.19.0/tests/linode/0000755000004100000410000000000012261242552015022 5ustar www-datawww-datafog-1.19.0/tests/linode/requests/0000755000004100000410000000000012261242552016675 5ustar www-datawww-datafog-1.19.0/tests/linode/requests/dns/0000755000004100000410000000000012261242552017461 5ustar www-datawww-datafog-1.19.0/tests/linode/requests/dns/dns_tests.rb0000644000004100000410000001550012261242552022015 0ustar www-datawww-dataShindo.tests('Fog::DNS[:linode] | DNS requests', ['linode', 'dns']) do @domain = '' @new_zones = [] @new_records =[] tests( 'success') do test('get current zone count') do pending if Fog.mocking? @org_zone_count= 0 response = Fog::DNS[:linode].domain_list() if response.status == 200 zones = response.body['DATA'] @org_zone_count = zones.count end response.status == 200 end test('create zone - simple') do pending if Fog.mocking? type = 'master' domain= generate_unique_domain options = { :SOA_email => "netops@#{domain}", :description => "Sample-Domain Inc", :status => 0} response = Fog::DNS[:linode].domain_create( domain, type, options) if response.status == 200 @master_zone_id = response.body['DATA']['DomainID'] @new_zones << @master_zone_id end response.status == 200 end test('create zone - set all parameters') do pending if Fog.mocking? type = 'slave' @domain= generate_unique_domain options = { :SOA_email => "netops@#{@domain}", :refresh_sec => 14400, :retry_sec => 3600, :expire_sec => 604800, :ttl_sec => 28800, :status => 0, :master_ips => '1.2.3.4;2.3.4.5' } response = Fog::DNS[:linode].domain_create( @domain, type, options) if response.status == 200 @slave_zone_id = response.body['DATA']['DomainID'] @new_zones << @slave_zone_id end response.status == 200 end test("get zone #{@slave_zone_id} - check all parameters for #{@domain}") do pending if Fog.mocking? result= false response = Fog::DNS[:linode].domain_list( @slave_zone_id) if response.status == 200 zones = response.body['DATA'] num_zones = zones.count if num_zones == 1 zone= zones[0] if (zone['SOA_EMAIL'] == "netops@#{@domain}") and (zone['REFRESH_SEC'] == 14400) and (zone['RETRY_SEC'] == 3600) and (zone['EXPIRE_SEC'] == 604800) and (zone['TTL_SEC'] == 28800) and (zone['STATUS'] == 0) and (zone['DOMAIN'] == @domain) and (zone['TYPE'] == 'slave') (zone['MASTER_IPS'] == '1.2.3.4;2.3.4.5') result= true end end end result end test("update zone #{@slave_zone_id}- update TTL parameter") do pending if Fog.mocking? result= false options = { :ttl_sec => 14400 } response = Fog::DNS[:linode].domain_update( @slave_zone_id, options) if response.status == 200 result= true end result end test("get zone #{@slave_zone_id} - check TTL parameters") do pending if Fog.mocking? result= false response = Fog::DNS[:linode].domain_list( @slave_zone_id) if response.status == 200 zones = response.body['DATA'] num_zones = zones.count if num_zones == 1 zone= zones[0] if (zone['TTL_SEC'] == 14400) result= true end end end result end test('create record - simple A record') do pending if Fog.mocking? host= 'www.' + @domain options = { :name => host, :target => '4.5.6.7', :ttl_sec => 3600 } response = Fog::DNS[:linode].domain_resource_create( @master_zone_id, 'A', options) if response.status == 200 record_id = response.body['DATA']['ResourceID'] @new_records << record_id end response.status == 200 end test('create record - CNAME record') do pending if Fog.mocking? host= 'mail' options = { :name => host, :target => 'www.' + @domain } response = Fog::DNS[:linode].domain_resource_create( @master_zone_id, 'CNAME', options) if response.status == 200 record_id = response.body['DATA']['ResourceID'] @new_records << record_id end response.status == 200 end test('create record - NS record') do pending if Fog.mocking? options = { :name => @domain, :target => 'ns.' + @domain} response = Fog::DNS[:linode].domain_resource_create( @master_zone_id, 'NS', options) if response.status == 200 record_id = response.body['DATA']['ResourceID'] @new_records << record_id end response.status == 200 end test('create record - MX record') do pending if Fog.mocking? options = { :target => 'mail.' + @domain, :ttl_sec => 7200, :priority => 5 } response = Fog::DNS[:linode].domain_resource_create( @master_zone_id, 'MX', options) if response.status == 200 @record_id = response.body['DATA']['ResourceID'] @new_records << @record_id end response.status == 200 end test("get record #{@record_id} - verify all parameters") do pending if Fog.mocking? result= false domain= 'mail.' + @domain response = Fog::DNS[:linode].domain_resource_list(@master_zone_id, @record_id) if response.status == 200 records= response.body['DATA'] if records.count == 1 record = records[0] if (record['TYPE'] == 'MX') and (record['PRIORITY'] == 5) and (record['TTL_SEC'] == 7200) and (record['TARGET'] == domain) result= true end end end result end test("update record #{@record_id} - change target") do pending if Fog.mocking? options = { :target => 'mail2.' + @domain } response = Fog::DNS[:linode].domain_resource_update( @master_zone_id, @record_id, options) response.status == 200 end test("get record #{@record_id} - verify target changed") do pending if Fog.mocking? result= false domain= 'mail2.' + @domain response = Fog::DNS[:linode].domain_resource_list(@master_zone_id, @record_id) if response.status == 200 records= response.body['DATA'] if records.count == 1 record = records[0] if record['TARGET'] == domain result= true end end end result end test("delete #{@new_records.count} records created") do pending if Fog.mocking? result= true @new_records.each { |record_id| response = Fog::DNS[:linode].domain_resource_delete( @master_zone_id, record_id) if response.status != 200 result= false; end } result end test("delete #{@new_zones.count} zones created") do pending if Fog.mocking? result= true @new_zones.each { |zone_id| response = Fog::DNS[:linode].domain_delete( zone_id) if response.status != 200 result= false; end } result end end tests( 'failure') do end end fog-1.19.0/tests/linode/requests/compute/0000755000004100000410000000000012261242552020351 5ustar www-datawww-datafog-1.19.0/tests/linode/requests/compute/datacenter_tests.rb0000644000004100000410000000065112261242552024234 0ustar www-datawww-dataShindo.tests('Fog::Compute[:linode] | datacenter requests', ['linode']) do @datacenters_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => [{ 'DATACENTERID' => Integer, 'LOCATION' => String }] }) tests('success') do tests('#avail_datacenters').formats(@datacenters_format) do pending if Fog.mocking? Fog::Compute[:linode].avail_datacenters.body end end end fog-1.19.0/tests/linode/requests/compute/kernel_tests.rb0000644000004100000410000000136112261242552023401 0ustar www-datawww-dataShindo.tests('Fog::Compute[:linode] | kernel requests', ['linode']) do @kernels_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => [{ 'LABEL' => String, 'ISXEN' => Integer, 'ISPVOPS' => Integer, 'KERNELID' => Integer }] }) tests('success') do @kernel_id = nil tests('#avail_kernels').formats(@kernels_format) do pending if Fog.mocking? data = Fog::Compute[:linode].avail_kernels.body @kernel_id = data['DATA'].first['KERNELID'] data end tests("@avail_kernels(#{@kernel_id})").formats(@kernels_format) do pending if Fog.mocking? Fog::Compute[:linode].avail_kernels(@kernel_id).body end end end fog-1.19.0/tests/linode/requests/compute/linode_tests.rb0000644000004100000410000001074012261242552023374 0ustar www-datawww-dataShindo.tests('Fog::Compute[:linode] | linode requests', ['linode']) do @linode_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => { 'LinodeID' => Integer } }) @linodes_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => [{ 'ALERT_BWIN_ENABLED' => Integer, 'ALERT_CPU_THRESHOLD' => Integer, 'ALERT_BWOUT_ENABLED' => Integer, 'ALERT_BWOUT_THRESHOLD' => Integer, 'ALERT_BWQUOTA_ENABLED' => Integer, 'ALERT_BWQUOTA_THRESHOLD' => Integer, 'ALERT_BWIN_THRESHOLD' => Integer, 'ALERT_CPU_ENABLED' => Integer, 'ALERT_DISKIO_ENABLED' => Integer, 'ALERT_DISKIO_THRESHOLD' => Integer, 'BACKUPSENABLED' => Integer, 'BACKUPWEEKLYDAY' => Integer, 'BACKUPWINDOW' => Integer, 'DATACENTERID' => Integer, 'LABEL' => String, 'LINODEID' => Integer, 'LPM_DISPLAYGROUP' => String, 'STATUS' => Integer, 'TOTALHD' => Integer, 'TOTALRAM' => Integer, 'TOTALXFER' => Integer, 'WATCHDOG' => Integer, }] }) @reboot_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => { 'JobID' => Integer } }) @ip_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => { 'IPAddressID' => Integer } }) @disks_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => [{ "UPDATE_DT" => String, "DISKID" => Integer, "LABEL" => String, "TYPE" => String, "LINODEID" => Integer, "ISREADONLY" => Integer, "STATUS" => Integer, "CREATE_DT" => String, "SIZE" => Integer }] }) @disk_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => { 'JobID' => Integer, 'DiskID' => Integer } }) tests('success') do @linode_id = nil # (2 => Dallas, TX, USA), (1 => 1 month), (1 => Linode 512) tests('#linode_create(2, 1, 1)').formats(@linode_format) do pending if Fog.mocking? data = Fog::Compute[:linode].linode_create(2, 1, 1).body @linode_id = data['DATA']['LinodeID'] data end tests("#linode_list(#{@linode_id})").formats(@linodes_format) do pending if Fog.mocking? Fog::Compute[:linode].linode_list(@linode_id).body end tests('#linode_list').formats(@linodes_format) do pending if Fog.mocking? Fog::Compute[:linode].linode_list.body end tests('#linode_update').formats(@linode_format) do pending if Fog.mocking? Fog::Compute[:linode].linode_update(@linode_id, :label => 'testing').body end tests('#linode_ip_addprivate').formats(@ip_format) do pending if Fog.mocking? Fog::Compute[:linode].linode_ip_addprivate(@linode_id).body end tests('#linode_disk_create').formats(@disk_format) do pending if Fog.mocking? data = Fog::Compute[:linode].linode_disk_create(@linode_id, 'test1', 'ext3', 1).body @disk1_id = data['DATA']['DiskID'] data end tests('#linode_disk_createfromdistribution').formats(@disk_format) do pending if Fog.mocking? data = Fog::Compute[:linode].linode_disk_createfromdistribution(@linode_id, 73, 'test1', 600, 'P@SSW)RD').body @disk2_id = data['DATA']['DiskID'] data end tests('#linode_disk_list').formats(@disks_format) do pending if Fog.mocking? Fog::Compute[:linode].linode_disk_list(@linode_id).body end # tests("#linode_reboot(#{@linode_id})").formats(@reboot_format) do # Fog::Compute[:linode].linode_reboot(@linode_id).body # end tests('#linode_disk_delete').formats(@disk_format) do pending if Fog.mocking? Fog::Compute[:linode].linode_disk_delete(@linode_id, @disk1_id).body Fog::Compute[:linode].linode_disk_delete(@linode_id, @disk2_id).body end tests('#linode_delete(#{@linode_id})').succeeds do pending if Fog.mocking? sleep 1 until Fog::Compute[:linode].linode_disk_list(@linode_id).body['DATA'].size == 0 Fog::Compute[:linode].linode_delete(@linode_id) end end tests('failure') do tests('#linode_reboot(0)').raises(Fog::Compute::Linode::NotFound) do pending if Fog.mocking? Fog::Compute[:linode].linode_reboot(1) end tests('#linode_delete(0)').raises(Fog::Compute::Linode::NotFound) do pending if Fog.mocking? Fog::Compute[:linode].linode_delete(1) end end end fog-1.19.0/tests/linode/requests/compute/stackscripts_tests.rb0000644000004100000410000000212112261242552024631 0ustar www-datawww-dataShindo.tests('Fog::Compute[:linode] | stack_script requests', ['linode']) do @stack_scripts_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => [{ 'STACKSCRIPTID' => Integer, 'SCRIPT' => String, 'DESCRIPTION' => String, 'DISTRIBUTIONIDLIST' => String, 'LABEL' => String, 'DEPLOYMENTSTOTAL' => Integer, 'LATESTREV' => Integer, 'CREATE_DT' => String, 'DEPLOYMENTSACTIVE' => Integer, 'REV_NOTE' => String, 'REV_DT' => String, 'ISPUBLIC' => Integer, 'USERID' => Integer }] }) tests('success') do tests('#avail_stackscripts').formats(@stack_scripts_format) do pending if Fog.mocking? Fog::Compute[:linode].avail_stackscripts.body end tests('#stackscript_list').formats(@stack_scripts_format) do pending # TODO: REV_NOTE can be either string or float? pending if Fog.mocking? Fog::Compute[:linode].stackscript_list.body end end end fog-1.19.0/tests/linode/requests/compute/helper.rb0000644000004100000410000000023612261242552022156 0ustar www-datawww-dataclass Linode module Compute module Formats BASIC = { 'ERRORARRAY' => [], 'ACTION' => String } end end end fog-1.19.0/tests/linode/requests/compute/distribution_tests.rb0000644000004100000410000000162112261242552024637 0ustar www-datawww-dataShindo.tests('Fog::Compute[:linode] | distribution requests', ['linode']) do @distributions_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => [{ 'CREATE_DT' => String, 'DISTRIBUTIONID' => Integer, 'IS64BIT' => Integer, 'LABEL' => String, 'MINIMAGESIZE' => Integer, 'REQUIRESPVOPSKERNEL' => Integer }] }) tests('success') do @distribution_id = nil tests('#avail_distributions').formats(@distributions_format) do pending if Fog.mocking? data = Fog::Compute[:linode].avail_distributions.body @distribution_id = data['DATA'].first['DISTRIBUTIONID'] data end tests("@avail_distributions(#{@distribution_id})").formats(@distributions_format) do pending if Fog.mocking? Fog::Compute[:linode].avail_distributions(@distribution_id).body end end end fog-1.19.0/tests/linode/requests/compute/linodeplans_tests.rb0000644000004100000410000000173212261242552024433 0ustar www-datawww-dataShindo.tests('Fog::Compute[:linode] | linodeplans requests', ['linode']) do @linodeplans_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => [{ 'AVAIL' => { '2' => Integer, '3' => Integer, '4' => Integer, '6' => Integer, '7' => Integer, '8' => Integer }, 'DISK' => Integer, 'PLANID' => Integer, 'PRICE' => Float, 'RAM' => Integer, 'LABEL' => String, 'XFER' => Integer }] }) tests('success') do @linodeplan_id = nil tests('#avail_linodeplans').formats(@linodeplans_format) do pending if Fog.mocking? data = Fog::Compute[:linode].avail_linodeplans.body @linodeplan_id = data['DATA'].first['PLANID'] data end tests("#avail_linodeplans(#{@linodeplan_id})").formats(@linodeplans_format) do pending if Fog.mocking? Fog::Compute[:linode].avail_linodeplans(@linodeplan_id).body end end end fog-1.19.0/tests/hp/0000755000004100000410000000000012261242552014157 5ustar www-datawww-datafog-1.19.0/tests/hp/user_agent_tests.rb0000644000004100000410000000106512261242552020064 0ustar www-datawww-dataShindo.tests('Fog::Compute[:hp] | user agent', ['hp', 'user_agent']) do tests('default for HP providers').returns("hpfog/#{Fog::HP::VERSION}") do pending if Fog.mocking? conn = Fog::Compute[:hp] conn.instance_variable_get(:@connection_options)[:headers]['User-Agent'] end tests('overriden by clients').returns("hpfog/#{Fog::HP::VERSION} (TesterClient/1.0.0)") do pending if Fog.mocking? conn = Fog::Compute::HP.new(:user_agent => "TesterClient/1.0.0") conn.instance_variable_get(:@connection_options)[:headers]['User-Agent'] end endfog-1.19.0/tests/hp/requests/0000755000004100000410000000000012261242552016032 5ustar www-datawww-datafog-1.19.0/tests/hp/requests/network/0000755000004100000410000000000012261242552017523 5ustar www-datawww-datafog-1.19.0/tests/hp/requests/network/port_tests.rb0000644000004100000410000000423312261242552022260 0ustar www-datawww-dataShindo.tests('HP::Network | networking port requests', ['hp', 'networking', 'port']) do @port_format = { 'id' => String, 'name' => Fog::Nullable::String, 'network_id' => String, 'fixed_ips' => Array, 'mac_address' => String, 'status' => String, 'admin_state_up' => Fog::Boolean, 'binding:vif_type' => String, 'device_owner' => String, 'device_id' => String, 'security_groups' => Array, 'tenant_id' => String } n_data = HP[:network].create_network({:name => 'fog_network'}).body['network'] @network_id = n_data['id'] tests('success') do @port_id = nil tests('#create_port').formats(@port_format) do attributes = {:name => 'myport', :fixed_ips => [], :mac_address => 'fa:16:3e:71:26:c8', :admin_state_up => true, :device_owner => '2222222', :device_id => '3333333', :tenant_id => '111111111'} data = HP[:network].create_port(@network_id, attributes).body['port'] @port_id = data['id'] data end tests('#list_port').formats({'ports' => [@port_format]}) do HP[:network].list_ports.body end tests("#get_port(#{@port_id})").formats({'port' => @port_format}) do HP[:network].get_port(@port_id).body end tests("#update_port(#{@port_id})").formats({'port' => @port_format}) do attributes = {:name => 'myport_upd', :fixed_ips => [], :admin_state_up => true, :device_owner => 'device_owner', :device_id => 'device_id'} HP[:network].update_port(@port_id, attributes).body end tests("#delete_port(#{@port_id})").succeeds do HP[:network].delete_port(@port_id) end end tests('failure') do tests('#get_port(0)').raises(Fog::HP::Network::NotFound) do HP[:network].get_port(0) end tests('#update_port(0)').raises(Fog::HP::Network::NotFound) do HP[:network].update_port(0, {}) end tests('#delete_port(0)').raises(Fog::HP::Network::NotFound) do HP[:network].delete_port(0) end end # cleanup HP[:network].delete_network(@network_id) endfog-1.19.0/tests/hp/requests/network/security_group_tests.rb0000644000004100000410000000266212261242552024363 0ustar www-datawww-dataShindo.tests('HP::Network | networking security group requests', ['hp', 'networking', 'securitygroup']) do @security_group_format = { 'id' => String, 'name' => String, 'description' => String, 'tenant_id' => String, 'security_group_rules' => [Hash] } tests('success') do @sec_group_id = nil tests("#create_security_group('fog_security_group', 'tests group')").formats(@security_group_format) do attributes = {:name => 'fog_security_group', :description => 'tests group'} data = HP[:network].create_security_group(attributes).body['security_group'] @sec_group_id = data['id'] data end tests("#get_security_group('#{@sec_group_id}')").formats(@security_group_format) do HP[:network].get_security_group(@sec_group_id).body['security_group'] end tests("#list_security_groups").formats('security_groups' => [@security_group_format]) do HP[:network].list_security_groups.body end tests("#delete_security_group('#{@sec_group_id}')").succeeds do HP[:network].delete_security_group(@sec_group_id) end end tests('failure') do tests("#get_security_group(0)").raises(Fog::HP::Network::NotFound) do HP[:network].get_security_group(0) end tests("#delete_security_group(0)").raises(Fog::HP::Network::NotFound) do HP[:network].delete_security_group(0) end end end fog-1.19.0/tests/hp/requests/network/floating_ip_tests.rb0000644000004100000410000000451612261242552023573 0ustar www-datawww-dataShindo.tests('HP::Network | networking floating ip requests', ['hp', 'networking', 'floatingip']) do @floating_ip_format = { 'id' => String, 'tenant_id' => String, 'floating_network_id' => String, 'router_id' => Fog::Nullable::String, 'fixed_ip_address' => Fog::Nullable::String, 'floating_ip_address' => String, 'port_id' => Fog::Nullable::String } @ext_network_id = HP[:network].list_networks({'router:external'=>true}).body['networks'][0]['id'] s_data = HP[:network].create_port(@ext_network_id, {:name => 'fog_port'}).body['port'] @port_id = s_data['id'] tests('success') do @floating_ip_id = nil tests("#create_floating_ip(#{@ext_network_id})").formats(@floating_ip_format) do data = HP[:network].create_floating_ip(@ext_network_id).body['floatingip'] @floating_ip_id = data['id'] data end tests('#list_floating_ips').formats({'floatingips' => [@floating_ip_format]}) do HP[:network].list_floating_ips.body end tests("#get_floating_ip(#{@floating_ip_id})").formats({'floatingip' => @floating_ip_format}) do HP[:network].get_floating_ip(@floating_ip_id).body end tests("#associate_floating_ip(#{@floating_ip_id}, #{@port_id})").formats({'floatingip' => @floating_ip_format}) do HP[:network].associate_floating_ip(@floating_ip_id, @port_id).body end tests("#disassociate_floating_ip(#{@floating_ip_id}, nil)").formats({'floatingip' => @floating_ip_format}) do HP[:network].disassociate_floating_ip(@floating_ip_id, nil).body end tests("#delete_floating_ip(#{@floating_ip_id})").succeeds do HP[:network].delete_floating_ip(@floating_ip_id) end end tests('failure') do tests('#get_floating_ip("0")').raises(Fog::HP::Network::NotFound) do HP[:network].get_floating_ip(0) end tests("#associate_floating_ip('0', #{@port_id})").raises(Fog::HP::Network::NotFound) do HP[:network].associate_floating_ip('0', @port_id) end tests('#disassociate_floating_ip("0")').raises(Fog::HP::Network::NotFound) do HP[:network].disassociate_floating_ip("0") end tests('#delete_floating_ip("0")').raises(Fog::HP::Network::NotFound) do HP[:network].delete_floating_ip("0") end end # cleanup HP[:network].delete_port(@port_id) endfog-1.19.0/tests/hp/requests/network/subnet_tests.rb0000644000004100000410000000437212261242552022600 0ustar www-datawww-dataShindo.tests('HP::Network | networking subnet requests', ['hp', 'networking', 'subnet']) do @subnet_format = { 'id' => String, 'name' => Fog::Nullable::String, 'network_id' => String, 'cidr' => String, 'ip_version' => Integer, 'gateway_ip' => Fog::Nullable::String, 'allocation_pools' => Fog::Nullable::Array, 'dns_nameservers' => Fog::Nullable::Array, 'host_routes' => Fog::Nullable::Array, 'enable_dhcp' => Fog::Boolean, 'tenant_id' => String, } n_data = HP[:network].create_network({:name => 'fog_network'}).body['network'] @network_id = n_data['id'] tests('success') do @subnet_id = nil tests('#create_subnet').formats(@subnet_format) do attributes = {:name => 'mysubnet', :gateway_ip => '10.0.3.1', :allocation_pools => [], :dns_nameservers => [], :host_routes => [], :enable_dhcp => true, :tenant_id => '111111111'} data = HP[:network].create_subnet(@network_id, '10.0.3.0/24', 4, attributes).body['subnet'] @subnet_id = data['id'] data end tests('#list_subnets').formats({'subnets' => [@subnet_format]}) do HP[:network].list_subnets.body end tests("#get_subnet(#{@subnet_id})").formats({'subnet' => @subnet_format}) do HP[:network].get_subnet(@subnet_id).body end tests("#update_subnet(#{@subnet_id})").formats({'subnet' => @subnet_format}) do attributes = {:name => 'mysubnet_upd',:gateway_ip => '10.0.3.1', :dns_nameservers => [], :host_routes => [], :enable_dhcp => true} HP[:network].update_subnet(@subnet_id, attributes).body end tests("#delete_subnet(#{@subnet_id})").succeeds do HP[:network].delete_subnet(@subnet_id) end end tests('failure') do tests('#get_subnet(0)').raises(Fog::HP::Network::NotFound) do HP[:network].get_subnet(0) end tests('#update_subnet(0)').raises(Fog::HP::Network::NotFound) do HP[:network].update_subnet(0, {}) end tests('#delete_subnet(0)').raises(Fog::HP::Network::NotFound) do HP[:network].delete_subnet(0) end end # cleanup HP[:network].delete_network(@network_id) endfog-1.19.0/tests/hp/requests/network/router_tests.rb0000644000004100000410000000725312261242552022621 0ustar www-datawww-dataShindo.tests('HP::Network | networking router requests', ['hp', 'networking', 'router']) do @router_format = { 'id' => String, 'name' => String, 'tenant_id' => String, 'status' => String, 'admin_state_up' => Fog::Boolean, 'external_gateway_info' => Fog::Nullable::Hash } @router_interface_format = { 'subnet_id' => String, 'port_id' => String } n_data = HP[:network].create_network({:name => 'fog_network'}).body['network'] @network_id = n_data['id'] p_data = HP[:network].create_port(@network_id, {:name => 'fog_port'}).body['port'] @port_id = p_data['id'] tests('success') do @router_id = nil tests('#create_router').formats(@router_format) do attributes = {:name => 'my_router', :admin_state_up => true} data = HP[:network].create_router(attributes).body['router'] @router_id = data['id'] data end tests('#list_routers').formats({'routers' => [@router_format]}) do HP[:network].list_routers.body end tests("#get_router(#{@router_id})").formats({'router' => @router_format}) do HP[:network].get_router(@router_id).body end tests("#update_router(#{@router_id})").formats({'router' => @router_format}) do attributes = { :name => 'my_router_upd', :external_gateway_info => { :network_id => '11111111111' }, :admin_state_up => true } HP[:network].update_router(@router_id, attributes).body end tests("#add_router_interface(#{@router_id}, '1111111111', nil) - using subnet_id").formats(@router_interface_format) do HP[:network].add_router_interface(@router_id, '1111111111', nil).body end #tests("#remove_router_interface(#{@router_id}, '1111111111', nil) - using subnet_id").formats('') do # HP[:network].remove_router_interface(@router_id, '1111111111', nil).body #end tests("#add_router_interface(#{@router_id}, nil, #{@port_id}) - using port_id").formats(@router_interface_format) do HP[:network].add_router_interface(@router_id, nil, @port_id).body end tests("#add_router_interface(#{@router_id}, '1111111111', '2222222222') - using port_id and subnet_id").raises(ArgumentError) do HP[:network].add_router_interface(@router_id, '1111111111', '2222222222').body end tests("#remove_router_interface(#{@router_id}, nil, #{@port_id}) - using port_id").formats('') do HP[:network].remove_router_interface(@router_id, nil, @port_id).body end tests("#remove_router_interface(#{@router_id}, '1111111111', '2222222222') - using port_id and subnet_id").raises(ArgumentError) do HP[:network].remove_router_interface(@router_id, '1111111111', '2222222222').body end tests("#delete_router(#{@router_id})").succeeds do HP[:network].delete_router(@router_id) end end tests('failure') do tests('#get_router(0)').raises(Fog::HP::Network::NotFound) do HP[:network].get_router(0) end tests('#update_router(0)').raises(Fog::HP::Network::NotFound) do HP[:network].update_router(0, {}) end tests('#delete_router(0)').raises(Fog::HP::Network::NotFound) do HP[:network].delete_router(0) end tests("#add_router_interface(0, '1111111111')").raises(Fog::HP::Network::NotFound) do HP[:network].add_router_interface(0, '1111111111').body end tests("#remove_router_interface(0, '1111111111')").raises(Fog::HP::Network::NotFound) do HP[:network].remove_router_interface(0, '1111111111').body end end # cleanup # remove_router_interface method removes the port #HP[:network].delete_port(@port_id) HP[:network].delete_network(@network_id) endfog-1.19.0/tests/hp/requests/network/network_tests.rb0000644000004100000410000000331212261242552022762 0ustar www-datawww-dataShindo.tests('HP::Network | networking network requests', ['hp', 'networking', 'network']) do @network_format = { 'id' => String, 'name' => Fog::Nullable::String, 'tenant_id' => String, 'status' => String, 'subnets' => Array, 'router:external' => Fog::Boolean, 'admin_state_up' => Fog::Boolean, 'shared' => Fog::Boolean } tests('success') do @network_id = nil tests('#create_network').formats(@network_format) do attributes = {:name => 'my_network', :admin_state_up => true, :shared => false} data = HP[:network].create_network(attributes).body['network'] @network_id = data['id'] data end tests('#list_networks').formats({'networks' => [@network_format]}) do HP[:network].list_networks.body end tests("#get_network(#{@network_id})").formats({'network' => @network_format}) do HP[:network].get_network(@network_id).body end tests("#update_network(#{@network_id})").formats({'network' => @network_format}) do attributes = {:name => 'my_network_upd', :shared => false, :admin_state_up => true} HP[:network].update_network(@network_id, attributes).body end tests("#delete_network(#{@network_id})").succeeds do HP[:network].delete_network(@network_id) end end tests('failure') do tests('#get_network(0)').raises(Fog::HP::Network::NotFound) do HP[:network].get_network(0) end tests('#update_network(0)').raises(Fog::HP::Network::NotFound) do HP[:network].update_network(0, {}) end tests('#delete_network(0)').raises(Fog::HP::Network::NotFound) do HP[:network].delete_network(0) end end endfog-1.19.0/tests/hp/requests/network/security_group_rule_tests.rb0000644000004100000410000000417412261242552025412 0ustar www-datawww-dataShindo.tests('HP::Network | networking security group rule requests', ['hp', 'networking', 'securitygroup']) do @security_group_rule_format = { 'id' => String, 'remote_group_id' => Fog::Nullable::String, 'direction' => String, 'remote_ip_prefix' => Fog::Nullable::String, 'protocol' => Fog::Nullable::String, 'ethertype' => String, 'port_range_max' => Fog::Nullable::Integer, 'port_range_min' => Fog::Nullable::Integer, 'security_group_id' => String, 'tenant_id' => String } tests('success') do attributes = {:name => 'my_security_group', :description => 'tests group'} data = HP[:network].create_security_group(attributes).body['security_group'] @sec_group_id = data['id'] @sec_group_rule_id = nil tests("#create_security_group_rule(#{@sec_group_id}, 'ingress', attributes)").formats(@security_group_rule_format) do attributes = {:remote_ip_prefix => '0.0.0.0/0', :protocol => 'tcp', :port_range_min => 22, :port_range_max => 22} data = HP[:network].create_security_group_rule(@sec_group_id, 'ingress', attributes).body['security_group_rule'] @sec_group_rule_id = data['id'] data end tests("#get_security_group_rule('#{@sec_group_rule_id}')").formats(@security_group_rule_format) do HP[:network].get_security_group_rule(@sec_group_rule_id).body['security_group_rule'] end tests("#list_security_group_rules").formats('security_group_rules' => [@security_group_rule_format]) do HP[:network].list_security_group_rules.body end tests("#delete_security_group_rule('#{@sec_group_rule_id}')").succeeds do HP[:network].delete_security_group_rule(@sec_group_rule_id) end end tests('failure') do tests('#get_security_group_rule(0)').raises(Fog::HP::Network::NotFound) do HP[:network].get_security_group_rule(0) end tests('#delete_security_group_rule(0)').raises(Fog::HP::Network::NotFound) do HP[:network].delete_security_group_rule(0) end end HP[:network].delete_security_group(@sec_group_id) end fog-1.19.0/tests/hp/requests/storage/0000755000004100000410000000000012261242552017476 5ustar www-datawww-datafog-1.19.0/tests/hp/requests/storage/object_tests.rb0000644000004100000410000001204612261242552022516 0ustar www-datawww-dataShindo.tests("Fog::Storage[:hp] | object requests", ['hp', 'storage']) do @directory = Fog::Storage[:hp].directories.create(:key => 'fogobjecttests') @dir_name = @directory.identity tests('success') do tests("#put_object('#{@dir_name}', 'fog_object')").succeeds do Fog::Storage[:hp].put_object(@dir_name, 'fog_object', lorem_file) end tests("#post_object('#{@dir_name}', 'fog_object', {'X-Object-Meta-Foo' => 'foometa'})").succeeds do Fog::Storage[:hp].post_object(@dir_name, 'fog_object', {'X-Object-Meta-Foo' => 'foometa'}) end tests("#get_object('#{@dir_name}', 'fog_object')").succeeds do Fog::Storage[:hp].get_object(@dir_name, 'fog_object') end tests("#get_object('#{@dir_name}', 'fog_object', &block)").returns(lorem_file.read) do data = '' Fog::Storage[:hp].get_object(@dir_name, 'fog_object') do |chunk, remaining_bytes, total_bytes| data << chunk end data end tests("#head_object('#{@dir_name}', 'fog_object')").succeeds do Fog::Storage[:hp].head_object(@dir_name, 'fog_object') end tests("#get_object_temp_url('#{@dir_name}', 'fog_object', 60, 'GET')").succeeds do Fog::Storage[:hp].get_object_temp_url(@dir_name, 'fog_object', 60, 'GET') end # copy a file within the same container tests("#put_object('#{@dir_name}', 'fog_other_object', nil, {'X-Copy-From' => '/#{@dir_name}/fog_object'})" ).succeeds do Fog::Storage[:hp].put_object(@dir_name, 'fog_other_object', nil, {'X-Copy-From' => "/#{@dir_name}/fog_object"}) end @directory.files.get('fog_other_object').destroy # copy a file from one container to another @another_dir = Fog::Storage[:hp].directories.create(:key => 'fogobjecttests2') tests("#put_object('#{@another_dir.identity}', 'fog_another_object', nil, {'X-Copy-From' => '/#{@dir_name}/fog_object'})" ).succeeds do Fog::Storage[:hp].put_object(@another_dir.identity, 'fog_another_object', nil, {'X-Copy-From' => "/#{@dir_name}/fog_object"}) end @another_dir.files.get('fog_another_object').destroy @another_dir.destroy tests("#post_object('#{@dir_name}', 'fog_delete_object', {'X-Delete-After' => 40})" ).succeeds do Fog::Storage[:hp].put_object(@dir_name, 'fog_delete_object', lorem_file) Fog::Storage[:hp].post_object(@dir_name, 'fog_delete_object', {'X-Delete-After' => 40}) end tests("#delete_object('#{@dir_name}', 'fog_object')").succeeds do Fog::Storage[:hp].delete_object(@dir_name, 'fog_object') Fog::Storage[:hp].delete_object(@dir_name, 'fog_delete_object') end tests("#get_object_http_url('#{@directory.identity}', 'fog_object', expiration timestamp)").returns(true) do object_url = Fog::Storage[:hp].get_object_http_url(@dir_name, 'fog_object', (Time.now + 60)) object_url.include? "fog_object" object_url.include? "&temp_url_expires=" object_url.include? "temp_url_sig=" object_url.include? @dir_name object_url.start_with? "http://" end tests("#get_object_https_url('#{@directory.identity}', 'fog_object', expiration timestamp)").returns(true) do object_url = Fog::Storage[:hp].get_object_https_url(@dir_name, 'fog_object', (Time.now + 60)) object_url.include? "fog_object" object_url.include? "&temp_url_expires=" object_url.include? "temp_url_sig=" object_url.include? @dir_name object_url.start_with? "https://" end end tests('failure') do tests("#put_object('fognoncontainer', 'fog_object')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].put_object('fognoncontainer', 'fog_object', lorem_file) end tests("#post_object('fognoncontainer', 'fog_object')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].post_object('fognoncontainer', 'fog_object') end tests("#get_object('#{@dir_name}', 'fog_non_object')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].get_object(@dir_name, 'fog_non_object') end tests("#get_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].get_object('fognoncontainer', 'fog_non_object') end tests("#get_object_temp_url('#{@dir_name}', 'fog_object', 60, 'POST')").raises(ArgumentError) do Fog::Storage[:hp].get_object_temp_url(@dir_name, 'fog_object', 60, 'POST') end tests("#head_object('#{@dir_name}', 'fog_non_object')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].head_object(@dir_name, 'fog_non_object') end tests("#head_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].head_object('fognoncontainer', 'fog_non_object') end tests("#delete_object('#{@dir_name}', 'fog_non_object')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].delete_object(@dir_name, 'fog_non_object') end tests("#delete_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].delete_object('fognoncontainer', 'fog_non_object') end end @directory.destroy end fog-1.19.0/tests/hp/requests/storage/container_tests.rb0000644000004100000410000000553512261242552023237 0ustar www-datawww-dataShindo.tests("Fog::Storage[:hp] | container requests", ['hp']) do @container_format = [String] @containers_format = [{ 'bytes' => Integer, 'count' => Integer, 'name' => String }] tests('success') do tests("#put_container('fogcontainertests')").succeeds do Fog::Storage[:hp].put_container('fogcontainertests') end tests("#post_container('fogcontainertests', {'X-Container-Meta-Foo' => 'foometa'})").succeeds do Fog::Storage[:hp].post_container('fogcontainertests', {'X-Container-Meta-Foo' => 'foometa'}) end tests("#get_container('fogcontainertests')").formats(@container_format) do Fog::Storage[:hp].get_container('fogcontainertests').body end tests("#get_containers").formats(@containers_format) do Fog::Storage[:hp].get_containers.body end tests("#head_container('fogcontainertests')").succeeds do Fog::Storage[:hp].head_container('fogcontainertests') end tests("#head_containers").succeeds do Fog::Storage[:hp].head_containers end tests("#delete_container('fogcontainertests')").succeeds do Fog::Storage[:hp].delete_container('fogcontainertests') end tests("#put_container('fogacltests', {'X-Container-Read' => 'private'})").succeeds do Fog::Storage[:hp].put_container('fogacltests', {'X-Container-Read' => 'private'}) end Fog::Storage[:hp].delete_container('fogacltests') tests("#put_container('fogacltests', {'X-Container-Read' => 'public-read'})").succeeds do Fog::Storage[:hp].put_container('fogacltests', {'X-Container-Read' => 'public-read'}) end Fog::Storage[:hp].delete_container('fogacltests') tests("#put_container('fogacltests', {'X-Container-Read' => 'invalid'})").succeeds do Fog::Storage[:hp].put_container('fogacltests', {'X-Container-Read' => 'invalid'}) end Fog::Storage[:hp].delete_container('fogacltests') end tests('failure') do tests("#get_container('fognoncontainer')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].get_container('fognoncontainer') end tests("#post_container('fognoncontainer', {})").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].post_container('fognoncontainer', {}) end tests("#head_container('fognoncontainer')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].head_container('fognoncontainer') end tests("#delete_container('fognoncontainer')").raises(Fog::Storage::HP::NotFound) do Fog::Storage[:hp].delete_container('fognoncontainer') end @container = Fog::Storage[:hp].directories.create(:key => 'fognonempty') @file = @container.files.create(:key => 'foo', :body => 'bar') tests("#delete_container('fognonempty')").raises(Excon::Errors::Conflict) do Fog::Storage[:hp].delete_container('fognonempty') end @file.destroy @container.destroy end end fog-1.19.0/tests/hp/requests/dns/0000755000004100000410000000000012261242552016616 5ustar www-datawww-datafog-1.19.0/tests/hp/requests/dns/domain_tests.rb0000644000004100000410000000406712261242552021643 0ustar www-datawww-dataShindo.tests("HP::DNS | domain requests", ['hp', 'dns', 'domain']) do @domain_format = { 'id' => String, 'name' => String, 'description' => String, 'ttl' => Integer, 'serial' => Integer, 'email' => String, 'created_at' => String } @server_format = { 'id' => String, 'name' => String, 'created_at' => String, 'updated_at' => String } tests('success') do @domain_name = 'www.fogtest.com.' @email = 'test@fogtest.com' tests("#create_domain(#{@domain_name}, #{@email})").formats(@domain_format) do data = HP[:dns].create_domain(@domain_name, @email).body @domain_id = data['id'] data end tests('#list_domains').formats({'domains' => [@domain_format]}) do HP[:dns].list_domains.body end tests("#get_domain(#{@domain_id})").formats(@domain_format) do HP[:dns].get_domain(@domain_id).body end tests("#get_servers_hosting_domain(#{@domain_id})").formats('servers' => [@server_format]) do HP[:dns].get_servers_hosting_domain(@domain_id).body end tests("#update_domain(#{@domain_id}, {:email => 'updated@fogtest.com'})").formats(@domain_format) do HP[:dns].update_domain(@domain_id, {:email => 'updated@fogtest.com'}).body end tests("#delete_domain(#{@domain_id})").succeeds do HP[:dns].delete_domain(@domain_id) end end tests('failure') do tests("#get_domain('invalid_domain')").raises(Fog::HP::DNS::NotFound) do HP[:dns].get_domain('invalid_domain') end tests("#get_servers_hosting_domain('invalid_domain')").raises(Fog::HP::DNS::NotFound) do HP[:dns].get_servers_hosting_domain('invalid_domain') end tests("#update_domain('invalid_domain', {:email => 'updated@fogtest.com'})").raises(Fog::HP::DNS::NotFound) do HP[:dns].update_domain('invalid_domain', {:email => 'updated@fogtest.com'}) end tests("#delete_domain('invalid_domain')").raises(Fog::HP::DNS::NotFound) do HP[:dns].delete_domain('invalid_domain') end end endfog-1.19.0/tests/hp/requests/dns/records_tests.rb0000644000004100000410000000421512261242552022030 0ustar www-datawww-dataShindo.tests("HP::DNS | record requests", ['hp', 'dns', 'record']) do @record_format = { 'id' => String, 'name' => String, 'description' => String, 'type' => String, 'domain_id' => String, 'ttl' => Integer, 'data' => String, 'priority' => Fog::Nullable::Integer, 'created_at' => String, 'updated_at' => String } tests('success') do @domain_name = 'www.fogtest.com.' @email = 'test@fogtest.com' @domain_id = HP[:dns].create_domain(@domain_name, @email).body['id'] @record_name = 'www.fogtest.com.' @record_data = '15.185.172.152' tests("#create_record(#{@domain_id}, #{@record_name}, 'A', #{@record_data})").formats(@record_format) do data = HP[:dns].create_record(@domain_id, @record_name, 'A', @record_data).body @record_id = data['id'] data end tests("#list_records_in_a_domain(#{@domain_id})").formats({'records' => [@record_format]}) do HP[:dns].list_records_in_a_domain(@domain_id).body end tests("#get_record(#{@domain_id}, #{@record_id})").formats(@record_format) do HP[:dns].get_record(@domain_id, @record_id).body end tests("#update_record(#{@domain_id}, #{@record_id}, {:description => 'desc for record'})").formats(@record_format) do HP[:dns].update_record(@domain_id, @record_id, {:description => 'desc for record'}).body end tests("#delete_record(#{@domain_id}, #{@record_id})").succeeds do HP[:dns].delete_record(@domain_id, @record_id) end HP[:dns].delete_domain(@domain_id) end tests('failure') do tests("#get_record(#{@domain_id}, 'invalid_record')").raises(Fog::HP::DNS::NotFound) do HP[:dns].get_record(@domain_id, 'invalid_record') end tests("#update_record(#{@domain_id}, 'invalid_record', {:email => 'updated@fogtest.com'})").raises(Fog::HP::DNS::NotFound) do HP[:dns].update_record(@domain_id, 'invalid_record', {:email => 'updated@fogtest.com'}) end tests("#delete_record(#{@domain_id}, 'invalid_record')").raises(Fog::HP::DNS::NotFound) do HP[:dns].delete_record(@domain_id, 'invalid_record') end end endfog-1.19.0/tests/hp/requests/compute_v2/0000755000004100000410000000000012261242552020115 5ustar www-datawww-datafog-1.19.0/tests/hp/requests/compute_v2/availability_zone_tests.rb0000644000004100000410000000066612261242552025401 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | availability_zone requests", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @zone_format = { 'zoneName' => String, 'zoneState' => Hash, 'hosts' => nil } tests('success') do tests('#list_availability_zones').formats([@zone_format]) do service.list_availability_zones.body['availabilityZoneInfo'] end end endfog-1.19.0/tests/hp/requests/compute_v2/metadata_tests.rb0000644000004100000410000000745412261242552023456 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | metadata requests", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @metadata_format = { 'metadata' => Fog::Nullable::Hash } @metaitem_format = { 'meta' => Fog::Nullable::Hash } @base_image_id = ENV["BASE_IMAGE_ID"] || "7f60b54c-cd15-433f-8bed-00acbcd25a17" tests('success') do @server_name = 'fogmetadatatest' @server_id = nil # check to see if there are any existing servers, otherwise create one if (data = service.list_servers(:status => 'ACTIVE').body['servers'][0]) @server_id = data['id'] else #@server = service.servers.create(:name => @server_name, :flavor_id => 100, :image_id => @base_image_id, :metadata => {'Meta1' => 'MetaValue1', 'Meta2' => 'MetaValue2'} ) #@server.wait_for { ready? } data = service.create_server(@server_name, 100, @base_image_id, {'metadata' => {'Meta1' => 'MetaValue1', 'Meta2' => 'MetaValue2'} }).body['server'] @server_id = data['id'] end tests("#list_metadata('servers', #{@server_id})").formats(@metadata_format) do metadata = service.list_metadata('servers', @server_id).body test ("metadata exists") do metadata['metadata']['Meta1'] == "MetaValue1" end metadata end tests("#set_metadata('servers', #{@server_id}, {'MetaNew3' => 'MetaNewValue3'})").formats(@metadata_format) do data = service.set_metadata('servers', @server_id, {'MetaNew3' => 'MetaNewValue3'}).body test ("metadata set correctly") do metadata = service.list_metadata('servers', @server_id).body metadata['metadata']['MetaNew3'] == "MetaNewValue3" end data end tests("#update_metadata('servers', #{@server_id}, {'MetaUpd4' => 'MetaUpdValue4'})").formats(@metadata_format) do data = service.update_metadata('servers', @server_id, {'MetaUpd4' => 'MetaUpdValue4'}).body test ("metadata updated correctly") do metadata = service.list_metadata('servers', @server_id).body metadata['metadata']['MetaUpd4'] == "MetaUpdValue4" end data end tests("#get_meta('servers', #{@server_id}, 'MetaNew3')").formats(@metaitem_format) do mitem = service.get_meta('servers', @server_id, 'MetaNew3').body test ("metadata item exists") do mitem['meta']['MetaNew3'] == "MetaNewValue3" end mitem end tests("#update_meta('servers', #{@server_id}, 'MetaNew3', 'MetaUpdValue3')").formats(@metaitem_format) do mitem = service.update_meta('servers', @server_id, 'MetaNew3', 'MetaUpdValue3').body test ("metadata item updated correctly") do mitem['meta']['MetaNew3'] == "MetaUpdValue3" end mitem end tests("#delete_meta('servers', #{@server_id}, 'MetaNew3')").succeeds do data = service.delete_meta('servers', @server_id, 'MetaNew3').body test ("metadata item deleted correctly") do metadata = service.list_metadata('servers', @server_id).body metadata['metadata'].fetch('MetaNew3', nil) == nil end data end service.delete_server(@server_id) end tests('failure') do tests("#update_metadata('servers', 0, {'MetaUpd4' => 'MetaUpdValue4'})").raises(Fog::Compute::HPV2::NotFound) do service.update_metadata('servers', 0, {'MetaUpd4' => 'MetaUpdValue4'}) end tests("#get_meta('servers', 0, 'MetaNew3')").raises(Fog::Compute::HPV2::NotFound) do service.get_meta('servers', 0, 'MetaNew3') end tests("#update_meta('servers', 0, 'MetaNew3', 'MetaUpdValue3')").raises(Fog::Compute::HPV2::NotFound) do service.update_meta('servers', 0, 'MetaNew3', 'MetaUpdValue3') end tests("#delete_meta('servers', 0, 'MetaNew3')").raises(Fog::Compute::HPV2::NotFound) do service.delete_meta('servers', 0, 'MetaNew3') end end endfog-1.19.0/tests/hp/requests/compute_v2/flavor_tests.rb0000644000004100000410000000203612261242552023156 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | flavor requests", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @flavor_format = { 'id' => String, 'name' => String, 'vcpus' => Integer, 'disk' => Integer, 'ram' => Integer, 'OS-FLV-EXT-DATA:ephemeral' => Integer, 'links' => [Hash] } @list_flavors_format = { 'id' => String, 'name' => String, 'links' => [Hash] } tests('success') do tests('#list_flavors').formats({'flavors' => [@list_flavors_format]}) do service.list_flavors.body end tests('#get_flavor_details("1")').formats(@flavor_format) do service.get_flavor_details("1").body['flavor'] end tests('#list_flavors_detail').formats({'flavors' => [@flavor_format]}) do service.list_flavors_detail.body end end tests('failure') do tests('#get_flavor_details("9999")').raises(Fog::Compute::HPV2::NotFound) do service.get_flavor_details('9999') end end end fog-1.19.0/tests/hp/requests/compute_v2/image_tests.rb0000644000004100000410000000475212261242552022756 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | image requests", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @image_format = { 'id' => String, 'links' => [Hash], 'metadata' => Fog::Nullable::Hash, 'server' => Fog::Nullable::Hash, 'name' => String, 'progress' => Fog::Nullable::Integer, 'minDisk' => Fog::Nullable::Integer, 'minRam' => Fog::Nullable::Integer, 'status' => String, 'created' => Fog::Nullable::String, 'updated' => Fog::Nullable::String } @list_images_format = { 'id' => String, 'links' => Fog::Nullable::Array, 'name' => String } @base_image_id = ENV["BASE_IMAGE_ID"] || "7f60b54c-cd15-433f-8bed-00acbcd25a17" tests('success') do @server_name = 'fogservertest' @image_name = 'fogimagetest' @image_id = nil @server_id = nil # check to see if there are any existing servers, otherwise create one if (data = service.list_servers(:status => 'ACTIVE').body['servers'][0]) @server_id = data['id'] else #@server = service.servers.create(:name => @server_name, :flavor_id => 100, :image_id => @base_image_id) #@server.wait_for { ready? } data = service.create_server(@server_name, 100, @base_image_id).body['server'] @server_id = data['id'] end tests("#create_image(#{@server_id}, #{@image_name})").formats({}) do response = service.create_image(@server_id, @image_name) # no data is returned for the call, so get id off the header @image_id = response.headers["Location"].split("/")[5] {} end #unless Fog.mocking? # service.images.get(@image_id).wait_for { ready? } #end tests("#get_image_details(#{@image_id})").formats(@image_format) do service.get_image_details(@image_id).body['image'] end tests('#list_images').formats({'images' => [@list_images_format]}) do service.list_images.body end tests('#list_images_detail').formats({'images' => [@image_format]}) do service.list_images_detail.body end tests("#delete_image(#{@image_id})").succeeds do service.delete_image(@image_id) end service.delete_server(@server_id) end tests('failure') do tests('#delete_image("0")').raises(Fog::Compute::HPV2::NotFound) do service.delete_image('0') end tests('#get_image_details("0")').raises(Fog::Compute::HPV2::NotFound) do service.get_image_details('0') end end end fog-1.19.0/tests/hp/requests/compute_v2/server_tests.rb0000644000004100000410000000637612261242552023206 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | server requests", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @server_format = { 'addresses' => Fog::Nullable::Hash, 'flavor' => Hash, 'id' => String, 'image' => Hash, 'links' => [Hash], 'hostId' => String, 'metadata' => Fog::Nullable::Hash, 'name' => String, 'accessIPv4' => Fog::Nullable::String, 'accessIPv6' => Fog::Nullable::String, 'progress' => Fog::Nullable::Integer, 'status' => String, 'created' => String, 'updated' => String, 'user_id' => String, 'tenant_id' => String, 'config_drive' => Fog::Nullable::String, 'security_groups' => [Hash], 'key_name' => Fog::Nullable::String } @list_servers_format = { 'links' => [Hash], 'name' => String, 'id' => String } @get_console_output_format = { 'output' => String } @base_image_id = ENV["BASE_IMAGE_ID"] || "7f60b54c-cd15-433f-8bed-00acbcd25a17" tests('success') do @server_id = nil @server_name = 'fogservertests' tests("#create_server(#{@server_name}, 100, #{@base_image_id})").formats(@server_format.merge('adminPass' => String)) do data = service.create_server(@server_name, 100, @base_image_id).body['server'] @server_id = data['id'] data end tests("#get_server_details(#{@server_id})").formats(@server_format) do service.get_server_details(@server_id).body['server'] end tests('#list_servers').formats({'servers' => [@list_servers_format]}) do service.list_servers.body end tests('#list_servers_detail').formats({'servers' => [@server_format]}) do service.list_servers_detail.body end tests("#update_server(#{@server_id}, :name => 'fogupdateserver')").succeeds do service.update_server(@server_id, :name => 'fogupdateserver') end tests("#reboot_server(#{@server_id}, 'SOFT')").succeeds do pending unless Fog.mocking? service.reboot_server(@server_id, 'SOFT') end tests("#get_console_output('#{@server_id}', 10)").formats(@get_console_output_format) do service.get_console_output(@server_id, 10).body end #tests("#get_vnc_console('#{@server_id}', 'novnc')").succeeds do # service.get_console_output(@server_id, 'novnc') #end tests("#delete_server(#{@server_id})").succeeds do service.delete_server(@server_id) end end tests('failure') do tests('#delete_server(0)').raises(Fog::Compute::HPV2::NotFound) do service.delete_server(0) end tests('#get_server_details(0)').raises(Fog::Compute::HPV2::NotFound) do service.get_server_details(0) end tests("#update_server(0, :name => 'fognonserver')").raises(Fog::Compute::HPV2::NotFound) do service.update_server(0, :name => 'fognonserver') end tests('#reboot_server(0)').raises(Fog::Compute::HPV2::NotFound) do service.reboot_server(0) end tests('#get_console_output(0, 10)').raises(Fog::Compute::HPV2::NotFound) do service.get_console_output(0, 10).body end #tests("#get_vnc_console(0, 'novnc')").raises(Fog::Compute::HPV2::NotFound) do # service.get_console_output(0, 'novnc') #end end end fog-1.19.0/tests/hp/requests/compute_v2/server_security_group_tests.rb0000644000004100000410000000233112261242552026334 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | server security group requests", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @base_image_id = ENV['BASE_IMAGE_ID'] || '7f60b54c-cd15-433f-8bed-00acbcd25a17' tests('success') do @server_name = 'fogsecgrouptests' @server_id = nil # create a server without a sec group data = service.create_server(@server_name, 100, @base_image_id).body['server'] @server_id = data['id'] # now add the 'default' sec group to the server tests("#add_security_group(#{@server_id}, 'default')").succeeds do service.add_security_group(@server_id, 'default') end # now remove the 'default' sec group to the server tests("#remove_security_group(#{@server_id}, 'default')").succeeds do service.remove_security_group(@server_id, 'default') end service.delete_server(@server_id) end tests('failure') do tests("#add_security_group(0, 'default')").raises(Fog::Compute::HPV2::NotFound) do service.add_security_group(0, 'default') end tests("#remove_security_group(0, 'default')").raises(Fog::Compute::HPV2::NotFound) do service.remove_security_group(0, 'default') end end end fog-1.19.0/tests/hp/requests/compute_v2/server_volume_tests.rb0000644000004100000410000000520312261242552024561 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | volume requests", ['hp', 'v2', 'compute', 'volumes']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @list_volume_attachments_format = { 'volumeAttachments' => [{ 'device' => String, 'serverId' => String, 'id' => String, 'volumeId' => String }] } @volume_attachment_format = { 'volumeAttachment' => { 'device' => String, 'serverId' => String, 'id' => String, 'volumeId' => String } } @base_image_id = ENV['BASE_IMAGE_ID'] || '7f60b54c-cd15-433f-8bed-00acbcd25a17' @server = service.servers.create(:name => 'fogservoltests', :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } tests('success') do response = HP[:block_storage_v2].create_volume('display_name' => 'fogvoltest', 'display_description' => 'fogvoltest desc', 'size' => 1) @volume_id = response.body['volume']['id'] @device = "\/dev\/sdf" tests("#attach_volume(#{@server.id}, #{@volume_id}, #{@device}").formats(@volume_attachment_format) do service.attach_volume(@server.id, @volume_id, @device).body end tests("#list_server_volumes(#{@server.id})").formats(@list_volume_attachments_format) do service.list_server_volumes(@server.id).body end tests("#get_server_volume_details(#{@server.id}, #{@volume_id})").formats(@volume_attachment_format) do service.get_server_volume_details(@server.id, @volume_id).body end tests("#detach_volume(#{@server.id}, #{@volume_id}").succeeds do service.detach_volume(@server.id, @volume_id) end end tests('failure') do tests('#list_server_volumes(0)').raises(Fog::Compute::HPV2::NotFound) do service.list_server_volumes(0) end tests('#get_server_volume_details(0, 0)').raises(Fog::Compute::HPV2::NotFound) do service.get_server_volume_details(0, 0) end tests("#attach_volume(#{@server.id}, 0, #{@device})").raises(Fog::Compute::HPV2::NotFound) do pending if Fog.mocking? service.attach_volume(@server.id, 0, @device) end tests("#attach_volume(0, #{@volume_id}, #{@device})").raises(Fog::Compute::HPV2::NotFound) do service.attach_volume(0, @volume_id, @device) end tests("#detach_volume(#{@server.id}, 0)").raises(Fog::Compute::HPV2::NotFound) do pending if Fog.mocking? service.detach_volume(@server.id, 0) end tests("#detach_volume(0, #{@volume_id})").raises(Fog::Compute::HPV2::NotFound) do service.detach_volume(0, @volume_id) end end HP[:block_storage_v2].delete_volume(@volume_id) service.delete_server(@server.id) end fog-1.19.0/tests/hp/requests/compute_v2/persistent_server_tests.rb0000644000004100000410000000420412261242552025452 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | persistent server requests", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @server_format = { 'addresses' => Fog::Nullable::Hash, 'flavor' => Hash, 'id' => String, 'links' => [Hash], 'hostId' => String, 'metadata' => Fog::Nullable::Hash, 'name' => String, 'accessIPv4' => Fog::Nullable::String, 'accessIPv6' => Fog::Nullable::String, 'progress' => Fog::Nullable::Integer, 'status' => String, 'created' => String, 'updated' => String, 'user_id' => String, 'tenant_id' => String, 'config_drive' => Fog::Nullable::String, 'security_groups' => [Hash], 'key_name' => Fog::Nullable::String } @volume = HP[:block_storage_v2].volumes.create(:name => 'fogvoltests', :description => 'fog vol test desc', :size => 1) @volume.wait_for { ready? } tests('success') do @server_id = nil @server_name = 'fogpersservertests' @block_device_mapping = [{ 'volume_size' => '', 'volume_id' => "#{@volume.id}", 'delete_on_termination' => '0', 'device_name' => 'vda' }] tests("#create_persistent_server(#{@server_name}, 101, #{@block_device_mapping})").formats(@server_format.merge('adminPass' => String)) do data = service.create_persistent_server(@server_name, 101, @block_device_mapping).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("#delete_server(#{@server_id})").succeeds do service.delete_server(@server_id) end end tests('failure') do tests("#create_persistent_server(#{@server_name}, 101, nil)").raises(Excon::Errors::BadRequest) do service.create_persistent_server(@server_name, 101, nil) end end HP[:block_storage_v2].delete_volume(@volume.id) end fog-1.19.0/tests/hp/requests/compute_v2/key_pair_tests.rb0000644000004100000410000000456412261242552023500 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | key pair requests", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) tests('success') do @keypair_format = { 'public_key' => String, 'fingerprint' => String, 'name' => String } @keypairs_format = { 'keypairs' => [{ 'keypair' => { 'public_key' => String, 'fingerprint' => String, 'name' => Fog::Nullable::String } }] } @key_pair_name = 'fog_create_key_pair' @public_key_material = 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA1SL+kgze8tvSFW6Tyj3RyZc9iFVQDiCKzjgwn2tS7hyWxaiDhjfY2mBYSZwFdKN+ZdsXDJL4CPutUg4DKoQneVgIC1zuXrlpPbaT0Btu2aFd4qNfJ85PBrOtw2GrWZ1kcIgzZ1mMbQt6i1vhsySD2FEj+5kGHouNxQpI5dFR5K+nGgcTLFGnzb/MPRBk136GVnuuYfJ2I4va/chstThoP8UwnoapRHcBpwTIfbmmL91BsRVqjXZEUT73nxpxFeXXidYwhHio+5dXwE0aM/783B/3cPG6FVoxrBvjoNpQpAcEyjtRh9lpwHZtSEW47WNzpIW3PhbQ8j4MryznqF1Rhw==' tests("#create_key_pair('#{@key_pair_name}')").formats({'keypair' => @keypair_format.merge({'private_key' => String, 'user_id' => String})}) do body = service.create_key_pair(@key_pair_name).body tests("private_key").returns(OpenSSL::PKey::RSA, "is a valid private RSA key") do OpenSSL::PKey::RSA.new(body['keypair']['private_key']).class end body end tests('#list_key_pairs').formats(@keypairs_format) do service.list_key_pairs.body end tests("#get_key_pair(#{@key_pair_name})").formats({'keypair' => @keypair_format}) do service.get_key_pair(@key_pair_name).body end tests("#delete_key_pair('#{@key_pair_name}')").succeeds do service.delete_key_pair(@key_pair_name) end tests("#create_key_pair('fog_import_key_pair', '#{@public_key_material}')").formats({'keypair' => @keypair_format.merge({'user_id' => String})}) do service.create_key_pair('fog_import_key_pair', @public_key_material).body end tests("#delete_key_pair('fog_import_key_pair)").succeeds do service.delete_key_pair('fog_import_key_pair') end end tests('failure') do tests("#get_key_pair('not_a_key_name')").raises(Fog::Compute::HPV2::NotFound) do service.get_key_pair('not_a_key_name') end tests("#delete_key_pair('not_a_key_name')").raises(Fog::Compute::HPV2::NotFound) do service.delete_key_pair('not_a_key_name') end end end fog-1.19.0/tests/hp/requests/compute_v2/server_address_tests.rb0000644000004100000410000000310012261242552024671 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | server address requests", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @base_image_id = ENV['BASE_IMAGE_ID'] || '7f60b54c-cd15-433f-8bed-00acbcd25a17' tests('success') do @server_name = 'fogaddresstests' @server_id = nil # check to see if there are any existing servers, otherwise create one if (data = service.list_servers(:status => 'ACTIVE').body['servers'][0]) @server_id = data['id'] else #@server = service.servers.create(:name => @server_name, :flavor_id => 100, :image_id => @base_image_id) #@server.wait_for { ready? } data = service.create_server(@server_name, 100, @base_image_id).body['server'] @server_id = data['id'] end # the network name is currently named 'private' tests("#list_server_addresses(#{@server_id})").formats({'addresses' => {'hpcloud' => [{'version' => Integer, 'addr' => String}]}}) do service.list_server_addresses(@server_id).body end tests("#list_server_addresses_by_network(#{@server_id}, 'network_name')").succeeds do service.list_server_addresses_by_network(@server_id, 'network_name').body end service.delete_server(@server_id) end tests('failure') do tests('#list_server_addresses(0)').raises(Fog::Compute::HPV2::NotFound) do service.list_server_addresses(0) end tests("#list_server_addresses_by_network(0, 'network_name')").raises(Fog::Compute::HPV2::NotFound) do service.list_server_addresses_by_network(0, 'network_name') end end end fog-1.19.0/tests/hp/requests/compute_v2/address_tests.rb0000644000004100000410000000503412261242552023313 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | address requests", ['hp', 'v2', 'compute', 'address']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @floating_ips_format = { 'instance_id' => Fog::Nullable::String, 'ip' => Fog::Nullable::String, 'fixed_ip' => Fog::Nullable::String, 'id' => String } @base_image_id = ENV["BASE_IMAGE_ID"] || "7f60b54c-cd15-433f-8bed-00acbcd25a17" tests('success') do @server_name = 'fogservertest' @server_id = nil @server = service.servers.create(:name => @server_name, :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } #data = service.create_server(@server_name, 100, @base_image_id).body['server'] #@server_id = data['id'] tests("#list_addresses").formats({'floating_ips' => [@floating_ips_format]}) do service.list_addresses.body end tests("#allocate_address").formats(@floating_ips_format) do data = service.allocate_address.body['floating_ip'] @address_id = data['id'] @ip_address = data['ip'] data end tests("#get_address('#{@address_id}')").formats(@floating_ips_format) do service.get_address(@address_id).body['floating_ip'] end tests("#associate_address('#{@server.id}', '#{@ip_address}')").succeeds do service.associate_address(@server.id, @ip_address) #tests("#get_address").returns(@ip_address, "server has associated ip address") do # @server.reload # @server.addresses['custom'][0]['addr'] #end end #tests("#disassociate_address('#{@server.id}', '#{@ip_address}')").succeeds do # service.disassociate_address(@server.id, @ip_address) #end tests("#release_address('#{@address_id}')").succeeds do service.release_address(@address_id) end @server.destroy #service.delete_server(@server_id) end tests('failure') do tests("#get_address('invalidaddress', 'invalidip')").raises(Fog::Compute::HPV2::NotFound) do service.get_address('invalidaddress') end tests("#associate_address('invalidserver', 'invalidip')").raises(Excon::Errors::InternalServerError) do service.associate_address('invalidserver', 'invalidip') end tests("#disassociate_address('invalidserver', 'invalidip')").raises(Excon::Errors::InternalServerError) do service.disassociate_address('invalidserver', 'invalidip') end tests("#release_address('invalidaddress')").raises(Fog::Compute::HPV2::NotFound) do service.release_address('invalidaddress') end end end fog-1.19.0/tests/hp/requests/cdn/0000755000004100000410000000000012261242552016576 5ustar www-datawww-datafog-1.19.0/tests/hp/requests/cdn/container_tests.rb0000644000004100000410000000322212261242552022326 0ustar www-datawww-dataShindo.tests("Fog::CDN[:hp] | container requests", ['hp']) do @cdn_containers_format = [{ 'x-cdn-ssl-uri' => String, 'cdn_enabled' => Fog::Boolean, 'name' => String, 'x-cdn-uri' => String, 'ttl' => Integer, 'log_retention' => Fog::Boolean }] tests('success') do tests("#put_container('fogcdncontainertests')").succeeds do Fog::CDN[:hp].put_container('fogcdncontainertests') end tests("duplicate #put_container('fogcdncontainertests')").succeeds do Fog::CDN[:hp].put_container('fogcdncontainertests') end tests("#get_containers").formats(@cdn_containers_format) do Fog::CDN[:hp].get_containers.body end tests("#post_container('fogcdncontainertests', {'x-ttl' => 3200})").succeeds do Fog::CDN[:hp].post_container('fogcdncontainertests', {'x-ttl' => 3200}) end tests("#head_container('fogcdncontainertests')").succeeds do Fog::CDN[:hp].head_container('fogcdncontainertests') end tests("#delete_container('fogcdncontainertests')").succeeds do Fog::CDN[:hp].delete_container('fogcdncontainertests') end end tests('failure') do tests("#post_container('fognoncdncontainer', {'x-ttl' => 3200})").raises(Fog::CDN::HP::NotFound) do Fog::CDN[:hp].post_container('fogcdnnoncontainer', {'x-ttl' => 3200}) end tests("#head_container('fognoncdncontainer')").raises(Fog::CDN::HP::NotFound) do Fog::CDN[:hp].head_container('fognoncdncontainer') end tests("#delete_container('fognoncdncontainer')").raises(Fog::CDN::HP::NotFound) do Fog::CDN[:hp].delete_container('fognoncdncontainer') end end end fog-1.19.0/tests/hp/requests/compute/0000755000004100000410000000000012261242552017506 5ustar www-datawww-datafog-1.19.0/tests/hp/requests/compute/security_group_tests.rb0000644000004100000410000000371012261242552024341 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | security group requests", ['hp']) do @security_groups_format = { 'security_groups' => [{ 'rules' => [Fog::Nullable::Hash], 'tenant_id' => String, 'id' => Integer, 'name' => String, 'description' => String }] } @security_group_format = { 'rules' => [Fog::Nullable::Hash], 'tenant_id' => String, 'id' => Integer, 'name' => String, 'description' => String } tests('success') do tests("#create_security_group('fog_security_group', 'tests group')").formats({'security_group' => @security_group_format}) do data = Fog::Compute[:hp].create_security_group('fog_security_group', 'tests group').body @sec_group_id = data['security_group']['id'] data end tests("#get_security_group('#{@sec_group_id}')").formats({'security_group' => @security_group_format}) do Fog::Compute[:hp].get_security_group(@sec_group_id).body end tests("#list_security_groups").formats(@security_groups_format) do Fog::Compute[:hp].list_security_groups.body end tests("#delete_security_group('#{@sec_group_id}')").succeeds do Fog::Compute[:hp].delete_security_group(@sec_group_id).body end end tests('failure') do @security_group = Fog::Compute[:hp].security_groups.create(:name => 'fog_security_group_fail', :description => 'tests group') tests("duplicate #create_security_group(#{@security_group.name}, #{@security_group.description})").raises(Excon::Errors::BadRequest) do Fog::Compute[:hp].create_security_group(@security_group.name, @security_group.description) end tests("#get_security_group(0)").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].get_security_group(0) end tests("#delete_security_group(0)").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].delete_security_group(0) end @security_group.destroy end end fog-1.19.0/tests/hp/requests/compute/metadata_tests.rb0000644000004100000410000000523512261242552023042 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | metadata requests", ['hp']) do @metadata_format = { 'metadata' => Fog::Nullable::Hash } @metaitem_format = { 'meta' => Fog::Nullable::Hash } @base_image_id = ENV["BASE_IMAGE_ID"] || 1242 tests('success') do @server_name = "fogmetadatatest" @server = Fog::Compute[:hp].servers.create(:name => @server_name, :flavor_id => 100, :image_id => @base_image_id, :metadata => {'Meta1' => 'MetaValue1', 'Meta2' => 'MetaValue2'} ) @server.wait_for { ready? } tests("#list_metadata('servers', #{@server.id})").formats(@metadata_format) do metadata = Fog::Compute[:hp].list_metadata('servers', @server.id).body test ("metadata exists") do metadata['metadata']['Meta1'] == "MetaValue1" end metadata end tests("#set_metadata('servers', #{@server.id}, {'MetaNew3' => 'MetaNewValue3'})").formats(@metadata_format) do data = Fog::Compute[:hp].set_metadata('servers', @server.id, {'MetaNew3' => 'MetaNewValue3'}).body test ("metadata set correctly") do metadata = Fog::Compute[:hp].list_metadata('servers', @server.id).body metadata['metadata']['MetaNew3'] == "MetaNewValue3" end data end tests("#update_metadata('servers', #{@server.id}, {'MetaUpd4' => 'MetaUpdValue4'})").formats(@metadata_format) do data = Fog::Compute[:hp].update_metadata('servers', @server.id, {'MetaUpd4' => 'MetaUpdValue4'}).body test ("metadata updated correctly") do metadata = Fog::Compute[:hp].list_metadata('servers', @server.id).body metadata['metadata']['MetaUpd4'] == "MetaUpdValue4" end data end tests("#get_meta('servers', #{@server.id}, 'MetaNew3')").formats(@metaitem_format) do mitem = Fog::Compute[:hp].get_meta('servers', @server.id, 'MetaNew3').body test ("metadata item exists") do mitem['meta']['MetaNew3'] == "MetaNewValue3" end mitem end tests("#update_meta('servers', #{@server.id}, 'MetaNew3', 'MetaUpdValue3')").formats(@metaitem_format) do mitem = Fog::Compute[:hp].update_meta('servers', @server.id, 'MetaNew3', 'MetaUpdValue3').body test ("metadata item updated correctly") do mitem['meta']['MetaNew3'] == "MetaUpdValue3" end mitem end tests("#delete_meta('servers', #{@server.id}, 'MetaNew3')").succeeds do data = Fog::Compute[:hp].delete_meta('servers', @server.id, 'MetaNew3').body test ("metadata item deleted correctly") do metadata = Fog::Compute[:hp].list_metadata('servers', @server.id).body metadata['metadata'].fetch('MetaNew3', nil) == nil end data end @server.destroy end endfog-1.19.0/tests/hp/requests/compute/flavor_tests.rb0000644000004100000410000000202512261242552022545 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | flavor requests", ['hp']) do @flavor_format = { 'rxtx_quota' => Integer, 'rxtx_cap' => Integer, 'vcpus' => Integer, 'swap' => Integer, 'disk' => Integer, 'ram' => Integer, 'id' => Integer, 'links' => [Hash], 'name' => String } @list_flavors_format = { 'id' => Integer, 'name' => String, 'links' => [Hash] } tests('success') do tests('#list_flavors').formats({'flavors' => [@list_flavors_format]}) do Fog::Compute[:hp].list_flavors.body end tests('#get_flavor_details(1)').formats(@flavor_format) do Fog::Compute[:hp].get_flavor_details(1).body['flavor'] end tests('#list_flavors_detail').formats({'flavors' => [@flavor_format]}) do Fog::Compute[:hp].list_flavors_detail.body end end tests('failure') do tests('#get_flavor_details(9999)').raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].get_flavor_details(9999) end end end fog-1.19.0/tests/hp/requests/compute/image_tests.rb0000644000004100000410000000425012261242552022340 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | image requests", ['hp']) do @image_format = { 'id' => String, 'links' => [Hash], 'metadata' => Fog::Nullable::Hash, 'server' => Fog::Nullable::Hash, 'name' => String, 'progress' => Fog::Nullable::Integer, 'status' => String, 'created' => Fog::Nullable::String, 'updated' => Fog::Nullable::String } @list_images_format = { 'id' => String, 'links' => Fog::Nullable::Array, 'name' => String } @base_image_id = ENV["BASE_IMAGE_ID"] || 1242 tests('success') do @server_name = "fogservertest" @image_name = "fogimagetest" @server = Fog::Compute[:hp].servers.create(:name => @server_name, :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } @image_id = nil tests("#create_image(#{@server.id}, #{@image_name})").formats({}) do response = Fog::Compute[:hp].create_image(@server.id, @image_name) # no data is returned for the call, so get id off the header @image_id = response.headers["Location"].split("/")[5] {} end unless Fog.mocking? Fog::Compute[:hp].images.get(@image_id).wait_for { ready? } end tests("#get_image_details(#{@image_id})").formats(@image_format) do pending if Fog.mocking? Fog::Compute[:hp].get_image_details(@image_id).body['image'] end tests('#list_images').formats({'images' => [@list_images_format]}) do Fog::Compute[:hp].list_images.body end tests('#list_images_detail').formats({'images' => [@image_format]}) do Fog::Compute[:hp].list_images_detail.body end unless Fog.mocking? Fog::Compute[:hp].images.get(@image_id).wait_for { ready? } end tests("#delete_image(#{@image_id})").succeeds do pending if Fog.mocking? Fog::Compute[:hp].delete_image(@image_id) end @server.destroy end tests('failure') do tests('#delete_image(0)').raises(Excon::Errors::InternalServerError) do Fog::Compute[:hp].delete_image(0) end tests('#get_image_details(0)').raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].get_image_details(0) end end end fog-1.19.0/tests/hp/requests/compute/server_tests.rb0000644000004100000410000000746112261242552022573 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | server requests", ['hp']) do @server_format = { 'addresses' => Fog::Nullable::Hash, 'flavor' => Hash, 'id' => Integer, 'image' => Hash, 'links' => [Hash], 'hostId' => String, 'metadata' => Fog::Nullable::Hash, 'name' => String, 'accessIPv4' => Fog::Nullable::String, 'accessIPv6' => Fog::Nullable::String, 'progress' => Fog::Nullable::Integer, 'status' => String, 'created' => String, 'updated' => String, 'user_id' => String, 'tenant_id' => String, 'uuid' => String, 'config_drive' => Fog::Nullable::String, 'security_groups' => [Hash], 'key_name' => Fog::Nullable::String } @list_servers_format = { 'uuid' => Fog::Nullable::String, 'links' => [Hash], 'name' => String, 'id' => Integer } @get_console_output_format = { 'output' => String } @base_image_id = ENV["BASE_IMAGE_ID"] || 1242 tests('success') do @server_id = nil @server_name = "fogservertests" tests("#create_server(#{@server_name}, 100, #{@base_image_id})").formats(@server_format.merge('adminPass' => String)) do data = Fog::Compute[:hp].create_server(@server_name, 100, @base_image_id).body['server'] @server_id = data['id'] data end Fog::Compute[:hp].servers.get(@server_id).wait_for { ready? } tests("#get_server_details(#{@server_id})").formats(@server_format) do Fog::Compute[:hp].get_server_details(@server_id).body['server'] end tests('#list_servers').formats({'servers' => [@list_servers_format]}) do Fog::Compute[:hp].list_servers.body end tests('#list_servers_detail').formats({'servers' => [@server_format]}) do Fog::Compute[:hp].list_servers_detail.body end Fog::Compute[:hp].servers.get(@server_id).wait_for { ready? } tests("#update_server(#{@server_id}, :name => 'fogupdateserver')").succeeds do Fog::Compute[:hp].update_server(@server_id, :name => 'fogupdateserver') end Fog::Compute[:hp].servers.get(@server_id).wait_for { ready? } tests("#reboot_server(#{@server_id}, 'SOFT')").succeeds do Fog::Compute[:hp].reboot_server(@server_id, 'SOFT') end Fog::Compute[:hp].servers.get(@server_id).wait_for { ready? } tests("#reboot_server(#{@server_id}, 'HARD')").succeeds do Fog::Compute[:hp].reboot_server(@server_id, 'HARD') end Fog::Compute[:hp].servers.get(@server_id).wait_for { ready? } tests("#change_password_server(#{@server_id}, 'new_password')").succeeds do Fog::Compute[:hp].change_password_server(@server_id, 'new_password') end Fog::Compute[:hp].servers.get(@server_id).wait_for { ready? } tests("#get_console_output('#{@server_id}', 10)").formats(@get_console_output_format) do Fog::Compute[:hp].get_console_output(@server_id, 10).body end Fog::Compute[:hp].servers.get(@server_id).wait_for { ready? } tests("#delete_server(#{@server_id})").succeeds do Fog::Compute[:hp].delete_server(@server_id) end end tests('failure') do tests('#delete_server(0)').raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].delete_server(0) end tests('#get_server_details(0)').raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].get_server_details(0) end tests("#update_server(0, :name => 'fognonserver')").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].update_server(0, :name => 'fognonserver') end tests('#reboot_server(0)').raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].reboot_server(0) end tests("#change_password_server(0}, 'new_password')").raises(Excon::Errors::InternalServerError) do Fog::Compute[:hp].change_password_server(0, 'new_password') end end end fog-1.19.0/tests/hp/requests/compute/server_volume_tests.rb0000644000004100000410000000463312261242552024160 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | volume requests", ['hp', 'compute', 'volumes']) do @list_volume_attachments_format = { 'volumeAttachments' => [{ 'device' => String, 'serverId' => Integer, 'id' => Integer, 'volumeId' => Integer }] } @volume_attachment_format = { 'volumeAttachment' => { "volumeId" => Integer, "id" => Integer } } @base_image_id = ENV["BASE_IMAGE_ID"] || 1242 @server = Fog::Compute[:hp].servers.create(:name => 'fogservoltests', :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } tests('success') do response = HP[:block_storage].create_volume('fogvoltest', 'fogvoltest desc', 1) @volume_id = response.body['volume']['id'] @device = "\/dev\/sdf" HP[:block_storage].volumes.get(@volume_id).wait_for { ready? } tests("#attach_volume(#{@server.id}, #{@volume_id}, #{@device}").formats(@volume_attachment_format) do Fog::Compute[:hp].attach_volume(@server.id, @volume_id, @device).body end HP[:block_storage].volumes.get(@volume_id).wait_for { in_use? } unless Fog.mocking? tests("#detach_volume(#{@server.id}, #{@volume_id}").succeeds do Fog::Compute[:hp].detach_volume(@server.id, @volume_id) end HP[:block_storage].volumes.get(@volume_id).wait_for { ready? } tests("#list_server_volumes(#{@server.id})").formats(@list_volume_attachments_format) do Fog::Compute[:hp].list_server_volumes(@server.id).body end end tests('failure') do tests("#list_server_volumes(0)").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].list_server_volumes(0) end tests("#attach_volume(#{@server.id}, 0, #{@device})").raises(Fog::Compute::HP::NotFound) do pending if Fog.mocking? Fog::Compute[:hp].attach_volume(@server.id, 0, @device) end tests("#attach_volume(0, #{@volume_id}, #{@device})").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].attach_volume(0, @volume_id, @device) end tests("#detach_volume(#{@server.id}, 0)").raises(Fog::Compute::HP::NotFound) do pending if Fog.mocking? Fog::Compute[:hp].detach_volume(@server.id, 0) end tests("#detach_volume(0, #{@volume_id})").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].detach_volume(0, @volume_id) end end HP[:block_storage].delete_volume(@volume_id) Fog::Compute[:hp].delete_server(@server.id) end fog-1.19.0/tests/hp/requests/compute/persistent_server_tests.rb0000644000004100000410000000420512261242552025044 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | persistent server requests", ['hp', 'compute']) do @server_format = { 'addresses' => Fog::Nullable::Hash, 'flavor' => Hash, 'id' => Integer, 'links' => [Hash], 'hostId' => String, 'metadata' => Fog::Nullable::Hash, 'name' => String, 'accessIPv4' => Fog::Nullable::String, 'accessIPv6' => Fog::Nullable::String, 'progress' => Fog::Nullable::Integer, 'status' => String, 'created' => String, 'updated' => String, 'user_id' => String, 'tenant_id' => String, 'uuid' => String, 'config_drive' => Fog::Nullable::String, 'security_groups' => [Hash], 'key_name' => Fog::Nullable::String } @volume = HP[:block_storage].volumes.create(:name => 'fogvoltests', :description => 'fog vol test desc', :size => 1) @volume.wait_for { ready? } tests('success') do @server_id = nil @server_name = "fogpersservertests" @block_device_mapping = [{ 'volume_size' => '', 'volume_id' => "#{@volume.id}", 'delete_on_termination' => '0', 'device_name' => 'vda' }] tests("#create_persistent_server(#{@server_name}, 100, #{@block_device_mapping})").formats(@server_format.merge('adminPass' => String)) do data = Fog::Compute[:hp].create_persistent_server(@server_name, 100, @block_device_mapping).body['server'] @server_id = data['id'] data end Fog::Compute[:hp].servers.get(@server_id).wait_for { ready? } tests("#get_server_details(#{@server_id})").formats(@server_format) do Fog::Compute[:hp].get_server_details(@server_id).body['server'] end tests("#delete_server(#{@server_id})").succeeds do Fog::Compute[:hp].delete_server(@server_id) end end tests('failure') do tests("#create_persistent_server(#{@server_name}, 100, nil)").raises(Excon::Errors::BadRequest) do Fog::Compute[:hp].create_persistent_server(@server_name, 100, nil) end end HP[:block_storage].delete_volume(@volume.id) end fog-1.19.0/tests/hp/requests/compute/key_pair_tests.rb0000644000004100000410000000450512261242552023064 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | key pair requests", ['hp']) do tests('success') do @keypair_format = { 'public_key' => String, 'fingerprint' => String, 'name' => String } @keypairs_format = { 'keypairs' => [{ 'keypair' => { 'public_key' => String, 'fingerprint' => String, 'name' => Fog::Nullable::String } }] } @key_pair_name = 'fog_create_key_pair' @public_key_material = 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA1SL+kgze8tvSFW6Tyj3RyZc9iFVQDiCKzjgwn2tS7hyWxaiDhjfY2mBYSZwFdKN+ZdsXDJL4CPutUg4DKoQneVgIC1zuXrlpPbaT0Btu2aFd4qNfJ85PBrOtw2GrWZ1kcIgzZ1mMbQt6i1vhsySD2FEj+5kGHouNxQpI5dFR5K+nGgcTLFGnzb/MPRBk136GVnuuYfJ2I4va/chstThoP8UwnoapRHcBpwTIfbmmL91BsRVqjXZEUT73nxpxFeXXidYwhHio+5dXwE0aM/783B/3cPG6FVoxrBvjoNpQpAcEyjtRh9lpwHZtSEW47WNzpIW3PhbQ8j4MryznqF1Rhw==' tests("#create_key_pair('#{@key_pair_name}')").formats({'keypair' => @keypair_format.merge({'private_key' => String, 'user_id' => String})}) do body = Fog::Compute[:hp].create_key_pair(@key_pair_name).body tests("private_key").returns(OpenSSL::PKey::RSA, "is a valid private RSA key") do OpenSSL::PKey::RSA.new(body['keypair']['private_key']).class end body end tests('#list_key_pairs').formats(@keypairs_format) do Fog::Compute[:hp].list_key_pairs.body end tests("#delete_key_pair('#{@key_pair_name}')").succeeds do Fog::Compute[:hp].delete_key_pair(@key_pair_name) end tests("#create_key_pair('fog_import_key_pair', '#{@public_key_material}')").formats({'keypair' => @keypair_format.merge({'user_id' => String})}) do Fog::Compute[:hp].create_key_pair('fog_import_key_pair', @public_key_material).body end tests("#delete_key_pair('fog_import_key_pair)").succeeds do Fog::Compute[:hp].delete_key_pair('fog_import_key_pair') end end tests('failure') do tests("#delete_key_pair('not_a_key_name')").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].delete_key_pair('not_a_key_name') end @key_pair = Fog::Compute[:hp].key_pairs.create(:name => 'fog_key_pair') tests("duplicate #create_key_pair('#{@key_pair.name}')").raises(Excon::Errors::BadRequest) do Fog::Compute[:hp].create_key_pair(@key_pair.name) end @key_pair.destroy end end fog-1.19.0/tests/hp/requests/compute/server_address_tests.rb0000644000004100000410000000316712261242552024277 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | address requests", ['hp']) do @base_image_id = ENV["BASE_IMAGE_ID"] || 1242 tests('success') do @server = Fog::Compute[:hp].servers.create(:name => 'fogaddresstests', :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } @address = Fog::Compute[:hp].addresses.create @address.server = @server # the network name is currently named 'private' tests("#list_server_addresses(#{@server.id})").formats({'addresses' => {"private" => [{'version' => Integer, 'addr' => String}]}}) do Fog::Compute[:hp].list_server_addresses(@server.id).body end tests("#list_server_private_addresses(#{@server.id}, 'private')").formats({'private' => [{'version' => Integer, 'addr' => String}]}) do Fog::Compute[:hp].list_server_private_addresses(@server.id, 'private').body end tests("#list_server_public_addresses(#{@server.id}, 'private')").formats({'public' => [{'version' => Integer, 'addr' => String}]}) do Fog::Compute[:hp].list_server_public_addresses(@server.id, 'private').body end @address.destroy @server.destroy end tests('failure') do tests("#list_server_addresses(0)").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].list_server_addresses(0) end tests("#list_server_private_addresses(0, 'private')").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].list_server_private_addresses(0, 'private') end tests("#list_server_public_addresses(0, 'private')").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].list_server_public_addresses(0, 'private') end end end fog-1.19.0/tests/hp/requests/compute/address_tests.rb0000644000004100000410000000450012261242552022701 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | address requests", ['hp', 'address']) do @floating_ips_format = { 'instance_id' => Fog::Nullable::Integer, 'ip' => Fog::Nullable::String, 'fixed_ip' => Fog::Nullable::String, 'id' => Integer } @base_image_id = ENV["BASE_IMAGE_ID"] || 1242 tests('success') do tests("#list_addresses").formats({'floating_ips' => [@floating_ips_format]}) do Fog::Compute[:hp].list_addresses.body end tests("#allocate_address").formats(@floating_ips_format) do data = Fog::Compute[:hp].allocate_address.body['floating_ip'] @address_id = data['id'] @ip_address = data['ip'] data end tests("#get_address('#{@address_id}')").formats(@floating_ips_format) do Fog::Compute[:hp].get_address(@address_id).body['floating_ip'] end @server = Fog::Compute[:hp].servers.create(:name => 'fogaddresstests', :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } tests("#associate_address('#{@server.id}', '#{@ip_address}')").succeeds do Fog::Compute[:hp].associate_address(@server.id, @ip_address) tests("#get_address").returns(@ip_address, "server has associated ip address") do @server.reload @server.addresses['private'][1]['addr'] end end tests("#disassociate_address('#{@server.id}', '#{@ip_address}')").succeeds do Fog::Compute[:hp].disassociate_address(@server.id, @ip_address) end @server.destroy tests("#release_address('#{@address_id}')").succeeds do Fog::Compute[:hp].release_address(@address_id) end end tests('failure') do tests("#get_address('invalidaddress', 'invalidip')").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].get_address('invalidaddress') end tests("#associate_address('invalidserver', 'invalidip')").raises(Excon::Errors::InternalServerError) do Fog::Compute[:hp].associate_address('invalidserver', 'invalidip') end tests("#disassociate_address('invalidserver', 'invalidip')").raises(Excon::Errors::InternalServerError) do Fog::Compute[:hp].disassociate_address('invalidserver', 'invalidip') end tests("#release_address('invalidaddress')").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].release_address('invalidaddress') end end end fog-1.19.0/tests/hp/requests/compute/security_group_rule_tests.rb0000644000004100000410000000377012261242552025376 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | security group requests", ['hp']) do @security_group_rule_format = { 'from_port' => Integer, 'group' => Fog::Nullable::Hash, 'ip_protocol' => String, 'to_port' => Integer, 'parent_group_id' => Integer, 'ip_range' => { 'cidr' => String }, 'id' => Integer } tests('success') do @security_group = Fog::Compute[:hp].security_groups.create(:name => 'fog_security_group', :description => 'tests group') tests("tcp #create_security_group_rule('#{@security_group.id}', 'tcp', '80', '80', '0.0.0.0/0'}')").formats({'security_group_rule' => @security_group_rule_format}) do data = Fog::Compute[:hp].create_security_group_rule(@security_group.id, 'tcp', '80', '80', '0.0.0.0/0').body @sec_group_rule_id_1 = data['security_group_rule']['id'] data end tests("icmp #create_security_group_rule('#{@security_group.id}', 'icmp', '-1', '-1', '0.0.0.0/0'}')").formats({'security_group_rule' => @security_group_rule_format}) do data = Fog::Compute[:hp].create_security_group_rule(@security_group.id, 'icmp', '-1', '-1', '0.0.0.0/0').body @sec_group_rule_id_2 = data['security_group_rule']['id'] data end tests("tcp #delete_security_group_rule('#{@sec_group_rule_id_1}')").succeeds do Fog::Compute[:hp].delete_security_group_rule(@sec_group_rule_id_1).body end tests("icmp #delete_security_group_rule('#{@sec_group_rule_id_2}')").succeeds do Fog::Compute[:hp].delete_security_group_rule(@sec_group_rule_id_2).body end @security_group.destroy end tests('failure') do tests("#create_security_group_rule(0, 'tcp', '80', '80', '0.0.0.0/0'}')").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].create_security_group_rule(0, 'tcp', '80', '80', '0.0.0.0/0') end tests("#delete_security_group_rule(0)").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].delete_security_group_rule(0) end end end fog-1.19.0/tests/hp/requests/lb/0000755000004100000410000000000012261242552016427 5ustar www-datawww-datafog-1.19.0/tests/hp/requests/lb/versions_tests.rb0000644000004100000410000000054312261242552022050 0ustar www-datawww-dataShindo.tests("HP::LB | versions requests", ['hp', 'lb', 'versions']) do @version_format = { 'id' => String, 'links' => [Hash], 'status' => String, 'updated' => String } tests('success') do tests('#list_versions').formats({'versions' => [@version_format]}) do HP[:lb].list_versions.body end end endfog-1.19.0/tests/hp/requests/lb/virtual_ips_tests.rb0000644000004100000410000000177312261242552022547 0ustar www-datawww-dataShindo.tests("HP::LB | virtual ips requests", ['hp', 'lb', 'virtual_ips']) do @virtual_ips_format = { 'id' => String, 'address' => String, 'type' => String, 'ipVersion' => String } tests('success') do @nodes = [{'address' => '15.185.1.1', 'port' => '80'}] @virtual_ip = [{ 'ipVersion' => 'IPV4', 'type' => 'PUBLIC', 'id' => '11111111', 'address' => '15.185.3.3' }] data = HP[:lb].create_load_balancer('rg-fog-lb3', @nodes, {'virtualIps' => @virtual_ip}).body @lb_id = data['id'] tests('#list_load_balancer_virtual_ips').formats({'virtualIps' => [@virtual_ips_format]}) do HP[:lb].list_load_balancer_virtual_ips(@lb_id).body end HP[:lb].delete_load_balancer(@lb_id) end tests('failure') do tests('#list_load_balancer_virtual_ips(0)').raises(Fog::HP::LB::NotFound) do HP[:lb].list_load_balancer_virtual_ips('0') end end endfog-1.19.0/tests/hp/requests/lb/algorithms_tests.rb0000644000004100000410000000041112261242552022343 0ustar www-datawww-dataShindo.tests("HP::LB | algorithms", ['hp', 'lb', 'algorithms']) do @algo_format = { 'name' => String } tests('success') do tests('#list_algorithms').formats({'algorithms' => [@algo_format]}) do HP[:lb].list_algorithms.body end end endfog-1.19.0/tests/hp/requests/lb/load_balancer_nodes_tests.rb0000644000004100000410000000271012261242552024134 0ustar www-datawww-dataShindo.tests('HP::LB | load balancer nodes', ['hp', 'lb', 'nodes']) do @node_format = { 'id' => String, 'address' => String, 'port' => String, 'condition' => String, 'status' => String } tests('successs') do data = HP[:lb].create_load_balancer('rg-fog-lb2', [{'address' => '15.185.1.1', 'port' => '80'}]).body @lb_id = data['id'] tests("#create_load_balancer_node(#{@lb_id}, '15.185.2.2', '88')").formats({'nodes' => [@node_format]}) do data = HP[:lb].create_load_balancer_node(@lb_id, '15.185.2.2', '88').body @lb_node_id = data['nodes'][0]['id'] data end tests("#list_load_balancer_nodes(#{@lb_id})").formats({'nodes' => [@node_format]}) do HP[:lb].list_load_balancer_nodes(@lb_id).body end tests("#get_load_balancer_node(#{@lb_id}, #{@lb_node_id})").formats(@node_format) do HP[:lb].get_load_balancer_node(@lb_id, @lb_node_id).body end tests("#update_load_balancer_node(#{@lb_id}, #{@lb_node_id}, 'DISABLED')").succeeds do HP[:lb].update_load_balancer_node(@lb_id, @lb_node_id, 'DISABLED') end tests("#delete_load_balancer_node(#{@lb_id}, #{@lb_node_id})").succeeds do HP[:lb].delete_load_balancer_node(@lb_id, @lb_node_id) end HP[:lb].delete_load_balancer(@lb_id) end tests('failure') do tests('#list_node_balancer_nodes(0)').raises(Fog::HP::LB::NotFound) do HP[:lb].list_load_balancer_nodes('0') end end endfog-1.19.0/tests/hp/requests/lb/protocols_tests.rb0000644000004100000410000000046112261242552022223 0ustar www-datawww-dataShindo.tests("HP::LB | protocols requests", ['hp', 'lb', 'protocols']) do @protocol_format = { 'name' => String, 'port' => Integer } tests('success') do tests('#list_protocols').formats({'protocols' => [@protocol_format]}) do HP[:lb].list_protocols.body end end endfog-1.19.0/tests/hp/requests/lb/load_balancer_tests.rb0000644000004100000410000000314112261242552022743 0ustar www-datawww-dataShindo.tests("HP::LB | load balancers requests", ['hp', 'lb', 'load_balancer']) do @lb_format = { 'id' => String, 'name' => String, 'protocol' => String, 'port' => String, 'algorithm' => String, 'status' => String, 'created' => String, 'updated' => String, 'nodes' => Array } tests('success') do @lb_name = 'fog-lb' @nodes = [{'address' => '15.185.1.1', 'port' => '80'}] tests("#create_load_balancer(#{@lb_name}, #{@nodes})").formats(@lb_format) do data = HP[:lb].create_load_balancer(@lb_name, @nodes).body @lb_id = data['id'] data end tests('#list_load_balancers').formats({'loadBalancers' => [@lb_format]}) do HP[:lb].list_load_balancers.body end tests("#get_load_balancer(#{@lb_id})").formats(@lb_format) do HP[:lb].get_load_balancer(@lb_id).body end tests("#update_load_balancer(#{@lb_id}, {'name' => 'updated-fog-lb'})").returns('') do HP[:lb].update_load_balancer(@lb_id, {'name' => 'updated-fog-lb'}).body end tests("#delete_load_balancer(#{@lb_id})").succeeds do HP[:lb].delete_load_balancer(@lb_id) end end tests('failure') do tests("#get_load_balancer(0)").raises(Fog::HP::LB::NotFound) do HP[:lb].get_load_balancer('0') end tests("#update_load_balancer(0, {'name' => 'updated-fog-lb'})").raises(Fog::HP::LB::NotFound) do HP[:lb].update_load_balancer('0', {'name' => 'updated-fog-lb'}) end tests("#delete_load_balancer(0)").raises(Fog::HP::LB::NotFound) do HP[:lb].delete_load_balancer('0') end end endfog-1.19.0/tests/hp/requests/lb/limits_tests.rb0000644000004100000410000000065412261242552021504 0ustar www-datawww-dataShindo.tests("HP::LB | limits requests", ['hp', 'lb', 'limits']) do @limits_format = { 'maxLoadBalancerNameLength' => Integer, 'maxLoadBalancers' => Integer, 'maxNodesPerLoadBalancer' => Integer, 'maxVIPsPerLoadBalancer' => Integer, } tests('success') do tests('#list_limits').formats({'limits' => [{'values' => @limits_format }]}) do HP[:lb].list_limits.body end end endfog-1.19.0/tests/hp/requests/block_storage_v2/0000755000004100000410000000000012261242552021257 5ustar www-datawww-datafog-1.19.0/tests/hp/requests/block_storage_v2/snapshot_tests.rb0000644000004100000410000000453712261242552024676 0ustar www-datawww-dataShindo.tests('HP::BlockStorageV2 | snapshot requests', ['hp', 'v2', 'block_storage', 'snapshots']) do @snapshot_format = { 'status' => String, 'display_description' => Fog::Nullable::String, 'display_name' => Fog::Nullable::String, 'volume_id' => String, 'size' => Integer, 'id' => String, 'created_at' => String, 'metadata' => Fog::Nullable::Hash } tests('success') do @snapshot_id = nil @snapshot_name = 'fogsnapshot2tests' @snapshot_desc = @snapshot_name + ' desc' @volume = HP[:block_storage_v2].volumes.create(:name => 'fogvol2forsnap', :size => 1) @volume.wait_for { ready? } tests("#create_snapshot(#{@volume.id}, {'display_name' => #{@snapshot_name}, 'display_description' => #{@snapshot_desc} })").formats(@snapshot_format) do data = HP[:block_storage_v2].create_snapshot(@volume.id, {'display_name' => @snapshot_name, 'display_description' => @snapshot_desc} ).body['snapshot'] @snapshot_id = data['id'] data end tests("#get_snapshot_details(#{@snapshot_id})").formats(@snapshot_format) do HP[:block_storage_v2].get_snapshot_details(@snapshot_id).body['snapshot'] end tests("#update_snapshot(#{@snapshot_id}, 'display_name' => '#{@snapshot_name} Updated')").formats(@snapshot_format) do HP[:block_storage_v2].update_snapshot(@snapshot_id, 'display_name' => "#{@snapshot_name} Updated").body['snapshot'] end tests('#list_snapshots').formats({'snapshots' => [@snapshot_format]}) do HP[:block_storage_v2].list_snapshots.body end tests('#list_snapshots_detail').formats({'snapshots' => [@snapshot_format]}) do HP[:block_storage_v2].list_snapshots_detail.body end tests("#delete_snapshot(#{@snapshot_id})").succeeds do HP[:block_storage_v2].delete_snapshot(@snapshot_id) end end tests('failure') do tests('#get_snapshot_details(0)').raises(Fog::HP::BlockStorageV2::NotFound) do HP[:block_storage_v2].get_snapshot_details(0) end tests('#update_snapshot(0)').raises(Fog::HP::BlockStorageV2::NotFound) do HP[:block_storage_v2].update_snapshot(0) end tests('#delete_snapshot(0)').raises(Fog::HP::BlockStorageV2::NotFound) do HP[:block_storage_v2].delete_snapshot(0) end end @volume.destroy end fog-1.19.0/tests/hp/requests/block_storage_v2/volume_backup_tests.rb0000644000004100000410000001060312261242552025662 0ustar www-datawww-dataShindo.tests("Fog::HP::BlockStorageV2 | volume backup requests", ['hp', 'v2', 'block_storage', 'volume_backup']) do @backup_details_format = { 'id' => String, 'status' => String, 'name' => Fog::Nullable::String, 'description' => Fog::Nullable::String, 'container' => String, 'availability_zone' => String, 'created_at' => String, 'volume_id' => String, 'size' => Integer, 'links' => [Fog::Nullable::Hash], 'fail_reason' => Fog::Nullable::String, 'object_count' => Integer } @backup_format = { 'id' => String, 'name' => Fog::Nullable::String, 'links' => [Fog::Nullable::Hash] } @restore_format = { 'backup_id' => String, 'volume_id' => String } tests('success') do @backup_id = nil @backup_name = 'fogvolbackup2tests' @backup_desc = @backup_name + ' desc' @volume = HP[:block_storage_v2].volumes.create(:name => 'fogvol2forbackup', :size => 1) @volume.wait_for { ready? } @target_volume = HP[:block_storage_v2].volumes.create(:name => 'fogtargetvolume', :size => 2) @target_volume.wait_for { ready? } tests("#create_volume_backup(#{@volume.id}, {'name' => #{@backup_name}, 'description' => #{@backup_desc}, 'container' => 'my_backups')").formats(@backup_format) do data = HP[:block_storage_v2].create_volume_backup(@volume.id, {'name' => @backup_name, 'description' => @backup_desc, 'container' => 'my_backups'}).body['backup'] @backup_id = data['id'] data end tests("#get_volume_backup_details(#{@backup_id})").formats(@backup_details_format) do HP[:block_storage_v2].get_volume_backup_details(@backup_id).body['backup'] end tests('#list_volume_backups').formats({'backups' => [@backup_format]}) do HP[:block_storage_v2].list_volume_backups.body end tests('#list_volume_backups_detail').formats({'backups' => [@backup_details_format]}) do HP[:block_storage_v2].list_volume_backups_detail.body end # restore into new volume tests("#restore_volume_backup(#{@backup_id}").formats(@restore_format) do data = HP[:block_storage_v2].restore_volume_backup(@backup_id).body['restore'] restored_volume_id = data['volume_id'] restored_volume = HP[:block_storage_v2].get_volume_details(restored_volume_id).body['volume'] test ('should create a new volume with backup restored') do restored_volume['display_name'] == @volume.name restored_volume['display_description'] == @volume.description restored_volume['availability_zone'] == @volume.availability_zone restored_volume['size'] == @volume.size end data end ## restore into existing volume tests("#restore_volume_backup(#{@backup_id}, {'volume_id' => #{@target_volume.id}}").formats(@restore_format) do data = HP[:block_storage_v2].restore_volume_backup(@backup_id, {'volume_id' => @target_volume.id}).body['restore'] restored_volume_id = data['volume_id'] restored_volume = HP[:block_storage_v2].get_volume_details(restored_volume_id).body['volume'] test ('should overwrite the existing volume with backup restored') do restored_volume['id'] == @target_volume.id restored_volume['display_name'] == @volume.name restored_volume['display_description'] == @volume.description restored_volume['availability_zone'] == @volume.availability_zone restored_volume['size'] == @volume.size end data end # tests("#delete_volume_backup(#{@backup_id})").succeeds do HP[:block_storage_v2].delete_volume_backup(@backup_id) end end tests('failure') do tests('#get_volume_backup_details("0")').raises(Fog::HP::BlockStorageV2::NotFound) do HP[:block_storage_v2].get_volume_backup_details('0') end tests('#restore_volume_backup("0")').raises(Fog::HP::BlockStorageV2::NotFound) do HP[:block_storage_v2].restore_volume_backup('0') end tests("#restore_volume_backup(#{@backup_id}, '0')").raises(Fog::HP::BlockStorageV2::NotFound) do HP[:block_storage_v2].restore_volume_backup(@backup_id, '0') end tests('#delete_volume_backup("0")').raises(Fog::HP::BlockStorageV2::NotFound) do HP[:block_storage_v2].delete_volume_backup('0') end end @target_volume.destroy @volume.destroy end fog-1.19.0/tests/hp/requests/block_storage_v2/volume_tests.rb0000644000004100000410000000730712261242552024344 0ustar www-datawww-dataShindo.tests("Fog::HP::BlockStorageV2 | volume requests", ['hp', 'v2', 'block_storage', 'volumes']) do compute_service = Fog::Compute.new(:provider => 'HP', :version => :v2) @volume_format = { 'id' => String, 'display_name' => Fog::Nullable::String, 'display_description' => Fog::Nullable::String, 'size' => Integer, 'status' => String, 'volume_type' => Fog::Nullable::String, 'snapshot_id' => Fog::Nullable::String, 'source_volid' => Fog::Nullable::String, 'bootable' => Fog::Boolean, 'created_at' => String, 'availability_zone' => String, 'attachments' => [Fog::Nullable::Hash], 'metadata' => Fog::Nullable::Hash } @volume_attach_format = { 'device' => String, 'serverId' => String, 'volumeId' => String, 'id' => String } tests('success') do @volume_id = nil @volume_name = 'fogvolume2tests' @volume_desc = @volume_name + ' desc' @base_image_id = ENV['BASE_IMAGE_ID'] || '7f60b54c-cd15-433f-8bed-00acbcd25a17' @server = compute_service.servers.create(:name => 'fogvoltests', :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } tests("#create_volume('display_name' => #{@volume_name}, 'display_description' => #{@volume_desc}, 'size' => 1)").formats(@volume_format) do data = HP[:block_storage_v2].create_volume('display_name' => @volume_name, 'display_description' => @volume_desc, 'size' => 1).body['volume'] @volume_id = data['id'] data end tests("#get_volume_details(#{@volume_id})").formats(@volume_format) do HP[:block_storage_v2].get_volume_details(@volume_id).body['volume'] end tests("#update_volume(#{@volume_id}, 'display_name' => #{@volume_name}+' Upd'").formats(@volume_format) do data = HP[:block_storage_v2].update_volume(@volume_id, 'display_name' => @volume_name).body['volume'] @volume_id = data['id'] data end tests('#list_volumes').formats({'volumes' => [@volume_format]}) do HP[:block_storage_v2].list_volumes.body end tests('#list_volumes_detail').formats({'volumes' => [@volume_format]}) do HP[:block_storage_v2].list_volumes_detail.body end tests("#attach_volume(#{@server.id}, #{@volume_id}, '/dev/sdg')").formats(@volume_attach_format) do compute_service.attach_volume(@server.id, @volume_id, "/dev/sdg").body['volumeAttachment'] end tests("#detach_volume(#{@server.id}, #{@volume_id})").succeeds do compute_service.detach_volume(@server.id, @volume_id) end tests("#delete_volume(#{@volume_id})").succeeds do HP[:block_storage_v2].delete_volume(@volume_id) end end tests('failure') do tests('#get_volume_details(0)').raises(Fog::HP::BlockStorageV2::NotFound) do HP[:block_storage_v2].get_volume_details(0) end tests("#attach_volume(0, 0, '/dev/sdg')").raises(Fog::Compute::HPV2::NotFound) do compute_service.attach_volume(0, 0, "/dev/sdg") end tests("#attach_volume(#{@server.id}, 0, '/dev/sdg')").raises(Fog::HP::BlockStorageV2::NotFound) do pending if Fog.mocking? compute_service.attach_volume(@server.id, 0, "/dev/sdg") end tests('#detach_volume(0, 0)').raises(Fog::Compute::HPV2::NotFound) do compute_service.detach_volume(0, 0) end tests("#detach_volume(#{@server.id}, 0)").raises(Fog::HP::BlockStorageV2::NotFound) do pending if Fog.mocking? compute_service.detach_volume(@server.id, 0) end tests('#delete_volume(0)').raises(Fog::HP::BlockStorageV2::NotFound) do HP[:block_storage_v2].delete_volume(0) end end @server.destroy end fog-1.19.0/tests/hp/requests/block_storage/0000755000004100000410000000000012261242552020650 5ustar www-datawww-datafog-1.19.0/tests/hp/requests/block_storage/bootable_volume_tests.rb0000644000004100000410000000512012261242552025573 0ustar www-datawww-dataShindo.tests("HP::BlockStorage | bootable volume requests", ['hp', 'block_storage', 'volumes']) do @volume_format = { 'status' => String, 'displayDescription' => Fog::Nullable::String, 'availabilityZone' => String, 'displayName' => Fog::Nullable::String, 'attachments' => [Fog::Nullable::Hash], 'volumeType' => Fog::Nullable::String, 'snapshotId' => Fog::Nullable::String, 'size' => Integer, 'id' => Integer, 'createdAt' => String, 'metadata' => Fog::Nullable::Hash } @boot_volume_format = { 'status' => String, 'displayDescription' => Fog::Nullable::String, 'availabilityZone' => String, 'displayName' => Fog::Nullable::String, 'attachments' => [Fog::Nullable::Hash], 'volumeType' => Fog::Nullable::String, 'snapshotId' => Fog::Nullable::String, 'source_image_id' => Fog::Nullable::String, 'size' => Integer, 'id' => Integer, 'createdAt' => String, 'metadata' => Fog::Nullable::Hash } @volume_attach_format = { "volumeId" => Integer, "id" => Integer } tests('success') do @volume_id = nil @volume_name = "fogbvolumetests" @volume_desc = @volume_name + " desc" @base_image_id = ENV["BASE_IMAGE_ID"] || 1242 tests("#create_volume(#{@volume_name}, #{@volume_desc}, 10, {'imageRef' => '#{@base_image_id}'})").formats(@volume_format) do data = HP[:block_storage].create_volume(@volume_name, @volume_desc, 10, {'imageRef' => "#{@base_image_id}"}).body['volume'] @volume_id = data['id'] data end HP[:block_storage].volumes.get(@volume_id).wait_for { ready? } tests("#get_bootable_volume_details(#{@volume_id})").formats(@boot_volume_format) do HP[:block_storage].get_bootable_volume_details(@volume_id).body['volume'] end tests("#list_bootable_volumes").formats({'volumes' => [@boot_volume_format]}) do HP[:block_storage].list_bootable_volumes.body end HP[:block_storage].volumes.get(@volume_id).wait_for { ready? } tests("#delete_volume(#{@volume_id})").succeeds do HP[:block_storage].delete_volume(@volume_id) end end tests('failure') do tests("#get_bootable_volume_details(0)").raises(Fog::HP::BlockStorage::NotFound) do HP[:block_storage].get_bootable_volume_details(0) end tests("#delete_volume(0)").raises(Fog::HP::BlockStorage::NotFound) do HP[:block_storage].delete_volume(0) end end end fog-1.19.0/tests/hp/requests/block_storage/snapshot_tests.rb0000644000004100000410000000322112261242552024254 0ustar www-datawww-dataShindo.tests('HP::BlockStorage | snapshot requests', ['hp', 'block_storage', 'snapshots']) do @snapshot_format = { 'status' => String, 'displayDescription' => Fog::Nullable::String, 'displayName' => Fog::Nullable::String, 'volumeId' => Integer, 'size' => Integer, 'id' => Integer, 'createdAt' => String } tests('success') do @snapshot_id = nil @snapshot_name = "fogsnapshottests" @snapshot_desc = @snapshot_name + " desc" @volume = HP[:block_storage].volumes.create(:name => 'fogvolforsnap', :size => 1) @volume.wait_for { ready? } tests("#create_snapshot(#{@snapshot_name}, #{@snapshot_desc}, #{@volume.id})").formats(@snapshot_format) do data = HP[:block_storage].create_snapshot(@snapshot_name, @snapshot_desc, @volume.id).body['snapshot'] @snapshot_id = data['id'] data end tests("#get_snapshot_details(#{@snapshot_id})").formats(@snapshot_format) do HP[:block_storage].get_snapshot_details(@snapshot_id).body['snapshot'] end tests('#list_snapshots').formats({'snapshots' => [@snapshot_format]}) do HP[:block_storage].list_snapshots.body end tests("#delete_snapshot(#{@snapshot_id})").succeeds do HP[:block_storage].delete_snapshot(@snapshot_id) end end tests('failure') do tests('#get_snapshot_details(0)').raises(Fog::HP::BlockStorage::NotFound) do HP[:block_storage].get_snapshot_details(0) end tests("#delete_snapshot(0)").raises(Fog::HP::BlockStorage::NotFound) do HP[:block_storage].delete_snapshot(0) end end @volume.destroy end fog-1.19.0/tests/hp/requests/block_storage/volume_tests.rb0000644000004100000410000000627412261242552023737 0ustar www-datawww-dataShindo.tests("HP::BlockStorage | volume requests", ['hp', 'block_storage', 'volumes']) do @volume_format = { 'status' => String, 'displayDescription' => Fog::Nullable::String, 'availabilityZone' => String, 'displayName' => Fog::Nullable::String, 'attachments' => [Fog::Nullable::Hash], 'volumeType' => Fog::Nullable::String, 'snapshotId' => Fog::Nullable::String, 'size' => Integer, 'id' => Integer, 'createdAt' => String, 'metadata' => Fog::Nullable::Hash } @volume_attach_format = { "volumeId" => Integer, "id" => Integer } tests('success') do @volume_id = nil @volume_name = "fogvolumetests" @volume_desc = @volume_name + " desc" @base_image_id = ENV["BASE_IMAGE_ID"] || 1242 @server = Fog::Compute[:hp].servers.create(:name => 'fogvoltests', :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } tests("#create_volume(#{@volume_name}, #{@volume_desc}, 1)").formats(@volume_format) do data = HP[:block_storage].create_volume(@volume_name, @volume_desc, 1).body['volume'] @volume_id = data['id'] data end HP[:block_storage].volumes.get(@volume_id).wait_for { ready? } tests("#get_volume_details(#{@volume_id})").formats(@volume_format) do HP[:block_storage].get_volume_details(@volume_id).body['volume'] end tests('#list_volumes').formats({'volumes' => [@volume_format]}) do HP[:block_storage].list_volumes.body end HP[:block_storage].volumes.get(@volume_id).wait_for { ready? } tests("#attach_volume(#{@server.id}, #{@volume_id}, '/dev/sdg')").formats(@volume_attach_format) do Fog::Compute[:hp].attach_volume(@server.id, @volume_id, "/dev/sdg").body['volumeAttachment'] end HP[:block_storage].volumes.get(@volume_id).wait_for { in_use? } unless Fog.mocking? tests("#detach_volume(#{@server.id}, #{@volume_id})").succeeds do Fog::Compute[:hp].detach_volume(@server.id, @volume_id) end HP[:block_storage].volumes.get(@volume_id).wait_for { ready? } tests("#delete_volume(#{@volume_id})").succeeds do HP[:block_storage].delete_volume(@volume_id) end end tests('failure') do tests('#get_volume_details(0)').raises(Fog::HP::BlockStorage::NotFound) do HP[:block_storage].get_volume_details(0) end tests("#attach_volume(0, 0, '/dev/sdg')").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].attach_volume(0, 0, "/dev/sdg") end tests("#attach_volume(#{@server.id}, 0, '/dev/sdg')").raises(Fog::HP::BlockStorage::NotFound) do pending if Fog.mocking? Fog::Compute[:hp].attach_volume(@server.id, 0, "/dev/sdg") end tests("#detach_volume(0, 0)").raises(Fog::Compute::HP::NotFound) do Fog::Compute[:hp].detach_volume(0, 0) end tests("#detach_volume(#{@server.id}, 0)").raises(Fog::HP::BlockStorage::NotFound) do pending if Fog.mocking? Fog::Compute[:hp].detach_volume(@server.id, 0) end tests("#delete_volume(0)").raises(Fog::HP::BlockStorage::NotFound) do HP[:block_storage].delete_volume(0) end end @server.destroy end fog-1.19.0/tests/hp/cdn_tests.rb0000644000004100000410000000133312261242552016472 0ustar www-datawww-dataShindo.tests('Fog::CDN::HP', ['hp', 'cdn']) do credentials = { :auth_token => 'auth_token', :endpoint_url => 'http://127.0.0.1/cdnpath/', :cdn_endpoint_url => 'http://127.0.0.1/cdnpath/', :service_catalog => { :"CDN" => { :zone => 'http://127.0.0.1/cdnpath/'}}, :expires => (DateTime.now + 1).to_s } options = { :hp_access_key => 'key', :hp_secret_key => 'secret', :hp_tenant_id => 'tenant', :hp_avl_zone => 'zone', :hp_auth_uri => 'https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/tokens', :credentials => credentials } tests('Test cached CDN credentials').returns(credentials) do conn = Fog::CDN::HP::Real.new(options) conn.credentials end end fog-1.19.0/tests/hp/block_storage_tests.rb0000644000004100000410000000315612261242552020551 0ustar www-datawww-datarequire 'date' Shindo.tests('Fog::HP::BlockStorage', ['hp', 'blockstorage']) do credentials = { :auth_token => 'auth_token', :endpoint_url => 'http://127.0.0.1/bpath/', :service_catalog => { :"Block Storage" => { :zone => 'http://127.0.0.1/bpath/'}}, :expires => (DateTime.now + 1).to_s } options = { :hp_access_key => 'key', :hp_secret_key => 'secret', :hp_tenant_id => 'tenant', :hp_avl_zone => 'zone', :hp_auth_uri => 'https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/tokens', :credentials => credentials } tests('Test good credentials').returns(credentials) do conn = Fog::HP::BlockStorage::Real.new(options) conn.credentials end tests('Test expired credentials') do credentials[:expires] = (DateTime.now - 1).to_s raises(Excon::Errors::Unauthorized) { Fog::HP::BlockStorage::Real.new(options) } end tests('Test no expires') do credentials[:expires] = nil raises(Excon::Errors::Unauthorized) { Fog::HP::BlockStorage::Real.new(options) } end tests('Test no creds') do options[:credentials] = nil raises(Excon::Errors::Unauthorized) { Fog::HP::BlockStorage::Real.new(options) } end tests('Test no service') do options[:credentials] = credentials options[:credentials][:service_catalog] = { :"CDN" => { :zone => 'http://127.0.0.1/bpath/'}}, raises(Excon::Errors::Unauthorized) { Fog::HP::BlockStorage::Real.new(options) } end tests('Test no creds') do options[:credentials][:service_catalog] = nil raises(Excon::Errors::Unauthorized) { Fog::HP::BlockStorage::Real.new(options) } end end fog-1.19.0/tests/hp/compute_tests.rb0000644000004100000410000000130112261242552017375 0ustar www-datawww-dataShindo.tests('Fog::Compute::HP', ['hp', 'compute']) do credentials = { :auth_token => 'auth_token', :endpoint_url => 'http://127.0.0.1/computepath/', :service_catalog => { :"Compute" => { :zone => 'http://127.0.0.1/computepath/'}}, :expires => (DateTime.now + 1).to_s } options = { :hp_access_key => 'key', :hp_secret_key => 'secret', :hp_tenant_id => 'tenant', :hp_avl_zone => 'zone', :hp_auth_uri => 'https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/tokens', :credentials => credentials } tests('Test cached Compute credentials').returns(credentials) do conn = Fog::Compute::HP::Real.new(options) conn.credentials end end fog-1.19.0/tests/hp/models/0000755000004100000410000000000012261242552015442 5ustar www-datawww-datafog-1.19.0/tests/hp/models/network/0000755000004100000410000000000012261242552017133 5ustar www-datawww-datafog-1.19.0/tests/hp/models/network/port_tests.rb0000644000004100000410000000130712261242552021667 0ustar www-datawww-dataShindo.tests('HP::Network | networking port model', ['hp', 'networking', 'port']) do @network = HP[:network].networks.create(:name => 'my_network') attributes = {:name => 'fogport', :network_id => @network.id} model_tests(HP[:network].ports, attributes, true) tests('success') do tests('#create').succeeds do attributes = {:name => 'my_port', :network_id => @network.id} @port = HP[:network].ports.create(attributes) @port.wait_for { ready? } unless Fog.mocking? !@port.id.nil? end tests('#save').succeeds do @port.name = 'my_port_upd' @port.save end tests('#destroy').succeeds do @port.destroy end end @network.destroy end fog-1.19.0/tests/hp/models/network/security_group_tests.rb0000644000004100000410000000105112261242552023762 0ustar www-datawww-dataShindo.tests('HP::Network | networking security group model', ['hp', 'networking', 'securitygroup']) do model_tests(HP[:network].security_groups, {:name => 'fogsecgroup'}, true) tests('success') do tests('#create').succeeds do attributes = {:name => 'my_secgroup', :description => 'my sec group desc'} @secgroup = HP[:network].security_groups.create(attributes) @secgroup.wait_for { ready? } unless Fog.mocking? !@secgroup.id.nil? end tests('#destroy').succeeds do @secgroup.destroy end end end fog-1.19.0/tests/hp/models/network/routers_tests.rb0000644000004100000410000000104012261242552022400 0ustar www-datawww-dataShindo.tests('HP::Network | networking routers collection', ['hp', 'networking', 'router']) do attributes = {:name => 'my_router', :admin_state_up => true} collection_tests(HP[:network].routers, attributes, true) tests('success') do attributes = {:name => 'fogrouter', :admin_state_up => true} @router = HP[:network].routers.create(attributes) tests('#all(filter)').succeeds do routers = HP[:network].routers.all({:name => 'fogrouter'}) routers.first.name == 'fogrouter' end @router.destroy end endfog-1.19.0/tests/hp/models/network/networks_tests.rb0000644000004100000410000000066412261242552022564 0ustar www-datawww-dataShindo.tests('HP::Network | networking networks collection', ['hp', 'networking', 'network']) do attributes = {:name => 'my_network', :admin_state_up => true, :shared => false} collection_tests(HP[:network].networks, attributes, true) tests('success') do tests('#all(filter)').succeeds do networks = HP[:network].networks.all({'router:external'=>true}) networks.first.router_external == true end end endfog-1.19.0/tests/hp/models/network/floating_ip_tests.rb0000644000004100000410000000202512261242552023174 0ustar www-datawww-dataShindo.tests('HP::Network | networking floating ip model', ['hp', 'networking', 'floatingip']) do @ext_network = HP[:network].networks.all({'router:external'=>true}).first attributes = {:floating_network_id => @ext_network.id} model_tests(HP[:network].floating_ips, attributes, true) tests('success') do @network = HP[:network].networks.create(:name => 'my_network') attributes = {:name => 'port1', :network_id => @network.id} @port = HP[:network].ports.create(attributes) tests('#create').succeeds do attributes = {:floating_network_id => @ext_network.id} @fip = HP[:network].floating_ips.create(attributes) @fip.wait_for { ready? } unless Fog.mocking? !@fip.id.nil? end tests("#associate_port(#{@port.id})").succeeds do @fip.associate_port(@port.id) end # this will delete the port as well tests('#disassociate_port').succeeds do @fip.disassociate_port end tests('#destroy').succeeds do @fip.destroy end @network.destroy end end fog-1.19.0/tests/hp/models/network/security_groups_tests.rb0000644000004100000410000000115712261242552024154 0ustar www-datawww-dataShindo.tests('HP::Network | networking security groups collection', ['hp', 'networking', 'securitygroup']) do attributes = {:name => 'my_secgroup', :description => 'my sec group desc'} collection_tests(HP[:network].security_groups, attributes, true) tests('success') do attributes = {:name => 'fogsecgroup', :description => 'fog sec group desc'} @secgroup = HP[:network].security_groups.create(attributes) tests('#all(filter)').succeeds do secgroup = HP[:network].security_groups.all({:name => 'fogsecgroup'}) secgroup.first.name == 'fogsecgroup' end @secgroup.destroy end endfog-1.19.0/tests/hp/models/network/floating_ips_tests.rb0000644000004100000410000000046312261242552023363 0ustar www-datawww-dataShindo.tests('HP::Network | networking floating ips collection', ['hp', 'networking', 'floatingip']) do @ext_network = HP[:network].networks.all({'router:external'=>true}).first attributes = {:floating_network_id => @ext_network.id} collection_tests(HP[:network].floating_ips, attributes, true) endfog-1.19.0/tests/hp/models/network/subnet_tests.rb0000644000004100000410000000147312261242552022207 0ustar www-datawww-dataShindo.tests('HP::Network | networking subnet model', ['hp', 'networking', 'subnet']) do @network = HP[:network].networks.create(:name => 'my_network') attributes = {:name => 'fogsubnet', :network_id => @network.id, :cidr => '11.11.11.11/11', :ip_version => 4} model_tests(HP[:network].subnets, attributes, true) tests('success') do tests('#create').succeeds do attributes = {:name => 'my_subnet', :network_id => @network.id, :cidr => '12.12.12.12/12', :ip_version => 4} @subnet = HP[:network].subnets.create(attributes) @subnet.wait_for { ready? } unless Fog.mocking? !@subnet.id.nil? end tests('#save').succeeds do @subnet.name = 'my_subnet_upd' @subnet.save end tests('#destroy').succeeds do @subnet.destroy end end @network.destroy end fog-1.19.0/tests/hp/models/network/router_tests.rb0000644000004100000410000000346612261242552022233 0ustar www-datawww-dataShindo.tests('HP::Network | networking router model', ['hp', 'networking', 'router']) do # needed to test router_interface calls @network = HP[:network].networks.create(:name => 'fognetwork') @subnet = HP[:network].subnets.create({:name => 'fogsubnet', :network_id => @network.id, :cidr => '13.13.13.13/13', :ip_version => 4}) @port = HP[:network].ports.create({:name => 'fogport', :network_id => @network.id}) attributes = {:name => 'fogrouter', :admin_state_up => true} model_tests(HP[:network].routers, attributes, true) tests('success') do tests('#create').succeeds do attributes = {:name => 'my_router', :admin_state_up => true} @router = HP[:network].routers.create(attributes) @router.wait_for { ready? } unless Fog.mocking? !@router.id.nil? end tests('#save').succeeds do @router.name = 'my_router_upd' @router.save end tests("#add_interface(#{@subnet.id}, nil) - with subnet").succeeds do @router.add_interface(@subnet.id) end #tests("#remove_interface(#{@subnet.id}, nil) - with subnet").succeeds do # @router.remove_interface(@subnet.id) #end tests("#add_interface(nil, #{@port.id}) - with port").succeeds do @router.add_interface(nil, @port.id) end ## deletes the port as well tests("#remove_interface(nil, #{@port.id}) - with port").succeeds do @router.remove_interface(nil, @port.id) end tests("#add_interface(#{@subnet.id}, #{@port.id}) - with both").succeeds do @router.add_interface(@subnet.id, @port.id) == false end tests("#add_interface(#{@subnet.id}, #{@port.id}) - with both").succeeds do @router.remove_interface(@subnet.id, @port.id) == false end tests('#destroy').succeeds do @router.destroy end end @subnet.destroy @network.destroy end fog-1.19.0/tests/hp/models/network/security_group_rules_tests.rb0000644000004100000410000000153612261242552025204 0ustar www-datawww-dataShindo.tests('HP::Network | networking security group rules collection', ['hp', 'networking', 'securitygroup']) do @secgroup = HP[:network].security_groups.create({:name => 'my_secgroup'}) attributes = {:security_group_id => @secgroup.id, :direction => 'ingress'} collection_tests(HP[:network].security_group_rules, attributes, true) tests('success') do attributes = {:security_group_id => @secgroup.id, :direction => 'ingress', :protocol => 'tcp', :port_range_min => 22, :port_range_max => 22, :remote_ip_prefix => '0.0.0.0/0'} @secgrouprule = HP[:network].security_group_rules.create(attributes) tests('#all(filter)').succeeds do secgrouprule = HP[:network].security_group_rules.all({:direction => 'ingress'}) secgrouprule.first.direction == 'ingress' end @secgrouprule.destroy end @secgroup.destroy endfog-1.19.0/tests/hp/models/network/network_tests.rb0000644000004100000410000000116112261242552022372 0ustar www-datawww-dataShindo.tests('HP::Network | networking network model', ['hp', 'networking', 'network']) do model_tests(HP[:network].networks, {:name => 'fognetwork'}, true) tests('success') do tests('#create').succeeds do attributes = {:name => 'my_network', :admin_state_up => true, :shared => false} @network = HP[:network].networks.create(attributes) @network.wait_for { ready? } unless Fog.mocking? !@network.id.nil? end tests('#save').succeeds do @network.name = 'my_network_upd' @network.save end tests('#destroy').succeeds do @network.destroy end end end fog-1.19.0/tests/hp/models/network/subnets_tests.rb0000644000004100000410000000133712261242552022371 0ustar www-datawww-dataShindo.tests('HP::Network | networking subnets collection', ['hp', 'networking', 'subnet']) do @network = HP[:network].networks.create(:name => 'my_network') attributes = {:name => 'my_subnet', :network_id => @network.id, :cidr => '11.11.11.11/11', :ip_version => 4} collection_tests(HP[:network].subnets, attributes, true) tests('success') do attributes = {:name => 'fogsubnet', :network_id => @network.id, :cidr => '12.12.12.12/12', :ip_version => 4} @subnet = HP[:network].subnets.create(attributes) tests('#all(filter)').succeeds do subnets = HP[:network].subnets.all({:cidr => '12.12.12.12/12'}) subnets.first.cidr == '12.12.12.12/12' end @subnet.destroy end @network.destroy endfog-1.19.0/tests/hp/models/network/security_group_rule_tests.rb0000644000004100000410000000152412261242552025016 0ustar www-datawww-dataShindo.tests('HP::Network | networking security group rule model', ['hp', 'networking', 'securitygroup']) do @secgroup = HP[:network].security_groups.create({:name => 'fogsecgroup'}) attributes = {:security_group_id => @secgroup.id, :direction => 'ingress'} model_tests(HP[:network].security_group_rules, attributes, true) tests('success') do tests('#create').succeeds do attributes = {:security_group_id => @secgroup.id, :direction => 'ingress', :protocol => 'tcp', :port_range_min => 22, :port_range_max => 22, :remote_ip_prefix => '0.0.0.0/0'} @secgrouprule = HP[:network].security_group_rules.create(attributes) @secgrouprule.wait_for { ready? } unless Fog.mocking? !@secgrouprule.id.nil? end tests('#destroy').succeeds do @secgrouprule.destroy end end @secgroup.destroy end fog-1.19.0/tests/hp/models/network/ports_tests.rb0000644000004100000410000000106512261242552022053 0ustar www-datawww-dataShindo.tests('HP::Network | networking ports collection', ['hp', 'networking', 'port']) do @network = HP[:network].networks.create(:name => 'my_network') attributes = {:name => 'my_port', :network_id => @network.id} collection_tests(HP[:network].ports, attributes, true) tests('success') do attributes = {:name => 'fogport', :network_id => @network.id} @port = HP[:network].ports.create(attributes) tests('#all(filter)').succeeds do HP[:network].ports.all({:name => 'fogport'}) end @port.destroy end @network.destroy endfog-1.19.0/tests/hp/models/storage/0000755000004100000410000000000012261242552017106 5ustar www-datawww-datafog-1.19.0/tests/hp/models/storage/file_tests.rb0000644000004100000410000000162712261242552021602 0ustar www-datawww-dataShindo.tests("Fog::Storage[:hp] | directory", ['hp', 'storage']) do file_attributes = { :key => 'fog_file_tests', :body => lorem_file, :public => true } directory_attributes = { :key => 'fogfilestests' } @directory = Fog::Storage[:hp].directories.create(directory_attributes) model_tests(@directory.files, file_attributes, true) do @file = @directory.files.get('fog_file_tests') tests('success') do tests("#directory").returns(@directory.key) do @file.directory.key end tests("#cdn_public_url").succeeds do pending if Fog.mocking? @file.cdn_public_url end tests("#cdn_public_ssl_url").succeeds do pending if Fog.mocking? @file.cdn_public_ssl_url end tests("#temp_signed_url(60, 'GET')").succeeds do @file.temp_signed_url(60, 'GET') end end end @directory.destroy endfog-1.19.0/tests/hp/models/storage/directory_tests.rb0000644000004100000410000000650512261242552022667 0ustar www-datawww-dataShindo.tests("Fog::Storage[:hp] | directory", ['hp', 'storage']) do model_tests(Fog::Storage[:hp].directories, {:key => "fogdirtests"}, true) do tests('success') do tests("#grant('pr')").succeeds do @instance.grant('pr') tests("public?").returns(true) do @instance.public? end end tests("#revoke('pr')").succeeds do @instance.revoke('pr') tests("public?").returns(false) do @instance.public? end end @instance.files.create(:key => 'sample.txt', :body => lorem_file) tests("#files").succeeds do @instance.files end @instance.files.get('sample.txt').destroy tests("#cdn_enable=(true)").succeeds do pending if Fog.mocking? @instance.cdn_enable=(true) tests("cdn_enabled?").returns(true) do pending if Fog.mocking? @instance.cdn_enable? end end tests("#cdn_public_url").succeeds do pending if Fog.mocking? @instance.cdn_public_url end tests("#cdn_public_ssl_url").succeeds do pending if Fog.mocking? @instance.cdn_public_ssl_url end # metadata tests tests('#metadata.all').succeeds do @instance.metadata.all end tests('#metadata.set').succeeds do @instance.metadata.set('X-Container-Meta-One' => 'One') end tests('#metadata.get set meta').succeeds do meta = @instance.metadata.get('X-Container-Meta-One') tests('gets correct value') do meta.value == 'One' end meta end tests('#metadata.update').succeeds do @instance.metadata.update('X-Container-Meta-One' => 'One Updated') end tests('#metadata.get updated meta').succeeds do meta = @instance.metadata.get('X-Container-Meta-One') tests('gets correct value') do meta.value == 'One Updated' end meta end # metadata set via setter tests('#metadata=').succeeds do @instance.metadata = {'X-Container-Meta-Two' => 'Two'} @instance.save end tests('#metadata.get set meta via setter').succeeds do meta = @instance.metadata.get('X-Container-Meta-Two') tests('gets correct value') do meta.value == 'Two' end meta end #metadata set via Meta object tests('metadata set via Meta object').succeeds do m = Fog::Storage::HP::Meta.new m.key = 'X-Container-Meta-Three' m.value = 'Three' @instance.metadata << m @instance.save end tests('#metadata.get set via Meta object').succeeds do meta = @instance.metadata.get('X-Container-Meta-Three') tests('gets correct value') do meta.value == 'Three' end meta end # invalid metadata tests("#metadata.get('invalid-meta')").succeeds do meta = @instance.metadata.get('X-Container-Meta-InValidMeta') tests('gets nil') do meta == nil end meta end end tests('failure') do tests("#grant('invalid-acl')").raises(ArgumentError) do @instance.grant('invalid-acl') end tests("#revoke('invalid-acl')").raises(ArgumentError) do @instance.revoke('invalid-acl') end end end end fog-1.19.0/tests/hp/models/storage/files_tests.rb0000644000004100000410000000164212261242552021762 0ustar www-datawww-dataShindo.tests("Fog::Storage[:hp] | files", ['hp', 'storage']) do file_attributes = { :key => 'fog_files_tests', :body => lorem_file } directory_attributes = { :key => 'fogfilestests' } collection_tests(Fog::Storage[:hp].directories.create(directory_attributes).files, file_attributes, true) @directory = Fog::Storage[:hp].directories.create(directory_attributes) @file = @directory.files.create(file_attributes) tests('success') do tests("#get_url('#{@directory.key}')").succeeds do @directory.files.get_url(@directory.key) end tests("#get_cdn_url('#{@directory.key}')").succeeds do pending if Fog.mocking? @directory.files.get_cdn_url(@directory.key) end tests("#get_cdn_ssl_url('#{@directory.key}')").succeeds do pending if Fog.mocking? @directory.files.get_cdn_ssl_url(@directory.key) end end @file.destroy @directory.destroy endfog-1.19.0/tests/hp/models/storage/directories_tests.rb0000644000004100000410000000106612261242552023174 0ustar www-datawww-dataShindo.tests("Fog::Storage[:hp] | directories", ['hp', 'storage']) do collection_tests(Fog::Storage[:hp].directories, {:key => "fogdirtests"}, true) tests('success') do tests("#create('fogdirtests')").succeeds do Fog::Storage[:hp].directories.create(:key => 'fogdirtests') end tests("#head('fogdirtests')").succeeds do Fog::Storage[:hp].directories.head('fogdirtests') end tests("#get('fogdirtests')").succeeds do @directory = Fog::Storage[:hp].directories.get('fogdirtests') end @directory.destroy end endfog-1.19.0/tests/hp/models/dns/0000755000004100000410000000000012261242552016226 5ustar www-datawww-datafog-1.19.0/tests/hp/models/dns/domains_tests.rb0000644000004100000410000000047712261242552021437 0ustar www-datawww-dataShindo.tests('HP::DNS | domains collection', ['hp', 'dns', 'domains']) do attributes = {:name => 'www.fogtest.com.', :email => 'test@fogtest.com', :ttl => 3600} collection_tests(HP[:dns].domains, attributes, true) tests('success') do tests('#all').succeeds do HP[:dns].domains.all end end endfog-1.19.0/tests/hp/models/dns/domain_tests.rb0000644000004100000410000000115012261242552021241 0ustar www-datawww-dataShindo.tests('HP::DNS | domain model', ['hp', 'dns', 'domain']) do attributes = {:name => 'www.fogtest.com.', :email => 'test@fogtest.com'} model_tests(HP[:dns].domains, attributes, true) tests('success') do tests('#create').succeeds do attributes = {:name => 'www.fogtest.com.', :email => 'test@fogtest.com', :ttl => 3600} @domain = HP[:dns].domains.create(attributes) !@domain.id.nil? end tests('Update via #save').succeeds do @domain.email = 'update@fogtest.com' @domain.save end tests('#destroy').succeeds do @domain.destroy end end end fog-1.19.0/tests/hp/models/dns/records_tests.rb0000644000004100000410000000055112261242552021437 0ustar www-datawww-dataShindo.tests('HP::DNS | records collection', ['hp', 'dns', 'records']) do @domain = HP[:dns].domains.create({:name => 'www.fogtest.com.', :email => 'test@fogtest.com'}) attributes = {:domain_id => @domain.id, :name => 'www.fogtest.com.', :type => 'A', :data => '15.185.172.152'} collection_tests(@domain.records, attributes, true) @domain.destroy endfog-1.19.0/tests/hp/models/dns/record_tests.rb0000644000004100000410000000154312261242552021256 0ustar www-datawww-dataShindo.tests('HP::DNS | record model', ['hp', 'dns', 'record']) do @domain = HP[:dns].domains.create({:name => 'www.fogtest.com.', :email => 'test@fogtest.com'}) attributes = {:domain_id => @domain.id, :name => 'www.fogtest.com.', :type => 'A', :data => '15.185.100.152'} model_tests(@domain.records, attributes, true) tests('success') do tests('#create').succeeds do attributes = {:domain_id => @domain.id, :name => 'www.fogtest.com.', :type => 'A', :data => '15.185.200.152', :description => 'test record'} @record = HP[:dns].records.create(attributes) !@record.id.nil? end tests('Update via #save').succeeds do @record.name = 'www.fogupdate.com.' @record.description = 'desc for record' @record.save end tests('#destroy').succeeds do @record.destroy end end @domain.destroy end fog-1.19.0/tests/hp/models/compute_v2/0000755000004100000410000000000012261242552017525 5ustar www-datawww-datafog-1.19.0/tests/hp/models/compute_v2/availability_zone_tests.rb0000644000004100000410000000043612261242552025004 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | availability zone model", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @zones = service.availability_zones tests('#available?').succeeds do @zones.first.respond_to?('available?') end end fog-1.19.0/tests/hp/models/compute_v2/server_tests.rb0000644000004100000410000000235712261242552022611 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | server model", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @base_image_id = ENV['BASE_IMAGE_ID'] || '7f60b54c-cd15-433f-8bed-00acbcd25a17' model_tests(service.servers, {:name => 'fogservertest', :flavor_id => 100, :image_id => @base_image_id}, true) do @server = service.servers.create(:name => 'fogservertest', :flavor_id => 100, :image_id => @base_image_id) tests('#console_output(10)').succeeds do @server.console_output(10) end tests('#vnc_console_url').succeeds do @server.vnc_console_url end tests("#create_image('fogimgfromserver')").succeeds do @server.create_image('fogimgfromserver') end tests("#reboot('SOFT')").succeeds do pending unless Fog.mocking? @server.reboot('SOFT') end tests("#rebuild(#{@base_image_id}, 'fogrebuildserver')").succeeds do pending @server.rebuild(@base_image_id, 'fogrebuildserver') end tests('#add_security_group("default")').succeeds do @server.add_security_group('default') end tests('#remove_security_group("default")').succeeds do @server.remove_security_group('default') end @server.destroy end end fog-1.19.0/tests/hp/models/compute_v2/metadata_image_tests.rb0000644000004100000410000000332112261242552024215 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | metadata for images", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @base_image_id = ENV['BASE_IMAGE_ID'] || '7f60b54c-cd15-433f-8bed-00acbcd25a17' @server = service.servers.create(:name => 'fogsermdtests', :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } @image = @server.create_image('fogimgmetadatatests', :metadata => {'Meta1' => 'MetaValue1', 'Meta2' => 'MetaValue2'}) @image.wait_for { ready? } @image.reload tests('success') do tests('#all').succeeds do @image.metadata.all end tests("#get('Meta1')").succeeds do pending if Fog.mocking? @image.metadata.get('Meta1') end tests("#update({'Meta3' => 'MetaValue3'})").succeeds do @data = @image.metadata.update({'Meta3' => 'MetaValue3'}) test('metadata has updated correctly') do @image.metadata.get('Meta3').value == 'MetaValue3' end end tests("#set({'Meta4' => 'MetaValue4'})").succeeds do @data = @image.metadata.set({'Meta4' => 'MetaValue4'}) test('metadata has set correctly') do @image.metadata.get('Meta4').value == 'MetaValue4' end end tests("#save").succeeds do m = @image.metadata.new(:key => 'Meta5', :value => 'MetaValue5') @data = m.save test('metadata has saved correctly') do @image.metadata.get('Meta5').value == 'MetaValue5' end end tests("#destroy('Meta5')").succeeds do @image.metadata.destroy('Meta5') test('metadata has been destroyed') do @image.metadata.get('Meta5') == nil end end end unless Fog.mocking? @image.destroy end @server.destroy end fog-1.19.0/tests/hp/models/compute_v2/servers_tests.rb0000644000004100000410000000055012261242552022765 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | servers collection", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @base_image_id = ENV['BASE_IMAGE_ID'] || '7f60b54c-cd15-433f-8bed-00acbcd25a17' collection_tests(service.servers, {:name => 'fogservercolltest', :flavor_id => 100, :image_id => @base_image_id}, true) endfog-1.19.0/tests/hp/models/compute_v2/volume_attachment_tests.rb0000644000004100000410000000243712261242552025021 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | volume_attachment model", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @base_image_id = ENV['BASE_IMAGE_ID'] || '7f60b54c-cd15-433f-8bed-00acbcd25a17' @server = service.servers.create(:name => 'fogserattachtests', :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } @volume = HP[:block_storage_v2].volumes.create(:name => 'fogvolumetest', :size => 1) @volume.wait_for { ready? } tests('success') do tests('#create').succeeds do volume_attachment = @server.volume_attachments.create(:server_id => @server.id, :volume_id => @volume.id, :device => '/dev/sdf') test('volume attached to server') do volume_attachment.server_id == @server.id end end tests('#get').succeeds do volume_attachment = @server.volume_attachments.get(@volume.id) test('get server in volume attachment') do volume_attachment.server_id == @server.id end test('get volume in volume attachment') do volume_attachment.id == @volume.id end end tests('#detach').succeeds do volume_attachment = @server.volume_attachments.get(@volume.id) volume_attachment.detach end end @volume.destroy @server.destroy end fog-1.19.0/tests/hp/models/compute_v2/key_pair_tests.rb0000644000004100000410000000116612261242552023103 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | key_pair model", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) model_tests(service.key_pairs, {:name => 'fogkeyname'}, true) after do @keypair.destroy end tests('new keypair') do @keypair = service.key_pairs.create(:name => 'fogtestkey') test('writable?') do @keypair.writable? == true end end tests('existing keypair') do service.key_pairs.create(:name => 'fogtestkey') @keypair = service.key_pairs.get('fogtestkey') test('writable?') do @keypair.writable? == false end end end fog-1.19.0/tests/hp/models/compute_v2/metadata_server_tests.rb0000644000004100000410000000323412261242552024444 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | metadata for servers", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @base_image_id = ENV['BASE_IMAGE_ID'] || '7f60b54c-cd15-433f-8bed-00acbcd25a17' @server = service.servers.create(:name => 'fogsermetadatatests', :flavor_id => 100, :image_id => @base_image_id, :metadata => {'Meta1' => 'MetaValue1', 'Meta2' => 'MetaValue2'}) @server.wait_for { ready? } tests('success') do tests('#all').succeeds do @server.metadata.all end tests("#get('Meta1')").succeeds do @data = @server.metadata.get('Meta1') test('metadata gets correct value') do @data.value == 'MetaValue1' end end tests("#update({'Meta3' => 'MetaValue3'})").succeeds do @data = @server.metadata.update({'Meta3' => 'MetaValue3'}) test('metadata has updated correctly') do @server.metadata.get('Meta3').value == 'MetaValue3' end end tests("#set({'Meta4' => 'MetaValue4'})").succeeds do @data = @server.metadata.set({'Meta4' => 'MetaValue4'}) test('metadata has set correctly') do @server.metadata.get('Meta4').value == 'MetaValue4' end end tests('#save').succeeds do m = @server.metadata.new(:key => 'Meta5', :value => 'MetaValue5') @data = m.save test('metadata has saved correctly') do @server.metadata.get('Meta5').value == 'MetaValue5' end end tests("#destroy('Meta5')").succeeds do @data = @server.metadata.destroy('Meta5') test('metadata has been destroyed') do @server.metadata.get('Meta5') == nil end end end @server.destroy end fog-1.19.0/tests/hp/models/compute_v2/key_pairs_tests.rb0000644000004100000410000000034212261242552023261 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | key pairs collection", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) collection_tests(service.key_pairs, {:name => 'fogkeyname'}, true) endfog-1.19.0/tests/hp/models/compute_v2/availability_zones_tests.rb0000644000004100000410000000046712261242552025173 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | availability zones collection", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) tests('#all').succeeds do @zones = service.availability_zones end tests('#get').succeeds do @zones.get('az1').name == 'az1' end endfog-1.19.0/tests/hp/models/compute_v2/addresses_tests.rb0000644000004100000410000000031512261242552023250 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | addresses collection", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) collection_tests(service.addresses, {}, true) endfog-1.19.0/tests/hp/models/compute_v2/address_tests.rb0000644000004100000410000000115012261242552022716 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | address model", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @base_image_id = ENV['BASE_IMAGE_ID'] || '7f60b54c-cd15-433f-8bed-00acbcd25a17' model_tests(service.addresses, {}, true) do @server = service.servers.create(:name => 'fogseraddtests', :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } tests('#server=').succeeds do @instance.server = @server test('server attached') do @instance.instance_id == @server.id end end @server.destroy end end fog-1.19.0/tests/hp/models/compute_v2/volume_attachments_tests.rb0000644000004100000410000000124712261242552025202 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | volume attachments collection", ['hp', 'v2', 'compute']) do service = Fog::Compute.new(:provider => 'HP', :version => :v2) @base_image_id = ENV['BASE_IMAGE_ID'] || '7f60b54c-cd15-433f-8bed-00acbcd25a17' @server = service.servers.create(:name => 'fogserverattachtest', :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } @volume = HP[:block_storage_v2].volumes.create(:name => 'fogvolumetest', :size => 1) @volume.wait_for { ready? } collection_tests(@server.volume_attachments, {:server_id => @server.id, :volume_id => @volume.id, :device => '/dev/sdf'}, true) @volume.destroy @server.destroy endfog-1.19.0/tests/hp/models/compute/0000755000004100000410000000000012261242552017116 5ustar www-datawww-datafog-1.19.0/tests/hp/models/compute/security_group_tests.rb0000644000004100000410000000253412261242552023754 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | security_group", ['hp']) do # Disabled due to https://github.com/fog/fog/1546 pending model_tests(Fog::Compute[:hp].security_groups, {:name => 'foggroupname', :description => 'foggroupdescription'}, true) tests("a group with trailing whitespace") do @group = Fog::Compute[:hp].security_groups.create(:name => " foggroup with spaces ", :description => " fog group desc ") test("all spaces are removed from name") do @group.name == " foggroup with spaces ".strip! end test("all spaces are removed from description") do @group.description == " fog group desc ".strip! end @other_group = Fog::Compute[:hp].security_groups.create(:name => 'other group', :description => 'another group') test("authorize access by another security group") do sgrule = @group.create_rule(80..80, "tcp", nil, @other_group.id) @sg_rule_id = sgrule.body['security_group_rule']['id'] @group.reload s = @group.rules.select {|r| r['id'] == @sg_rule_id unless r.nil?} s[0]['id'] == @sg_rule_id end test("revoke access from another security group") do @group.delete_rule(@sg_rule_id) @group.reload s = @group.rules.select {|r| r['id'] == @sg_rule_id unless r.nil?} s.empty? end @other_group.destroy @group.destroy end end fog-1.19.0/tests/hp/models/compute/security_groups_tests.rb0000644000004100000410000000030312261242552024127 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | security_groups", ['hp']) do collection_tests(Fog::Compute[:hp].security_groups, {:name => 'foggroupname', :description => 'foggroupdescription'}, true) end fog-1.19.0/tests/hp/models/compute/metadata_image_tests.rb0000644000004100000410000000332512261242552023612 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | metadata for images", ['hp']) do @base_image_id = ENV["BASE_IMAGE_ID"] || 1242 @server = Fog::Compute[:hp].servers.create(:name => "fogsermdtests", :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } response = @server.create_image("fogimgmetadatatests", :metadata => {'Meta1' => 'MetaValue1', 'Meta2' => 'MetaValue2'}) unless Fog.mocking? sleep(10) end new_image_id = response.headers["Location"].split("/")[5] @image = Fog::Compute[:hp].images.get(new_image_id) tests('success') do tests("#all").succeeds do @image.metadata.all end tests("#get('Meta1')").succeeds do pending if Fog.mocking? @image.metadata.get('Meta1') end tests("#update({'Meta3' => 'MetaValue3'})").succeeds do @data = @image.metadata.update({'Meta3' => 'MetaValue3'}) test("metadata has updated correctly") do @image.metadata.get('Meta3').value == "MetaValue3" end end tests("#set({'Meta4' => 'MetaValue4'})").succeeds do @data = @image.metadata.set({'Meta4' => 'MetaValue4'}) test("metadata has set correctly") do @image.metadata.get('Meta4').value == "MetaValue4" end end tests("#save").succeeds do m = @image.metadata.new(:key => 'Meta5', :value => 'MetaValue5') @data = m.save test("metadata has saved correctly") do @image.metadata.get('Meta5').value == "MetaValue5" end end tests("#destroy('Meta5')").succeeds do @image.metadata.destroy('Meta5') test("metadata has been destroyed") do @image.metadata.get('Meta5') == nil end end end unless Fog.mocking? @image.destroy end @server.destroy end fog-1.19.0/tests/hp/models/compute/key_pair_tests.rb0000644000004100000410000000107212261242552022470 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | key_pair", ['hp']) do model_tests(Fog::Compute[:hp].key_pairs, {:name => 'fogkeyname'}, true) after do @keypair.destroy end tests("new keypair") do @keypair = Fog::Compute[:hp].key_pairs.create(:name => 'testkey') test ("writable?") do @keypair.writable? == true end end tests("existing keypair") do Fog::Compute[:hp].key_pairs.create(:name => 'testkey') @keypair = Fog::Compute[:hp].key_pairs.get('testkey') test("writable?") do @keypair.writable? == false end end end fog-1.19.0/tests/hp/models/compute/metadata_server_tests.rb0000644000004100000410000000306012261242552024032 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | metadata for servers", ['hp']) do @base_image_id = ENV["BASE_IMAGE_ID"] || 1242 @server = Fog::Compute[:hp].servers.create(:name => "fogsermetadatatests", :flavor_id => 100, :image_id => @base_image_id, :metadata => {'Meta1' => 'MetaValue1', 'Meta2' => 'MetaValue2'}) @server.wait_for { ready? } tests('success') do tests("#all").succeeds do @server.metadata.all end tests("#get('Meta1')").succeeds do @data = @server.metadata.get('Meta1') test("metadata gets correct value") do @data.value == "MetaValue1" end end tests("#update({'Meta3' => 'MetaValue3'})").succeeds do @data = @server.metadata.update({'Meta3' => 'MetaValue3'}) test("metadata has updated correctly") do @server.metadata.get('Meta3').value == "MetaValue3" end end tests("#set({'Meta4' => 'MetaValue4'})").succeeds do @data = @server.metadata.set({'Meta4' => 'MetaValue4'}) test("metadata has set correctly") do @server.metadata.get('Meta4').value == "MetaValue4" end end tests("#save").succeeds do m = @server.metadata.new(:key => 'Meta5', :value => 'MetaValue5') @data = m.save test("metadata has saved correctly") do @server.metadata.get('Meta5').value == "MetaValue5" end end tests("#destroy('Meta5')").succeeds do @data = @server.metadata.destroy('Meta5') test("metadata has been destroyed") do @server.metadata.get('Meta5') == nil end end end @server.destroy end fog-1.19.0/tests/hp/models/compute/key_pairs_tests.rb0000644000004100000410000000021512261242552022651 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | key_pairs", ['hp']) do collection_tests(Fog::Compute[:hp].key_pairs, {:name => 'fogkeyname'}, true) endfog-1.19.0/tests/hp/models/compute/addresses_tests.rb0000644000004100000410000000017012261242552022640 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | addresses", ['hp']) do collection_tests(Fog::Compute[:hp].addresses, {}, true) endfog-1.19.0/tests/hp/models/compute/address_tests.rb0000644000004100000410000000065112261242552022314 0ustar www-datawww-dataShindo.tests("Fog::Compute[:hp] | address", ['hp']) do @base_image_id = ENV["BASE_IMAGE_ID"] || 1242 model_tests(Fog::Compute[:hp].addresses, {}, true) do @server = Fog::Compute[:hp].servers.create(:name => "fogservertests", :flavor_id => 100, :image_id => @base_image_id) @server.wait_for { ready? } tests('#server=').succeeds do @instance.server = @server end @server.destroy end end fog-1.19.0/tests/hp/models/lb/0000755000004100000410000000000012261242552016037 5ustar www-datawww-datafog-1.19.0/tests/hp/models/lb/algorithms_tests.rb0000644000004100000410000000042212261242552021755 0ustar www-datawww-dataShindo.tests('HP::LB | algorithms collection', ['hp', 'lb', 'algorithms']) do tests('success') do tests('#all').succeeds do HP[:lb].algorithms end tests('#get("ROUND_ROBIN")').succeeds do HP[:lb].algorithms.get("ROUND_ROBIN") end end endfog-1.19.0/tests/hp/models/lb/load_balancers_tests.rb0000644000004100000410000000112612261242552022537 0ustar www-datawww-dataShindo.tests('HP::LB | load balancer collection', ['hp', 'lb', 'load_balancer']) do attributes = {:name => 'fog-lb', :nodes => [{'address' => '15.185.1.1', 'port' => '80'}]} collection_tests(HP[:lb].load_balancers, attributes, true) tests('success') do attributes = {:name => 'fog-lb', :nodes => [{'address' => '15.185.1.1', 'port' => '80'}]} @lb = HP[:lb].load_balancers.create(attributes) tests('#all').succeeds do HP[:lb].load_balancers.all end tests("#get(#{@lb.id})").succeeds do HP[:lb].load_balancers.get(@lb.id) end @lb.destroy end endfog-1.19.0/tests/hp/models/lb/load_balancer_virtual_ips_tests.rb0000644000004100000410000000105312261242552024774 0ustar www-datawww-dataShindo.tests('HP::LB | load balancer virtual ips collection', ['hp', 'lb', 'virtual_ip']) do attributes = {:name => 'fog-lb', :nodes => [{'address' => '15.185.1.1', 'port' => '80'}]} @lb = HP[:lb].load_balancers.create(attributes) tests('success') do @vip = HP[:lb].virtual_ips(:load_balancer => @lb).all.first tests('#all').succeeds do HP[:lb].virtual_ips(:load_balancer => @lb).all end tests("#get(#{@vip.id})").succeeds do HP[:lb].virtual_ips(:load_balancer => @lb).get(@vip.id) end end @lb.destroy endfog-1.19.0/tests/hp/models/lb/load_balancer_nodes_tests.rb0000644000004100000410000000117712261242552023552 0ustar www-datawww-dataShindo.tests('HP::LB | load balancer nodes collection', ['hp', 'lb', 'node']) do attributes = {:name => 'fog-lb', :nodes => [{'address' => '15.185.1.1', 'port' => '80'}]} @lb = HP[:lb].load_balancers.create(attributes) attributes = {:address => '15.185.1.1', :port => '80'} collection_tests(@lb.nodes, attributes, true) tests('success') do attributes = {:address => '15.185.1.1', :port => '80'} @node = @lb.nodes.create(attributes) tests('#all').succeeds do @lb.nodes.all end tests("#get(#{@node.id})").succeeds do @lb.nodes.get(@node.id) end @node.destroy end @lb.destroy endfog-1.19.0/tests/hp/models/lb/protocols_tests.rb0000644000004100000410000000037612261242552021640 0ustar www-datawww-dataShindo.tests('HP::LB | protocol collection', ['hp', 'lb', 'protocol']) do tests('success') do tests('#all').succeeds do HP[:lb].protocols end tests('#get("HTTP")').succeeds do HP[:lb].protocols.get('HTTP') end end endfog-1.19.0/tests/hp/models/lb/load_balancer_tests.rb0000644000004100000410000000035012261242552022352 0ustar www-datawww-dataShindo.tests('HP::LB | load balancer model', ['hp', 'lb', 'load_balancer']) do attributes = {:name => 'fog-lb', :nodes => [{'address' => '15.185.1.1', 'port' => '80'}]} model_tests(HP[:lb].load_balancers, attributes, true) endfog-1.19.0/tests/hp/models/lb/load_balancer_node_tests.rb0000644000004100000410000000050312261242552023357 0ustar www-datawww-dataShindo.tests('HP::LB | load balancer node model', ['hp', 'lb', 'node']) do attributes = {:name => 'fog-lb', :nodes => [{'address' => '15.185.1.1', 'port' => '80'}]} @lb = HP[:lb].load_balancers.create(attributes) attributes = {:address => '15.185.1.1', :port => '80'} model_tests(@lb.nodes, attributes, true) endfog-1.19.0/tests/hp/models/block_storage_v2/0000755000004100000410000000000012261242552020667 5ustar www-datawww-datafog-1.19.0/tests/hp/models/block_storage_v2/snapshots_tests.rb0000644000004100000410000000064012261242552024460 0ustar www-datawww-dataShindo.tests("HP::BlockStorageV2 | snapshots collection", ['hp', 'v2', 'block_storage', 'snapshots']) do @volume = HP[:block_storage_v2].volumes.create(:name => 'testsnap2vol', :size => 1) @volume.wait_for { ready? } unless Fog.mocking? collection_tests(HP[:block_storage_v2].snapshots, {:name => 'fogsnap2tests', :description => 'fogsnaptests-desc', :volume_id => @volume.id}, true) @volume.destroy end fog-1.19.0/tests/hp/models/block_storage_v2/snapshot_tests.rb0000644000004100000410000000125112261242552024274 0ustar www-datawww-dataShindo.tests("HP::BlockStorageV2 | snapshot model", ['hp', 'v2', 'block_storage', 'snapshots']) do @volume = HP[:block_storage_v2].volumes.create(:name => 'testsnap2vol', :size => 1) @volume.wait_for { ready? } unless Fog.mocking? model_tests(HP[:block_storage_v2].snapshots, {:name => 'fogsnap2tests', :description => 'fogsnaptests-desc', :volume_id => @volume.id}, true) do test("get(#{@instance.id})") do HP[:block_storage_v2].snapshots.get(@instance.id) != nil? end test("update(#{@instance.id}") do @instance.name = 'Updated' @instance.save @instance.reload @instance.name == 'Updated' end end @volume.destroy end fog-1.19.0/tests/hp/models/block_storage_v2/volumes_tests.rb0000644000004100000410000000035512261242552024133 0ustar www-datawww-dataShindo.tests("HP::BlockStorage | volumes collection", ['hp', 'v2', 'block_storage', 'volumes']) do collection_tests(HP[:block_storage_v2].volumes, {:name => 'fogvol2tests', :description => 'fogvol2tests-desc', :size => 1}, true) end fog-1.19.0/tests/hp/models/block_storage_v2/volume_backups_tests.rb0000644000004100000410000000071712261242552025462 0ustar www-datawww-dataShindo.tests("Fog::Compute::HPV2 | volume backups collection", ['hp', 'v2', 'block_storage', 'backup']) do @volume = HP[:block_storage_v2].volumes.create(:name => 'fogvolbkp2tests', :description => 'fogvolbkp2tests-desc', :size => 1) @volume.wait_for { ready? } unless Fog.mocking? collection_tests(HP[:block_storage_v2].volume_backups, {:name => 'fogbkp2tests', :description => 'fogbkp2tests-desc', :volume_id => @volume.id}, true) @volume.destroy endfog-1.19.0/tests/hp/models/block_storage_v2/volume_backup_tests.rb0000644000004100000410000000125512261242552025275 0ustar www-datawww-dataShindo.tests("HP::BlockStorage | volume backup model", ['hp', 'v2', 'block_storage', 'backup']) do @volume = HP[:block_storage_v2].volumes.create(:name => 'fogvolbkp2tests', :description => 'fogvolbkp2tests-desc', :size => 1) @volume.wait_for { ready? } unless Fog.mocking? model_tests(HP[:block_storage_v2].volume_backups, {:name => 'fogbkp2tests', :description => 'fogbkp2tests-desc', :volume_id => @volume.id}, true) do # restore to new volume tests('restore()').succeeds do @instance.restore end # restore to specified volume tests("restore(#{@volume.id})").succeeds do @instance.restore(@volume.id) end end @volume.destroy end fog-1.19.0/tests/hp/models/block_storage_v2/volume_tests.rb0000644000004100000410000000114312261242552023744 0ustar www-datawww-dataShindo.tests("HP::BlockStorage | volume model", ['hp', 'v2', 'block_storage', 'volumes']) do model_tests(HP[:block_storage_v2].volumes, {:name => 'fogvol2tests', :description => 'fogvol2tests-desc', :size => 1}, true) do test("get(#{@instance.id})") do HP[:block_storage_v2].volumes.get(@instance.id) != nil? end test("update(#{@instance.id})") do @instance.name = 'fogvol2tests Updated' @instance.save @instance.reload @instance.name == 'fogvol2tests Updated' end test("has_attachments?") do @instance.has_attachments? == false end end end fog-1.19.0/tests/hp/models/block_storage/0000755000004100000410000000000012261242552020260 5ustar www-datawww-datafog-1.19.0/tests/hp/models/block_storage/bootable_volume_tests.rb0000644000004100000410000000135212261242552025206 0ustar www-datawww-dataShindo.tests("HP::BlockStorage | bootable volumes", ['hp', 'block_storage', 'volumes']) do @base_image_id = ENV["BASE_IMAGE_ID"] || 1242 model_tests(HP[:block_storage].bootable_volumes, {:name => "fogbvoltests", :description => "fogbvoltests-desc", :size => 10, :image_id => @base_image_id}, true) tests("new volume") do @volume = HP[:block_storage].bootable_volumes.create(:name => "testbvol", :size => 10, :image_id => @base_image_id) @volume.wait_for { ready? } unless Fog.mocking? test("get(#{@volume.id})") do HP[:block_storage].bootable_volumes.get(@volume.id) != nil? end test("has_attachments?") do @volume.has_attachments? == false end after do @volume.destroy end end end fog-1.19.0/tests/hp/models/block_storage/snapshot_tests.rb0000644000004100000410000000132212261242552023664 0ustar www-datawww-dataShindo.tests("HP::BlockStorage | snapshots", ['hp', 'block_storage', 'snapshots']) do @volume = HP[:block_storage].volumes.create(:name => "testsnapvol", :size => 1) @volume.wait_for { ready? } unless Fog.mocking? model_tests(HP[:block_storage].snapshots, {:name => "fogsnaptests", :description => "fogsnaptests-desc", :volume_id => @volume.id}, true) tests("new snapshot") do @snapshot = HP[:block_storage].snapshots.create(:name => "testvol", :volume_id => @volume.id) @snapshot.wait_for { ready? } unless Fog.mocking? test("get(#{@snapshot.id})") do HP[:block_storage].snapshots.get(@snapshot.id) != nil? end after do @snapshot.destroy end end @volume.destroy end fog-1.19.0/tests/hp/models/block_storage/volume_tests.rb0000644000004100000410000000112612261242552023336 0ustar www-datawww-dataShindo.tests("HP::BlockStorage | volumes", ['hp', 'block_storage', 'volumes']) do model_tests(HP[:block_storage].volumes, {:name => "fogvoltests", :description => "fogvoltests-desc", :size => 1}, true) tests("new volume") do @volume = HP[:block_storage].volumes.create(:name => "testvol", :size => 1) @volume.wait_for { ready? } unless Fog.mocking? test("get(#{@volume.id})") do HP[:block_storage].volumes.get(@volume.id) != nil? end test("has_attachments?") do @volume.has_attachments? == false end after do @volume.destroy end end end fog-1.19.0/tests/hp/storage_tests.rb0000644000004100000410000000145712261242552017401 0ustar www-datawww-dataShindo.tests('Fog::Storage::HP', ['hp', 'storage']) do credentials = { :auth_token => 'auth_token', :endpoint_url => 'http://127.0.0.1/path/', :cdn_endpoint_url => 'http://127.0.0.1/cdnpath/', :service_catalog => { :"Object Storage" => { :zone => 'http://127.0.0.1/path/'}, :"CDN" => { :zone => 'http://127.0.0.1/cdnpath/'}}, :expires => (DateTime.now + 1).to_s } options = { :hp_access_key => 'key', :hp_secret_key => 'secret', :hp_tenant_id => 'tenant', :hp_avl_zone => 'zone', :hp_auth_uri => 'https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/tokens', :credentials => credentials } tests('Test cached Storage credentials').returns(credentials) do conn = Fog::Storage::HP::Real.new(options) conn.credentials end end fog-1.19.0/tests/rackspace/0000755000004100000410000000000012261242552015504 5ustar www-datawww-datafog-1.19.0/tests/rackspace/auto_scale_tests.rb0000644000004100000410000001025012261242552021370 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").has_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 endfog-1.19.0/tests/rackspace/queues_tests.rb0000644000004100000410000001144012261242552020562 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues', ['rackspace']) do 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::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 pending if Fog.mocking? 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 pending if Fog.mocking? 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").has_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 pending if Fog.mocking? 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 pending if Fog.mocking? @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 pending if Fog.mocking? 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-1.19.0/tests/rackspace/identity_tests.rb0000644000004100000410000000232312261242552021104 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Identity', ['rackspace']) do tests('current authentication') do pending if Fog.mocking? 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 pending if Fog.mocking? 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 endfog-1.19.0/tests/rackspace/helper.rb0000644000004100000410000000601212261242552017307 0ustar www-datawww-dataLINKS_FORMAT = [{ 'href' => String, 'rel' => String }] module Shindo class Tests unless Fog.mocking? Fog.timeout = 2000 Fog::Logger.warning "Setting default fog timeout to #{Fog.timeout} seconds" end 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 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 endfog-1.19.0/tests/rackspace/url_encoding_tests.rb0000644000004100000410000000043312261242552021723 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-1.19.0/tests/rackspace/service_tests.rb0000644000004100000410000000456512261242552020725 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-1.19.0/tests/rackspace/dns_tests.rb0000644000004100000410000001273212261242552020044 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").has_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 endfog-1.19.0/tests/rackspace/databases_tests.rb0000644000004100000410000001441612261242552021210 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").has_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-1.19.0/tests/rackspace/requests/0000755000004100000410000000000012261242552017357 5ustar www-datawww-datafog-1.19.0/tests/rackspace/requests/databases/0000755000004100000410000000000012261242552021306 5ustar www-datawww-datafog-1.19.0/tests/rackspace/requests/databases/helper.rb0000644000004100000410000000226712261242552023121 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-1.19.0/tests/rackspace/requests/databases/flavor_tests.rb0000644000004100000410000000060212261242552024344 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-1.19.0/tests/rackspace/requests/databases/database_tests.rb0000644000004100000410000000241112261242552024617 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-1.19.0/tests/rackspace/requests/databases/instance_tests.rb0000644000004100000410000000423312261242552024663 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-1.19.0/tests/rackspace/requests/databases/user_tests.rb0000644000004100000410000000224612261242552024037 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-1.19.0/tests/rackspace/requests/storage/0000755000004100000410000000000012261242552021023 5ustar www-datawww-datafog-1.19.0/tests/rackspace/requests/storage/object_tests.rb0000644000004100000410000002103712261242552024043 0ustar www-datawww-dataShindo.tests('Fog::Storage[:rackspace] | object requests', ["rackspace"]) do unless Fog.mocking? @directory = Fog::Storage[:rackspace].directories.create(:key => 'fogobjecttests') end module RackspaceStorageHelpers def override_path(path) @uri.path = path end end tests('success') do tests("#put_object('fogobjecttests', 'fog_object')").succeeds do pending if Fog.mocking? Fog::Storage[:rackspace].put_object('fogobjecttests', 'fog_object', lorem_file) end tests("#get_object('fogobjectests', 'fog_object')").succeeds do pending if Fog.mocking? Fog::Storage[:rackspace].get_object('fogobjecttests', 'fog_object').body == lorem_file.read end tests("#get_object('fogobjecttests', 'fog_object', &block)").succeeds do pending if Fog.mocking? 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 pending if Fog.mocking? Fog::Storage[:rackspace].head_object('fogobjecttests', 'fog_object') end tests("#delete_object('fogobjecttests', 'fog_object')").succeeds do pending if Fog.mocking? 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 pending if Fog.mocking? 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) object_url =~ /http:\/\/.*clouddrive.com\/[^\/]+\/[^\/]+\/fogobjecttests\/fog_object\?temp_url_sig=7e69a73092e333095a70b3be826a7350fcbede86&temp_url_expires=1344149532/ end # an object key with no special characters tests("#get_object_https_url('fogobjecttests', 'fog_object','expiration timestamp')").succeeds do pending if Fog.mocking? 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) object_url =~ /https:\/\/.*clouddrive.com\/[^\/]+\/[^\/]+\/fogobjecttests\/fog_object\?temp_url_sig=7e69a73092e333095a70b3be826a7350fcbede86&temp_url_expires=1344149532/ end # an object key nested under a / tests("#get_object_https_url('fogobjecttests', 'fog/object','expiration timestamp')").succeeds do pending if Fog.mocking? 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) object_url =~ /https:\/\/.*clouddrive.com\/[^\/]+\/[^\/]+\/fogobjecttests\/fog\/object\?temp_url_sig=3e99892828804e3d0fdadd18c543b688591ca8b8&temp_url_expires=1344149532/ end # an object key containing a - tests("#get_object_https_url('fogobjecttests', 'fog-object','expiration timestamp')").succeeds do pending if Fog.mocking? 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) object_url =~ /https:\/\/.*clouddrive.com\/[^\/]+\/[^\/]+\/fogobjecttests\/fog-object\?temp_url_sig=a24dd5fc955a57adce7d1b5bc4ec2c7660ab8396&temp_url_expires=1344149532/ end tests("put_object with block") do pending if Fog.mocking? 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 pending if Fog.mocking? 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 pending if Fog.mocking? Fog::Storage[:rackspace].get_object('fogobjecttests', 'fog_non_object') end tests("#get_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::Rackspace::NotFound) do pending if Fog.mocking? Fog::Storage[:rackspace].get_object('fognoncontainer', 'fog_non_object') end tests("#head_object('fogobjecttests', 'fog_non_object')").raises(Fog::Storage::Rackspace::NotFound) do pending if Fog.mocking? Fog::Storage[:rackspace].head_object('fogobjecttests', 'fog_non_object') end tests("#head_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::Rackspace::NotFound) do pending if Fog.mocking? Fog::Storage[:rackspace].head_object('fognoncontainer', 'fog_non_object') end tests("#delete_object('fogobjecttests', 'fog_non_object')").raises(Fog::Storage::Rackspace::NotFound) do pending if Fog.mocking? Fog::Storage[:rackspace].delete_object('fogobjecttests', 'fog_non_object') end tests("#delete_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::Rackspace::NotFound) do pending if Fog.mocking? Fog::Storage[:rackspace].delete_object('fognoncontainer', 'fog_non_object') end tests('#delete_multiple_objects') do pending if Fog.mocking? 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 unless Fog.mocking? @directory.destroy end end fog-1.19.0/tests/rackspace/requests/storage/large_object_tests.rb0000644000004100000410000003426212261242552025221 0ustar www-datawww-dataShindo.tests('Fog::Storage[:rackspace] | large object requests', ['rackspace']) do unless Fog.mocking? @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' } } end tests('success') do tests('upload test segments').succeeds do pending if Fog.mocking? @segments.each_value do |segment| Fog::Storage[:rackspace].put_object(segment[:container], segment[:name], segment[:data]) end end tests('dynamic large object requests') do pending if Fog.mocking? 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 pending if Fog.mocking? 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 pending if Fog.mocking? 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 pending if Fog.mocking? 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 unless Fog.mocking? @directory.destroy @directory2.destroy end end fog-1.19.0/tests/rackspace/requests/storage/container_tests.rb0000644000004100000410000000427012261242552024557 0ustar www-datawww-dataShindo.tests('Fog::Storage[:rackspace] | container requests', ["rackspace"]) do @container_format = [String] @containers_format = [{ 'bytes' => Integer, 'count' => Integer, 'name' => String }] tests('success') do tests("#put_container('fogcontainertests', {})").succeeds do pending if Fog.mocking? Fog::Storage[:rackspace].put_container('fogcontainertests') end tests("#put_container('fogcontainertests', 'X-Container-Meta-Color'=>'green')").succeeds do pending if Fog.mocking? 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 pending if Fog.mocking? Fog::Storage[:rackspace].get_container('fogcontainertests').body end tests("#get_containers").formats(@containers_format) do pending if Fog.mocking? Fog::Storage[:rackspace].get_containers.body end tests("#head_container('fogcontainertests')").succeeds do pending if Fog.mocking? Fog::Storage[:rackspace].head_container('fogcontainertests') end tests("#head_containers").succeeds do pending if Fog.mocking? Fog::Storage[:rackspace].head_containers end tests("#delete_container('fogcontainertests')").succeeds do pending if Fog.mocking? Fog::Storage[:rackspace].delete_container('fogcontainertests') end end tests('failure') do tests("#get_container('fognoncontainer')").raises(Fog::Storage::Rackspace::NotFound) do pending if Fog.mocking? Fog::Storage[:rackspace].get_container('fognoncontainer') end tests("#head_container('fognoncontainer')").raises(Fog::Storage::Rackspace::NotFound) do pending if Fog.mocking? Fog::Storage[:rackspace].head_container('fognoncontainer') end tests("#delete_container('fognoncontainer')").raises(Fog::Storage::Rackspace::NotFound) do pending if Fog.mocking? Fog::Storage[:rackspace].delete_container('fognoncontainer') end end endfog-1.19.0/tests/rackspace/requests/storage/account_tests.rb0000644000004100000410000000051612261242552024230 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 pending if Fog.mocking? Fog::Storage[:rackspace].post_set_meta_temp_url_key('super_secret_key') end end tests('failure') do end end fog-1.19.0/tests/rackspace/requests/auto_scale/0000755000004100000410000000000012261242552021476 5ustar www-datawww-datafog-1.19.0/tests/rackspace/requests/auto_scale/config_tests.rb0000644000004100000410000000616312261242552024520 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) endfog-1.19.0/tests/rackspace/requests/auto_scale/helper.rb0000644000004100000410000001054312261242552023305 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 endfog-1.19.0/tests/rackspace/requests/auto_scale/webhook_tests.rb0000644000004100000410000000405112261242552024703 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 endfog-1.19.0/tests/rackspace/requests/auto_scale/policy_tests.rb0000644000004100000410000000420212261242552024542 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 endfog-1.19.0/tests/rackspace/requests/auto_scale/group_tests.rb0000644000004100000410000000306312261242552024403 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 endfog-1.19.0/tests/rackspace/requests/identity/0000755000004100000410000000000012261242552021210 5ustar www-datawww-datafog-1.19.0/tests/rackspace/requests/identity/tenants_tests.rb0000644000004100000410000000070512261242552024435 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-1.19.0/tests/rackspace/requests/identity/token_tests.rb0000644000004100000410000000347212261242552024105 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Identity | tokens', ['rackspace']) do pending if Fog.mock? 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 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.has_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-1.19.0/tests/rackspace/requests/identity/user_tests.rb0000644000004100000410000000526312261242552023743 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-1.19.0/tests/rackspace/requests/load_balancers/0000755000004100000410000000000012261242552022310 5ustar www-datawww-datafog-1.19.0/tests/rackspace/requests/load_balancers/algorithm_tests.rb0000644000004100000410000000060312261242552026044 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-1.19.0/tests/rackspace/requests/load_balancers/error_page_tests.rb0000644000004100000410000000163112261242552026205 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-1.19.0/tests/rackspace/requests/load_balancers/helper.rb0000644000004100000410000001754212261242552024125 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' => [SINGLE_NODE_FORMAT], '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-1.19.0/tests/rackspace/requests/load_balancers/protocol_tests.rb0000644000004100000410000000063112261242552025720 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-1.19.0/tests/rackspace/requests/load_balancers/connection_logging_tests.rb0000644000004100000410000000142212261242552027723 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-1.19.0/tests/rackspace/requests/load_balancers/ssl_termination_tests.rb0000644000004100000410000000231412261242552027271 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-1.19.0/tests/rackspace/requests/load_balancers/node_tests.rb0000644000004100000410000000637212261242552025014 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("#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-1.19.0/tests/rackspace/requests/load_balancers/get_stats_tests.rb0000644000004100000410000000056412261242552026061 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 endfog-1.19.0/tests/rackspace/requests/load_balancers/load_balancer_usage_tests.rb0000644000004100000410000000122212261242552030006 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-1.19.0/tests/rackspace/requests/load_balancers/content_caching_tests.rb0000644000004100000410000000137212261242552027210 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-1.19.0/tests/rackspace/requests/load_balancers/usage_tests.rb0000644000004100000410000000100312261242552025155 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-1.19.0/tests/rackspace/requests/load_balancers/virtual_ip_tests.rb0000644000004100000410000000240512261242552026236 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-1.19.0/tests/rackspace/requests/load_balancers/monitor_tests.rb0000644000004100000410000000302212261242552025543 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-1.19.0/tests/rackspace/requests/load_balancers/connection_throttling_tests.rb0000644000004100000410000000232112261242552030472 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-1.19.0/tests/rackspace/requests/load_balancers/access_list_tests.rb0000644000004100000410000000405412261242552026356 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-1.19.0/tests/rackspace/requests/load_balancers/load_balancer_tests.rb0000644000004100000410000000604512261242552026632 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_name = 'fog' + Time.now.to_i.to_s 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_id = 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_id = 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 tests("#delete_load_balancer(#{@ld_id})").succeeds do @service.delete_load_balancer(@lb_id).body 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-1.19.0/tests/rackspace/requests/load_balancers/session_persistence_tests.rb0000644000004100000410000000211012261242552030140 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-1.19.0/tests/rackspace/requests/dns/0000755000004100000410000000000012261242552020143 5ustar www-datawww-datafog-1.19.0/tests/rackspace/requests/dns/helper.rb0000644000004100000410000000562612261242552021760 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.collect { |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-1.19.0/tests/rackspace/requests/dns/dns_tests.rb0000644000004100000410000001257012261242552022503 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'].collect { |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-1.19.0/tests/rackspace/requests/dns/records_tests.rb0000644000004100000410000000712412261242552023357 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'].collect { |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-1.19.0/tests/rackspace/requests/compute_v2/0000755000004100000410000000000012261242552021442 5ustar www-datawww-datafog-1.19.0/tests/rackspace/requests/compute_v2/metadata_tests.rb0000644000004100000410000001130612261242552024772 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-1.19.0/tests/rackspace/requests/compute_v2/flavor_tests.rb0000644000004100000410000000214712261242552024506 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-1.19.0/tests/rackspace/requests/compute_v2/image_tests.rb0000644000004100000410000000432012261242552024272 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-1.19.0/tests/rackspace/requests/compute_v2/server_tests.rb0000644000004100000410000001042412261242552024520 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) 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('#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('#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 end end fog-1.19.0/tests/rackspace/requests/compute_v2/keypair_tests.rb0000644000004100000410000000262112261242552024656 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-1.19.0/tests/rackspace/requests/compute_v2/attachment_tests.rb0000644000004100000410000000452512261242552025347 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-1.19.0/tests/rackspace/requests/compute_v2/network_tests.rb0000644000004100000410000000227012261242552024703 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-1.19.0/tests/rackspace/requests/compute_v2/address_tests.rb0000644000004100000410000000274012261242552024641 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-1.19.0/tests/rackspace/requests/cdn/0000755000004100000410000000000012261242552020123 5ustar www-datawww-datafog-1.19.0/tests/rackspace/requests/cdn/cdn_tests.rb0000644000004100000410000000441612261242552022443 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-1.19.0/tests/rackspace/requests/compute/0000755000004100000410000000000012261242552021033 5ustar www-datawww-datafog-1.19.0/tests/rackspace/requests/compute/resize_tests.rb0000644000004100000410000000226412261242552024107 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-1.19.0/tests/rackspace/requests/compute/helper.rb0000644000004100000410000000023412261242552022636 0ustar www-datawww-dataclass Rackspace module Compute module Formats SUMMARY = { 'id' => Integer, 'name' => String } end end end fog-1.19.0/tests/rackspace/requests/compute/flavor_tests.rb0000644000004100000410000000171512261242552024077 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-1.19.0/tests/rackspace/requests/compute/image_tests.rb0000644000004100000410000000365412261242552023674 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-1.19.0/tests/rackspace/requests/compute/server_tests.rb0000644000004100000410000000534112261242552024113 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-1.19.0/tests/rackspace/requests/compute/address_tests.rb0000644000004100000410000000227212261242552024232 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-1.19.0/tests/rackspace/requests/queues/0000755000004100000410000000000012261242552020666 5ustar www-datawww-datafog-1.19.0/tests/rackspace/requests/queues/queues_tests.rb0000644000004100000410000000214612261242552023747 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | queue_tests', ['rackspace']) do pending if Fog.mocking? 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-1.19.0/tests/rackspace/requests/queues/helper.rb0000644000004100000410000000126112261242552022472 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-1.19.0/tests/rackspace/requests/queues/claim_tests.rb0000644000004100000410000000364112261242552023526 0ustar www-datawww-data Shindo.tests('Fog::Rackspace::Queues | claim_tests', ['rackspace']) do pending if Fog.mocking? 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-1.19.0/tests/rackspace/requests/queues/messages_tests.rb0000644000004100000410000000402512261242552024245 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | messages_tests', ['rackspace']) do pending if Fog.mocking? 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-1.19.0/tests/rackspace/requests/block_storage/0000755000004100000410000000000012261242552022175 5ustar www-datawww-datafog-1.19.0/tests/rackspace/requests/block_storage/volume_type_tests.rb0000644000004100000410000000112412261242552026312 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-1.19.0/tests/rackspace/requests/block_storage/snapshot_tests.rb0000644000004100000410000000373312261242552025611 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-1.19.0/tests/rackspace/requests/block_storage/volume_tests.rb0000644000004100000410000000260212261242552025253 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, 'attachments' => Array, 'metadata' => Hash } get_volume_format = { 'volume' => volume_format } list_volume_format = { 'volumes' => [volume_format] } service = Fog::Rackspace::BlockStorage.new tests('success') do id = nil size = 100 tests("#create_volume(#{size})").formats(get_volume_format) do data = service.create_volume(size).body id = data['volume']['id'] data end tests("#list_volumes").formats(list_volume_format) do service.list_volumes.body end tests("#get_volume(#{id})").formats(get_volume_format) do service.get_volume(id).body end tests("#delete_volume(#{id})").succeeds do service.delete_volume(id) 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-1.19.0/tests/rackspace/requests/monitoring/0000755000004100000410000000000012261242552021544 5ustar www-datawww-datafog-1.19.0/tests/rackspace/requests/monitoring/alarm_example_tests.rb0000644000004100000410000000225612261242552026127 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-1.19.0/tests/rackspace/requests/monitoring/helper.rb0000644000004100000410000000607412261242552023357 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-1.19.0/tests/rackspace/requests/monitoring/entity_tests.rb0000644000004100000410000000254212261242552024632 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-1.19.0/tests/rackspace/requests/monitoring/check_tests.rb0000644000004100000410000000274312261242552024376 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-1.19.0/tests/rackspace/requests/monitoring/alarm_tests.rb0000644000004100000410000000424512261242552024414 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-1.19.0/tests/rackspace/requests/monitoring/notification_tests.rb0000644000004100000410000000333212261242552026002 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-1.19.0/tests/rackspace/requests/monitoring/list_tests.rb0000644000004100000410000000612712261242552024274 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-1.19.0/tests/rackspace/requests/monitoring/agent_tests.rb0000644000004100000410000000225112261242552024411 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" } 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('#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 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 end end fog-1.19.0/tests/rackspace/cdn_tests.rb0000644000004100000410000002066212261242552020025 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").has_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(nil, "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-1.19.0/tests/rackspace/monitoring_tests.rb0000644000004100000410000000716512261242552021451 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").has_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 endfog-1.19.0/tests/rackspace/block_storage_tests.rb0000644000004100000410000001400212261242552022066 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").has_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 endfog-1.19.0/tests/rackspace/compute_tests.rb0000644000004100000410000001147312261242552020735 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").has_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-1.19.0/tests/rackspace/rackspace_tests.rb0000644000004100000410000000417512261242552021216 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 endfog-1.19.0/tests/rackspace/models/0000755000004100000410000000000012261242552016767 5ustar www-datawww-datafog-1.19.0/tests/rackspace/models/databases/0000755000004100000410000000000012261242552020716 5ustar www-datawww-datafog-1.19.0/tests/rackspace/models/databases/flavors_tests.rb0000644000004100000410000000061312261242552024141 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-1.19.0/tests/rackspace/models/databases/instances_tests.rb0000644000004100000410000000054312261242552024456 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-1.19.0/tests/rackspace/models/databases/databases_tests.rb0000644000004100000410000000065112261242552024416 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-1.19.0/tests/rackspace/models/databases/users_tests.rb0000644000004100000410000000073212261242552023630 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-1.19.0/tests/rackspace/models/databases/database_tests.rb0000644000004100000410000000064312261242552024234 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) instance.destroy end fog-1.19.0/tests/rackspace/models/databases/instance_tests.rb0000644000004100000410000000224312261242552024272 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-1.19.0/tests/rackspace/models/databases/user_tests.rb0000644000004100000410000000072412261242552023446 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-1.19.0/tests/rackspace/models/storage/0000755000004100000410000000000012261242552020433 5ustar www-datawww-datafog-1.19.0/tests/rackspace/models/storage/metadata_tests.rb0000644000004100000410000001415612261242552023771 0ustar www-datawww-datarequire 'fog/rackspace/models/storage/metadata' require 'fog/rackspace/models/storage/directory' 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('#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 endfog-1.19.0/tests/rackspace/models/storage/file_tests.rb0000644000004100000410000002470712261242552023133 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 pending if Fog.mocking? 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 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-1.19.0/tests/rackspace/models/storage/directory_tests.rb0000644000004100000410000001037212261242552024211 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Storage | directory', ['rackspace']) do pending if Fog.mocking? @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 pending if Fog.mocking? 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 endfog-1.19.0/tests/rackspace/models/storage/files_tests.rb0000644000004100000410000000226112261242552023305 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 pending if Fog.mocking? collection_tests(Fog::Storage[:rackspace].directories.create(directory_attributes).files, file_attributes, false) @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 pending if Fog.mocking? 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 pending if Fog.mocking? expire_time = Time.now + 3600 @directory.files.get_https_url(@file.key, expire_time) end @file.destroy @directory.destroy end endfog-1.19.0/tests/rackspace/models/storage/directories_tests.rb0000644000004100000410000000152612261242552024522 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Storage | directories', ['rackspace']) do pending if Fog.mocking? @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 endfog-1.19.0/tests/rackspace/models/storage/account_tests.rb0000644000004100000410000000154512261242552023643 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Storage | account', ['rackspace']) do pending if Fog.mocking? @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 endfog-1.19.0/tests/rackspace/models/auto_scale/0000755000004100000410000000000012261242552021106 5ustar www-datawww-datafog-1.19.0/tests/rackspace/models/auto_scale/webhook_tests.rb0000644000004100000410000000171212261242552024314 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 endfog-1.19.0/tests/rackspace/models/auto_scale/groups_tests.rb0000644000004100000410000000075312261242552024201 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 endfog-1.19.0/tests/rackspace/models/auto_scale/policy_tests.rb0000644000004100000410000000143712261242552024161 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 endfog-1.19.0/tests/rackspace/models/auto_scale/group_tests.rb0000644000004100000410000000143312261242552024012 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 endfog-1.19.0/tests/rackspace/models/auto_scale/policies_tests.rb0000644000004100000410000000116012261242552024462 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 endfog-1.19.0/tests/rackspace/models/auto_scale/webhooks_tests.rb0000644000004100000410000000140712261242552024500 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 endfog-1.19.0/tests/rackspace/models/auto_scale/group_builder_tests.rb0000644000004100000410000001172312261242552025523 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-1.19.0/tests/rackspace/models/identity/0000755000004100000410000000000012261242552020620 5ustar www-datawww-datafog-1.19.0/tests/rackspace/models/identity/service_catalog_tests.rb0000644000004100000410000002646612261242552025537 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.collect {|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 endfog-1.19.0/tests/rackspace/models/identity/tenants_tests.rb0000644000004100000410000000071712261242552024050 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-1.19.0/tests/rackspace/models/identity/credentials_tests.rb0000644000004100000410000000121512261242552024663 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-1.19.0/tests/rackspace/models/identity/users_tests.rb0000644000004100000410000000065412261242552023535 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-1.19.0/tests/rackspace/models/identity/roles_tests.rb0000644000004100000410000000051012261242552023507 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-1.19.0/tests/rackspace/models/identity/user_tests.rb0000644000004100000410000000061012261242552023342 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-1.19.0/tests/rackspace/models/load_balancers/0000755000004100000410000000000012261242552021720 5ustar www-datawww-datafog-1.19.0/tests/rackspace/models/load_balancers/access_lists_tests.rb0000644000004100000410000000050612261242552026147 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-1.19.0/tests/rackspace/models/load_balancers/node_tests.rb0000644000004100000410000000076012261242552024417 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-1.19.0/tests/rackspace/models/load_balancers/virtual_ips_tests.rb0000644000004100000410000000045612261242552026035 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-1.19.0/tests/rackspace/models/load_balancers/load_balancers_tests.rb0000644000004100000410000000101712261242552026417 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-1.19.0/tests/rackspace/models/load_balancers/nodes_tests.rb0000644000004100000410000000051412261242552024577 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-1.19.0/tests/rackspace/models/load_balancers/virtual_ip_tests.rb0000644000004100000410000000063212261242552025646 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-1.19.0/tests/rackspace/models/load_balancers/access_list_tests.rb0000644000004100000410000000050012261242552025756 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-1.19.0/tests/rackspace/models/load_balancers/load_balancer_tests.rb0000644000004100000410000001345612261242552026246 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | load_balancer', ['rackspace']) do pending if Fog.mocking? LOAD_BALANCER_ATTRIBUTES = { :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'}] } given_a_load_balancer_service do model_tests(@service.load_balancers, LOAD_BALANCER_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 algorithm...)') do attributes = LOAD_BALANCER_ATTRIBUTES.clone attributes[:algorithm] = 'LEAST_CONNECTIONS' attributes[:timeout] = 60 @lb = @service.load_balancers.create attributes returns('LEAST_CONNECTIONS') { @lb.algorithm } returns(60) { @lb.timeout } @lb.wait_for { ready? } @lb.destroy end tests('failure') do @lb = @service.load_balancers.new LOAD_BALANCER_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-1.19.0/tests/rackspace/models/dns/0000755000004100000410000000000012261242552017553 5ustar www-datawww-datafog-1.19.0/tests/rackspace/models/dns/zones_tests.rb0000644000004100000410000000273512261242552022467 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-1.19.0/tests/rackspace/models/dns/zone_tests.rb0000644000004100000410000000072112261242552022275 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-1.19.0/tests/rackspace/models/compute_v2/0000755000004100000410000000000012261242552021052 5ustar www-datawww-datafog-1.19.0/tests/rackspace/models/compute_v2/networks_tests.rb0000644000004100000410000000041612261242552024476 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-1.19.0/tests/rackspace/models/compute_v2/flavors_tests.rb0000644000004100000410000000062612261242552024301 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-1.19.0/tests/rackspace/models/compute_v2/metadata_tests.rb0000644000004100000410000000254412261242552024406 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 endfog-1.19.0/tests/rackspace/models/compute_v2/image_tests.rb0000644000004100000410000000461612261242552023712 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-1.19.0/tests/rackspace/models/compute_v2/server_tests.rb0000644000004100000410000001700612261242552024133 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.1/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('#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 perform_setup = lambda { |attributes| Fog::SSH::Mock.data.clear server = Fog::Compute::RackspaceV2::Server.new(attributes) address = 123 server.ipv4_address = address server.identity = "bar" server.public_key = "baz" server.setup Fog::SSH::Mock.data[address].first[:commands] } test("leaves user unlocked only when requested") do perform_setup.call(:service => service, :no_passwd_lock => true) .none? { |c| c =~ /passwd\s+-l\s+root/ } end test("locks user by default") do perform_setup.call(:service => service) .one? { |c| c =~ /passwd\s+-l\s+root/ } 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-1.19.0/tests/rackspace/models/compute_v2/servers_tests.rb0000644000004100000410000000103412261242552024310 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-1.19.0/tests/rackspace/models/compute_v2/keypairs_tests.rb0000644000004100000410000000231312261242552024447 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-1.19.0/tests/rackspace/models/compute_v2/network_tests.rb0000644000004100000410000000041012261242552024305 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-1.19.0/tests/rackspace/models/compute_v2/images_tests.rb0000644000004100000410000000067612261242552024077 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-1.19.0/tests/rackspace/models/queues/0000755000004100000410000000000012261242552020276 5ustar www-datawww-datafog-1.19.0/tests/rackspace/models/queues/queues_tests.rb0000644000004100000410000000040112261242552023347 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | queues', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Queues.new options = { :name => "fog_instance_#{Time.now.to_i.to_s}", } collection_tests(service.queues, options, false) end fog-1.19.0/tests/rackspace/models/queues/message_tests.rb0000644000004100000410000000304012261242552023466 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | message', ['rackspace']) do pending if Fog.mocking? 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, false) 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-1.19.0/tests/rackspace/models/queues/claim_tests.rb0000644000004100000410000000171512261242552023136 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | claim', ['rackspace']) do pending if Fog.mocking? 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, false) 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-1.19.0/tests/rackspace/models/queues/claims_tests.rb0000644000004100000410000000252112261242552023315 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | claims', ['rackspace']) do pending if Fog.mocking? 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, false) 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-1.19.0/tests/rackspace/models/queues/messages_tests.rb0000644000004100000410000000053712261242552023661 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | messages', ['rackspace']) do pending if Fog.mocking? 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, false) queue.destroy end fog-1.19.0/tests/rackspace/models/queues/queue_tests.rb0000644000004100000410000000131612261242552023172 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | queue', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Queues.new options = { :name => "fog_instance_#{Time.now.to_i.to_s}", } model_tests(service.queues, options, false) 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 end end fog-1.19.0/tests/rackspace/models/block_storage/0000755000004100000410000000000012261242552021605 5ustar www-datawww-datafog-1.19.0/tests/rackspace/models/block_storage/snapshots_tests.rb0000644000004100000410000000076712261242552025410 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-1.19.0/tests/rackspace/models/block_storage/volume_types_tests.rb0000644000004100000410000000064612261242552026115 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-1.19.0/tests/rackspace/models/block_storage/snapshot_tests.rb0000644000004100000410000000123612261242552025215 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-1.19.0/tests/rackspace/models/block_storage/volumes_tests.rb0000644000004100000410000000044512261242552025051 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-1.19.0/tests/rackspace/models/block_storage/volume_tests.rb0000644000004100000410000000150312261242552024662 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-1.19.0/tests/rackspace/models/monitoring/0000755000004100000410000000000012261242552021154 5ustar www-datawww-datafog-1.19.0/tests/rackspace/models/monitoring/alarm_example_tests.rb0000644000004100000410000000112212261242552025526 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-1.19.0/tests/rackspace/models/monitoring/checks_tests.rb0000644000004100000410000000077712261242552024176 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-1.19.0/tests/rackspace/models/monitoring/entity_tests.rb0000644000004100000410000000133612261242552024242 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-1.19.0/tests/rackspace/models/monitoring/check_tests.rb0000644000004100000410000000323312261242552024001 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-1.19.0/tests/rackspace/models/monitoring/agent_tokens_tests.rb0000644000004100000410000000041512261242552025404 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-1.19.0/tests/rackspace/models/monitoring/alarm_tests.rb0000644000004100000410000000363212261242552024023 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( :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 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 ensure @entity.destroy if @entity end end fog-1.19.0/tests/rackspace/models/monitoring/alarms_tests.rb0000644000004100000410000000157012261242552024205 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-1.19.0/tests/rackspace/models/monitoring/notification_tests.rb0000644000004100000410000000117312261242552025413 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-1.19.0/tests/rackspace/models/monitoring/metrics_tests.rb0000644000004100000410000000106212261242552024370 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-1.19.0/tests/rackspace/models/monitoring/entities_tests.rb0000644000004100000410000000062012261242552024545 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-1.19.0/tests/rackspace/models/monitoring/agent_token_tests.rb0000644000004100000410000000040712261242552025222 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-1.19.0/tests/rackspace/models/monitoring/notifications_tests.rb0000644000004100000410000000054612261242552025601 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-1.19.0/tests/rackspace/models/monitoring/check_types_tests.rb0000644000004100000410000000050512261242552025224 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-1.19.0/tests/rackspace/models/monitoring/metric_tests.rb0000644000004100000410000000120612261242552024205 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-1.19.0/tests/rackspace/models/monitoring/data_points_tests.rb0000644000004100000410000000133312261242552025230 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-1.19.0/tests/rackspace/models/monitoring/alarm_examples_tests.rb0000644000004100000410000000105012261242552025711 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-1.19.0/tests/rackspace/load_balancer_tests.rb0000644000004100000410000001470412261242552022027 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").has_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-1.19.0/tests/rackspace/compute_v2_tests.rb0000644000004100000410000001367612261242552021353 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").has_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-1.19.0/tests/rackspace/storage_tests.rb0000644000004100000410000001452712261242552020730 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 pending if Fog.mocking? 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 pending if Fog.mocking? 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").has_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 pending if Fog.mocking? 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 pending if Fog.mocking? 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 pending if Fog.mocking? 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-1.19.0/tests/compute/0000755000004100000410000000000012261242552015224 5ustar www-datawww-datafog-1.19.0/tests/compute/helper.rb0000644000004100000410000001045012261242552017030 0ustar www-datawww-datadef compute_providers { :aws => { :server_attributes => {}, :mocked => true }, :bluebox => { :server_attributes => { :flavor_id => '94fd37a7-2606-47f7-84d5-9000deda52ae', # Block 1GB Virtual Server :image_id => 'a8f05200-7638-47d1-8282-2474ef57c4c3', # Scientific Linux 6 :location_id => '37c2bd9a-3e81-46c9-b6e2-db44a25cc675', # Seattle, WA :password => 'chunkybacon' }, :mocked => false }, :brightbox => { :server_attributes => { :image_id => Brightbox::Compute::TestSupport.image_id }, :mocked => false }, :ecloud => { :server_attributes => { :name => "VM4", :row => "Layout Row 1", :group => "Layout Group 1", :catalog_network_name => "bridged", :description => "blarg", :operating_system => { :name => "Red Hat Enterprise Linux 5 (64-bit)", :href => "/cloudapi/ecloud/operatingsystems/rhel5_64guest/computepools/963", }, :organization_uri => 'organizations/2' }.tap do |hash| [:template_href, :network_uri, :environment_name, :organization_uri].each do |k| key = "ecloud_#{k}".to_sym if Fog.credentials[key] hash[k]= Fog.credentials[key] end end end, :mocked => true, }, :cloudstack => { :provider_attributes => { :cloudstack_host => 'http://host.foo' }, :server_attributes => {}.tap do |hash| [:zone_id, :network_ids, :template_id, :service_offering_id].each do |k| key = "cloudstack_#{k}".to_sym if Fog.credentials[key] hash[k]= Fog.credentials[key] end end end, :volume_attributes => {:name => "somevolume"}.tap do |hash| [:zone_id, :disk_offering_id].each do |k| key = "cloudstack_#{k}".to_sym if Fog.credentials[key] hash[k]= Fog.credentials[key] end end end, :snapshot_attributes => {:volume_id => "89198f7c-0245-aa1d-136a-c5f479ef9db7"}.tap do |hash| [:volume_id, :domain_id, :policy_id].each do |k| key = "cloudstack_#{k}".to_sym if Fog.credentials[key] hash[k]= Fog.credentials[key] end end end, :security_group_attributes => {:name => "cloudstack.sg.#{Time.now.to_i}"}, :security_group_rule_attributes => { :cidr => '0.0.0.0/0', :start_port => 123, :end_port => 456, :protocol => 'tcp' }, :disk_offering_attributes => { :name => "new disk offering", :display_text => 'New Disk Offering' }, :mocked => true }, :glesys => { :server_attributes => { :rootpassword => "secret_password_#{Time.now.to_i}", :hostname => "fog.example#{Time.now.to_i}.com" }, :mocked => false }, :hp => { :server_attributes => { :flavor_id => 100, :image_id => 1242, :name => "fog_#{Time.now.to_i}" }, :mocked => true }, :ibm => { :server_attributes => {}, :mocked => true }, :joyent => { :mocked => false }, :hp => { :server_attributes => { :flavor_id => 100, :image_id => 1242, :name => "fog_#{Time.now.to_i}" }, :mocked => true }, :ninefold => { :mocked => false }, :openstack => { :mocked => true, :server_attributes => { :flavor_ref => 2, :image_ref => "0e09fbd6-43c5-448a-83e9-0d3d05f9747e", :name => "fog_#{Time.now.to_i}" } }, :rackspace => { :provider_attributes => { :version => :v2 }, :server_attributes => { :image_id => "23b564c9-c3e6-49f9-bc68-86c7a9ab5018", # Ubuntu 12.04 LTS (Precise Pangolin) :flavor_id => 2, :name => "fog_#{Time.now.to_i}" }, :mocked => true }, :voxel => { :server_attributes => { :name => "fog.#{Time.now.to_i}", :disk_size => 10, :processing_cores => 1, :image_id => 55, # image 55 = Ubuntu 10.04 (Lucid), 64-bit, base install :facility => "LDJ1" }, :mocked => false } } end fog-1.19.0/tests/compute/models/0000755000004100000410000000000012261242552016507 5ustar www-datawww-datafog-1.19.0/tests/compute/models/flavors_tests.rb0000644000004100000410000000064412261242552021736 0ustar www-datawww-datafor provider, config in compute_providers next if [:glesys, :voxel, :ibm, :ecloud].include?(provider) Shindo.tests("Fog::Compute[:#{provider}] | flavors", [provider.to_s]) do provider_attributes = config[:provider_attributes] || {} provider_attributes.merge!(:provider => provider) flavors_tests(Fog::Compute.new(provider_attributes), (config[:flavors_attributes] || {}), config[:mocked]) end end fog-1.19.0/tests/compute/models/server_tests.rb0000644000004100000410000000114112261242552021561 0ustar www-datawww-datafor provider, config in compute_providers next if [:ecloud].include?(provider) Shindo.tests("Fog::Compute[:#{provider}] | server", [provider.to_s]) do provider_attributes = config[:provider_attributes] || {} provider_attributes.merge!(:provider => provider) server_tests(Fog::Compute.new(provider_attributes), (config[:server_attributes] || {}), config[:mocked]) do if Fog.mocking? && !config[:mocked] pending else responds_to(:boostrap) responds_to(:public_ip_address) responds_to(:scp) responds_to(:ssh) end end end end fog-1.19.0/tests/compute/models/servers_tests.rb0000644000004100000410000000061412261242552021750 0ustar www-datawww-datafor provider, config in compute_providers next if [:ecloud].include?(provider) Shindo.tests("Fog::Compute[:#{provider}] | servers", [provider.to_s]) do provider_attributes = config[:provider_attributes] || {} provider_attributes.merge!(:provider => provider) servers_tests(Fog::Compute.new(provider_attributes), (config[:server_attributes] || {}), config[:mocked]) end end fog-1.19.0/tests/riakcs/0000755000004100000410000000000012261242552015024 5ustar www-datawww-datafog-1.19.0/tests/riakcs/requests/0000755000004100000410000000000012261242552016677 5ustar www-datawww-datafog-1.19.0/tests/riakcs/requests/provisioning/0000755000004100000410000000000012261242552021425 5ustar www-datawww-datafog-1.19.0/tests/riakcs/requests/provisioning/provisioning_tests.rb0000644000004100000410000001203612261242552025724 0ustar www-datawww-dataShindo.tests('RiakCS::Provisioning | provisioning requests', ['riakcs']) do current_timestamp = Time.now.to_i user_format = { 'email' => String, 'display_name' => String, 'name' => String, 'key_id' => String, 'key_secret' => String, 'id' => String, 'status' => String, } tests('User creation') do tests('is successful').returns(String) do # Create a user. # email, name = "successful_user_creation_test_#{current_timestamp}@example.com", "Fog User" key_id = Fog::RiakCS[:provisioning].create_user(email, name).body['key_id'] key_id.class end tests('is successful anonymously').returns(String) do # Create a user. # email, name = "successful_anonymous_user_creation_test_#{current_timestamp}@example.com", "Fog User" key_id = Fog::RiakCS[:provisioning].create_user(email, name, :anonymous => true).body['key_id'] key_id.class end tests('fails if duplicate').raises(Fog::RiakCS::Provisioning::UserAlreadyExists) do 2.times do email, name = "failed_duplicate_user_creation_test_#{current_timestamp}@example.com", "Fog User" key_id = Fog::RiakCS[:provisioning].create_user(email, name).body['key_id'] end end tests('fails if invalid email').raises(Fog::RiakCS::Provisioning::ServiceUnavailable) do email, name = "failed_duplicate_user_creation_test_#{current_timestamp}", "Fog User" key_id = Fog::RiakCS[:provisioning].create_user(email, name).body['key_id'] end end tests('User disable') do tests('is successful').returns(200) do # Create a user. # email, name = "successful_user_disable_test_#{current_timestamp}@example.com", "Fog User" key_id = Fog::RiakCS[:provisioning].create_user(email, name).body['key_id'] Fog::RiakCS[:provisioning].disable_user(key_id).status end end tests('User enable') do tests('is successful').returns(200) do # Create a user. # email, name = "successful_user_disable_enable_test_#{current_timestamp}@example.com", "Fog User" key_id = Fog::RiakCS[:provisioning].create_user(email, name).body['key_id'] Fog::RiakCS[:provisioning].disable_user(key_id).status Fog::RiakCS[:provisioning].enable_user(key_id).status end end tests('User granted new key secret') do tests('is successful').returns(true) do # Create a user. # email, name = "successful_user_regrant_test_#{current_timestamp}@example.com", "Fog User" user = Fog::RiakCS[:provisioning].create_user(email, name).body key_id, key_secret = user['key_id'], user['key_secret'] Fog::RiakCS[:provisioning].regrant_secret(key_id).status # Verify new secret. # new_key_secret = Fog::RiakCS[:provisioning].get_user(key_id).body['key_secret'] new_key_secret != key_secret end end tests('User retrieval') do tests('is successful').formats(user_format) do # Create a user. # email, name = "user_retrieval_test_#{current_timestamp}@example.com", "Fog User" key_id = Fog::RiakCS[:provisioning].create_user(email, name).body['key_id'] # Get user details. # Fog::RiakCS[:provisioning].get_user(key_id).body end end tests('User listing') do tests('sucessfully lists users').formats(user_format) do # Create a user. # email, name = "user_listing_test_#{current_timestamp}@example.com", "Fog User" key_id = Fog::RiakCS[:provisioning].create_user(email, name).body['key_id'] # Ensure the list users response contains the user that we just # created. # Fog::RiakCS[:provisioning].list_users.body.select { |x| x['email'] == email }.first end tests('successfully lists users containing no disabled users').returns(nil) do # Create a user. # email, name = "user_listing_without_disabled_users_test_#{current_timestamp}@example.com", "Fog User" key_id = Fog::RiakCS[:provisioning].create_user(email, name).body['key_id'] # Disable that user. # Fog::RiakCS[:provisioning].disable_user(key_id) # Ensure the list users response does not contain the user that we # just created and disabled. # Fog::RiakCS[:provisioning].list_users(:status => :enabled).body.select { |x| x['Email'] == email }.first end tests('successfully lists users containing disabled users').formats(user_format) do # Create a user. # email, name = "user_listing_with_disabled_users_test_#{current_timestamp}@example.com", "Fog User" key_id = Fog::RiakCS[:provisioning].create_user(email, name).body['key_id'] # Disable that user. # Fog::RiakCS[:provisioning].disable_user(key_id) # Ensure the list users response contains the user that we just # created and disabled. # Fog::RiakCS[:provisioning].list_users.body.select { |x| x['email'] == email }.first end end end fog-1.19.0/tests/riakcs/requests/usage/0000755000004100000410000000000012261242552020003 5ustar www-datawww-datafog-1.19.0/tests/riakcs/requests/usage/usage_tests.rb0000644000004100000410000000132612261242552022660 0ustar www-datawww-dataShindo.tests('RiakCS::Usage | usage requests', ['riakcs']) do @blank_usage_format = { 'Access' => { 'Nodes' => [], 'Errors' => [] }, 'Storage' => { 'Samples' => [], 'Errors' => [] } } tests('Statistics retrieval with no data returned') do start_time = Time.now.utc + 86400 end_time = start_time + 86400 tests('via JSON').returns(@blank_usage_format) do Fog::RiakCS[:usage].get_usage(Fog.credentials[:riakcs_access_key_id], :types => [:access, :storage], :start_time => start_time, :end_time => end_time).body end end end fog-1.19.0/tests/serverlove/0000755000004100000410000000000012261242552015744 5ustar www-datawww-datafog-1.19.0/tests/serverlove/requests/0000755000004100000410000000000012261242552017617 5ustar www-datawww-datafog-1.19.0/tests/serverlove/requests/compute/0000755000004100000410000000000012261242552021273 5ustar www-datawww-datafog-1.19.0/tests/serverlove/requests/compute/image_tests.rb0000644000004100000410000000345512261242552024133 0ustar www-datawww-dataShindo.tests('Fog::Compute[:serverlove] | drive requests', ['serverlove']) do @image_format = { 'drive' => String, 'name' => String, 'user' => String, 'size' => Integer, 'claimed' => Fog::Nullable::String, 'status' => String, 'encryption:cipher' => String, 'read:bytes' => String, 'write:bytes' => String, 'read:requests' => String, 'write:requests' => String } tests('success') do attributes = { 'name' => 'Test', 'size' => '24234567890' } tests("#create_image").formats(@image_format) do @image = Fog::Compute[:serverlove].create_image(attributes).body end tests("#list_images").succeeds do Fog::Compute[:serverlove].images end tests("#update_image").returns(true) do @image['name'] = "Diff" Fog::Compute[:serverlove].update_image(@image['drive'], { :name => @image['name'], :size => @image['size']}) Fog::Compute[:serverlove].images.get(@image['drive']).name == "Diff" end tests("#load_standard_image").returns(true) do # Load centos Fog::Compute[:serverlove].load_standard_image(@image['drive'], '88ed067f-d2b8-42ce-a25f-5297818a3b6f') Fog::Compute[:serverlove].images.get(@image['drive']).imaging != "" # This will be "x%" when imaging end tests("waits for imaging...").returns(true) do while(percent_complete = Fog::Compute[:serverlove].images.get(@image['drive']).imaging) sleep(1) STDERR.print "#{percent_complete} " break if percent_complete.include?("100") end STDERR.print "100% " true end tests("#destroy_image").succeeds do Fog::Compute[:serverlove].destroy_image(@image['drive']) end end end fog-1.19.0/tests/serverlove/requests/compute/server_tests.rb0000644000004100000410000000611312261242552024351 0ustar www-datawww-dataShindo.tests('Fog::Compute[:serverlove] | server requests', ['serverlove']) do @server_format = { 'server' => String, 'name' => String, 'user' => String, 'status' => String, 'started' => Fog::Nullable::String, 'cpu' => Integer, 'mem' => Integer, 'smp' => Fog::Nullable::String, 'persistent' => Fog::Nullable::String, 'vnc' => Fog::Nullable::String, 'vnc:password' => Fog::Nullable::String, 'nic:0:dhcp' => String, 'nic:0:model' => String } tests('success') do attributes = { 'name' => 'Test', 'cpu' => '1000', 'mem' => '1000', 'persistent' => 'true' } tests("#create_server").formats(@server_format) do @server = Fog::Compute[:serverlove].create_server(Fog::Compute::Serverlove::Server.defaults.merge(attributes)).body end tests("#list_servers").succeeds do Fog::Compute[:serverlove].servers end tests("#update_server").returns(true) do @server['name'] = "Diff" Fog::Compute[:serverlove].update_server(@server['server'], { :name => @server['name']}) Fog::Compute[:serverlove].servers.get(@server['server']).name == "Diff" end tests("assigns drive to server").succeeds do @image = Fog::Compute[:serverlove].create_image('name' => 'Test', 'size' => '24234567890').body # Load debian Fog::Compute[:serverlove].load_standard_image(@image['drive'], 'aca2fa0b-40bc-4e06-ad99-f1467690d5de') Fog::Compute[:serverlove].update_server(@server['server'], { 'ide:0:0' => @image['drive'], 'boot' => 'ide:0:0'}) end tests("waits for imaging...").returns(true) do while(percent_complete = Fog::Compute[:serverlove].images.get(@image['drive']).imaging) sleep(1) STDERR.print "#{percent_complete} " break if percent_complete.include?("100") end STDERR.print "100% " true end tests("#start_server").returns(true) do Fog::Compute[:serverlove].start_server(@server['server']) Fog::Compute[:serverlove].servers.get(@server['server']).status == "active" end tests("#reset_server").returns(true) do Fog::Compute[:serverlove].reset_server(@server['server']) Fog::Compute[:serverlove].servers.get(@server['server']).status == "active" end tests("#shutdown_server").succeeds do Fog::Compute[:serverlove].shutdown_server(@server['server']) # Can't guarantee the OS will honour this command so don't test status end tests("#stop_server").returns(true) do Fog::Compute[:serverlove].start_server(@server['server']) Fog::Compute[:serverlove].stop_server(@server['server']) Fog::Compute[:serverlove].servers.get(@server['server']).status == "stopped" end tests("#destroy_server").succeeds do Fog::Compute[:serverlove].destroy_server(@server['server']) end tests("destroy test drive").succeeds do Fog::Compute[:serverlove].destroy_image(@image['drive']) end end end fog-1.19.0/tests/serverlove/util/0000755000004100000410000000000012261242552016721 5ustar www-datawww-datafog-1.19.0/tests/serverlove/util/compute/0000755000004100000410000000000012261242552020375 5ustar www-datawww-datafog-1.19.0/tests/serverlove/util/compute/password_generator_tests.rb0000644000004100000410000000102012261242552026045 0ustar www-datawww-datarequire 'fog/serverlove/util/compute/password_generator' Shindo.tests('Fog::Compute::Serverlove::PasswordGenerator | generate password', ['serverlove']) do @password = Fog::Compute::Serverlove::PasswordGenerator.generate tests("@password.length").returns(8) do @password.length end tests("@password contains one capital letter").returns(true) do @password.match(/[A-Z]/) && true end tests("@password contains one lower case letter").returns(true) do @password.match(/[a-z]/) && true end endfog-1.19.0/tests/helpers/0000755000004100000410000000000012261242552015212 5ustar www-datawww-datafog-1.19.0/tests/helpers/responds_to_helper.rb0000644000004100000410000000037612261242552021443 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-1.19.0/tests/helpers/formats_helper.rb0000644000004100000410000000705712261242552020562 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-1.19.0/tests/helpers/succeeds_helper.rb0000644000004100000410000000021012261242552020665 0ustar www-datawww-datamodule Shindo class Tests def succeeds test('succeeds') do !!instance_eval(&Proc.new) end end end end fog-1.19.0/tests/helpers/collection_helper.rb0000644000004100000410000000502112261242552021227 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 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-1.19.0/tests/helpers/compute/0000755000004100000410000000000012261242552016666 5ustar www-datawww-datafog-1.19.0/tests/helpers/compute/servers_helper.rb0000644000004100000410000000035612261242552022247 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? } end end end fog-1.19.0/tests/helpers/compute/server_helper.rb0000644000004100000410000000121612261242552022060 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]) 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-1.19.0/tests/helpers/compute/flavors_helper.rb0000644000004100000410000000146512261242552022234 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-1.19.0/tests/helpers/model_helper.rb0000644000004100000410000000140512261242552020176 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 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-1.19.0/tests/helpers/formats_helper_tests.rb0000644000004100000410000000702112261242552021773 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-1.19.0/tests/helpers/mock_helper.rb0000644000004100000410000001354612261242552020040 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 = { :aws_access_key_id => 'aws_access_key_id', :aws_secret_access_key => 'aws_secret_access_key', :ia_access_key_id => 'aws_access_key_id', :ia_secret_access_key => 'aws_secret_access_key', :atmos_storage_token => 'atmos_token', :atmos_storage_secret => 'atmos_secret', :atmos_storage_endpoint => 'http://atmos.is.cool:1000/test1.0', :bluebox_api_key => 'bluebox_api_key', :bluebox_customer_id => 'bluebox_customer_id', :brightbox_client_id => 'brightbox_client_id', :brightbox_secret => 'brightbox_secret', :cloudstack_disk_offering_id => '', :cloudstack_host => 'http://cloudstack.example.org', :cloudstack_network_ids => '', :cloudstack_service_offering_id => '4437ac6c-9fe3-477a-57ec-60a5a45896a4', :cloudstack_template_id => '8a31cf9c-f248-0588-256e-9dbf58785216', :cloudstack_zone_id => 'c554c592-e09c-9df5-7688-4a32754a4305', :clodo_api_key => 'clodo_api_key', :clodo_username => 'clodo_username', :digitalocean_api_key => 'digitalocean_api_key', :digitalocean_client_id => 'digitalocean_client_id', :dnsimple_email => 'dnsimple_email', :dnsimple_password => 'dnsimple_password', :dnsmadeeasy_api_key => 'dnsmadeeasy_api_key', :dnsmadeeasy_secret_key => 'dnsmadeeasy_secret_key', :ecloud_username => 'ecloud_username', :ecloud_password => 'ecloud_password', :ecloud_versions_uri => 'http://ecloud.versions.uri', :glesys_username => 'glesys_username', :glesys_api_key => 'glesys_api_key', :go_grid_api_key => 'go_grid_api_key', :go_grid_shared_secret => 'go_grid_shared_secret', :google_storage_access_key_id => 'google_storage_access_key_id', :google_storage_secret_access_key => 'google_storage_secret_access_key', :google_project => 'google_project_name', :google_client_email => 'fake@developer.gserviceaccount.com', :google_key_location => '~/fake.p12', :hp_access_key => 'hp_access_key', :hp_secret_key => 'hp_secret_key', :hp_tenant_id => 'hp_tenant_id', :hp_avl_zone => 'hp_avl_zone', :os_account_meta_temp_url_key => 'os_account_meta_temp_url_key', :ibm_username => 'ibm_username', :ibm_password => 'ibm_password', :joyent_username => "joyentuser", :joyent_password => "joyentpass", :linode_api_key => 'linode_api_key', :local_root => '~/.fog', :bare_metal_cloud_password => 'bare_metal_cloud_password', :bare_metal_cloud_username => 'bare_metal_cloud_username', :ninefold_compute_key => 'ninefold_compute_key', :ninefold_compute_secret => 'ninefold_compute_secret', :ninefold_storage_secret => 'ninefold_storage_secret', :ninefold_storage_token => 'ninefold_storage_token', # :public_key_path => '~/.ssh/id_rsa.pub', # :private_key_path => '~/.ssh/id_rsa', :openstack_api_key => 'openstack_api_key', :openstack_username => 'openstack_username', :openstack_tenant => 'openstack_tenant', :openstack_auth_url => 'http://openstack:35357/v2.0/tokens', :ovirt_url => 'http://ovirt:8080/api', :ovirt_username => 'admin@internal', :ovirt_password => '123123', :libvirt_uri => 'qemu://libvirt/system', :rackspace_api_key => 'rackspace_api_key', :rackspace_username => 'rackspace_username', :riakcs_access_key_id => 'riakcs_access_key_id', :riakcs_secret_access_key => 'riakcs_secret_access_key', :storm_on_demand_username => 'storm_on_demand_username', :storm_on_demand_password => 'storm_on_demand_password', :vcloud_host => 'vcloud_host', :vcloud_password => 'vcloud_password', :vcloud_username => 'vcloud_username', :vcloud_director_host => 'vcloud-director-host', :vcloud_director_password => 'vcloud_director_password', :vcloud_director_username => 'vcd_user@vcd_org_name', :voxel_api_key => 'voxel_api_key', :voxel_api_secret => 'voxel_api_secret', :zerigo_email => 'zerigo_email', :zerigo_token => 'zerigo_token', :dynect_customer => 'dynect_customer', :dynect_username => 'dynect_username', :dynect_password => 'dynect_password', :vsphere_server => 'virtualcenter.lan', :vsphere_username => 'apiuser', :vsphere_password => 'apipassword', :vsphere_expected_pubkey_hash => 'abcdef1234567890', :libvirt_uri => 'qemu:///system', :libvirt_username => 'root', :libvirt_password => 'password', :cloudsigma_username => 'csuname', :cloudsigma_password => 'cspass' }.merge(Fog.credentials) end fog-1.19.0/tests/helpers/schema_validator_tests.rb0000644000004100000410000000723112261242552022271 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-1.19.0/tests/bluebox/0000755000004100000410000000000012261242552015210 5ustar www-datawww-datafog-1.19.0/tests/bluebox/requests/0000755000004100000410000000000012261242552017063 5ustar www-datawww-datafog-1.19.0/tests/bluebox/requests/dns/0000755000004100000410000000000012261242552017647 5ustar www-datawww-datafog-1.19.0/tests/bluebox/requests/dns/dns_tests.rb0000644000004100000410000001463212261242552022210 0ustar www-datawww-dataShindo.tests('Fog::DNS[:bluebox] | DNS requests', ['bluebox', 'dns']) do @domain = '' @new_zones = [] @new_records =[] tests( 'success') do test('get current zone count') do pending if Fog.mocking? @org_zone_count= 0 response = Fog::DNS[:bluebox].get_zones() if response.status == 200 zones = response.body['zones'] @org_zone_count = zones.count end response.status == 200 end test('create zone - simple') do pending if Fog.mocking? domain = generate_unique_domain response = Fog::DNS[:bluebox].create_zone(:name => domain, :ttl => 360) if response.status == 202 zone_id = response.body['id'] @new_zones << zone_id end response.status == 202 end test('create zone - set all parameters') do pending if Fog.mocking? options = { :ttl => 60, :retry => 3600, :refresh => 1800, :minimum => 30 } @domain= generate_unique_domain response = Fog::DNS[:bluebox].create_zone(options.merge(:name => @domain)) if response.status == 202 @zone_id = response.body['id'] @new_zones << @zone_id end response.status == 202 end test("get zone #{@zone_id} - check all parameters for #{@domain}") do pending if Fog.mocking? result = false response = Fog::DNS[:bluebox].get_zone(@zone_id) if response.status == 200 zone = response.body if (zone['name'] == @domain) and (zone['ttl'] == 60) result = true end end result end test('get zones - make sure total count is correct') do pending if Fog.mocking? result = false response = Fog::DNS[:bluebox].get_zones() if response.status == 200 zones = response.body['zones'] if (@org_zone_count+2) == zones.count result= true; end end result end test('get zones - check all parameters for a zone') do pending if Fog.mocking? result= false response = Fog::DNS[:bluebox].get_zones() if response.status == 200 zones = response.body['zones'] zones.each { |zone| if zone['id'] == @new_zones[1] options = { :ttl => 60, :retry => 3600, :refresh => 1800, :minimum => 30 } if (zone['name'] == @domain) and (zone['ttl'] == 60) and (zone['retry'] == 3600) and (zone['refresh'] == 1800) and (zone['minimum'] == 30) result = true; end end } if (@org_zone_count+2) == zones.count result = true; end end result end test('create record - simple A record') do pending if Fog.mocking? host= 'www.' + @domain zone_id= @new_zones[1] response = Fog::DNS[:bluebox].create_record(zone_id, 'A', host, '1.2.3.4') if response.status == 202 record_id = response.body['id'] @new_records << record_id end response.status == 202 end test('create record - A record - all parameters set') do pending if Fog.mocking? host= 'ftp.' + @domain zone_id= @new_zones[1] response = Fog::DNS[:bluebox].create_record( zone_id, 'A', host, '1.2.3.4') if response.status == 202 record_id = response.body['id'] @new_records << record_id end response.status == 202 end test('create record - CNAME record') do pending if Fog.mocking? zone_id= @new_zones[1] response = Fog::DNS[:bluebox].create_record( zone_id, 'CNAME', 'mail', @domain) if response.status == 202 record_id = response.body['id'] @new_records << record_id end response.status == 202 end test('create record - NS record') do pending if Fog.mocking? ns_domain = 'ns.' + @domain zone_id= @new_zones[1] response = Fog::DNS[:bluebox].create_record( zone_id, 'NS', @domain, ns_domain) if response.status == 202 record_id = response.body['id'] @new_records << record_id end response.status == 202 end test('create record - MX record') do pending if Fog.mocking? mail_domain = 'mail.' + @domain zone_id= @new_zones[1] response = Fog::DNS[:bluebox].create_record( zone_id, 'MX', @domain, mail_domain, :priority => 10) if response.status == 202 @record_id = response.body['id'] @new_records << @record_id end response.status == 202 end test("get record #{@record_id} - verify all parameters") do pending if Fog.mocking? result= false response = Fog::DNS[:bluebox].get_record(@new_zones[1], @record_id) if response.status == 200 mail_domain = 'mail.' + @domain + "." record = response.body if (record['type'] == 'MX') and (record['name'] == @domain) and (record['content'] == mail_domain) and (record['priority'] == '10') result= true end end result end test('get records - verify all parameters for one record') do pending if Fog.mocking? result= false response = Fog::DNS[:bluebox].get_records(@new_zones[1]) if response.status == 200 records = response.body['records'] #find mx record records.each {|record| if record['type'] == 'MX' mail_domain = 'mail.' + @domain + "." if (record['type'] == 'MX') and (record['name'] == @domain) and (record['content'] == mail_domain) and (record['priority'] == '10') result= true break end end } end result end test("delete #{@new_records.count} records created") do pending if Fog.mocking? result= true @new_records.each { |record_id| response = Fog::DNS[:bluebox].delete_record(@new_zones[1], record_id) if response.status != 200 result= false; end } result end test("delete #{@new_zones.count} zones created") do pending if Fog.mocking? result= true @new_zones.each { |zone_id| response = Fog::DNS[:bluebox].delete_zone( zone_id) if response.status != 200 result= false; end } result end end tests( 'failure') do #create a zone with invalid parameters #get zonfo info with invalid zone id #delete a zone with an invalid zone id tests('#create_zone') do end end end fog-1.19.0/tests/bluebox/requests/compute/0000755000004100000410000000000012261242552020537 5ustar www-datawww-datafog-1.19.0/tests/bluebox/requests/compute/helper.rb0000644000004100000410000000045212261242552022344 0ustar www-datawww-dataclass Bluebox module Compute module Formats PRODUCT = { 'cost' => String, 'description' => String, 'id' => String }, LOCATION = { 'id' => String, 'description' => String } end end end fog-1.19.0/tests/bluebox/requests/compute/template_tests.rb0000644000004100000410000000172312261242552024124 0ustar www-datawww-dataShindo.tests('Fog::Compute[:bluebox] | template requests', ['bluebox']) do @template_format = { 'created' => String, 'description' => String, 'id' => String, 'public' => Fog::Boolean, 'locations' => [ String ], 'status' => String } tests('success') do @template_id = compute_providers[:bluebox][:server_attributes][:image_id] tests("get_template('#{@template_id}')").formats(@template_format) do pending if Fog.mocking? Fog::Compute[:bluebox].get_template(@template_id).body end tests("get_templates").formats([@template_format]) do pending if Fog.mocking? Fog::Compute[:bluebox].get_templates.body end end tests('failure') do tests("get_template('00000000-0000-0000-0000-000000000000')").raises(Fog::Compute::Bluebox::NotFound) do pending if Fog.mocking? Fog::Compute[:bluebox].get_template('00000000-0000-0000-0000-000000000000') end end end fog-1.19.0/tests/bluebox/requests/compute/product_tests.rb0000644000004100000410000000152312261242552023767 0ustar www-datawww-dataShindo.tests('Fog::Compute[:bluebox] | product requests', ['bluebox']) do @product_format = { 'id' => String, 'description' => String, 'cost' => String } tests('success') do @flavor_id = compute_providers[:bluebox][:server_attributes][:flavor_id] tests("get_product('#{@flavor_id}')").formats(@product_format) do pending if Fog.mocking? Fog::Compute[:bluebox].get_product(@flavor_id).body end tests("get_products").formats([@product_format]) do pending if Fog.mocking? Fog::Compute[:bluebox].get_products.body end end tests('failure') do tests("get_product('00000000-0000-0000-0000-000000000000')").raises(Fog::Compute::Bluebox::NotFound) do pending if Fog.mocking? Fog::Compute[:bluebox].get_product('00000000-0000-0000-0000-000000000000') end end end fog-1.19.0/tests/bluebox/requests/compute/block_tests.rb0000644000004100000410000000557712261242552023416 0ustar www-datawww-dataShindo.tests('Fog::Compute[:bluebox] | block requests', ['bluebox']) do @block_format = { 'cpu' => Float, 'description' => String, 'hostname' => String, 'id' => String, 'ips' => [{'address' => String}], 'lb_applications' => [], 'memory' => Integer, 'product' => {'cost' => String, 'description' => String, 'id' => String}, 'status' => String, 'storage' => Integer, 'location_id' => String } tests('success') do @flavor_id = compute_providers[:bluebox][:server_attributes][:flavor_id] @image_id = compute_providers[:bluebox][:server_attributes][:image_id] @location_id = compute_providers[:bluebox][:server_attributes][:location_id] @password = compute_providers[:bluebox][:server_attributes][:password] @block_id = nil tests("create_block('#{@flavor_id}', '#{@image_id}', '#{@location_id}', {'password' => '#{@password}'})").formats(@block_format.merge('add_to_lb_application_results' => {'text' => String})) do pending if Fog.mocking? data = Fog::Compute[:bluebox].create_block(@flavor_id, @image_id, @location_id, {'password' => @password}).body @block_id = data['id'] data end unless Fog.mocking? Fog::Compute[:bluebox].servers.get(@block_id).wait_for { ready? } end tests("get_block('#{@block_id}')").formats(@block_format) do pending if Fog.mocking? Fog::Compute[:bluebox].get_block(@block_id).body end tests("get_blocks").formats([@block_format.reject {|key,value| ['product', 'template'].include?(key)}]) do pending if Fog.mocking? Fog::Compute[:bluebox].get_blocks.body end tests("reboot_block('#{@block_id}')").formats([{'status' => String}, {'text' => String}]) do pending if Fog.mocking? Fog::Compute[:bluebox].reboot_block(@block_id).body end unless Fog.mocking? Fog::Compute[:bluebox].servers.get(@block_id).wait_for { ready? } end tests("destroy_block('#{@block_id})'").formats({'text' => String}) do pending if Fog.mocking? Fog::Compute[:bluebox].destroy_block(@block_id).body end end tests('failure') do tests("get_block('00000000-0000-0000-0000-000000000000')").raises(Fog::Compute::Bluebox::NotFound) do pending if Fog.mocking? Fog::Compute[:bluebox].get_block('00000000-0000-0000-0000-000000000000') end tests("reboot_block('00000000-0000-0000-0000-000000000000')").raises(Fog::Compute::Bluebox::NotFound) do pending if Fog.mocking? Fog::Compute[:bluebox].reboot_block('00000000-0000-0000-0000-000000000000') end tests("destroy_block('00000000-0000-0000-0000-000000000000')").raises(Fog::Compute::Bluebox::NotFound) do pending if Fog.mocking? Fog::Compute[:bluebox].destroy_block('00000000-0000-0000-0000-000000000000') end end end fog-1.19.0/tests/bluebox/requests/compute/location_tests.rb0000644000004100000410000000153312261242552024120 0ustar www-datawww-dataShindo.tests('Fog::Compute[:bluebox] | location requests', ['bluebox']) do @location_format = { 'id' => String, 'description' => String } tests('success') do @location_id = compute_providers[:bluebox][:server_attributes][:location_id] tests("get_location('#{@location_id}')").formats(@location_format) do pending if Fog.mocking? Fog::Compute[:bluebox].get_location(@location_id).body end tests("get_locations").formats([@location_format]) do pending if Fog.mocking? Fog::Compute[:bluebox].get_locations.body end end tests('failure') do tests("get_location('00000000-0000-0000-0000-000000000000')").raises(Fog::Compute::Bluebox::NotFound) do pending if Fog.mocking? Fog::Compute[:bluebox].get_location('00000000-0000-0000-0000-000000000000') end end endfog-1.19.0/tests/bluebox/requests/blb/0000755000004100000410000000000012261242552017622 5ustar www-datawww-datafog-1.19.0/tests/bluebox/requests/blb/helper.rb0000644000004100000410000000306212261242552021427 0ustar www-datawww-dataclass Bluebox module BLB module Formats LB_APPLICATION = { 'id' => String, 'ip_v4' => String, 'ip_v6' => String, 'name' => String, 'lb_services' => Array, 'source_ip_v4' => Fog::Nullable::String, } LB_APPLICATIONS = [LB_APPLICATION] LB_SERVICE = { 'name' => String, 'port' => Integer, 'private' => Fog::Boolean, 'status_username' => String, 'status_password' => String, 'status_url' => String, 'service_type' => String, 'created' => String, 'lb_backends' => Array, 'pem_file_uploaded?' => Fog::Nullable::Boolean, } LB_SERVICES = [LB_SERVICE] LB_BACKEND = { 'id' => String, 'backend_name' => String, 'lb_machines' => Array, 'acl_name' => String, 'acl_name' => String, 'monitoring_url_hostname' => String, 'monitoring_url' => String, 'monitoring_url_hostname' => String, 'check_interval' => Integer, 'rise' => Fog::Nullable::Integer, 'order' => Fog::Nullable::Integer, 'fall' => Fog::Nullable::Integer, } LB_BACKENDS = [LB_BACKEND] LB_MACHINE = { 'port' => Integer, 'id' => String, 'ip' => String, 'maxconn' => Integer, 'hostname' => String, 'created' => String, } ADD_MACHINE_TO_LB = [ { 'text' => String }, { 'status' => String }, ] REMOVE_MACHINE_FROM_BACKEND = 'Record Removed.' end end end fog-1.19.0/tests/bluebox/requests/blb/lb_tests.rb0000644000004100000410000000672312261242552021776 0ustar www-datawww-datarequire 'securerandom' Shindo.tests('Bluebox::BLB | lb_tests', ['bluebox']) do pending if Fog.mocking? tests('success') do @flavor_id = compute_providers[:bluebox][:server_attributes][:flavor_id] @image_id = compute_providers[:bluebox][:server_attributes][:image_id] @location_id = compute_providers[:bluebox][:server_attributes][:location_id] @password = SecureRandom.base64(18) tests("get_lb_applications").formats(Bluebox::BLB::Formats::LB_APPLICATIONS) do @lb_applications = Fog::Bluebox[:blb].get_lb_applications.body end tests("get_lb_application").formats(Bluebox::BLB::Formats::LB_APPLICATION) do Fog::Bluebox[:blb].get_lb_application(@lb_applications.first['id']).body end tests("get_lb_services").formats(Bluebox::BLB::Formats::LB_SERVICES) do @lb_services = Fog::Bluebox[:blb].get_lb_services(@lb_applications.first['id']).body end tests("get_lb_service").formats(Bluebox::BLB::Formats::LB_SERVICE) do Fog::Bluebox[:blb].get_lb_service(@lb_applications.first['id'], @lb_services.first['id']).body end tests("get_lb_backends").formats(Bluebox::BLB::Formats::LB_BACKENDS) do @lb_backends = Fog::Bluebox[:blb].get_lb_backends(@lb_services.first['id']).body end tests("get_lb_backend").formats(Bluebox::BLB::Formats::LB_BACKEND) do Fog::Bluebox[:blb].get_lb_backend(@lb_services.first['id'], @lb_backends.first['id']).body end # create block data = Fog::Compute[:bluebox].create_block(@flavor_id, @image_id, @location_id, {'password' => @password}).body @block_id = data['id'] Fog::Compute[:bluebox].servers.get(@block_id).wait_for { ready? } tests("add_machine_to_lb_application").formats(Bluebox::BLB::Formats::ADD_MACHINE_TO_LB) do Fog::Bluebox[:blb].add_machine_to_lb_application(@lb_applications.first['id'], @block_id).body end @default_backend = @lb_backends.select { |x| x['backend_name'] == 'default' }.first @id_in_backend = @default_backend['lb_machines'].last['id'] @machine_opts = { 'port' => 4361, 'backup' => true }; tests("update_lb_backend_machine(#{@lb_backends.first['id']}, #{@id_in_backend}, #{@machine_opts})").formats(Bluebox::BLB::Formats::LB_MACHINE) do Fog::Bluebox[:blb].update_lb_backend_machine(@lb_backends.first['id'], @id_in_backend, @machine_opts).body end tests("remove_machine_from_lb_backend(#{@default_backend['id']}, #{@id_in_backend})").formats(Bluebox::BLB::Formats::REMOVE_MACHINE_FROM_BACKEND) do Fog::Bluebox[:blb].remove_machine_from_lb_backend(@default_backend['id'], @id_in_backend).body end tests("add_machine_to_lb_backend(#{@default_backend['id']}, #{@block_id})").formats(Bluebox::BLB::Formats::ADD_MACHINE_TO_LB) do Fog::Bluebox[:blb].add_machine_to_lb_backend(@default_backend['id'], @block_id).body end Fog::Compute[:bluebox].destroy_block(@block_id).body end tests('failure') do tests('get_lb_application').raises(Fog::Compute::Bluebox::NotFound) do Fog::Bluebox[:blb].get_lb_application('00000000-0000-0000-0000-000000000000') end tests('get_lb_service').raises(Fog::Compute::Bluebox::NotFound) do Fog::Bluebox[:blb].get_lb_service('00000000-0000-0000-0000-000000000000','00000000-0000-0000-0000-000000000000') end tests('get_lb_backend').raises(Fog::Compute::Bluebox::NotFound) do Fog::Bluebox[:blb].get_lb_backend('00000000-0000-0000-0000-000000000000','00000000-0000-0000-0000-000000000000') end end end fog-1.19.0/tests/local/0000755000004100000410000000000012261242552014642 5ustar www-datawww-datafog-1.19.0/tests/local/models/0000755000004100000410000000000012261242552016125 5ustar www-datawww-datafog-1.19.0/tests/local/models/file_tests.rb0000644000004100000410000000240312261242552020612 0ustar www-datawww-dataShindo.tests('Storage[:local] | file', ["local"]) do pending if Fog.mocking? before do @options = { :local_root => '~/.fog' } end tests('#public_url') do tests('when connection has an endpoint'). returns('http://example.com/files/directory/file.txt') do @options[:endpoint] = 'http://example.com/files' connection = Fog::Storage::Local.new(@options) directory = connection.directories.new(:key => 'directory') file = directory.files.new(:key => 'file.txt') file.public_url end tests('when connection has no endpoint'). returns(nil) do @options[:endpoint] = nil connection = Fog::Storage::Local.new(@options) directory = connection.directories.new(:key => 'directory') file = directory.files.new(:key => 'file.txt') file.public_url end tests('when file path has escapable characters'). returns('http://example.com/files/my%20directory/my%20file.txt') do @options[:endpoint] = 'http://example.com/files' connection = Fog::Storage::Local.new(@options) directory = connection.directories.new(:key => 'my directory') file = directory.files.new(:key => 'my file.txt') file.public_url end end end fog-1.19.0/tests/local/models/directory_tests.rb0000644000004100000410000000056512261242552021706 0ustar www-datawww-dataShindo.tests('Storage[:local] | directory', ["local"]) do pending if Fog.mocking? before do @options = { :local_root => '~/.fog' } end tests('save') do returns(true) do connection = Fog::Storage::Local.new(@options) connection.directories.create(:key => 'directory') connection.directories.create(:key => 'directory') end end end fog-1.19.0/tests/local/models/directories_tests.rb0000644000004100000410000000066212261242552022214 0ustar www-datawww-dataShindo.tests('Storage[:local] | directories', ["local"]) do pending if Fog.mocking? @options = { :local_root => "/tmp/fogtests" } @collection = Fog::Storage::Local.new(@options).directories collection_tests(@collection, {:key => "fogdirtests"}, true) tests("#all") do tests("succeeds when :local_root does not exist").succeeds do FileUtils.rm_rf(@options[:local_root]) @collection.all end end end fog-1.19.0/tests/local/storage_tests.rb0000644000004100000410000000172712261242552020064 0ustar www-datawww-dataShindo.tests('Local | storage') do pending if Fog.mocking? before do @options = { :local_root => "~/.fog" } end tests('#endpoint') do tests('when no endpoint is provided'). returns(nil) do Fog::Storage::Local.new(@options).endpoint end tests('when no host is provided'). returns(nil) do @options[:scheme] = 'http' @options[:path] = '/files' @options[:port] = 80 Fog::Storage::Local.new(@options).endpoint end tests('when endpoint is provided'). returns('http://example.com/files') do @options[:endpoint] = 'http://example.com/files' Fog::Storage::Local.new(@options).endpoint end tests('when at least host option is provided'). returns('http://example.com/files') do @options[:scheme] = 'http' @options[:host] = 'example.com' @options[:path] = '/files' Fog::Storage::Local.new(@options).endpoint end end end fog-1.19.0/tests/libvirt/0000755000004100000410000000000012261242552015223 5ustar www-datawww-datafog-1.19.0/tests/libvirt/requests/0000755000004100000410000000000012261242552017076 5ustar www-datawww-datafog-1.19.0/tests/libvirt/requests/compute/0000755000004100000410000000000012261242552020552 5ustar www-datawww-datafog-1.19.0/tests/libvirt/requests/compute/create_domain_tests.rb0000644000004100000410000000132512261242552025114 0ustar www-datawww-dataShindo.tests("Fog::Compute[:libvirt] | create_domain request", 'libvirt') do compute = Fog::Compute[:libvirt] xml = compute.servers.new( :nics => [{:bridge => "br180"}]).to_xml tests("Create Domain") do response = compute.create_domain(xml) test("should be a kind of Libvirt::Domain") { response.kind_of? Libvirt::Domain} end tests("Fail Creating Domain") do begin response = compute.create_domain(xml) test("should be a kind of Libvirt::Domain") { response.kind_of? Libvirt::Domain} #mock never raise exceptions rescue => e #should raise vm name already exist exception. test("error should be a kind of Libvirt::Error") { e.kind_of? Libvirt::Error} end end end fog-1.19.0/tests/libvirt/requests/compute/update_display.rb0000644000004100000410000000061312261242552024106 0ustar www-datawww-dataShindo.tests('Fog::Compute[:libvirt] | update_display request', ['libvirt']) do compute = Fog::Compute[:libvirt] reconfig_target = 'f74d728a-5b62-7e2f-1f84-239aead298ca' display_spec = {:password => 'ssaaa'} tests('The response should') do response = compute.update_display(:uuid => reconfig_target).merge(display_spec) test('should be true').succeeds { response } end end fog-1.19.0/tests/libvirt/requests/compute/define_domain_tests.rb0000644000004100000410000000047612261242552025111 0ustar www-datawww-dataShindo.tests("Fog::Compute[:libvirt] | define_domain request", 'libvirt') do compute = Fog::Compute[:libvirt] xml = compute.servers.new().to_xml tests("Define Domain") do response = compute.define_domain(xml) test("should be a kind of Libvirt::Domain") { response.kind_of? Libvirt::Domain} end end fog-1.19.0/tests/libvirt/compute_tests.rb0000644000004100000410000000126612261242552020453 0ustar www-datawww-dataShindo.tests('Fog::Compute[:libvirt]', ['libvirt']) do compute = Fog::Compute[:libvirt] tests("Compute collections") do %w{ servers interfaces networks nics nodes pools volumes}.each do |collection| test("it should respond to #{collection}") { compute.respond_to? collection } end end tests("Compute requests") do %w{ create_domain create_volume define_domain define_pool destroy_interface destroy_network get_node_info list_domains list_interfaces list_networks list_pools list_pool_volumes list_volumes pool_action vm_action volume_action }.each do |request| test("it should respond to #{request}") { compute.respond_to? request } end end end fog-1.19.0/tests/libvirt/models/0000755000004100000410000000000012261242552016506 5ustar www-datawww-datafog-1.19.0/tests/libvirt/models/compute/0000755000004100000410000000000012261242552020162 5ustar www-datawww-datafog-1.19.0/tests/libvirt/models/compute/networks_tests.rb0000644000004100000410000000075712261242552023616 0ustar www-datawww-dataShindo.tests('Fog::Compute[:libvirt] | networks collection', ['libvirt']) do networks = Fog::Compute[:libvirt].networks tests('The networks collection') do test('should be a kind of Fog::Compute::Libvirt::Networks') { networks.kind_of? Fog::Compute::Libvirt::Networks } tests('should be able to reload itself').succeeds { networks.reload } tests('should be able to get a model') do tests('by instance id').succeeds { networks.get networks.first.uuid } end end end fog-1.19.0/tests/libvirt/models/compute/server_tests.rb0000644000004100000410000000322512261242552023241 0ustar www-datawww-dataShindo.tests('Fog::Compute[:libvirt] | server model', ['libvirt']) do servers = Fog::Compute[:libvirt].servers server = servers.all.select{|v| v.name =~ /^fog/}.last tests('The server model should') do tests('have the action') do test('reload') { server.respond_to? 'reload' } %w{ start stop destroy reboot suspend }.each do |action| test(action) { server.respond_to? action } end %w{ start reboot suspend stop destroy}.each do |action| test("#{action} returns successfully") { begin server.send(action.to_sym) rescue Libvirt::Error #libvirt error is acceptable for the above actions. true end } end end tests('have attributes') do model_attribute_hash = server.attributes attributes = [ :id, :cpus, :cputime, :os_type, :memory_size, :max_memory_size, :name, :arch, :persistent, :domain_type, :uuid, :autostart, :display, :nics, :volumes, :active, :boot_order, :state] tests("The server model should respond to") do attributes.each do |attribute| test("#{attribute}") { server.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.delete(:volumes) attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::Libvirt::Server') { server.kind_of? Fog::Compute::Libvirt::Server } end end fog-1.19.0/tests/libvirt/models/compute/pool_tests.rb0000644000004100000410000000166412261242552022711 0ustar www-datawww-dataShindo.tests('Fog::Compute[:libvirt] | interface model', ['libvirt']) do pools = Fog::Compute[:libvirt].pools pool = pools.last tests('The interface model should') do tests('have the action') do test('reload') { pool.respond_to? 'reload' } end tests('have attributes') do model_attribute_hash = pool.attributes attributes = [ :uuid, :name, :persistent, :active, :autostart, :allocation, :capacity, :num_of_volumes, :state] tests("The interface model should respond to") do attributes.each do |attribute| test("#{attribute}") { pool.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::Libvirt::Pool') { pool.kind_of? Fog::Compute::Libvirt::Pool } end end fog-1.19.0/tests/libvirt/models/compute/volumes_tests.rb0000644000004100000410000000103412261242552023421 0ustar www-datawww-dataShindo.tests('Fog::Compute[:libvirt] | volumes collection', ['libvirt']) do volumes = Fog::Compute[:libvirt].volumes tests('The volumes collection') do test('should not be empty') { not volumes.empty? } test('should be a kind of Fog::Compute::Libvirt::Volumes') { volumes.kind_of? Fog::Compute::Libvirt::Volumes } tests('should be able to reload itself').succeeds { volumes.reload } tests('should be able to get a model') do tests('by instance uuid').succeeds { volumes.get volumes.first.id } end end end fog-1.19.0/tests/libvirt/models/compute/interface_tests.rb0000644000004100000410000000163312261242552023674 0ustar www-datawww-dataShindo.tests('Fog::Compute[:libvirt] | interface model', ['libvirt']) do interfaces = Fog::Compute[:libvirt].interfaces interface = interfaces.last tests('The interface model should') do tests('have the action') do test('reload') { interface.respond_to? 'reload' } end tests('have attributes') do model_attribute_hash = interface.attributes attributes = [ :name, :mac, :active] tests("The interface model should respond to") do attributes.each do |attribute| test("#{attribute}") { interface.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::Libvirt::Interface') { interface.kind_of? Fog::Compute::Libvirt::Interface } end end fog-1.19.0/tests/libvirt/models/compute/nic_tests.rb0000644000004100000410000000170412261242552022504 0ustar www-datawww-dataShindo.tests('Fog::Compute[:libvirt] | nic model', ['libvirt']) do nic = Fog::Compute[:libvirt].servers.all.select{|v| v.name =~ /^fog/}.first.nics.first tests('The nic model should') do tests('have the action') do test('reload') { nic.respond_to? 'reload' } end tests('have attributes') do model_attribute_hash = nic.attributes attributes = [ :mac, :model, :type, :network, :bridge] tests("The nic model should respond to") do attributes.each do |attribute| test("#{attribute}") { nic.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.delete(:bridge) attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::Libvirt::Nic') { nic.kind_of? Fog::Compute::Libvirt::Nic } end end fog-1.19.0/tests/libvirt/models/compute/servers_tests.rb0000644000004100000410000000103412261242552023420 0ustar www-datawww-dataShindo.tests('Fog::Compute[:libvirt] | servers collection', ['libvirt']) do servers = Fog::Compute[:libvirt].servers tests('The servers collection') do test('should not be empty') { not servers.empty? } test('should be a kind of Fog::Compute::Libvirt::Servers') { servers.kind_of? Fog::Compute::Libvirt::Servers } tests('should be able to reload itself').succeeds { servers.reload } tests('should be able to get a model') do tests('by instance uuid').succeeds { servers.get servers.first.id } end end end fog-1.19.0/tests/libvirt/models/compute/nics_tests.rb0000644000004100000410000000043512261242552022667 0ustar www-datawww-dataShindo.tests('Fog::Compute[:libvirt] | nics collection', ['libvirt']) do nics = Fog::Compute[:libvirt].servers.first.nics tests('The nics collection') do test('should not be empty') { not nics.empty? } test('should be a kind of Array') { nics.kind_of? Array } end end fog-1.19.0/tests/libvirt/models/compute/pools_tests.rb0000644000004100000410000000102012261242552023056 0ustar www-datawww-dataShindo.tests('Fog::Compute[:libvirt] | pools request', ['libvirt']) do pools = Fog::Compute[:libvirt].pools tests('The pools collection') do test('should not be empty') { not pools.empty? } test('should be a kind of Fog::Compute::Libvirt::Pools') { pools.kind_of? Fog::Compute::Libvirt::Pools } tests('should be able to reload itself').succeeds { pools.reload } tests('should be able to get a model') do tests('by instance id').succeeds { pools.get pools.first.uuid } end end end fog-1.19.0/tests/libvirt/models/compute/network_tests.rb0000644000004100000410000000160712261242552023426 0ustar www-datawww-dataShindo.tests('Fog::Compute[:libvirt] | network model', ['libvirt']) do networks = Fog::Compute[:libvirt].networks network = networks.last tests('The network model should') do tests('have the action') do test('reload') { network.respond_to? 'reload' } end tests('have attributes') do model_attribute_hash = network.attributes attributes = [ :name, :uuid, :bridge_name] tests("The network model should respond to") do attributes.each do |attribute| test("#{attribute}") { network.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::Libvirt::Network') { network.kind_of? Fog::Compute::Libvirt::Network } end end fog-1.19.0/tests/libvirt/models/compute/volume_tests.rb0000644000004100000410000000164012261242552023241 0ustar www-datawww-dataShindo.tests('Fog::Compute[:libvirt] | volume model', ['libvirt']) do volume = Fog::Compute[:libvirt].servers.all.select{|v| v.name !~ /^fog/}.first.volumes.first tests('The volume model should') do tests('have attributes') do model_attribute_hash = volume.attributes attributes = [ :id, :pool_name, :key, :name, :path, :capacity, :allocation, :format_type] tests("The volume model should respond to") do attributes.each do |attribute| test("#{attribute}") { volume.respond_to? attribute } end end tests("The attributes hash should have key") do attributes.each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::Libvirt::Volume') { volume.kind_of? Fog::Compute::Libvirt::Volume } end end fog-1.19.0/tests/libvirt/models/compute/interfaces_tests.rb0000644000004100000410000000107712261242552024061 0ustar www-datawww-dataShindo.tests('Fog::Compute[:libvirt] | interfaces collection', ['libvirt']) do interfaces = Fog::Compute[:libvirt].interfaces tests('The interfaces collection') do test('should not be empty') { not interfaces.empty? } test('should be a kind of Fog::Compute::Libvirt::Interfaces') { interfaces.kind_of? Fog::Compute::Libvirt::Interfaces } tests('should be able to reload itself').succeeds { interfaces.reload } tests('should be able to get a model') do tests('by instance name').succeeds { interfaces.get interfaces.first.name } end end end fog-1.19.0/tests/clodo/0000755000004100000410000000000012261242552014650 5ustar www-datawww-datafog-1.19.0/tests/clodo/requests/0000755000004100000410000000000012261242552016523 5ustar www-datawww-datafog-1.19.0/tests/clodo/requests/compute/0000755000004100000410000000000012261242552020177 5ustar www-datawww-datafog-1.19.0/tests/clodo/requests/compute/image_tests.rb0000644000004100000410000000135312261242552023032 0ustar www-datawww-dataShindo.tests('Fog::Compute[:clodo] | image requests', ['clodo']) do ### Fog.mock! clodo = Fog::Compute[:clodo] @image_format = { 'id' => String, 'name' => String, 'status' => String, 'vps_type' => String } @image_details_format = { 'os_type' => String, 'os_bits' => String, 'os_hvm' => String, '_attr' => @image_format } tests("success") do tests("- list_images").formats([@image_format]) do clodo.list_images.body['images'] end tests("- list_images_detail").formats([@image_details_format]) do clodo.list_images_detail.body['images'] end end tests("failure") do tests("- get_image_details(541)").returns(nil) do clodo.images.get(541) end end end fog-1.19.0/tests/clodo/requests/compute/server_tests.rb0000644000004100000410000001336112261242552023260 0ustar www-datawww-dataShindo.tests('Fog::Compute[:clodo] | server requests', ['clodo']) do @ip_format = { 'primary_ip' => Fog::Boolean, 'isp' => Fog::Boolean, 'ip' => String } @server_format = { 'addresses' => { 'public' => [@ip_format] }, 'id' => String, 'imageId' => String, 'name' => String, 'type' => String, 'status' => String } @server_details_format = @server_format.merge({ 'id' => Integer, 'vps_createdate' => String, 'vps_hdd_max' => String, 'vps_traff' => NilClass, 'vps_mem_1h_max' => String, 'vps_mem_load' => String, 'vps_user_pass' => String, 'vps_vnc_pass' => String, 'vps_adddate' => String, 'vps_os_title' => String, 'vps_update' => String, 'vps_mem_1h_min' => String, 'vps_mem_1h_avg' => NilClass, 'vps_memory_max' => String, 'vps_os_version' => String, 'vps_cpu_1h_max' => String, 'vps_hdd_load' => String, 'vps_disk_load' => String, 'vps_os_type' => String, 'vps_memory' => String, 'vps_cpu_load' => String, 'vps_update_days' => String, 'vps_os_bits' => String, 'vps_vnc' => String, 'vps_cpu_max' => String, 'vps_cpu_1h_min' => String, 'vps_cpu_1h_avg' => NilClass, 'vps_root_pass' => String }) @server_create_format = { 'name' => String, 'adminPass' => String, 'imageId' => String, 'id' => Integer } # Fog.mock! clodo = Fog::Compute[:clodo] tests('success') do tests('- create_server(541)').formats(@server_create_format) do data = clodo.create_server(541,{:vps_type => 'ScaleServer'}).body['server'] @server_id = data['id'] data end tests('- list_servers(ready)').formats([@server_format]) do clodo.list_servers.body['servers'].reject {|s| !['is_running', 'is_disabled'].include?(s['status']) } end tests('- list_servers(not ready)').formats([@server_format.merge({'addresses'=>{'public'=>NilClass}})]) do clodo.list_servers.body['servers'].reject {|s| !['is_request'].include?(s['status']) } end clodo.servers.get(@server_id).wait_for { ready? || state == 'is_error' } unless Fog.mocking? tests("- add_ip_address(#{@server_id})").succeeds do clodo.add_ip_address(@server_id) end # tests("- get_server_details(#{@server_id})").formats(@server_details_format) do # data = clodo.get_server_details(@server_id).body['server'] # @additional_ip = data['addresses']['public'].select {|a| !a['primary_ip'] }.first # data # end tests("- reboot_server(#{@server_id})").succeeds do clodo.reboot_server(@server_id, :hard) end clodo.servers.get(@server_id).wait_for { ready? || state == 'is_error' } unless Fog.mocking? # tests("- delete_ip_address(#{@server_id}, #{@additional_ip['ip']})").success do # clodo.delete_ip_address(@server_id, @additional_ip['ip']) # end tests("- stop_server(#{@server_id})").succeeds do clodo.stop_server(@server_id) end unless Fog.mocking? clodo.servers.get(@server_id).wait_for { state == 'is_disabled' || state == 'is_error' } end tests("- start_server(#{@server_id})").succeeds do clodo.start_server(@server_id) end clodo.servers.get(@server_id).wait_for { ready? || state == 'is_error' } unless Fog.mocking? tests("- delete_server(#{@server_id})").succeeds do clodo.delete_server(@server_id) end end tests('failure') do tests('- create_server(0)').raises(Excon::Errors::BadRequest) do data = clodo.create_server(0,{:vps_type => 'ScaleServer'}).body['server'] @server_id = data['id'] data end tests("- reboot_server(0)").raises(Excon::Errors::BadRequest) do clodo.reboot_server(0, :hard) end tests("- stop_server(0)").raises(Excon::Errors::BadRequest) do clodo.stop_server(0) end tests("- start_server(0)").raises(Excon::Errors::BadRequest) do clodo.start_server(0) end ## delete_server(0) in actual API, works not as it must, ## so I do not include this test in tests sequence. # tests("- delete_server(0)").raises(Fog::Compute::Clodo::NotFound) do # clodo.delete_server(0) # end # # tests("- delete_ip_address(0, 6.6.6.6)").raises(Fog::Compute::Clodo::NotFound) do # clodo.delete_ip_address(0, "6.6.6.6") # end tests("- delete_ip_address(#{@server_id}, 6.6.6.6)").raises(Excon::Errors::BadRequest) do clodo.delete_ip_address(@server_id, "6.6.6.6") end end end fog-1.19.0/tests/openvz/0000755000004100000410000000000012261242552015071 5ustar www-datawww-datafog-1.19.0/tests/openvz/helper.rb0000644000004100000410000000214612261242552016700 0ustar www-datawww-data # Shortcut for Fog::Compute[:openvz] def openvz_service Fog::Compute[:openvz] end # Create a long lived server for the tests def openvz_fog_test_server server = openvz_service.servers.find { |s| s.ctid == '104' } unless server server = openvz_service.servers.create :ctid => '104' server.start server.reload # Wait for the server to come up begin server.wait_for(120) { server.reload rescue nil; server.ready? } rescue Fog::Errors::TimeoutError # Server bootstrap took more than 120 secs! end end openvz_fog_test_cleanup server end # Destroy the long lived server def openvz_fog_test_server_destroy server = openvz_service.servers.find { |s| s.ctid == '104' } server.destroy if server end # Prepare a callback to destroy the long lived test server def openvz_fog_test_cleanup at_exit do unless Fog.mocking? server = openvz_service.servers.find { |s| s.name == '104' } if server server.wait_for(120) do reload rescue nil; ready? end end server.stop openvz_fog_test_server_destroy end end end fog-1.19.0/tests/openvz/models/0000755000004100000410000000000012261242552016354 5ustar www-datawww-datafog-1.19.0/tests/openvz/models/compute/0000755000004100000410000000000012261242552020030 5ustar www-datawww-datafog-1.19.0/tests/openvz/models/compute/server_tests.rb0000644000004100000410000000225212261242552023106 0ustar www-datawww-dataShindo.tests("Fog::Compute[:openvz] | server model", ['openvz', 'compute']) do server = openvz_fog_test_server tests('The server model should') do tests('have the action') do test('reload') { server.respond_to? 'reload' } %w{ destroy mount umount restart stop start quotaon quotaoff quotainit suspend resume }.each do |action| test(action) { server.respond_to? action } end end tests('have attributes') do model_attribute_hash = server.attributes attributes = [ :ctid, :description ] tests("The server model should respond to") do attributes.each do |attribute| test("#{attribute}") { server.respond_to? attribute } end end end test('#stop') do pending if Fog.mocking? server.stop server.wait_for { server.status == 'stopped' } server.status == 'stopped' end test('#start') do pending if Fog.mocking? server.start server.wait_for { ready? } server.ready? end end # restore server status server.start end fog-1.19.0/tests/openvz/models/compute/servers_tests.rb0000644000004100000410000000154612261242552023276 0ustar www-datawww-dataShindo.tests('Fog::Compute[:openvz] | servers collection', ['openvz']) do openvz_service = Fog::Compute[:openvz] tests('The servers collection') do servers = openvz_service.servers.all server = openvz_fog_test_server test('should NOT be empty') do servers.reload !servers.empty? end test('should be a kind of Fog::Compute::Openvz::Servers') do servers.kind_of? Fog::Compute::Openvz::Servers end tests('should have Fog::Compute::Openvz::Servers inside') do servers.each do |s| test { s.kind_of? Fog::Compute::Openvz::Server } end end tests('should be able to reload itself').succeeds { servers.reload } tests('should be able to get a model') do test('by instance ctid') do servers.get(server.ctid).kind_of? Fog::Compute::Openvz::Server end end end end fog-1.19.0/tests/cloudstack/0000755000004100000410000000000012261242552015704 5ustar www-datawww-datafog-1.19.0/tests/cloudstack/requests/0000755000004100000410000000000012261242552017557 5ustar www-datawww-datafog-1.19.0/tests/cloudstack/requests/security_group_tests.rb0000644000004100000410000000135312261242552024413 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | security group requests', ['cloudstack']) do @security_groups_format = { 'listsecuritygroupsresponse' => { 'count' => Integer, 'securitygroup' => [ 'id' => Integer, 'account' => String, 'description' => Fog::Nullable::String, 'domain' => String, 'domainid' => Integer, 'jobid' => Fog::Nullable::Integer, 'jobstatus' => Fog::Nullable::String, 'name' => String, 'ingressrule' => Fog::Nullable::Array ] } } tests('success') do tests('#list_security_groups').formats(@security_groups_format) do pending if Fog.mocking? Fog::Compute[:cloudstack].list_security_groups end end endfog-1.19.0/tests/cloudstack/requests/service_offering_tests.rb0000644000004100000410000000207212261242552024646 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | service offering requests', ['cloudstack']) do @service_offerings_format = { 'listserviceofferingsresponse' => { 'count' => Integer, 'serviceoffering' => [ 'id' => Integer, 'cpuspeed' => Integer, 'cpunumber' => Integer, 'created' => String, 'defaultuse' => Fog::Boolean, 'displaytext' => String, 'domain' => Fog::Nullable::String, 'domainid' => Fog::Nullable::Integer, 'hosttags' => Fog::Nullable::String, 'issystem' => Fog::Boolean, 'limitcpuuse' => Fog::Boolean, 'memory' => Integer, 'name' => String, 'networkrate' => Integer, 'offerha' => Fog::Boolean, 'storagetype' => String, 'systemvmtype' => Fog::Nullable::String, 'tags' => Fog::Nullable::String ] } } tests('success') do tests('#list_service_offerings').formats(@service_offerings_format) do pending if Fog.mocking? Fog::Compute[:cloudstack].list_service_offerings end end endfog-1.19.0/tests/cloudstack/requests/template_tests.rb0000644000004100000410000000321012261242552023135 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | template requests', ['cloudstack']) do @templates_format = { 'listtemplatesresponse' => { 'count' => Integer, 'template' => [ 'id' => Integer, 'name' => String, 'displaytext' => String, 'ispublic' => Fog::Boolean, 'created' => String, 'isready' => Fog::Boolean, 'passwordenabled' => Fog::Boolean, 'format' => String, 'isfeatured' => Fog::Boolean, 'crossZones' => Fog::Boolean, 'ostypeid' => Integer, 'ostypename' => String, 'account' => String, 'zoneid' => Integer, 'zonename' => String, 'status' => Fog::Nullable::String, 'size' => Fog::Nullable::Integer, 'templatetype' => String, 'hypervisor' => String, 'domain' => String, 'domainid' => Integer, 'isextractable' => Fog::Boolean, 'checksum' => Fog::Nullable::String, 'sourcetemplateid' => Fog::Nullable::Integer, 'accountid' => Fog::Nullable::Integer, 'bootable' => Fog::Nullable::Boolean, 'hostid' => Fog::Nullable::Integer, 'hostname' => Fog::Nullable::String, 'jobid' => Fog::Nullable::Integer, 'jobstatus' => Fog::Nullable::Integer, 'removed' => Fog::Nullable::Boolean, 'templatetag' => Fog::Nullable::String, 'templatetype' => Fog::Nullable::String ] } } tests('success') do tests('#list_templates').formats(@templates_format) do pending if Fog.mocking? Fog::Compute[:cloudstack].list_templates('templateFilter' => "executable") end end endfog-1.19.0/tests/cloudstack/requests/snapshot_tests.rb0000644000004100000410000000134612261242552023171 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | snapshot requests', ['cloudstack']) do @snapshots_format = { 'listsnapshotsresponse' => { 'count' => Integer, 'snapshot' => [ 'id' => Integer, 'account' => String, 'domainid' => Integer, 'domain' => String, 'snapshottype' => String, 'volumeid' => Integer, 'volumename' => String, 'volumetype' => String, 'created' => String, 'name' => String, 'intervaltype' => String, 'state' => String ] } } tests('success') do tests('#list_snapshots').formats(@snapshots_format) do pending if Fog.mocking? Fog::Compute[:cloudstack].list_snapshots end end endfog-1.19.0/tests/cloudstack/requests/ssh_key_pair_tests.rb0000644000004100000410000000077112261242552024013 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | ssh key pairs requests', ['cloudstack']) do @ssh_keys_format = { 'listsshkeypairsresponse' => { 'count' => Integer, 'sshkeypair' => [ 'fingerprint' => String, 'name' => String, 'privatekey' => Fog::Nullable::String ] } } tests('success') do tests('#list_ssh_key_pairs').formats(@ssh_keys_format) do pending if Fog.mocking? Fog::Compute[:cloudstack].list_ssh_key_pairs end end endfog-1.19.0/tests/cloudstack/requests/virtual_machine_tests.rb0000644000004100000410000000425112261242552024502 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | virtual machine requests', ['cloudstack']) do @virtual_machines_format = { 'listvirtualmachinesresponse' => { 'count' => Integer, 'virtualmachine' => [ 'id' => String, 'name' => String, 'displayname' => String, 'account' => String, 'domainid' => String, 'domain' => String, 'created' => String, 'state' => String, 'haenable' => Fog::Boolean, 'zoneid' => String, 'zonename' => String, 'hostid' => Fog::Nullable::String, 'hostname' => Fog::Nullable::String, 'templateid' => String, 'templatename' => String, 'templatedisplaytext' => String, 'passwordenabled' => Fog::Boolean, 'serviceofferingid' => String, 'serviceofferingname' => String, 'cpunumber' => Integer, 'cpuspeed' => Integer, 'networkkbsread' => Fog::Nullable::Integer, 'memory' => Integer, 'cpuused' => Fog::Nullable::String, 'guestosid' => String, 'networkkbswrite' => Fog::Nullable::Integer, 'rootdeviceid' => Integer, 'rootdevicetype' => String, 'hypervisor' => Fog::Nullable::String, 'group' => Fog::Nullable::String, 'groupid' => Fog::Nullable::Integer, 'isoname' => Fog::Nullable::String, 'isoid' => Fog::Nullable::Integer, 'securitygroup' => [ 'id' => Integer, 'name' => Fog::Nullable::String, 'description' => Fog::Nullable::String ], 'nic' => [ 'id' => String, 'networkid' => String, 'netmask' => String, 'gateway' => String, 'ipaddress' => String, 'traffictype' => String, 'type' => String, 'isdefault' => Fog::Boolean, 'macaddress' => String, 'broadcasturi' => Fog::Nullable::String, 'isolationuri' => Fog::Nullable::String ] ] } } tests('success') do tests('#list_virtual_machines').formats(@virtual_machines_format) do pending if Fog.mocking? Fog::Compute[:cloudstack].list_virtual_machines end end end fog-1.19.0/tests/cloudstack/requests/disk_offering_tests.rb0000644000004100000410000000133412261242552024140 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | disk offering requests', ['cloudstack']) do @disk_offerings_format = { 'listdiskofferingsresponse' => { 'count' => Integer, 'diskoffering' => [ 'id' => String, 'created' => String, 'disksize' => Integer, 'displaytext' => String, 'domain' => Fog::Nullable::String, 'domainid' => Fog::Nullable::String, 'iscustomized' => Fog::Boolean, 'name' => String, 'storagetype' => String, 'tags' => Fog::Nullable::String ] } } tests('success') do tests('#list_disk_offerings').formats(@disk_offerings_format) do Fog::Compute[:cloudstack].list_disk_offerings end end endfog-1.19.0/tests/cloudstack/requests/zone_tests.rb0000644000004100000410000000157312261242552022307 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | zone requests', ['cloudstack']) do @zones_format = { 'listzonesresponse' => { 'count' => Integer, 'zone' => [ 'id' => Integer, 'name' => String, 'dns1' => Fog::Nullable::String, 'dns2' => Fog::Nullable::String, 'internaldns1' => Fog::Nullable::String, 'internaldns2' => Fog::Nullable::String, 'vlan' => Fog::Nullable::String, 'guestcidraddress' => Fog::Nullable::String, 'networktype' => String, 'securitygroupsenabled' => Fog::Nullable::Boolean, 'allocationstate' => String, 'dhcpprovider' => String, 'zonetoken' => Fog::Nullable::String ] } } tests('success') do tests('#list_zones').formats(@zones_format) do pending if Fog.mocking? Fog::Compute[:cloudstack].list_zones end end end fog-1.19.0/tests/cloudstack/requests/volume_tests.rb0000644000004100000410000000271612261242552022643 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | volume requests', ['cloudstack']) do @volumes_format = { 'listvolumesresponse' => { 'count' => Integer, 'volume' => [ 'id' => Integer, 'name' => String, 'zoneid' => Integer, 'zonename' => String, 'type' => String, 'size' => Integer, 'created' => String, 'account' => String, 'domainid' => Integer, 'domain' => String, 'state' => String, 'storagetype' => String, 'hypervisor' => String, 'diskofferingid' => Fog::Nullable::Integer, 'diskofferingname' => Fog::Nullable::String, 'diskofferingdisplaytext' => Fog::Nullable::String, 'storage' => String, 'destroyed' => Fog::Boolean, 'isextractable' => Fog::Boolean, 'deviceid' => Fog::Nullable::Integer, 'virtualmachineid' => Fog::Nullable::Integer, 'vmname' => Fog::Nullable::String, 'vmdisplayname' => Fog::Nullable::String, 'vmstate' => Fog::Nullable::String, 'serviceofferingid' => Fog::Nullable::Integer, 'serviceofferingname' => Fog::Nullable::String, 'serviceofferingdisplaytext' => Fog::Nullable::String, 'attached' => Fog::Nullable::String ] } } tests('success') do tests('#list_volumes').formats(@volumes_format) do pending if Fog.mocking? Fog::Compute[:cloudstack].list_volumes('zoneid' => 1) end end end fog-1.19.0/tests/cloudstack/requests/os_type_tests.rb0000644000004100000410000000141512261242552023011 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | os type requests', ['cloudstack']) do @os_types_format = { 'listostypesresponse' => { 'count' => Integer, 'ostype' => [ 'id' => String, 'description' => String, 'oscategoryid' => String ] } } @os_categories_format = { 'listoscategoriesresponse' => { 'count' => Integer, 'oscategory' => [ 'id' => Integer, 'name' => String ] } } tests('success') do tests('#list_os_types').formats(@os_types_format) do Fog::Compute[:cloudstack].list_os_types end tests('#list_os_categories').formats(@os_categories_format) do pending if Fog.mocking? Fog::Compute[:cloudstack].list_os_categories end end endfog-1.19.0/tests/cloudstack/compute/0000755000004100000410000000000012261242552017360 5ustar www-datawww-datafog-1.19.0/tests/cloudstack/compute/models/0000755000004100000410000000000012261242552020643 5ustar www-datawww-datafog-1.19.0/tests/cloudstack/compute/models/security_group_tests.rb0000644000004100000410000000077212261242552025503 0ustar www-datawww-datadef security_group_tests(connection, params, mocks_implemented = true) model_tests(connection.security_groups, params[:security_group_attributes], mocks_implemented) do if Fog.mocking? && !mocks_implemented pending else responds_to(:rules) end end end provider, config = :cloudstack, compute_providers[:cloudstack] Shindo.tests("Fog::Compute[:#{provider}] | security_groups", [provider.to_s]) do security_group_tests(Fog::Compute[:cloudstack], config, config[:mocked]) end fog-1.19.0/tests/cloudstack/compute/models/server_tests.rb0000644000004100000410000000120612261242552023717 0ustar www-datawww-dataprovider, config = :cloudstack, compute_providers[:cloudstack] Shindo.tests("Fog::Compute[:#{provider}] | servers + security_groups", [provider.to_s]) do connection = Fog::Compute[provider] @security_group = connection.security_groups.create(config[:security_group_attributes]) @server = connection.servers.create(config[:server_attributes].merge(:security_groups => [@security_group])) tests('#security_group').succeeds do @server.wait_for { ready? } @server.security_groups.map(&:id) == [@security_group.id] end tests('#destroy').succeeds do @server.destroy.wait_for { ready? } @security_group.destroy end end fog-1.19.0/tests/cloudstack/compute/models/security_groups_tests.rb0000644000004100000410000000076312261242552025666 0ustar www-datawww-datadef security_group_tests(provider, params, mocks_implemented = true) collection_tests(provider.security_groups, params, mocks_implemented) do if Fog.mocking? && !mocks_implemented pending else responds_to(:rules) end end end provider, config = :cloudstack, compute_providers[:cloudstack] Shindo.tests("Fog::Compute[:#{provider}] | security_group", [provider.to_s]) do security_group_tests(Fog::Compute[provider], (config[:security_group_attributes] || {}), config[:mocked]) end fog-1.19.0/tests/cloudstack/compute/models/snapshot_tests.rb0000644000004100000410000000077012261242552024255 0ustar www-datawww-datadef snapshot_tests(connection, params, mocks_implemented = true) model_tests(connection.snapshots, params[:snapshot_attributes], mocks_implemented) do if !Fog.mocking? || mocks_implemented @instance.wait_for { ready? } end end end Shindo.tests("Fog::Compute[:cloudstack] | snapshot", "cloudstack") do config = compute_providers[:cloudstack] snapshot_tests(Fog::Compute[:cloudstack], config, config[:mocked]) tests('has volume relation') do responds_to(:volume) end end fog-1.19.0/tests/cloudstack/compute/models/volumes_tests.rb0000644000004100000410000000067312261242552024112 0ustar www-datawww-datadef volumes_tests(connection, params = {}, mocks_implemented = true) collection_tests(connection.volumes, params, mocks_implemented) do if !Fog.mocking? || mocks_implemented @instance.wait_for { ready? } end end end config = compute_providers[:cloudstack] Shindo.tests("Fog::Compute[:cloudstack] | volumes", ["cloudstack"]) do volumes_tests(Fog::Compute[:cloudstack], config[:volume_attributes], config[:mocked]) end fog-1.19.0/tests/cloudstack/compute/models/disk_offering_tests.rb0000644000004100000410000000037112261242552025224 0ustar www-datawww-dataShindo.tests("Fog::Compute[:cloudstack] | disk_offering", "cloudstack") do config = compute_providers[:cloudstack] compute = Fog::Compute[:cloudstack] model_tests(compute.disk_offerings, config[:disk_offering_attributes], config[:mocked]) end fog-1.19.0/tests/cloudstack/compute/models/volume_tests.rb0000644000004100000410000000150012261242552023715 0ustar www-datawww-datadef volume_tests(connection, params, mocks_implemented = true) model_tests(connection.volumes, params[:volume_attributes], mocks_implemented) do if !Fog.mocking? || mocks_implemented @instance.wait_for { ready? } end @server = @instance.connection.servers.create(params[:server_attributes]) @server.wait_for { ready? } tests('attach').succeeds do @instance.attach(@server) end tests('detach').succeeds do @instance.detach end @server.destroy end end Shindo.tests("Fog::Compute[:cloudstack] | volume", "cloudstack") do config = compute_providers[:cloudstack] volume_tests(Fog::Compute[:cloudstack], config, config[:mocked]) do if Fog.mocking? && !mocks_implemented pending else responds_to(:ready?) responds_to(:flavor) end end end fog-1.19.0/tests/cloudstack/compute/models/security_group_rule_tests.rb0000644000004100000410000000165712261242552026535 0ustar www-datawww-datadef security_group_rule_tests(connection, params, direction, mocks_implemented = true) @security_group = connection.security_groups.create(params[:security_group_attributes]) rule_params = params[:security_group_rule_attributes].merge(:security_group_id => @security_group.id, :direction => direction) model_tests(connection.security_group_rules, rule_params, mocks_implemented) do if Fog.mocking? && !mocks_implemented pending end end @security_group.destroy end provider, config = :cloudstack, compute_providers[:cloudstack] Shindo.tests("Fog::Compute[:#{provider}] | security_group_rules | ingress", [provider.to_s]) do security_group_rule_tests(Fog::Compute[:cloudstack], config, "ingress", config[:mocked]) end Shindo.tests("Fog::Compute[:#{provider}] | security_group_rules | egress", [provider.to_s]) do security_group_rule_tests(Fog::Compute[:cloudstack], config, "egress", config[:mocked]) end fog-1.19.0/tests/cloudstack/signed_params_tests.rb0000644000004100000410000000154112261242552022270 0ustar www-datawww-data# encoding: utf-8 Shindo.tests('Cloudstack | escape', ['cloudstack']) do returns( Fog::Cloudstack.escape( "'Stöp!' said Fred_-~." ) ) { "%27St%C3%B6p%21%27%20said%20Fred_-%7E." } end Shindo.tests('Cloudstack | signed_params', ['cloudstack']) do returns( Fog::Cloudstack.signed_params( 'abcdefg', 'account' => 'Lorem Ipsum', 'domainid' => 42, 'q' => 'keywords' ) ) { "V2CxRU4zQQtox1DZsH/66GDdzhg=" } returns( Fog::Cloudstack.signed_params( 'abcdefg', 'account' => 'Lorem Ipsum', 'domainid' => '42', 'q' => 'keywords' ) ) { "V2CxRU4zQQtox1DZsH/66GDdzhg=" } returns( Fog::Cloudstack.signed_params( 'abcdefg', 'account' => 'Lorem Ipsum', 'domainid' => 42, 'q' => nil ) ) { "5bsDirm5pPgVoreQ6vquKRN+4HI=" } returns( Fog::Cloudstack.signed_params( 'abcdefg', 'account' => 'Lorem Ipsum', 'domainid' => 42, 'q' => '' ) ) { "5bsDirm5pPgVoreQ6vquKRN+4HI=" } end fog-1.19.0/tests/dreamhost/0000755000004100000410000000000012261242552015536 5ustar www-datawww-datafog-1.19.0/tests/dreamhost/helper.rb0000644000004100000410000000103712261242552017343 0ustar www-datawww-datadef test_domain 'fog-dream.com' end def do_not_delete_record "do-not-delete.#{test_domain}" end ## Cleanup # We need to have at least one record defined for the Dreamhost DNS api to work # or you will get a no_such_zone runtime error # The first record needs to be created using the Dreamhost Web panel AFAIK # def cleanup_records Fog::DNS[:dreamhost].records.each do |r| # Do not delete the 'do-not-delete' record, we need it for the tests r.destroy if r.name =~ /#{test_domain}/ and r.name != do_not_delete_record end end fog-1.19.0/tests/dreamhost/dns_tests.rb0000644000004100000410000000123512261242552020072 0ustar www-datawww-dataShindo.tests('Fog::DNS[:dreamhost]', ['dreamhost', 'dns']) do service = Fog::DNS[:dreamhost] tests("collections") do %w{ records zones }.each do |collection| test("it should respond to #{collection}") { service.respond_to? collection } test("it should respond to #{collection}.all") { eval("service.#{collection}").respond_to? 'all' } test("it should respond to #{collection}.get") { eval("service.#{collection}").respond_to? 'get' } end end tests("requests") do %w{ list_records create_record delete_record }.each do |request| test("it should respond to #{request}") { service.respond_to? request } end end end fog-1.19.0/tests/dreamhost/requests/0000755000004100000410000000000012261242552017411 5ustar www-datawww-datafog-1.19.0/tests/dreamhost/requests/dns/0000755000004100000410000000000012261242552020175 5ustar www-datawww-datafog-1.19.0/tests/dreamhost/requests/dns/delete_record_tests.rb0000644000004100000410000000122512261242552024544 0ustar www-datawww-dataShindo.tests('Fog::DNS[:dreamhost] | delete_record request', ['dreamhost', 'dns']) do tests("success") do test("delete testing records") do name = "delete-test.#{test_domain}" type = "A" value = "1.2.3.4" comment = "test" Fog::DNS[:dreamhost].create_record(name, type, value, comment) response = Fog::DNS[:dreamhost].delete_record(name, type, value) response.body['result'] == 'success' end end tests( 'failure') do raises(RuntimeError, 'deleting non-existent record') do Fog::DNS[:dreamhost].delete_record('foo.bar.bar', 'A', '1.2.3.4') end end # helper cleanup_records end fog-1.19.0/tests/dreamhost/requests/dns/create_record_tests.rb0000644000004100000410000000175612261242552024556 0ustar www-datawww-dataShindo.tests('Fog::DNS[:dreamhost] | create_record request', ['dreamhost', 'dns']) do tests("success") do test("create an A resource record without comment") do name = "foo.testing.#{test_domain}" type = "A" value = "1.2.3.4" response = Fog::DNS[:dreamhost].create_record(name, type, value) response.body['result'] == 'success' end test("create an A resource record with comment") do name = "foo2.testing.#{test_domain}" type = "A" value = "1.2.3.4" comment = "test" response = Fog::DNS[:dreamhost].create_record(name, type, value, comment) response.body['result'] == 'success' end test("create TXT record") do name = "txt.testing.#{test_domain}" type = "txt" value = "foobar" comment = "test" response = Fog::DNS[:dreamhost].create_record(name, type, value, comment) response.body['result'] == 'success' end end # helper cleanup_records end fog-1.19.0/tests/dreamhost/requests/dns/list_records_tests.rb0000644000004100000410000000123612261242552024442 0ustar www-datawww-dataShindo.tests('Fog::DNS[:dreamhost] | list_records request', ['dreamhost', 'dns']) do tests("success") do response = Fog::DNS[:dreamhost].list_records test("should return 200") do if response.status == 200 @records = response.body["data"] end (response.status == 200) and (response.body.size == 2) end test("data should be an Array") do @records.is_a? Array end tests("should return records") do %w{type zone value comment record}.each do |elem| test("with #{elem}") do @records.first[elem].is_a? String end end end end # helper cleanup_records end fog-1.19.0/tests/dreamhost/models/0000755000004100000410000000000012261242552017021 5ustar www-datawww-datafog-1.19.0/tests/dreamhost/models/dns/0000755000004100000410000000000012261242552017605 5ustar www-datawww-datafog-1.19.0/tests/dreamhost/models/dns/zones_tests.rb0000644000004100000410000000123412261242552022512 0ustar www-datawww-dataShindo.tests("Fog::DNS[:dreamhost] | Zones Collection", ['dreamhost', 'dns']) do service = Fog::DNS[:dreamhost] tests('#all') do zones = service.zones test('should be an array') { zones.is_a? Array } test('should not be empty') { !zones.empty? } tests('should list Fog::DNS::Dreamhost::Zone') do zones.each do |r| test("as zone") { r.is_a?(Fog::DNS::Dreamhost::Zone) } end end end tests('#get') do tests('should fetch a zone') do zone = service.zones.get test_domain test('should be a Fog::DNS::Dreamhost::Zone') do zone.is_a? Fog::DNS::Dreamhost::Zone end end end end fog-1.19.0/tests/dreamhost/models/dns/zone_tests.rb0000644000004100000410000000310412261242552022325 0ustar www-datawww-dataShindo.tests("Fog::DNS[:dreamhost] | zone", ['dreamhost', 'dns']) do service = Fog::DNS[:dreamhost] zone = service.zones.first tests('#attributes') do tests('should have') do model_attribute_hash = zone.attributes attributes = [ :domain, :id, ] attributes.each do |attribute| test("#{attribute} method") { zone.respond_to? attribute } end attributes.each do |attribute| test("#{attribute} key") { model_attribute_hash.has_key? attribute } end end test('be a kind of Fog::DNS::Dreamhost::Zone') do zone.kind_of? Fog::DNS::Dreamhost::Zone end tests('Write operations') do name = "#{test_domain}" tests('#save') do # Does not capture the exception for some reason #raises(NotImplementedError, 'raises NotImplementedError') do # service.zones.create :domain => name #end test 'raises NotImplementedError' do begin service.zones.create :domain => name false rescue NotImplementedError => e true end end end tests('#destroy') do test 'raises NotImplementedError' do begin zone.destroy false rescue NotImplementedError => e true end end end tests('#records') do zone.records.each do |r| test('list records') { r.is_a? Fog::DNS::Dreamhost::Record } test('zone matches') { r.zone == test_domain } end end end end end fog-1.19.0/tests/dreamhost/models/dns/records_tests.rb0000644000004100000410000000127012261242552023015 0ustar www-datawww-dataShindo.tests("Fog::DNS[:dreamhost] | records", ['dreamhost', 'dns']) do service = Fog::DNS[:dreamhost] tests('#all') do records = service.records test('should be an array') { records.is_a? Array } test('should not be empty') { !records.empty? } tests('should list Fog::DNS::Dreamhost::Record') do records.each do |r| test("as records") { r.is_a?(Fog::DNS::Dreamhost::Record) } end end end tests('#get') do tests('should fetch a record') do record = service.records.get do_not_delete_record test('should be a Fog::DNS::Dreamhost::Record') do record.is_a? Fog::DNS::Dreamhost::Record end end end end fog-1.19.0/tests/dreamhost/models/dns/record_tests.rb0000644000004100000410000000377312261242552022644 0ustar www-datawww-dataShindo.tests("Fog::DNS[:dreamhost] | record", ['dreamhost', 'dns']) do service = Fog::DNS[:dreamhost] record = service.records.first tests('#attributes') do tests('should have') do model_attribute_hash = record.attributes attributes = [ :name, :value, :zone, :type, :editable, :account_id, :comment, ] attributes.each do |attribute| test("#{attribute} method") { record.respond_to? attribute } end attributes.each do |attribute| test("#{attribute} key") { model_attribute_hash.has_key? attribute } end end test('be a kind of Fog::DNS::Dreamhost::Record') do record.kind_of? Fog::DNS::Dreamhost::Record end tests('Write operations') do name = "test.#{test_domain}" r = service.records.create :name => name, :type => 'A', :value => "8.8.8.8" sleep 10 tests('#save') do test('returns Fog::DNS::Dreamhost::Record') do r.is_a? Fog::DNS::Dreamhost::Record end test('value is 8.8.8.8') do r.value == '8.8.8.8' end test("name is #{name}") do r.name == name end test("listed") do !(service.records.find { |r| r.name == name }).nil? end end tests('#destroy') do test('returns true') { r.destroy == true } test('destroyed record not listed') do (service.records.find { |r| r.name == name }).nil? end end tests('#save from zone') do name = "zone-create.#{test_domain}" r = service.zones.first.records.create :name => name, :type => 'A', :value => "8.8.8.8" sleep 10 test("listed") do !(service.records.find { |r| r.name == name }).nil? end end end end # cleanup cleanup_records end fog-1.19.0/tests/dreamhost/README.md0000644000004100000410000000317512261242552017023 0ustar www-datawww-data# Testing the Dreamhost DNS API Dreamhost API sandbox only permits read-only commands, so you'll need a Dreamhost PS account for the testing and a dedicated domain. See http://wiki.dreamhost.com/Application_programming_interface#Test_Account ## Create an API key You'll need a Dreamhost (PS I think) account and a dedicated domain for testing. 1. Go to the Dreamhost web panel and create an API key to manage DNS records https://panel.dreamhost.com/index.cgi?tree=home.api Select 'All dns functions' for the new API key to be able to add/remove/list records. 2. Create a .fog file in the tests/ directory with the following contents: ```yaml :default: :dreamhost_api_key: SDFASDFWQWASDFASDFAS ``` Where dreamhost_api_key is the key you created in the previous step. 3. Update the test_domain helper in tests/dreamhost/helper.rb to use your own domain for testing. You will also need at least a record created via the Dreamhost Webpanel (you'll get a **no_such_zone** error otherwise). I usually create a do-not-delete.my-domain.com record. The tests skip that record when cleaning up (see the do_not_delete_record helper). 4. Run the tests ``` shindo tests/dreamhost ``` ## Notes The API is rate limited, so do not smash the DH servers too often. Two consecutive test runs will trigger the rate limit. You'll see a **slow_down_bucko** error if the frequency is too high. http://wiki.dreamhost.com/Application_programming_interface#Rate_Limit ## Resources Dreamhost API: http://wiki.dreamhost.com/Application_programming_interface Dreamhost DNS API: http://wiki.dreamhost.com/API/Dns_commands fog-1.19.0/tests/brightbox/0000755000004100000410000000000012261242552015540 5ustar www-datawww-datafog-1.19.0/tests/brightbox/requests/0000755000004100000410000000000012261242552017413 5ustar www-datawww-datafog-1.19.0/tests/brightbox/requests/compute/0000755000004100000410000000000012261242552021067 5ustar www-datawww-datafog-1.19.0/tests/brightbox/requests/compute/application_test.rb0000644000004100000410000000460212261242552024760 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | api client requests', ['brightbox']) do tests('success') do create_options = { :name => "Fog@#{Time.now.iso8601}" } tests("#create_application(#{create_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].create_application(create_options) @application_id = result["id"] data_matches_schema(Brightbox::Compute::Formats::Full::APPLICATION, {:allow_extra_keys => true}) { result } end tests("#list_applications") do pending if Fog.mocking? result = Fog::Compute[:brightbox].list_applications data_matches_schema(Brightbox::Compute::Formats::Collection::APPLICATION, {:allow_extra_keys => true}) { result } end tests("#get_application('#{@application_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].get_application(@application_id) data_matches_schema(Brightbox::Compute::Formats::Full::APPLICATION, {:allow_extra_keys => true}) { result } end update_options = {:name => "Fog@#{Time.now.iso8601}"} tests("#update_application('#{@application_id}', #{update_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].update_application(@application_id, update_options) data_matches_schema(Brightbox::Compute::Formats::Full::APPLICATION, {:allow_extra_keys => true}) { result } end tests("#reset_secret_application('#{@application_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].reset_secret_application(@application_id) data_matches_schema(Brightbox::Compute::Formats::Full::APPLICATION, {:allow_extra_keys => true}) { result } test("new secret is visible") { ! result["secret"].nil? } end tests("#destroy_application('#{@application_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].destroy_application(@application_id) data_matches_schema(Brightbox::Compute::Formats::Full::APPLICATION, {:allow_extra_keys => true}) { result } end end tests('failure') do tests("#get_api_client('app-00000')").raises(Excon::Errors::NotFound) do pending if Fog.mocking? Fog::Compute[:brightbox].get_application('app-00000') end tests("#get_api_client").raises(ArgumentError) do pending if Fog.mocking? Fog::Compute[:brightbox].get_application end end end fog-1.19.0/tests/brightbox/requests/compute/helper.rb0000644000004100000410000000263712261242552022703 0ustar www-datawww-dataclass Brightbox module Compute module TestSupport # Find a suitable image for testing with # For speed of server building we're using an empty image # # Unless the tester has credentials this will fail so we rescue # any errors and return nil. # # This is used in the shared file +tests/compute/helper.rb+ so unfortunately # makes all tests reliant on hardcoded values and each other # # @return [String,NilClass] the most suitable test image's identifier or nil def self.image_id return @image_id unless @image_id.nil? image = select_testing_image_from_api @image_id = image["id"] rescue @image_id = nil end # Prepare a test server, wait for it to be usable but raise if it fails def self.get_test_server test_server_options = {:image_id => image_id} server = Fog::Compute[:brightbox].servers.create(test_server_options) server.wait_for { raise "Test server failed to build" if state == "failed" ready? } server end private def self.select_testing_image_from_api images = Fog::Compute[:brightbox].list_images raise "No available images!" if images.empty? images.select { |img| img["official"] && img["virtual_size"] != 0 }.sort_by { |img| img["disk_size"] }.first || images.first end end end end fog-1.19.0/tests/brightbox/requests/compute/server_type_tests.rb0000644000004100000410000000201512261242552025203 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | server type requests', ['brightbox']) do tests('success') do tests("#list_server_types") do pending if Fog.mocking? result = Fog::Compute[:brightbox].list_server_types @server_type_id = result.first["id"] data_matches_schema(Brightbox::Compute::Formats::Collection::SERVER_TYPES, {:allow_extra_keys => true}) { result } end tests("#get_server_type('#{@server_type_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].get_server_type(@server_type_id) data_matches_schema(Brightbox::Compute::Formats::Full::SERVER_TYPE, {:allow_extra_keys => true}) { result } end end tests('failure') do tests("#get_server_type('typ-00000')").raises(Excon::Errors::NotFound) do pending if Fog.mocking? Fog::Compute[:brightbox].get_server_type('typ-00000') end tests("#get_server").raises(ArgumentError) do pending if Fog.mocking? Fog::Compute[:brightbox].get_server_type end end end fog-1.19.0/tests/brightbox/requests/compute/image_tests.rb0000644000004100000410000000406112261242552023721 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | image requests', ['brightbox']) do tests('success') do ## Difficult to test without having uploaded an Image to your account to register # creation_options = { # "arch" => "i686", # "source" => "fnord" # } # tests("#create_image(#{creation_options.inspect})") # result = Fog::Compute[:brightbox].create_image(creation_options) # @image_id = result["id"] # formats(Brightbox::Compute::Formats::Full::IMAGE) { result } # end # Fog::Compute[:brightbox].images.get(@image_id).wait_for { ready? } tests("#list_images") do pending if Fog.mocking? result = Fog::Compute[:brightbox].list_images @image_id = result.first["id"] data_matches_schema(Brightbox::Compute::Formats::Collection::IMAGES, {:allow_extra_keys => true}) { result } end tests("#get_image('#{@image_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].get_image(@image_id) data_matches_schema(Brightbox::Compute::Formats::Full::IMAGE, {:allow_extra_keys => true}) { result } end ## Until Image creation can be automated, we shouldn't be updating Images randomly # update_options = {} # tests("#update_image('#{@image_id}', #{update_options.inspect})") do # result = Fog::Compute[:brightbox].update_image(@image_id, :name => "New name from Fog test") # formats(Brightbox::Compute::Formats::Full::IMAGE) { result } # end ## Same as other tests - can't be deleting them unless part of the test run # tests("#destroy_server('#{@image_id}')") do # result = Fog::Compute[:brightbox].destroy_image(@image_id) # formats(Brightbox::Compute::Formats::Full::IMAGE) { result } # end end tests('failure') do tests("#get_image('img-00000')").raises(Excon::Errors::NotFound) do pending if Fog.mocking? Fog::Compute[:brightbox].get_image('img-00000') end tests("#get_image").raises(ArgumentError) do pending if Fog.mocking? Fog::Compute[:brightbox].get_image end end end fog-1.19.0/tests/brightbox/requests/compute/server_tests.rb0000644000004100000410000000740412261242552024151 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | server requests', ['brightbox']) do tests('success') do unless Fog.mocking? image_id = Brightbox::Compute::TestSupport.image_id server_id = nil end tests("#create_server(:image => '#{image_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].create_server(:image => image_id) server_id = result["id"] data_matches_schema(Brightbox::Compute::Formats::Full::SERVER, {:allow_extra_keys => true}) { result } end unless Fog.mocking? Fog::Compute[:brightbox].servers.get(server_id).wait_for { ready? } end tests("#list_servers") do pending if Fog.mocking? result = Fog::Compute[:brightbox].list_servers data_matches_schema(Brightbox::Compute::Formats::Collection::SERVERS, {:allow_extra_keys => true}) { result } end tests("#get_server('#{server_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].get_server(server_id) data_matches_schema(Brightbox::Compute::Formats::Full::SERVER, {:allow_extra_keys => true}) { result } end tests("#update_server('#{server_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].update_server(server_id, :name => "Fog@#{Time.now.iso8601}") data_matches_schema(Brightbox::Compute::Formats::Full::SERVER, {:allow_extra_keys => true}) { result } end tests("#activate_console_server('#{server_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].activate_console_server(server_id) data_matches_schema(Brightbox::Compute::Formats::Full::SERVER, {:allow_extra_keys => true}) { result } test("has set 'console_url'") { ! result["console_url"].empty? } test("has set 'console_token'") { ! result["console_token"].empty? } test("has set 'console_token_expires'") { ! result["console_token_expires"].empty? } end tests("#stop_server('#{server_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].stop_server(server_id) data_matches_schema(Brightbox::Compute::Formats::Full::SERVER, {:allow_extra_keys => true}) { result } end tests("#start_server('#{server_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].start_server(server_id) data_matches_schema(Brightbox::Compute::Formats::Full::SERVER, {:allow_extra_keys => true}) { result } end tests("#shutdown_server('#{server_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].shutdown_server(server_id) data_matches_schema(Brightbox::Compute::Formats::Full::SERVER, {:allow_extra_keys => true}) { result } end tests("#snapshot_server('#{server_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].snapshot_server(server_id) data_matches_schema(Brightbox::Compute::Formats::Full::SERVER, {:allow_extra_keys => true}) { result } # Server should be exclusively for our test so assume we can delete the snapshot snapshot_id = result["snapshots"].first["id"] @snapshot = Fog::Compute[:brightbox].images.get(snapshot_id) @snapshot.wait_for { ready? } @snapshot.destroy end tests("#destroy_server('#{server_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].destroy_server(server_id) data_matches_schema(Brightbox::Compute::Formats::Full::SERVER, {:allow_extra_keys => true}) { result } end end tests('failure') do tests("#get_server('srv-00000')").raises(Excon::Errors::NotFound) do pending if Fog.mocking? Fog::Compute[:brightbox].get_server('srv-00000') end tests("#get_server").raises(ArgumentError) do pending if Fog.mocking? Fog::Compute[:brightbox].get_server end end end fog-1.19.0/tests/brightbox/requests/compute/firewall_rule_tests.rb0000644000004100000410000000310112261242552025465 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | firewall rule requests', ['brightbox']) do tests('success') do pending if Fog.mocking? unless Fog.mocking? policy = Fog::Compute[:brightbox].firewall_policies.create end create_options = { :firewall_policy => policy.id, :destination => "127.0.0.1" } tests("#create_firewall_rule(#{create_options.inspect})") do result = Fog::Compute[:brightbox].create_firewall_rule(create_options) @firewall_rule_id = result["id"] data_matches_schema(Brightbox::Compute::Formats::Full::FIREWALL_RULE, {:allow_extra_keys => true}) { result } end tests("#get_firewall_rule('#{@firewall_rule_id}')") do data_matches_schema(Brightbox::Compute::Formats::Full::FIREWALL_RULE, {:allow_extra_keys => true}) do Fog::Compute[:brightbox].get_firewall_rule(@firewall_rule_id) end end update_options = {:source => nil, :destination => "127.0.0.1"} tests("#update_firewall_rule('#{@firewall_rule_id}', #{update_options.inspect})") do data_matches_schema(Brightbox::Compute::Formats::Full::FIREWALL_RULE, {:allow_extra_keys => true}) do Fog::Compute[:brightbox].update_firewall_rule(@firewall_rule_id, update_options) end end tests("#destroy_firewall_rule('#{@firewall_rule_id}')") do result = Fog::Compute[:brightbox].destroy_firewall_rule(@firewall_rule_id) data_matches_schema(Brightbox::Compute::Formats::Full::FIREWALL_RULE, {:allow_extra_keys => true}) { result } end unless Fog.mocking? policy.destroy end end end fog-1.19.0/tests/brightbox/requests/compute/firewall_policy_tests.rb0000644000004100000410000000330412261242552026022 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | firewall policy requests', ['brightbox']) do tests('success') do pending if Fog.mocking? create_options = { :name => "Fog test policy A" } tests("#create_firewall_policy(#{create_options.inspect})") do result = Fog::Compute[:brightbox].create_firewall_policy(create_options) @firewall_policy_id = result["id"] data_matches_schema(Brightbox::Compute::Formats::Full::FIREWALL_POLICY, {:allow_extra_keys => true}) { result } end tests("#list_firewall_policies()") do data_matches_schema(Brightbox::Compute::Formats::Collection::FIREWALL_POLICIES, {:allow_extra_keys => true}) do Fog::Compute[:brightbox].list_firewall_policies end end tests("#get_firewall_policy('#{@firewall_policy_id}')") do data_matches_schema(Brightbox::Compute::Formats::Full::FIREWALL_POLICY, {:allow_extra_keys => true}) do Fog::Compute[:brightbox].get_firewall_policy(@firewall_policy_id) end end update_options = {:name => "Fog test policy B"} tests("#update_firewall_policy('#{@firewall_policy_id}', #{update_options.inspect})") do result = Fog::Compute[:brightbox].update_firewall_policy(@firewall_policy_id, update_options) data_matches_schema(Brightbox::Compute::Formats::Full::FIREWALL_POLICY, {:allow_extra_keys => true}) { result } returns("Fog test policy B") { result["name"] } end tests("#destroy_firewall_policy('#{@firewall_policy_id}')") do result = Fog::Compute[:brightbox].destroy_firewall_policy(@firewall_policy_id) data_matches_schema(Brightbox::Compute::Formats::Full::FIREWALL_POLICY, {:allow_extra_keys => true}) { result } end end end fog-1.19.0/tests/brightbox/requests/compute/user_collaboration_tests.rb0000644000004100000410000000401112261242552026520 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | user collaboration requests', ['brightbox']) do @service = Fog::Compute[:brightbox] tests("when accessing with user application") do pending unless @service.authenticating_as_user? tests("success") do tests("#list_user_collaborations") do pending if Fog.mocking? result = @service.list_user_collaborations formats(Brightbox::Compute::Formats::Collection::COLLABORATIONS, false) { result } end end tests("failure") do tests("get_user_collaboration('col-abcde')").raises(Excon::Errors::NotFound) do pending if Fog.mocking? @service.get_user_collaboration('col-abcde') end tests("accept_user_collaboration('col-abcde')").raises(Excon::Errors::NotFound) do pending if Fog.mocking? @service.accept_user_collaboration('col-abcde') end tests("reject_user_collaboration('col-abcde')").raises(Excon::Errors::NotFound) do pending if Fog.mocking? @service.reject_user_collaboration('col-abcde') end end end tests("when accessing with API client") do pending if @service.authenticating_as_user? tests("forbidden") do tests("#list_user_collaborations").raises(Excon::Errors::Forbidden) do pending if Fog.mocking? result = @service.list_user_collaborations formats(Brightbox::Compute::Formats::Collection::COLLABORATIONS, false) { result } end tests("get_user_collaboration('col-abcde')").raises(Excon::Errors::Forbidden) do pending if Fog.mocking? @service.get_user_collaboration('col-abcde') end tests("accept_user_collaboration('col-abcde')").raises(Excon::Errors::Forbidden) do pending if Fog.mocking? @service.accept_user_collaboration('col-abcde') end tests("reject_user_collaboration('col-abcde')").raises(Excon::Errors::Forbidden) do pending if Fog.mocking? @service.reject_user_collaboration('col-abcde') end end end end fog-1.19.0/tests/brightbox/requests/compute/interface_tests.rb0000644000004100000410000000165012261242552024600 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | interface requests', ['brightbox']) do @test_service = Fog::Compute[:brightbox] tests('success') do unless Fog.mocking? @test_server = Brightbox::Compute::TestSupport.get_test_server @interface_id = @test_server.interfaces.first["id"] tests("#get_interface('#{@interface_id}')") do pending if Fog.mocking? result = @test_service.get_interface(@interface_id) data_matches_schema(Brightbox::Compute::Formats::Full::INTERFACE, {:allow_extra_keys => true}) { result } end @test_server.destroy end end tests('failure') do tests("#get_interface('int-00000')").raises(Excon::Errors::NotFound) do pending if Fog.mocking? @test_service.get_interface('int-00000') end tests("#get_interface()").raises(ArgumentError) do pending if Fog.mocking? @test_service.get_interface() end end end fog-1.19.0/tests/brightbox/requests/compute/api_client_tests.rb0000644000004100000410000000463112261242552024751 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | api client requests', ['brightbox']) do tests('success') do create_options = { :name => "Fog@#{Time.now.iso8601}", :description => "Description from Fog test" } tests("#create_api_client(#{create_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].create_api_client(create_options) @api_client_id = result["id"] data_matches_schema(Brightbox::Compute::Formats::Full::API_CLIENT, {:allow_extra_keys => true}) { result } end tests("#list_api_clients") do pending if Fog.mocking? result = Fog::Compute[:brightbox].list_api_clients data_matches_schema(Brightbox::Compute::Formats::Collection::API_CLIENTS, {:allow_extra_keys => true}) { result } end tests("#get_api_client('#{@api_client_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].get_api_client(@api_client_id) data_matches_schema(Brightbox::Compute::Formats::Full::API_CLIENT, {:allow_extra_keys => true}) { result } end update_options = {:name => "Fog@#{Time.now.iso8601}"} tests("#update_api_client('#{@api_client_id}', #{update_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].update_api_client(@api_client_id, update_options) data_matches_schema(Brightbox::Compute::Formats::Full::API_CLIENT, {:allow_extra_keys => true}) { result } end tests("#reset_secret_api_client('#{@api_client_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].reset_secret_api_client(@api_client_id) data_matches_schema(Brightbox::Compute::Formats::Full::API_CLIENT, {:allow_extra_keys => true}) { result } test("new secret is visible") { ! result["secret"].nil? } end tests("#destroy_api_client('#{@api_client_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].destroy_api_client(@api_client_id) data_matches_schema(Brightbox::Compute::Formats::Full::API_CLIENT, {:allow_extra_keys => true}) { result } end end tests('failure') do tests("#get_api_client('cli-00000')").raises(Excon::Errors::NotFound) do pending if Fog.mocking? Fog::Compute[:brightbox].get_api_client('cli-00000') end tests("#get_api_client").raises(ArgumentError) do pending if Fog.mocking? Fog::Compute[:brightbox].get_api_client end end end fog-1.19.0/tests/brightbox/requests/compute/collaboration_tests.rb0000644000004100000410000000251412261242552025470 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | collaboration requests', ['brightbox']) do tests('success') do tests("#create_collaboration") do pending if Fog.mocking? collaboration = Fog::Compute[:brightbox].create_collaboration(:email => "paul@example.com", :role => "admin") @collaboration_id = collaboration['id'] formats(Brightbox::Compute::Formats::Full::COLLABORATION, false) { collaboration } end tests("#list_collaborations") do pending if Fog.mocking? result = Fog::Compute[:brightbox].list_collaborations formats(Brightbox::Compute::Formats::Collection::COLLABORATIONS, false) { result } end tests("#get_collaboration") do pending if Fog.mocking? result = Fog::Compute[:brightbox].get_collaboration(@collaboration_id) formats(Brightbox::Compute::Formats::Full::COLLABORATION, false) { result } end tests("#destroy_collaboration") do pending if Fog.mocking? result = Fog::Compute[:brightbox].destroy_collaboration(@collaboration_id) formats(Brightbox::Compute::Formats::Full::COLLABORATION, false) { result } end end tests("failure") do tests("get_collaboration('col-abcde')").raises(Excon::Errors::NotFound) do pending if Fog.mocking? Fog::Compute[:brightbox].get_collaboration("col-abcde") end end end fog-1.19.0/tests/brightbox/requests/compute/zone_tests.rb0000644000004100000410000000166012261242552023614 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | zone requests', ['brightbox']) do tests('success') do tests("#list_zones") do pending if Fog.mocking? result = Fog::Compute[:brightbox].list_zones @zone_id = result.first["id"] data_matches_schema(Brightbox::Compute::Formats::Collection::ZONES, {:allow_extra_keys => true}) { result } end tests("#get_zone('#{@zone_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].get_zone(@zone_id) data_matches_schema(Brightbox::Compute::Formats::Full::ZONE, {:allow_extra_keys => true}) { result } end end tests('failure') do tests("#get_zone('zon-00000')").raises(Excon::Errors::NotFound) do pending if Fog.mocking? Fog::Compute[:brightbox].get_zone('zon-00000') end tests("#get_zone").raises(ArgumentError) do pending if Fog.mocking? Fog::Compute[:brightbox].get_zone end end end fog-1.19.0/tests/brightbox/requests/compute/server_group_tests.rb0000644000004100000410000000745112261242552025367 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | server group requests', ['brightbox']) do tests('success') do unless Fog.mocking? @server = Brightbox::Compute::TestSupport.get_test_server server_id = @server.id end create_options = { :name => "Fog@#{Time.now.iso8601}", :servers => [{ :server => server_id }] } tests("#create_server_group(#{create_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].create_server_group(create_options) @server_group_id = result["id"] data_matches_schema(Brightbox::Compute::Formats::Full::SERVER_GROUP, {:allow_extra_keys => true}) { result } end tests("#list_server_groups") do pending if Fog.mocking? result = Fog::Compute[:brightbox].list_server_groups data_matches_schema(Brightbox::Compute::Formats::Collection::SERVER_GROUPS, {:allow_extra_keys => true}) { result } @default_group_id = result.select {|grp| grp["default"] == true }.first["id"] end tests("#get_server_group('#{@server_group_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].get_server_group(@server_group_id) data_matches_schema(Brightbox::Compute::Formats::Full::SERVER_GROUP, {:allow_extra_keys => true}) { result } end update_options = {:name => "Fog@#{Time.now.iso8601}"} tests("#update_server_group('#{@server_group_id}', #{update_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].update_server_group(@server_group_id, update_options) data_matches_schema(Brightbox::Compute::Formats::Full::SERVER_GROUP, {:allow_extra_keys => true}) { result } end remove_options = {:servers => [{:server => server_id}]} tests("#remove_servers_server_group('#{@server_group_id}', #{remove_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].remove_servers_server_group(@server_group_id, remove_options) data_matches_schema(Brightbox::Compute::Formats::Full::SERVER_GROUP, {:allow_extra_keys => true}) { result } end add_options = {:servers => [{:server => server_id}]} tests("#add_servers_server_group('#{@server_group_id}', #{remove_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].add_servers_server_group(@server_group_id, add_options) data_matches_schema(Brightbox::Compute::Formats::Full::SERVER_GROUP, {:allow_extra_keys => true}) { result } end move_options = {:destination => @default_group_id, :servers => [{:server => server_id}]} tests("#move_servers_server_group('#{@server_group_id}', #{move_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].move_servers_server_group(@server_group_id, move_options) data_matches_schema(Brightbox::Compute::Formats::Full::SERVER_GROUP, {:allow_extra_keys => true}) { result } test("group is emptied") { result["servers"].empty? } end tests("#destroy_server_group('#{@server_group_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].destroy_server_group(@server_group_id) data_matches_schema(Brightbox::Compute::Formats::Full::SERVER_GROUP, {:allow_extra_keys => true}) { result } end unless Fog.mocking? @server.destroy end end tests('failure') do tests("#create_server_group").raises(ArgumentError) do pending if Fog.mocking? Fog::Compute[:brightbox].create_server_group end tests("#get_server_group('grp-00000')").raises(Excon::Errors::NotFound) do pending if Fog.mocking? Fog::Compute[:brightbox].get_server_group('grp-00000') end tests("#get_server_group").raises(ArgumentError) do pending if Fog.mocking? Fog::Compute[:brightbox].get_server_group end end end fog-1.19.0/tests/brightbox/requests/compute/load_balancer_tests.rb0000644000004100000410000001127012261242552025405 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | load balancer requests', ['brightbox']) do tests('success') do unless Fog.mocking? @node = Brightbox::Compute::TestSupport.get_test_server node_id = @node.id end create_options = { :nodes => [{ :node => node_id }], :listeners => [{ :in => 80, :out => 8080, :protocol => "http" }], :healthcheck => { :type => "http", :port => 80 } } tests("#create_load_balancer(#{create_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].create_load_balancer(create_options) @load_balancer_id = result["id"] data_matches_schema(Brightbox::Compute::Formats::Full::LOAD_BALANCER, {:allow_extra_keys => true}) { result } end unless Fog.mocking? Fog::Compute[:brightbox].load_balancers.get(@load_balancer_id).wait_for { ready? } end tests("#list_load_balancers()") do pending if Fog.mocking? result = Fog::Compute[:brightbox].list_load_balancers data_matches_schema(Brightbox::Compute::Formats::Collection::LOAD_BALANCERS, {:allow_extra_keys => true}) { result } end tests("#get_load_balancer('#{@load_balancer_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].get_load_balancer(@load_balancer_id) data_matches_schema(Brightbox::Compute::Formats::Full::LOAD_BALANCER, {:allow_extra_keys => true}) { result } end update_options = {:name => "New name"} tests("#update_load_balancer('#{@load_balancer_id}', #{update_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].update_load_balancer(@load_balancer_id, update_options) data_matches_schema(Brightbox::Compute::Formats::Full::LOAD_BALANCER, {:allow_extra_keys => true}) { result } end add_listeners_options = {:listeners=>[{:out=>28080, :in=>8080, :protocol=>"http"}]} tests("#add_listeners_load_balancer('#{@load_balancer_id}', #{add_listeners_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].add_listeners_load_balancer(@load_balancer_id, add_listeners_options) data_matches_schema(Brightbox::Compute::Formats::Full::LOAD_BALANCER, {:allow_extra_keys => true}) { result } end remove_listeners_options = {:listeners=>[{:out=>28080, :in=>8080, :protocol=>"http"}]} tests("#remove_listeners_load_balancer('#{@load_balancer_id}', #{remove_listeners_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].remove_listeners_load_balancer(@load_balancer_id, remove_listeners_options) data_matches_schema(Brightbox::Compute::Formats::Full::LOAD_BALANCER, {:allow_extra_keys => true}) { result } end unless Fog.mocking? @node2 = Brightbox::Compute::TestSupport.get_test_server second_node_id = @node2.id end # Can't remove the last node so we need to add a second... add_nodes_options = {:nodes => [{:node => second_node_id}]} tests("#add_nodes_load_balancer('#{@load_balancer_id}', #{add_nodes_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].add_nodes_load_balancer(@load_balancer_id, add_nodes_options) data_matches_schema(Brightbox::Compute::Formats::Full::LOAD_BALANCER, {:allow_extra_keys => true}) { result } end # ...before we can attempt to remove either remove_nodes_options = {:nodes => [{:node => node_id}]} tests("#remove_nodes_load_balancer('#{@load_balancer_id}', #{remove_nodes_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].remove_nodes_load_balancer(@load_balancer_id, remove_nodes_options) data_matches_schema(Brightbox::Compute::Formats::Full::LOAD_BALANCER, {:allow_extra_keys => true}) { result } end tests("#destroy_load_balancer('#{@load_balancer_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].destroy_load_balancer(@load_balancer_id) data_matches_schema(Brightbox::Compute::Formats::Full::LOAD_BALANCER, {:allow_extra_keys => true}) { result } end unless Fog.mocking? @node.destroy @node2.destroy end end tests('failure') do tests("#create_load_balancer").raises(ArgumentError) do pending if Fog.mocking? Fog::Compute[:brightbox].create_load_balancer end tests("#get_load_balancer('lba-00000')").raises(Excon::Errors::NotFound) do pending if Fog.mocking? Fog::Compute[:brightbox].get_load_balancer('lba-00000') end tests("#get_load_balancer").raises(ArgumentError) do pending if Fog.mocking? Fog::Compute[:brightbox].get_load_balancer end end end fog-1.19.0/tests/brightbox/requests/compute/cloud_ip_tests.rb0000644000004100000410000000563212261242552024442 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | cloud ip requests', ['brightbox']) do tests('success') do unless Fog.mocking? @server = Brightbox::Compute::TestSupport.get_test_server end tests("#create_cloud_ip") do pending if Fog.mocking? result = Fog::Compute[:brightbox].create_cloud_ip @cloud_ip_id = result["id"] data_matches_schema(Brightbox::Compute::Formats::Full::CLOUD_IP, {:allow_extra_keys => true}) { result } end tests("#list_cloud_ips") do pending if Fog.mocking? result = Fog::Compute[:brightbox].list_cloud_ips data_matches_schema(Brightbox::Compute::Formats::Collection::CLOUD_IPS, {:allow_extra_keys => true}) { result } end tests("#get_cloud_ip('#{@cloud_ip_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].get_cloud_ip(@cloud_ip_id) data_matches_schema(Brightbox::Compute::Formats::Full::CLOUD_IP, {:allow_extra_keys => true}) { result } end unless Fog.mocking? map_options = {:destination => @server.interfaces.first["id"]} end tests("#map_cloud_ip('#{@cloud_ip_id}', #{map_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].map_cloud_ip(@cloud_ip_id, map_options) data_matches_schema(Brightbox::Compute::Formats::Full::CLOUD_IP, {:allow_extra_keys => true}) { result } end unless Fog.mocking? Fog::Compute[:brightbox].cloud_ips.get(@cloud_ip_id).wait_for { mapped? } end tests("#unmap_cloud_ip('#{@cloud_ip_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].unmap_cloud_ip(@cloud_ip_id) data_matches_schema(Brightbox::Compute::Formats::Full::CLOUD_IP, {:allow_extra_keys => true}) { result } end unless Fog.mocking? update_options = {:reverse_dns => "public.#{@server.id}.gb1.brightbox.com"} end tests("#update_cloud_ip('#{@cloud_ip_id}', #{update_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].update_cloud_ip(@cloud_ip_id, update_options) data_matches_schema(Brightbox::Compute::Formats::Full::CLOUD_IP, {:allow_extra_keys => true}) { result } result = Fog::Compute[:brightbox].update_cloud_ip(@cloud_ip_id, {:reverse_dns => ""}) end tests("#destroy_cloud_ip('#{@cloud_ip_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].destroy_cloud_ip(@cloud_ip_id) data_matches_schema(Brightbox::Compute::Formats::Full::CLOUD_IP, {:allow_extra_keys => true}) { result } end unless Fog.mocking? @server.destroy end end tests('failure') do tests("#get_cloud_ip('cip-00000')").raises(Excon::Errors::NotFound) do pending if Fog.mocking? Fog::Compute[:brightbox].get_cloud_ip('cip-00000') end tests("#get_cloud_ip").raises(ArgumentError) do pending if Fog.mocking? Fog::Compute[:brightbox].get_cloud_ip end end end fog-1.19.0/tests/brightbox/requests/compute/account_tests.rb0000644000004100000410000000523112261242552024273 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | account requests', ['brightbox']) do tests('success') do tests("#list_accounts") do pending if Fog.mocking? result = Fog::Compute[:brightbox].list_accounts data_matches_schema(Brightbox::Compute::Formats::Collection::ACCOUNTS, {:allow_extra_keys => true}) { result } end tests("#get_scoped_account") do pending if Fog.mocking? result = Fog::Compute[:brightbox].get_scoped_account @scoped_account_identifier = result["id"] data_matches_schema(Brightbox::Compute::Formats::Full::ACCOUNT, {:allow_extra_keys => true}) { result } test("ftp password is blanked") { result["library_ftp_password"].nil? } end tests("#get_account(#{@scoped_account_identifier}") do pending if Fog.mocking? result = Fog::Compute[:brightbox].get_account(@scoped_account_identifier) data_matches_schema(Brightbox::Compute::Formats::Full::ACCOUNT, {:allow_extra_keys => true}) { result } test("ftp password is blanked") { result["library_ftp_password"].nil? } end update_options = {:name => "Fog@#{Time.now.iso8601}"} tests("#update_scoped_account(#{update_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].update_scoped_account(update_options) data_matches_schema(Brightbox::Compute::Formats::Full::ACCOUNT, {:allow_extra_keys => true}) { result } end tests("#update_account(#{@scoped_account_identifier}, #{update_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].update_account(@scoped_account_identifier, update_options) data_matches_schema(Brightbox::Compute::Formats::Full::ACCOUNT, {:allow_extra_keys => true}) { result } end tests("#reset_ftp_password_scoped_account") do pending if Fog.mocking? result = Fog::Compute[:brightbox].reset_ftp_password_scoped_account data_matches_schema(Brightbox::Compute::Formats::Full::ACCOUNT, {:allow_extra_keys => true}) { result } test("new ftp password is visible") { ! result["library_ftp_password"].nil? } end tests("#reset_ftp_password_account(#{@scoped_account_identifier})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].reset_ftp_password_account(@scoped_account_identifier) data_matches_schema(Brightbox::Compute::Formats::Full::ACCOUNT, {:allow_extra_keys => true}) { result } test("new ftp password is visible") { ! result["library_ftp_password"].nil? } end end tests('failure') do tests("#update_account").raises(ArgumentError) do pending if Fog.mocking? Fog::Compute[:brightbox].update_account end end end fog-1.19.0/tests/brightbox/requests/compute/user_tests.rb0000644000004100000410000000215312261242552023615 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox] | user requests', ['brightbox']) do tests('success') do tests("#list_users") do pending if Fog.mocking? result = Fog::Compute[:brightbox].list_users @user_id = result.first["id"] data_matches_schema(Brightbox::Compute::Formats::Collection::USERS, {:allow_extra_keys => true}) { result } end tests("#get_user('#{@user_id}')") do pending if Fog.mocking? result = Fog::Compute[:brightbox].get_user(@user_id) data_matches_schema(Brightbox::Compute::Formats::Full::USER, {:allow_extra_keys => true}) { result } end update_options = { :name => "Example User" } tests("#update_user('#{@user_id}', #{update_options.inspect})") do pending if Fog.mocking? result = Fog::Compute[:brightbox].update_user(@user_id, update_options) data_matches_schema(Brightbox::Compute::Formats::Full::USER, {:allow_extra_keys => true}) { result } end end tests('failure') do tests("#update_user").raises(ArgumentError) do pending if Fog.mocking? Fog::Compute[:brightbox].update_user end end end fog-1.19.0/tests/brightbox/compute_tests.rb0000644000004100000410000000657312261242552020776 0ustar www-datawww-dataShindo.tests('Fog::Compute[:brightbox]', ['brightbox']) do @test_service = Fog::Compute[:brightbox] tests("#respond_to? :default_image").returns(true) do @test_service.respond_to?(:default_image) end end Shindo.tests('Fog::Compute.new', ['brightbox']) do tests("service options") do { :brightbox_api_url => "https://example.com", :brightbox_auth_url => "https://example.com", :brightbox_client_id => "app-12345", :brightbox_secret => "12345abdef6789", :brightbox_username => "user-12345", :brightbox_password => "password1234", :brightbox_account => "acc-12345", :brightbox_access_token => "12345abdef6789", :brightbox_refresh_token => "12345abdef6789", :brightbox_token_management => false }.each_pair do |option, sample| tests("recognises :#{option}").returns(true) do options = {:provider => "Brightbox"} options[option] = sample begin Fog::Compute.new(options) true rescue ArgumentError false end end end end tests("automatic token management") do service_options = {:provider => "Brightbox"} tests("when enabled (default)") do service_options[:brightbox_token_management] = true tests("using bad token") do service_options[:brightbox_access_token] = "bad-token" tests("#request").returns(true, "returns a Hash") do pending if Fog.mocking? service = Fog::Compute.new(service_options) response = service.get_authenticated_user response.is_a?(Hash) # This is an outstanding issue, should be Excon::Response end end end tests("when disabled") do service_options[:brightbox_token_management] = false tests("using bad token") do service_options[:brightbox_access_token] = "bad-token" tests("#request").raises(Excon::Errors::Unauthorized) do pending if Fog.mocking? service = Fog::Compute.new(service_options) service.get_authenticated_user end end end end tests("account scoping") do service = Fog::Compute.new(:provider => "Brightbox") configured_account = Fog.credentials[:brightbox_account] tests("when Fog.credentials are #{configured_account}") do test("#scoped_account == #{configured_account}") { service.scoped_account == configured_account } end set_account = "acc-35791" tests("when Compute instance is updated to #{set_account}") do service.scoped_account = set_account test("#scoped_account == #{set_account}") { service.scoped_account == set_account } end tests("when Compute instance is reset") do service.scoped_account_reset test("#scoped_account == #{configured_account}") { service.scoped_account == configured_account } end optioned_account = "acc-56789" tests("when Compute instance created with :brightbox_account => #{optioned_account}") do service = Fog::Compute.new(:provider => "Brightbox", :brightbox_account => optioned_account ) test("#scoped_account == #{optioned_account}") { service.scoped_account == optioned_account } end request_account = "acc-24680" tests("when requested with #{request_account}") do test("#scoped_account(#{request_account}) == #{request_account}") { service.scoped_account(request_account) == request_account } end end end fog-1.19.0/tests/brightbox/compute/0000755000004100000410000000000012261242552017214 5ustar www-datawww-datafog-1.19.0/tests/brightbox/compute/helper.rb0000644000004100000410000000007312261242552021020 0ustar www-datawww-datarequire File.expand_path("schema", File.dirname(__FILE__)) fog-1.19.0/tests/brightbox/compute/schema.rb0000644000004100000410000006530112261242552021006 0ustar www-datawww-datamodule Fog module Brightbox module Nullable module Account; end module ApiClient; end module FirewallPolicy; end module Image; end module Interface; end module LoadBalancer; end module Server; end module ServerGroup; end module User; end module Zone; end end end end Hash.send :include, Fog::Brightbox::Nullable::Account NilClass.send :include, Fog::Brightbox::Nullable::Account Hash.send :include, Fog::Brightbox::Nullable::ApiClient NilClass.send :include, Fog::Brightbox::Nullable::ApiClient Hash.send :include, Fog::Brightbox::Nullable::FirewallPolicy NilClass.send :include, Fog::Brightbox::Nullable::FirewallPolicy Hash.send :include, Fog::Brightbox::Nullable::Image NilClass.send :include, Fog::Brightbox::Nullable::Image Hash.send :include, Fog::Brightbox::Nullable::Interface NilClass.send :include, Fog::Brightbox::Nullable::Interface Hash.send :include, Fog::Brightbox::Nullable::LoadBalancer NilClass.send :include, Fog::Brightbox::Nullable::LoadBalancer Hash.send :include, Fog::Brightbox::Nullable::Server NilClass.send :include, Fog::Brightbox::Nullable::Server Hash.send :include, Fog::Brightbox::Nullable::ServerGroup NilClass.send :include, Fog::Brightbox::Nullable::ServerGroup Hash.send :include, Fog::Brightbox::Nullable::User NilClass.send :include, Fog::Brightbox::Nullable::User Hash.send :include, Fog::Brightbox::Nullable::Zone NilClass.send :include, Fog::Brightbox::Nullable::Zone class Brightbox module Compute module Formats module Struct CIP_PORT_TRANSLATOR = { "protocol" => String, "incoming" => Integer, "outgoing" => Integer } LB_LISTENER = { "in" => Integer, "out" => Integer, "protocol" => String, "timeout" => Integer } LB_HEALTHCHECK = { "type" => String, "request" => String, "port" => Integer, "interval" => Integer, "timeout" => Integer, "threshold_up" => Integer, "threshold_down" => Integer } end module Nested ACCOUNT = { "name" => String, "resource_type" => String, "url" => String, "id" => String, "status" => String } API_CLIENT = { "id" => String, "resource_type" => String, "url" => String, "name" => String, "description" => String, "revoked_at" => Fog::Nullable::String } CLOUD_IP = { "id" => String, "resource_type" => String, "url" => String, "name" => Fog::Nullable::String, "public_ip" => String, "status" => String, "reverse_dns" => String } FIREWALL_POLICY = { "id" => String, "resource_type" => String, "url" => String, "name" => Fog::Nullable::String, "default" => Fog::Boolean, "created_at" => String, "description" => Fog::Nullable::String } FIREWALL_RULE = { "id" => String, "resource_type" => String, "url" => String, "created_at" => String, "source" => Fog::Nullable::String, "source_port" => Fog::Nullable::String, "destination" => Fog::Nullable::String, "destination_port" => Fog::Nullable::String, "protocol" => Fog::Nullable::String, "icmp_type_name" => Fog::Nullable::String, "description" => Fog::Nullable::String } IMAGE = { "name" => String, "created_at" => String, "resource_type" => String, "arch" => String, "url" => String, "id" => String, "description" => String, "source" => String, "status" => String, "public" => Fog::Boolean, "official" => Fog::Boolean, "owner" => String, "username" => Fog::Nullable::String } INTERFACE = { "resource_type" => String, "url" => String, "id" => String, "ipv4_address" => String, "ipv6_address" => Fog::Nullable::String, "mac_address" => String } LOAD_BALANCER = { "id" => String, "resource_type" => String, "url" => String, "name" => String, "status" => String, "created_at" => String, "deleted_at" => Fog::Nullable::String } SERVER = { "id" => String, "resource_type" => String, "url" => String, "name" => String, "status" => String, "hostname" => String, "fqdn" => String, "created_at" => String, "started_at" => Fog::Nullable::String, "deleted_at" => Fog::Nullable::String, "username" => Fog::Nullable::String } SERVER_GROUP = { "id" => String, "resource_type" => String, "url" => String, "name" => Fog::Nullable::String, "created_at" => String, "default" => Fog::Boolean, "description" => Fog::Nullable::String, "created_at" => String } SERVER_TYPE = { "name" => String, "handle" => Fog::Nullable::String, "cores" => Integer, "resource_type" => String, "disk_size" => Integer, "url" => String, "id" => String, "ram" => Integer, "status" => String } USER = { "id" => String, "resource_type" => String, "url" => String, "name" => String, "email_address" => String } COLLABORATION = { "id" => String, "resource_type" => String, "url" => String, "status" => String, "email" => Fog::Nullable::String, "role" => String, "role_label" => String, "user" => Fog::Brightbox::Nullable::User, "account" => Brightbox::Compute::Formats::Nested::ACCOUNT, "inviter" => Brightbox::Compute::Formats::Nested::USER } ZONE = { "id" => String, "resource_type" => String, "url" => String, "handle" => Fog::Nullable::String } end module Collected ACCOUNT = { "id" => String, "resource_type" => String, "url" => String, "name" => String, "status" => String, "vat_registration_number" => Fog::Nullable::String, "telephone_number" => Fog::Nullable::String, "telephone_verified" => Fog::Nullable::Boolean, "ram_limit" => Integer, "ram_used" => Integer, "cloud_ips_limit" => Integer, "cloud_ips_used" => Integer, "load_balancers_limit" => Integer, "load_balancers_used" => Integer, "library_ftp_password" => Fog::Nullable::String, "verified_telephone" => Fog::Nullable::String, "verified_at" => Fog::Nullable::String, "verified_ip" => Fog::Nullable::String, "owner" => Brightbox::Compute::Formats::Nested::USER, "users" => [Brightbox::Compute::Formats::Nested::USER], "clients" => [Brightbox::Compute::Formats::Nested::API_CLIENT], "servers" => [Brightbox::Compute::Formats::Nested::SERVER], "load_balancers" => [Brightbox::Compute::Formats::Nested::LOAD_BALANCER], "cloud_ips" => [Brightbox::Compute::Formats::Nested::CLOUD_IP], "server_groups" => [Brightbox::Compute::Formats::Nested::SERVER_GROUP], "firewall_policies" => [Brightbox::Compute::Formats::Nested::FIREWALL_POLICY], "images" => [Brightbox::Compute::Formats::Nested::IMAGE], "zones" => [Brightbox::Compute::Formats::Nested::ZONE] } API_CLIENT = { "id" => String, "resource_type" => String, "url" => String, "name" => String, "description" => String, "revoked_at" => Fog::Nullable::String, "account" => Brightbox::Compute::Formats::Nested::ACCOUNT } APPLICATION = { "id" => String, "resource_type" => String, "url" => String, "name" => Fog::Nullable::String } CLOUD_IP = { "id" => String, "resource_type" => String, "url" => String, "name" => Fog::Nullable::String, "public_ip" => String, "status" => String, "reverse_dns" => String, "port_translators" => [Brightbox::Compute::Formats::Struct::CIP_PORT_TRANSLATOR], "account" => Brightbox::Compute::Formats::Nested::ACCOUNT, "interface" => Fog::Brightbox::Nullable::Interface, "load_balancer" => Fog::Brightbox::Nullable::LoadBalancer, "server" => Fog::Brightbox::Nullable::Server, "server_group" => Fog::Brightbox::Nullable::ServerGroup } FIREWALL_POLICY = { "id" => String, "resource_type" => String, "url" => String, "name" => Fog::Nullable::String, "description" => Fog::Nullable::String, "default" => Fog::Boolean, "created_at" => String, "server_group" => Fog::Brightbox::Nullable::ServerGroup, "rules" => [Brightbox::Compute::Formats::Nested::FIREWALL_RULE] } IMAGE = { "name" => String, "created_at" => String, "resource_type" => String, "arch" => String, "url" => String, "id" => String, "description" => String, "source" => String, "source_type" => String, "status" => String, "owner" => String, "username" => Fog::Nullable::String, "public" => Fog::Boolean, "official" => Fog::Boolean, "compatibility_mode" => Fog::Boolean, "virtual_size" => Integer, "disk_size" => Integer, "min_ram" => Fog::Nullable::Integer, "ancestor" => Fog::Brightbox::Nullable::Image, "username" => Fog::Nullable::String } LOAD_BALANCER = { "id" => String, "resource_type" => String, "url" => String, "name" => String, "status" => String, "created_at" => String, "deleted_at" => Fog::Nullable::String, "cloud_ips" => [Brightbox::Compute::Formats::Nested::CLOUD_IP], "account" => Brightbox::Compute::Formats::Nested::ACCOUNT, "listeners" => [Brightbox::Compute::Formats::Struct::LB_LISTENER], "nodes" => [Brightbox::Compute::Formats::Nested::SERVER] } SERVER = { "id" => String, "resource_type" => String, "url" => String, "name" => String, "status" => String, "hostname" => String, "fqdn" => String, "created_at" => String, "started_at" => Fog::Nullable::String, "deleted_at" => Fog::Nullable::String, "account" => Brightbox::Compute::Formats::Nested::ACCOUNT, "server_type" => Brightbox::Compute::Formats::Nested::SERVER_TYPE, "cloud_ips" => [Brightbox::Compute::Formats::Nested::CLOUD_IP], "image" => Brightbox::Compute::Formats::Nested::IMAGE, "server_groups" => [Brightbox::Compute::Formats::Nested::SERVER_GROUP], "snapshots" => [Brightbox::Compute::Formats::Nested::IMAGE], "interfaces" => [Brightbox::Compute::Formats::Nested::INTERFACE], "zone" => Fog::Brightbox::Nullable::Zone, "username" => Fog::Nullable::String, "compatibility_mode" => Fog::Boolean } SERVER_GROUP = { "created_at" => String, "id" => String, "resource_type" => String, "url" => String, "name" => Fog::Nullable::String, "description" => Fog::Nullable::String, "default" => Fog::Boolean, "created_at" => String, "account" => Brightbox::Compute::Formats::Nested::ACCOUNT, "servers" => [Brightbox::Compute::Formats::Nested::SERVER], "firewall_policy" => Fog::Brightbox::Nullable::FirewallPolicy } SERVER_TYPE = { "id" => String, "resource_type" => String, "url" => String, "handle" => Fog::Nullable::String, "name" => String, "status" => String, "cores" => Integer, "ram" => Integer, "disk_size" => Integer } USER = { "id" => String, "resource_type" => String, "url" => String, "name" => String, "email_address" => String, "email_verified" => Fog::Boolean, "accounts" => [Brightbox::Compute::Formats::Nested::ACCOUNT], "default_account" => NilClass } COLLABORATION = { "id" => String, "resource_type" => String, "url" => String, "status" => String, "role" => String, "role_label" => String, "email" => Fog::Nullable::String, "user" => Fog::Brightbox::Nullable::User, "account" => Brightbox::Compute::Formats::Nested::ACCOUNT, "inviter" => Brightbox::Compute::Formats::Nested::USER } ZONE = { "id" => String, "resource_type" => String, "url" => String, "handle" => Fog::Nullable::String } end module Full ACCOUNT = { "id" => String, "resource_type" => String, "url" => String, "name" => String, "status" => String, "address_1" => String, "address_2" => String, "city" => String, "county" => String, "postcode" => String, "country_code" => String, "country_name" => String, "vat_registration_number" => Fog::Nullable::String, "telephone_number" => String, "telephone_verified" => Fog::Boolean, "created_at" => String, "ram_limit" => Integer, "ram_used" => Integer, "cloud_ips_limit" => Integer, "cloud_ips_used" => Integer, "load_balancers_limit" => Integer, "load_balancers_used" => Integer, "library_ftp_host" => String, "library_ftp_user" => String, "library_ftp_password" => Fog::Nullable::String, "verified_telephone" => Fog::Nullable::String, "verified_at" => Fog::Nullable::String, "verified_ip" => Fog::Nullable::String, "valid_credit_card" => Fog::Boolean, "owner" => Brightbox::Compute::Formats::Nested::USER, "users" => [Brightbox::Compute::Formats::Nested::USER], "clients" => [Brightbox::Compute::Formats::Nested::API_CLIENT], "servers" => [Brightbox::Compute::Formats::Nested::SERVER], "load_balancers" => [Brightbox::Compute::Formats::Nested::LOAD_BALANCER], "cloud_ips" => [Brightbox::Compute::Formats::Nested::CLOUD_IP], "server_groups" => [Brightbox::Compute::Formats::Nested::SERVER_GROUP], "firewall_policies" => [Brightbox::Compute::Formats::Nested::FIREWALL_POLICY], "images" => [Brightbox::Compute::Formats::Nested::IMAGE], "zones" => [Brightbox::Compute::Formats::Nested::ZONE] } API_CLIENT = { "id" => String, "resource_type" => String, "url" => String, "name" => String, "description" => String, "revoked_at" => Fog::Nullable::String, "secret" => Fog::Nullable::String, "account" => Brightbox::Compute::Formats::Nested::ACCOUNT } APPLICATION = { "id" => String, "resource_type" => String, "url" => String, "name" => Fog::Nullable::String, "secret" => Fog::Nullable::String } CLOUD_IP = { "id" => String, "resource_type" => String, "url" => String, "name" => Fog::Nullable::String, "public_ip" => String, "status" => String, "reverse_dns" => String, "port_translators" => [Brightbox::Compute::Formats::Struct::CIP_PORT_TRANSLATOR], "account" => Fog::Brightbox::Nullable::Account, "interface" => Fog::Brightbox::Nullable::Interface, "load_balancer" => Fog::Brightbox::Nullable::LoadBalancer, "server" => Fog::Brightbox::Nullable::Server, "server_group" => Fog::Brightbox::Nullable::ServerGroup } FIREWALL_POLICY = { "id" => String, "resource_type" => String, "url" => String, "name" => Fog::Nullable::String, "description" => Fog::Nullable::String, "default" => Fog::Boolean, "created_at" => String, "server_group" => Fog::Brightbox::Nullable::ServerGroup, "rules" => [Brightbox::Compute::Formats::Nested::FIREWALL_RULE] } FIREWALL_RULE = { "id" => String, "resource_type" => String, "url" => String, "created_at" => String, "source" => Fog::Nullable::String, "source_port" => Fog::Nullable::String, "destination" => Fog::Nullable::String, "destination_port" => Fog::Nullable::String, "protocol" => Fog::Nullable::String, "icmp_type_name" => Fog::Nullable::String, "description" => Fog::Nullable::String, "firewall_policy" => Brightbox::Compute::Formats::Nested::FIREWALL_POLICY } IMAGE = { "name" => String, "created_at" => String, "resource_type" => String, "arch" => String, "url" => String, "id" => String, "description" => String, "source" => String, "source_type" => String, "status" => String, "owner" => String, # Account ID not object "username" => Fog::Nullable::String, "public" => Fog::Boolean, "official" => Fog::Boolean, "compatibility_mode" => Fog::Boolean, "virtual_size" => Integer, "disk_size" => Integer, "min_ram" => Fog::Nullable::Integer, "ancestor" => Fog::Brightbox::Nullable::Image, "username" => Fog::Nullable::String, "licence_name" => Fog::Nullable::String } INTERFACE = { "resource_type" => String, "url" => String, "id" => String, "ipv4_address" => String, "ipv6_address" => Fog::Nullable::String, "mac_address" => String, "server" => Brightbox::Compute::Formats::Nested::SERVER } LOAD_BALANCER = { "id" => String, "resource_type" => String, "url" => String, "name" => String, "status" => String, "listeners" => [Brightbox::Compute::Formats::Struct::LB_LISTENER], "policy" => String, "healthcheck" => Brightbox::Compute::Formats::Struct::LB_HEALTHCHECK, "certificate" => Fog::Nullable::Hash, "created_at" => String, "deleted_at" => Fog::Nullable::String, "account" => Brightbox::Compute::Formats::Nested::ACCOUNT, "nodes" => [Brightbox::Compute::Formats::Nested::SERVER], "cloud_ips" => [Brightbox::Compute::Formats::Nested::CLOUD_IP] } SERVER = { "id" => String, "resource_type" => String, "url" => String, "name" => String, "status" => String, "hostname" => String, "fqdn" => String, "created_at" => String, "started_at" => Fog::Nullable::String, "deleted_at" => Fog::Nullable::String, "user_data" => Fog::Nullable::String, "console_url" => Fog::Nullable::String, "console_token" => Fog::Nullable::String, "console_token_expires" => Fog::Nullable::String, "account" => Brightbox::Compute::Formats::Nested::ACCOUNT, "server_type" => Brightbox::Compute::Formats::Nested::SERVER_TYPE, "cloud_ips" => [Brightbox::Compute::Formats::Nested::CLOUD_IP], "image" => Brightbox::Compute::Formats::Nested::IMAGE, "snapshots" => [Brightbox::Compute::Formats::Nested::IMAGE], "server_groups" => [Brightbox::Compute::Formats::Nested::SERVER_GROUP], "interfaces" => [Brightbox::Compute::Formats::Nested::INTERFACE], "zone" => Fog::Brightbox::Nullable::Zone, "licence_name" => Fog::Nullable::String, "username" => Fog::Nullable::String, "compatibility_mode" => Fog::Boolean } SERVER_GROUP = { "created_at" => String, "id" => String, "resource_type" => String, "url" => String, "name" => String, "description" => Fog::Nullable::String, "default" => Fog::Boolean, "created_at" => String, "account" => Brightbox::Compute::Formats::Nested::ACCOUNT, "servers" => [Brightbox::Compute::Formats::Nested::SERVER], "firewall_policy" => Fog::Brightbox::Nullable::FirewallPolicy } SERVER_TYPE = { "id" => String, "resource_type" => String, "url" => String, "handle" => Fog::Nullable::String, "name" => String, "status" => String, "cores" => Integer, "ram" => Integer, "disk_size" => Integer } USER = { "id" => String, "resource_type" => String, "url" => String, "name" => String, "email_address" => String, "email_verified" => Fog::Boolean, "accounts" => [Brightbox::Compute::Formats::Nested::ACCOUNT], "default_account" => Fog::Brightbox::Nullable::Account, "ssh_key" => Fog::Nullable::String, "messaging_pref" => Fog::Boolean } COLLABORATION = { "id" => String, "resource_type" => String, "url" => String, "status" => String, "role" => String, "role_label" => String, "email" => Fog::Nullable::String, "user" => Fog::Brightbox::Nullable::User, "account" => Brightbox::Compute::Formats::Nested::ACCOUNT, "inviter" => Brightbox::Compute::Formats::Nested::USER } ZONE = { "id" => String, "resource_type" => String, "url" => String, "handle" => String } end module Collection ACCOUNTS = [Brightbox::Compute::Formats::Collected::ACCOUNT] API_CLIENTS = [Brightbox::Compute::Formats::Collected::API_CLIENT] APPLICATION = [Brightbox::Compute::Formats::Collected::APPLICATION] CLOUD_IPS = [Brightbox::Compute::Formats::Collected::CLOUD_IP] IMAGES = [Brightbox::Compute::Formats::Collected::IMAGE] FIREWALL_POLICIES = [Brightbox::Compute::Formats::Collected::FIREWALL_POLICY] LOAD_BALANCERS = [Brightbox::Compute::Formats::Collected::LOAD_BALANCER] SERVERS = [Brightbox::Compute::Formats::Collected::SERVER] SERVER_GROUPS = [Brightbox::Compute::Formats::Collected::SERVER_GROUP] SERVER_TYPES = [Brightbox::Compute::Formats::Collected::SERVER_TYPE] USERS = [Brightbox::Compute::Formats::Collected::USER] ZONES = [Brightbox::Compute::Formats::Collected::ZONE] COLLABORATIONS = [Brightbox::Compute::Formats::Collected::COLLABORATION] end end end end fog-1.19.0/tests/brightbox/compute/image_selector_tests.rb0000644000004100000410000000532512261242552023752 0ustar www-datawww-dataShindo.tests("Fog::Brightbox::Compute::ImageSelector.new", ["brightbox"]) do sample_images = [ { "id" => "img-00000", "name" => "Ubuntu Lucid 10.04 LTS", "official" => true, "arch" => "i686", "created_at" => "2013-04-30T12:34:56" }, { "id" => "img-11111", "name" => "ubuntu-precise-12.04-amd64-server", "official" => false, "arch" => "i686", "created_at" => "2013-05-01T12:34:56" }, { "id" => "img-22222", "name" => "ubuntu-quantal-12.10-i386-server", "official" => true, "arch" => "i686", "created_at" => "2013-05-01T12:34:56" }, { "id" => "img-33333", "name" => "ubuntu-raring-13.04-amd64-server", "official" => true, "arch" => "amd64", "created_at" => "2013-05-01T12:34:56" }, { "id" => "img-44444", "name" => "Fedora 17 server", "official" => true, "arch" => "i686", "created_at" => "2013-05-01T12:34:56" }, { "id" => "img-ubuntu", "name" => "ubuntu-raring-13.04-i386-server", "official" => true, "arch" => "i686", "created_at" => "2013-05-01T12:34:56" }, ] @image_selector = Fog::Brightbox::Compute::ImageSelector.new(sample_images) test("#respond_to?(:latest_ubuntu)") do @image_selector.respond_to?(:latest_ubuntu) end tests("when there are sample of images") do tests("#latest_ubuntu").returns("img-ubuntu") do @image_selector.latest_ubuntu end end tests("when only old format names are present") do tests("#latest_ubuntu").returns("img-ubuntu") do sample_images = [ { "id" => "img-11111", "name" => "Ubuntu Lucid 10.04 LTS server", "official" => true, "arch" => "i686", "created_at" => "2013-05-01T12:34:56" }, { "id" => "img-22222", "name" => "Ubuntu Quantal 12.10 server", "official" => false, "arch" => "x86_64", "created_at" => "2013-05-01T12:34:56" }, { "id" => "img-ubuntu", "name" => "Ubuntu Quantal 12.10 server", "official" => true, "arch" => "i686", "created_at" => "2013-05-01T12:34:56" }, { "id" => "img-33333", "name" => "Blank disk image", "official" => true, "arch" => "i686", "created_at" => "2013-05-01T12:34:56" } ] @image_selector = Fog::Brightbox::Compute::ImageSelector.new(sample_images) @image_selector.latest_ubuntu end end tests("when ") do tests("#latest_ubuntu").returns(nil) do Fog::Brightbox::Compute::ImageSelector.new([]).latest_ubuntu end end end fog-1.19.0/tests/brightbox/models/0000755000004100000410000000000012261242552017023 5ustar www-datawww-datafog-1.19.0/tests/brightbox/models/compute/0000755000004100000410000000000012261242552020477 5ustar www-datawww-datafog-1.19.0/tests/brightbox/models/compute/server_tests.rb0000644000004100000410000000076712261242552023566 0ustar www-datawww-dataShindo.tests("Fog::Compute[:brightbox] | Server model", ["brightbox"]) do pending if Fog.mocking? tests("success") do @server = Brightbox::Compute::TestSupport.get_test_server server_id = @server.id tests("#dns_name") do returns("public.#{@server.fqdn}") { @server.dns_name } end tests("#mapping_identity") do first_interface_id = @server.interfaces.first["id"] returns(first_interface_id) { @server.mapping_identity } end @server.destroy end end fog-1.19.0/tests/brightbox/models/compute/account_tests.rb0000644000004100000410000000104512261242552023702 0ustar www-datawww-dataShindo.tests("Fog::Compute[:brightbox] | Account model", ["brightbox"]) do pending if Fog.mocking? @account = Fog::Compute[:brightbox].account tests("success") do tests("#reset_ftp_password") do pending if Fog.mocking? test("original ftp password is blanked") { @account.library_ftp_password.nil? } @new_password = @account.reset_ftp_password test("new ftp password was not nil") { !@new_password.nil? } test("new ftp password is set") { @account.library_ftp_password == @new_password } end end end fog-1.19.0/tests/brightbox/oauth2_tests.rb0000644000004100000410000001155612261242552020521 0ustar www-datawww-dataShindo.tests("Fog::Brightbox::OAuth2", ["brightbox"]) do tests("CredentialSet") do @client_id = "app-12345" @client_secret = "__mashed_keys_123__" @username = "usr-12345" @password = "__mushed_keys_321__" @access_token = "12efde32fdfe4989" @refresh_token = "7894389f9074f071" @expires_in = 7200 tests("with client credentials") do credentials = Fog::Brightbox::OAuth2::CredentialSet.new(@client_id, @client_secret) tests("#user_details?").returns(false) { credentials.user_details? } tests("#access_token?").returns(false) { credentials.access_token? } tests("#refresh_token?").returns(false) { credentials.refresh_token? } tests("#best_grant_strategy").returns(true) do credentials.best_grant_strategy.is_a?(Fog::Brightbox::OAuth2::ClientCredentialsStrategy) end end tests("with user credentials") do options = {:username => @username, :password => @password} credentials = Fog::Brightbox::OAuth2::CredentialSet.new(@client_id, @client_secret, options) tests("#user_details?").returns(true) { credentials.user_details? } tests("#access_token?").returns(false) { credentials.access_token? } tests("#refresh_token?").returns(false) { credentials.refresh_token? } tests("#best_grant_strategy").returns(true) do credentials.best_grant_strategy.is_a?(Fog::Brightbox::OAuth2::UserCredentialsStrategy) end end tests("with existing tokens") do options = { :username => @username, :access_token => @access_token, :refresh_token => @refresh_token, :expires_in => @expires_in } credentials = Fog::Brightbox::OAuth2::CredentialSet.new(@client_id, @client_secret, options) tests("#user_details?").returns(false) { credentials.user_details? } tests("#access_token?").returns(true) { credentials.access_token? } tests("#refresh_token?").returns(true) { credentials.refresh_token? } tests("#expires_in").returns(7200) { credentials.expires_in } tests("#best_grant_strategy").returns(true) do credentials.best_grant_strategy.is_a?(Fog::Brightbox::OAuth2::RefreshTokenStrategy) end end end tests("GrantTypeStrategy") do credentials = Fog::Brightbox::OAuth2::CredentialSet.new(@client_id, @client_secret) strategy = Fog::Brightbox::OAuth2::GrantTypeStrategy.new(credentials) tests("#respond_to? :authorization_body_data").returns(true) do strategy.respond_to?(:authorization_body_data) end end tests("ClientCredentialsStrategy") do credentials = Fog::Brightbox::OAuth2::CredentialSet.new(@client_id, @client_secret) strategy = Fog::Brightbox::OAuth2::ClientCredentialsStrategy.new(credentials) tests("#respond_to? :authorization_body_data").returns(true) do strategy.respond_to?(:authorization_body_data) end tests("#authorization_body_data") do authorization_body_data = strategy.authorization_body_data test("grant_type == none") { authorization_body_data["grant_type"] == "none" } test("client_id == #{@client_id}") { authorization_body_data["client_id"] == @client_id } end end tests("UserCredentialsStrategy") do options = {:username => @username, :password => @password} credentials = Fog::Brightbox::OAuth2::CredentialSet.new(@client_id, @client_secret, options) strategy = Fog::Brightbox::OAuth2::UserCredentialsStrategy.new(credentials) tests("#respond_to? :authorization_body_data").returns(true) do strategy.respond_to?(:authorization_body_data) end tests("#authorization_body_data") do authorization_body_data = strategy.authorization_body_data test("grant_type == password") { authorization_body_data["grant_type"] == "password" } test("client_id == #{@client_id}") { authorization_body_data["client_id"] == @client_id } test("username == #{@username}") { authorization_body_data["username"] == @username } test("password == #{@password}") { authorization_body_data["password"] == @password } end end tests("RefreshTokenStrategy") do refresh_token = "ab4b39dddf909" options = {:refresh_token => refresh_token} credentials = Fog::Brightbox::OAuth2::CredentialSet.new(@client_id, @client_secret, options) strategy = Fog::Brightbox::OAuth2::RefreshTokenStrategy.new(credentials) tests("#respond_to? :authorization_body_data").returns(true) do strategy.respond_to?(:authorization_body_data) end tests("#authorization_body_data") do authorization_body_data = strategy.authorization_body_data test("grant_type == refresh_token") { authorization_body_data["grant_type"] == "refresh_token" } test("client_id == #{@client_id}") { authorization_body_data["client_id"] == @client_id } test("refresh_token == #{refresh_token}") { authorization_body_data["refresh_token"] == refresh_token } end end end fog-1.19.0/RELEASE.md0000644000004100000410000000242112261242551014006 0ustar www-datawww-data# Release process This is fog's current release process, documented so people know what is currently done. ## Versioning fog uses semantic versioning (http://semver.org/) ## When we release Releases occur monthly and are manually handled by fog's Benevolent Dictator Wes (@geemus). To request a new release please raise an issue. ## Prepare the release * Ensure the code is passing on the CI server [![Build Status](https://secure.travis-ci.org/fog/fog.png?branch=master)](http://travis-ci.org/fog/fog) * Ensure the code is passing for live tests (Requires Credentials for all services) * Ensure working on **master** * Update the version number (`lib/fog/version.rb`) * Run `rake changelog` to update `changelog.txt` * Run `rake release` to prepare the release which does: * Prepares the release (`rake release:prepare`) * Builds the gem * Tags the commit * Creates commits for version * Publishes the release (`rake release:publish`) * Pushes commit and tag to Github (Requires Credentials) * Pushes gem to Rubygems (Requires Credentials) ## Announce the release Once the release is prepared and uploaded it needs to be announced. * Send an email to https://groups.google.com/forum/?fromgroups#!forum/ruby-fog * Tweet as @fog on Twitter (Requires Credentials) fog-1.19.0/.irbrc0000644000004100000410000000426712261242551013520 0ustar www-datawww-data## This is primarily used for easier testing and development or # usage of Fog. # # How to use: # 1. Add this at the end of your `.irbrc` in your home directory. # # @working_directory = Dir.pwd # @local_irbrc = File.join(@working_directory, '.irbrc') # # if @working_directory != ENV['HOME'] # load @local_irbrc if File.exists?(@local_irbrc) # end # # remove_instance_variable(:@working_directory) # remove_instance_variable(:@local_irbrc) # # 2. Inside the Fog execute `bundle exec irb` # require 'fog' class ConnectionManager < Hash def [](key) $connection_manager_previous_key = key super(key) end def []=(key, value) $connection_manager_previous_key = key super(key, value) end end def connections return @connections if @connections @connections = ConnectionManager.new end def connection connections[$connection_manager_previous_key] end def connect_openstack(username, password, tenant = nil, url = 'http://192.168.27.100:35357/') parameters = { :provider => 'openstack', :openstack_api_key => password, :openstack_username => username, :openstack_auth_url => "#{url}v2.0/tokens" } parameters.merge!(:openstack_tenant => tenant) if tenant key = username.to_sym set_service(key, Fog::Identity, parameters) set_service(key, Fog::Compute, parameters) set_service(key, Fog::Volume, parameters) set_service(key, Fog::Image, parameters) end def connect(parameters) connections_count = connections.count connections[connections_count] = Hash.new set_service(connections_count, Fog::Identity, parameters) set_service(connections_count, Fog::Compute , parameters) set_service(connections_count, Fog::Storage , parameters) set_service(connections_count, Fog::Volume , parameters) set_service(connections_count, Fog::Image , parameters) set_service(connections_count, Fog::DNS , parameters) set_service(connections_count, Fog::CDN , parameters) connection end def set_service(connections_count, type, parameters) service_symbol = type.to_s.split('::').last.downcase.to_sym connections[connections_count].merge!({ service_symbol => type.new(parameters) }) rescue # Service not available end fog-1.19.0/LICENSE.md0000644000004100000410000000210512261242551014007 0ustar www-datawww-dataCopyright (c) 2013 [geemus (Wesley Beary)](http://github.com/geemus) 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-1.19.0/.travis.yml0000644000004100000410000000161112261242551014515 0ustar www-datawww-datalanguage: ruby gemfile: - Gemfile - Gemfile.1.8.7 rvm: - 1.8.7 - 1.9.2 - 1.9.3 - 2.0.0 - jruby-18mode - jruby-19mode - jruby-head script: bundle exec rake travis matrix: exclude: - rvm: 1.8.7 gemfile: Gemfile - rvm: 1.9.2 gemfile: Gemfile.1.8.7 - rvm: 1.9.3 gemfile: Gemfile.1.8.7 - rvm: 2.0.0 gemfile: Gemfile.1.8.7 - rvm: jruby-18mode gemfile: Gemfile - rvm: jruby-19mode gemfile: Gemfile.1.8.7 - rvm: jruby-head gemfile: Gemfile.1.8.7 allow_failures: - rvm: jruby-head notifications: email: false irc: channels: - "irc.freenode.org#ruby-fog" template: - "[#%{build_number}] %{message} %{build_url}" - "[#%{build_number}] %{commit} on %{branch} by %{author}" - "[#%{build_number}] %{compare_url}" on_success: always on_failure: always use_notice: false fog-1.19.0/lib/0000755000004100000410000000000012261242552013154 5ustar www-datawww-datafog-1.19.0/lib/fog/0000755000004100000410000000000012261242552013727 5ustar www-datawww-datafog-1.19.0/lib/fog/digitalocean/0000755000004100000410000000000012261242551016351 5ustar www-datawww-datafog-1.19.0/lib/fog/digitalocean/examples/0000755000004100000410000000000012261242551020167 5ustar www-datawww-datafog-1.19.0/lib/fog/digitalocean/examples/getting_started.md0000644000004100000410000000444512261242551023707 0ustar www-datawww-data# Getting started: the compute service You'll need a DigitalOcean account and API key to use this provider. Get one from http://www.digitalocean.com. To generate the API key, login to the DigitalOcean web panel and go to 'My Settings -> API Access -> Generate a new API key'. Write down the Client Key and API Key, you'll need both to use the service. ## Connecting, retrieving and managing server objects Before we start, I guess it will be useful to the reader to know that Fog servers are 'droplets' in DigitalOcean's parlance. 'Server' is the Fog way to name VMs, and we have respected that in the DigitalOcean's Fog provider. First, create a connection to the host: ```ruby require 'fog' docean = Fog::Compute.new({ :provider => 'DigitalOcean', :digitalocean_api_key => 'poiuweoruwoeiuroiwuer', # your API key here :digitalocean_client_id => 'lkjasoidfuoiu' # your client key here }) ``` ## Listing servers Listing servers and attributes: ```ruby docean.servers.each do |server| # remember, servers are droplets server.id server.name server.state server.backups_enabled server.image_id server.flavor_id # server 'size' in DigitalOcean's API parlance server.region_id end ``` ## Server creation and life-cycle management Creating a new server (droplet): ```ruby server = docean.servers.create :name => 'foobar', # use the first image listed :image_id => docean.images.first.id, # use the first flavor listed :flavor_id => docean.flavors.first.id, # use the first region listed :region_id => docean.regions.first.id ``` The server is automatically started after that. We didn't pay attention when choosing the flavor, image and region used but you can easily list them too, and then decide: ```ruby docean.images.each do |image| image.id image.name image.distribution end docean.flavors.each do |flavor| flavor.id flavor.name end docean.regions.each do |region| region.id region.name end ``` Rebooting a server: ```ruby server = docean.servers.first server.reboot ``` Power cycle a server: ```ruby server.power_cycle ``` Destroying the server: ```ruby server.destroy ``` fog-1.19.0/lib/fog/digitalocean/requests/0000755000004100000410000000000012261242551020224 5ustar www-datawww-datafog-1.19.0/lib/fog/digitalocean/requests/compute/0000755000004100000410000000000012261242551021700 5ustar www-datawww-datafog-1.19.0/lib/fog/digitalocean/requests/compute/power_cycle_server.rb0000644000004100000410000000130312261242551026123 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real def power_cycle_server( id ) request( :expects => [200], :method => 'GET', :path => "droplets/#{id}/power_cycle" ) end end class Mock def power_cycle_server( id ) response = Excon::Response.new response.status = 200 server = self.data[:servers].find { |s| s['id'] == id } server['status'] = 'off' if server response.body = { "event_id" => Fog::Mock.random_numbers(1).to_i, "status" => "OK" } response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/create_ssh_key.rb0000644000004100000410000000151312261242551025215 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real def create_ssh_key( name, pub_key ) request( :expects => [200], :method => 'GET', :path => 'ssh_keys/new', :query => { 'name' => name, 'ssh_pub_key' => pub_key } ) end end class Mock def create_ssh_key( name, pub_key ) response = Excon::Response.new response.status = 200 mock_data = { "id" => Fog::Mock.random_numbers(1).to_i, "name" => name, "ssh_pub_key" => pub_key } response.body = { "status" => "OK", "ssh_key" => mock_data } self.data[:ssh_keys] << mock_data response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/list_flavors.rb0000644000004100000410000000145512261242551024741 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real def list_flavors(options = {}) request( :expects => [200], :method => 'GET', :path => 'sizes' ) end end class Mock def list_flavors response = Excon::Response.new response.status = 200 response.body = { "status" => "OK", "sizes" => [ {"id" => 33,"name" => "512MB"}, {"id" => 34,"name" => "1GB"}, {"id" => 35,"name" => "2GB"}, {"id" => 36,"name" => "4GB"}, {"id" => 37,"name" => "8GB"}, {"id" => 38,"name" => "16GB"} ] } response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/destroy_server.rb0000644000004100000410000000131512261242551025304 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real # # FIXME: missing ssh keys support # def destroy_server( id ) request( :expects => [200], :method => 'GET', :path => "droplets/#{id}/destroy" ) end end class Mock def destroy_server( id ) response = Excon::Response.new response.status = 200 response.body = { "event_id" => Fog::Mock.random_numbers(1).to_i, "status" => "OK" } server = self.data[:servers].reject! { |s| s['id'] == id } response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/list_ssh_keys.rb0000644000004100000410000000106012261242551025105 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real def list_ssh_keys(options = {}) request( :expects => [200], :method => 'GET', :path => 'ssh_keys' ) end end class Mock def list_ssh_keys response = Excon::Response.new response.status = 200 response.body = { "status" => "OK", "ssh_keys" => self.data[:ssh_keys] } response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/power_on_server.rb0000644000004100000410000000126712261242551025451 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real def power_on_server( id ) request( :expects => [200], :method => 'GET', :path => "droplets/#{id}/power_on" ) end end class Mock def power_on_server( id ) response = Excon::Response.new response.status = 200 server = self.data[:servers].find { |s| s['id'] } server['status'] = 'active' if server response.body = { "event_id" => Fog::Mock.random_numbers(1).to_i, "status" => "OK" } response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/list_images.rb0000644000004100000410000000200312261242551024520 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real def list_images(options = {}) request( :expects => [200], :method => 'GET', :path => 'images' ) end end class Mock def list_images response = Excon::Response.new response.status = 200 response.body = { "status" => "OK", "images" => [ # Sample image { "id" => 1601, "name" => "CentOS 5.8 x64", "distribution" => "CentOS" }, { "id" => 1602, "name" => "CentOS 5.8 x32", "distribution" => "CentOS" }, { "id" => 2676, "name" => "Ubuntu 12.04 x64", "distribution" => "Ubuntu" }, ] } response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/shutdown_server.rb0000644000004100000410000000133012261242551025463 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real def shutdown_server( id ) request( :expects => [200], :method => 'GET', :path => "droplets/#{id}/shutdown" ) end end class Mock def shutdown_server( id ) response = Excon::Response.new response.status = 200 server = self.data[:servers].find { |s| s['id'] == id } # Simulate reboot server['status'] = 'off' if server response.body = { "event_id" => Fog::Mock.random_numbers(1).to_i, "status" => "OK" } response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/power_off_server.rb0000644000004100000410000000126712261242551025607 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real def power_off_server( id ) request( :expects => [200], :method => 'GET', :path => "droplets/#{id}/power_off" ) end end class Mock def power_off_server( id ) response = Excon::Response.new response.status = 200 server = self.data[:servers].find { |s| s['id'] } server['status'] = 'off' if server response.body = { "event_id" => Fog::Mock.random_numbers(1).to_i, "status" => "OK" } response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/get_ssh_key.rb0000644000004100000410000000157312261242551024537 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real # # This method shows a specific public SSH key in your account # that can be added to a droplet. # # @see https://www.digitalocean.com/api#ssh_keys # def get_ssh_key(id) request( :expects => [200], :method => 'GET', :path => "ssh_keys/#{id}" ) end end class Mock def get_ssh_key(id) response = Excon::Response.new response.status = 200 response.body = { "status" => "OK", # key listing does not return ssh_pub_key # https://www.digitalocean.com/api#ssh_keys "ssh_key" => self.data[:ssh_keys].find { |k| k['id'] == id } } response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/list_servers.rb0000644000004100000410000000105512261242551024752 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real def list_servers(options = {}) request( :expects => [200], :method => 'GET', :path => 'droplets' ) end end class Mock def list_servers response = Excon::Response.new response.status = 200 response.body = { "status" => "OK", "droplets" => self.data[:servers] } response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/list_regions.rb0000644000004100000410000000121312261242551024723 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real def list_regions(options = {}) request( :expects => [200], :method => 'GET', :path => 'regions' ) end end class Mock def list_regions response = Excon::Response.new response.status = 200 response.body = { "status" => "OK", "regions" => [ {"id" => 1,"name" => "New York 1"}, {"id" => 2,"name" => "Amsterdam 1"} ] } response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/create_server.rb0000644000004100000410000000346312261242551025064 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real # # FIXME: missing ssh keys support # def create_server( name, size_id, image_id, region_id, options = {} ) query_hash = { :name => name, :size_id => size_id, :image_id => image_id, :region_id => region_id } if options[:ssh_key_ids] options[:ssh_key_ids] = options[:ssh_key_ids].join(",") if options[:ssh_key_ids].is_a? Array query_hash[:ssh_key_ids] = options[:ssh_key_ids] end query_hash[:private_networking] = !!options[:private_networking] request( :expects => [200], :method => 'GET', :path => 'droplets/new', :query => query_hash ) end end class Mock def create_server( name, size_id, image_id, region_id, options = {} ) response = Excon::Response.new response.status = 200 mock_data = { "id" => Fog::Mock.random_numbers(1).to_i, "event_id" => Fog::Mock.random_numbers(2).to_i, "name" => name, "size_id" => size_id, "image_id" => image_id, "region_id" => region_id, "ip_address" => "127.0.0.1", "status" => 'active' } response.body = { "status" => "OK", "droplet" => mock_data } self.data[:servers] << mock_data response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/reboot_server.rb0000644000004100000410000000126412261242551025110 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real def reboot_server( id ) request( :expects => [200], :method => 'GET', :path => "droplets/#{id}/reboot" ) end end class Mock def reboot_server( id ) response = Excon::Response.new response.status = 200 server = self.data[:servers].find { |s| s['id'] == id } server['status'] = 'off' if server response.body = { "event_id" => Fog::Mock.random_numbers(1).to_i, "status" => "OK" } response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/get_server_details.rb0000644000004100000410000000127212261242551026101 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real def get_server_details(server_id) request( :expects => [200], :method => 'GET', :path => "droplets/#{server_id}" ) end end class Mock def get_server_details(server_id) response = Excon::Response.new response.status = 200 server = self.data[:servers].find { |s| s['id'] == server_id } response.body = { "status" => "OK", "droplet" => self.data[:servers].find { |s| s['id'] == server_id } } response end end end end end fog-1.19.0/lib/fog/digitalocean/requests/compute/destroy_ssh_key.rb0000644000004100000410000000142312261242551025443 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class Real # # Delete a SSH public key from your account # # @see https://www.digitalocean.com/api#ssh_keys # def destroy_ssh_key(id) request( :expects => [200], :method => 'GET', :path => "ssh_keys/#{id}/destroy" ) end end class Mock def destroy_ssh_key(id) response = Excon::Response.new response.status = 200 if self.data[:ssh_keys].reject! { |k| k['id'] == id } response.body = { "status" => "OK" } else response.body = { "status" => "ERROR" } end response end end end end end fog-1.19.0/lib/fog/digitalocean/models/0000755000004100000410000000000012261242551017634 5ustar www-datawww-datafog-1.19.0/lib/fog/digitalocean/models/compute/0000755000004100000410000000000012261242551021310 5ustar www-datawww-datafog-1.19.0/lib/fog/digitalocean/models/compute/regions.rb0000644000004100000410000000070412261242551023304 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/digitalocean/models/compute/region' module Fog module Compute class DigitalOcean class Regions < Fog::Collection model Fog::Compute::DigitalOcean::Region def all load service.list_regions.body['regions'] end def get(id) all.find { |f| f.id == id } rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/digitalocean/models/compute/images.rb0000644000004100000410000000067712261242551023114 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/digitalocean/models/compute/image' module Fog module Compute class DigitalOcean class Images < Fog::Collection model Fog::Compute::DigitalOcean::Image def all load service.list_images.body['images'] end def get(id) all.find { |f| f.id == id } rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/digitalocean/models/compute/servers.rb0000644000004100000410000000273012261242551023330 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/digitalocean/models/compute/server' module Fog module Compute class DigitalOcean class Servers < Fog::Collection model Fog::Compute::DigitalOcean::Server def all(filters = {}) data = service.list_servers.body['droplets'] load(data) end def bootstrap(new_attributes = {}) server = new(new_attributes) raise(ArgumentError, "public_key_path is required to configure the server.") unless new_attributes[:public_key_path] raise(ArgumentError, "private_key_path is required to configure the server.") unless new_attributes[:private_key_path] credential = Fog.respond_to?(:credential) && Fog.credential || :default name = "fog_#{credential}" ssh_key = service.ssh_keys.detect { |key| key.name == name } if ssh_key.nil? ssh_key = service.ssh_keys.create( :name => name, :ssh_pub_key => File.read(new_attributes[:public_key_path]) ) end server.ssh_keys = [ssh_key] server.save server.wait_for { ready? } server.setup :keys => [new_attributes[:private_key_path]] server end def get(id) server = service.get_server_details(id).body['droplet'] new(server) if server rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/digitalocean/models/compute/ssh_key.rb0000644000004100000410000000072712261242551023310 0ustar www-datawww-datamodule Fog module Compute class DigitalOcean class SshKey < Fog::Model identity :id attribute :name attribute :ssh_pub_key def save requires :name, :ssh_pub_key merge_attributes(service.create_ssh_key(name, ssh_pub_key).body['ssh_key']) true end def destroy requires :id service.destroy_ssh_key id true end end end end end fog-1.19.0/lib/fog/digitalocean/models/compute/flavors.rb0000644000004100000410000000070212261242551023310 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/digitalocean/models/compute/flavor' module Fog module Compute class DigitalOcean class Flavors < Fog::Collection model Fog::Compute::DigitalOcean::Flavor def all load service.list_flavors.body['sizes'] end def get(id) all.find { |f| f.id == id } rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/digitalocean/models/compute/ssh_keys.rb0000644000004100000410000000100012261242551023454 0ustar www-datawww-datarequire 'fog/digitalocean/models/compute/ssh_key' module Fog module Compute class DigitalOcean class SshKeys < Fog::Collection identity :href model Fog::Compute::DigitalOcean::SshKey def all data = service.list_ssh_keys.body['ssh_keys'] load(data) end def get(uri) data = service.get_ssh_key(uri).body['ssh_key'] new(data) rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/digitalocean/models/compute/region.rb0000644000004100000410000000030112261242551023112 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class DigitalOcean class Region < Fog::Model identity :id attribute :name end end end end fog-1.19.0/lib/fog/digitalocean/models/compute/flavor.rb0000644000004100000410000000030112261242551023120 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class DigitalOcean class Flavor < Fog::Model identity :id attribute :name end end end end fog-1.19.0/lib/fog/digitalocean/models/compute/server.rb0000644000004100000410000001343212261242551023146 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class DigitalOcean # A DigitalOcean Droplet # class Server < Fog::Compute::Server identity :id attribute :name attribute :state, :aliases => 'status' attribute :image_id attribute :region_id attribute :flavor_id, :aliases => 'size_id' # Not documented in their API, but # available nevertheless attribute :public_ip_address, :aliases => 'ip_address' attribute :private_ip_address attribute :backups_active attr_writer :ssh_keys # Deprecated: Use public_ip_address instead. def ip_address Fog::Logger.warning("ip_address has been deprecated. Use public_ip_address instead") public_ip_address end # Reboot the server (soft reboot). # # The preferred method of rebooting a server. def reboot requires :id service.reboot_server self.id end # Reboot the server (hard reboot). # # Powers the server off and then powers it on again. def power_cycle requires :id service.power_cycle_server self.id end # Shutdown the server # # Sends a shutdown signal to the operating system. # The server consumes resources while powered off # so you are still charged. # # @see https://www.digitalocean.com/community/questions/am-i-charged-while-my-droplet-is-in-a-powered-off-state def shutdown requires :id service.shutdown_server self.id end # Power off the server # # Works as a power switch. # The server consumes resources while powered off # so you are still charged. # # @see https://www.digitalocean.com/community/questions/am-i-charged-while-my-droplet-is-in-a-powered-off-state def stop requires :id service.power_off_server self.id end # Power on the server. # # The server consumes resources while powered on # so you will be charged. # # Each time a server is spun up, even if for a few seconds, # it is charged for an hour. # def start requires :id service.power_on_server self.id end def setup(credentials = {}) requires :public_ip_address require 'net/ssh' commands = [ %{mkdir .ssh}, %{passwd -l #{username}}, %{echo "#{Fog::JSON.encode(Fog::JSON.sanitize(attributes))}" >> ~/attributes.json} ] if public_key commands << %{echo "#{public_key}" >> ~/.ssh/authorized_keys} end # wait for aws to be ready wait_for { sshable?(credentials) } Fog::SSH.new(public_ip_address, username, credentials).run(commands) end # Creates the server (not to be called directly). # # Usually called by Fog::Collection#create # # docean = Fog::Compute.new({ # :provider => 'DigitalOcean', # :digitalocean_api_key => 'key-here', # your API key here # :digitalocean_client_id => 'client-id-here' # your client key here # }) # docean.servers.create :name => 'foobar', # :image_id => image_id_here, # :flavor_id => flavor_id_here, # :region_id => region_id_here # # @return [Boolean] def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :name, :flavor_id, :image_id, :region_id options = {} if attributes[:ssh_key_ids] options[:ssh_key_ids] = attributes[:ssh_key_ids] elsif @ssh_keys options[:ssh_key_ids] = @ssh_keys.map(&:id) end options[:private_networking] = !!attributes[:private_networking] data = service.create_server name, flavor_id, image_id, region_id, options merge_attributes(data.body['droplet']) true end # Destroy the server, freeing up the resources. # # DigitalOcean will stop charging you for the resources # the server was using. # # Once the server has been destroyed, there's no way # to recover it so the data is irrecoverably lost. # # IMPORTANT: As of 2013/01/31, you should wait some time to # destroy the server after creating it. If you try to destroy # the server too fast, the destroy event may be lost and the # server will remain running and consuming resources, so # DigitalOcean will keep charging you. # Double checked this with DigitalOcean staff and confirmed # that it's the way it works right now. # # Double check the server has been destroyed! def destroy requires :id service.destroy_server id end # Checks whether the server status is 'active'. # # The server transitions from 'new' to 'active' sixty to ninety # seconds after creating it (time varies and may take more # than 90 secs). # # @return [Boolean] def ready? state == 'active' end # DigitalOcean API does not support updating server state def update msg = 'DigitalOcean servers do not support updates' raise NotImplementedError.new(msg) end end end end end fog-1.19.0/lib/fog/digitalocean/models/compute/image.rb0000644000004100000410000000034012261242551022714 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class DigitalOcean class Image < Fog::Model identity :id attribute :name attribute :distribution end end end end fog-1.19.0/lib/fog/digitalocean/CHANGELOG.md0000644000004100000410000000023412261242551020161 0ustar www-datawww-data# 1.10.1 2013/04/04 * Initial release Getting started example: https://github.com/fog/fog/blob/master/lib/fog/digitalocean/examples/getting_started.md fog-1.19.0/lib/fog/digitalocean/compute.rb0000644000004100000410000000676112261242551020364 0ustar www-datawww-datarequire 'fog/digitalocean' require 'fog/compute' module Fog module Compute class DigitalOcean < Fog::Service requires :digitalocean_api_key requires :digitalocean_client_id recognizes :digitalocean_api_url model_path 'fog/digitalocean/models/compute' model :server collection :servers model :flavor collection :flavors model :image collection :images model :region collection :regions model :ssh_key collection :ssh_keys request_path 'fog/digitalocean/requests/compute' request :list_servers request :list_images request :list_regions request :list_flavors request :get_server_details request :create_server request :destroy_server request :reboot_server request :power_cycle_server request :power_off_server request :power_on_server request :shutdown_server request :list_ssh_keys request :create_ssh_key request :get_ssh_key request :destroy_ssh_key # request :digitalocean_resize class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = { :servers => [], :ssh_keys => [] } end end def self.reset @data = nil end def initialize(options={}) @digitalocean_api_key = options[:digitalocean_api_key] end def data self.class.data[@digitalocean_api_key] end def reset_data self.class.data.delete(@digitalocean_api_key) end end class Real def initialize(options={}) @digitalocean_api_key = options[:digitalocean_api_key] @digitalocean_client_id = options[:digitalocean_client_id] @digitalocean_api_url = options[:digitalocean_api_url] || \ "https://api.digitalocean.com" @connection = Fog::Connection.new(@digitalocean_api_url) end def reload @connection.reset end def request(params) params[:query] ||= {} params[:query].merge!(:api_key => @digitalocean_api_key) params[:query].merge!(:client_id => @digitalocean_client_id) response = retry_event_lock { parse @connection.request(params) } unless response.body.empty? if response.body['status'] != 'OK' case response.body['error_message'] when /No Droplets Found/ raise Fog::Errors::NotFound.new else raise Fog::Errors::Error.new response.body.to_s end end end response end private def parse(response) return response if response.body.empty? response.body = Fog::JSON.decode(response.body) response end def retry_event_lock count = 0 reponse = nil while count < 5 response = yield if response.body && response.body['error_message'] =~ /There is already a pending event for the droplet/ count += 1 sleep count ** 3 else break end end response end end end end end fog-1.19.0/lib/fog/digitalocean.rb0000644000004100000410000000022212261242551016672 0ustar www-datawww-datarequire 'fog/core' module Fog module DigitalOcean extend Fog::Provider service(:compute, 'digitalocean/compute', 'Compute') end end fog-1.19.0/lib/fog/bin/0000755000004100000410000000000012261242551014476 5ustar www-datawww-datafog-1.19.0/lib/fog/bin/digitalocean.rb0000644000004100000410000000134712261242551017453 0ustar www-datawww-dataclass DigitalOcean < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::DigitalOcean else raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("DigitalOcean[:compute] is not recommended, use Compute[:digitalocean] for portability") Fog::Compute.new(:provider => 'DigitalOcean') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::DigitalOcean.services end end end fog-1.19.0/lib/fog/bin/brightbox.rb0000644000004100000410000000141612261242551017015 0ustar www-datawww-dataclass Brightbox < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Brightbox else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("Brightbox[:compute] is not recommended, use Compute[:brightbox] for portability") Fog::Compute.new(:provider => 'Brightbox') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def account @@connections[:compute].account end def services Fog::Brightbox.services end end end fog-1.19.0/lib/fog/bin/aws.rb0000644000004100000410000000657112261242551015626 0ustar www-datawww-dataclass AWS < Fog::Bin class << self def class_for(key) case key when :auto_scaling Fog::AWS::AutoScaling when :beanstalk Fog::AWS::ElasticBeanstalk when :cdn Fog::CDN::AWS when :cloud_formation Fog::AWS::CloudFormation when :cloud_watch Fog::AWS::CloudWatch when :compute Fog::Compute::AWS when :data_pipeline Fog::AWS::DataPipeline when :ddb, :dynamodb Fog::AWS::DynamoDB when :dns Fog::DNS::AWS when :elasticache Fog::AWS::Elasticache when :elb Fog::AWS::ELB when :emr Fog::AWS::EMR when :glacier Fog::AWS::Glacier when :iam Fog::AWS::IAM when :redshift Fog::AWS::Redshift when :sdb, :simpledb Fog::AWS::SimpleDB when :ses Fog::AWS::SES when :sqs Fog::AWS::SQS when :eu_storage, :storage Fog::Storage::AWS when :rds Fog::AWS::RDS when :sns Fog::AWS::SNS when :sts Fog::AWS::STS else # @todo Replace most instances of ArgumentError with NotImplementedError # @todo For a list of widely supported Exceptions, see: # => http://www.zenspider.com/Languages/Ruby/QuickRef.html#35 raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :auto_scaling Fog::AWS::AutoScaling.new when :beanstalk Fog::AWS::ElasticBeanstalk.new when :cdn Fog::Logger.warning("AWS[:cdn] is not recommended, use CDN[:aws] for portability") Fog::CDN.new(:provider => 'AWS') when :cloud_formation Fog::AWS::CloudFormation.new when :cloud_watch Fog::AWS::CloudWatch.new when :compute Fog::Logger.warning("AWS[:compute] is not recommended, use Compute[:aws] for portability") Fog::Compute.new(:provider => 'AWS') when :data_pipeline Fog::AWS::DataPipeline when :ddb, :dynamodb Fog::AWS::DynamoDB.new when :dns Fog::Logger.warning("AWS[:dns] is not recommended, use DNS[:aws] for portability") Fog::DNS.new(:provider => 'AWS') when :elasticache Fog::AWS::Elasticache.new when :elb Fog::AWS::ELB.new when :emr Fog::AWS::EMR.new when :glacier Fog::AWS::Glacier.new when :iam Fog::AWS::IAM.new when :redshift Fog::AWS::Redshift.new when :rds Fog::AWS::RDS.new when :eu_storage Fog::Storage.new(:provider => 'AWS', :region => 'eu-west-1') when :sdb, :simpledb Fog::AWS::SimpleDB.new when :ses Fog::AWS::SES.new when :sqs Fog::AWS::SQS.new when :storage Fog::Logger.warning("AWS[:storage] is not recommended, use Storage[:aws] for portability") Fog::Storage.new(:provider => 'AWS') when :sns Fog::AWS::SNS.new when :sts Fog::AWS::STS.new else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::AWS.services end end end fog-1.19.0/lib/fog/bin/dreamhost.rb0000644000004100000410000000126612261242551017016 0ustar www-datawww-dataclass Dreamhost < Fog::Bin class << self def class_for(key) case key when :dns Fog::DNS::Dreamhost else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :dns Fog::Logger.warning("Dreamhost[:dns] is not recommended, use DNS[:dreamhost] for portability") Fog::DNS.new(:provider => 'Dreamhost') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Dreamhost.services end end end fog-1.19.0/lib/fog/bin/voxel.rb0000644000004100000410000000126612261242551016165 0ustar www-datawww-dataclass Voxel < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Voxel else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("Voxel[:compute] is not recommended, use Compute[:voxel] for portability") Fog::Compute.new(:provider => 'Voxel') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Voxel.services end end end fog-1.19.0/lib/fog/bin/riakcs.rb0000644000004100000410000000074712261242551016307 0ustar www-datawww-dataclass RiakCS < Fog::Bin class << self def class_for(key) case key when :provisioning Fog::RiakCS::Provisioning when :usage Fog::RiakCS::Usage else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = class_for(key) end @@connections[service] end def services Fog::RiakCS.services end end end fog-1.19.0/lib/fog/bin/libvirt.rb0000644000004100000410000000302412261242551016475 0ustar www-datawww-datamodule Libvirt # deviates from other bin stuff to accomodate gem class << self def class_for(key) case key when :compute Fog::Compute::Libvirt else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("Libvirt[:compute] is not recommended, use Compute[:libvirt] for portability") Fog::Compute.new(:provider => 'Libvirt') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def available? begin availability=true unless Gem::Specification::find_by_name("ruby-libvirt").nil? rescue Gem::LoadError availability=false rescue availability_gem=Gem.available?("ruby-libvirt") end if availability for service in services for collection in self.class_for(service).collections unless self.respond_to?(collection) self.class_eval <<-EOS, __FILE__, __LINE__ def self.#{collection} self[:#{service}].#{collection} end EOS end end end end availability end def collections services.map {|service| self[service].collections}.flatten.sort_by {|service| service.to_s} end def services Fog::Libvirt.services end end end fog-1.19.0/lib/fog/bin/vcloud.rb0000644000004100000410000000112112261242551016312 0ustar www-datawww-dataclass Vcloud < Fog::Bin class << self def class_for(key) case key when :compute Fog::Vcloud::Compute else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Compute.new(:provider => 'Vcloud') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Vcloud.services end end end fog-1.19.0/lib/fog/bin/cloudsigma.rb0000644000004100000410000000125312261242551017153 0ustar www-datawww-dataclass CloudSigma < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::CloudSigma else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Compute.new(:provider => 'CloudSigma') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::CloudSigma.services end end endfog-1.19.0/lib/fog/bin/internet_archive.rb0000644000004100000410000000170412261242551020356 0ustar www-datawww-dataclass InternetArchive < Fog::Bin class << self def class_for(key) case key when :storage Fog::Storage::InternetArchive else # @todo Replace most instances of ArgumentError with NotImplementedError # @todo For a list of widely supported Exceptions, see: # => http://www.zenspider.com/Languages/Ruby/QuickRef.html#35 raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :storage Fog::Logger.warning("InternetArchive[:storage] is not recommended, use Storage[:aws] for portability") Fog::Storage.new(:provider => 'InternetArchive') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::InternetArchive.services end end end fog-1.19.0/lib/fog/bin/go_grid.rb0000644000004100000410000000130412261242551016433 0ustar www-datawww-dataclass GoGrid < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::GoGrid else raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("GoGrid[:compute] is not recommended, use Compute[:gogrid] for portability") Fog::Compute.new(:provider => 'GoGrid') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::GoGrid.services end end end fog-1.19.0/lib/fog/bin/hp.rb0000644000004100000410000000330412261242551015432 0ustar www-datawww-dataclass HP < Fog::Bin class << self def class_for(key) case key when :block_storage Fog::HP::BlockStorage when :block_storage_v2 Fog::HP::BlockStorageV2 when :cdn Fog::CDN::HP when :compute Fog::Compute::HP when :dns Fog::HP::DNS when :lb Fog::HP::LB when :network Fog::HP::Network when :storage Fog::Storage::HP else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :block_storage Fog::Logger.deprecation "HP Cloud Block Storage V1 service will be soon deprecated. Please use `Fog::HP::BlockStorageV2` provider to use latest HP Cloud Block Storage service." Fog::HP::BlockStorage.new when :block_storage_v2 Fog::HP::BlockStorageV2.new when :cdn Fog::Logger.warning("HP[:cdn] is deprecated, use CDN[:hp] instead") Fog::CDN.new(:provider => 'HP') when :compute Fog::Logger.warning("HP[:compute] is deprecated, use Compute[:hp] instead") Fog::Compute.new(:provider => 'HP') when :dns Fog::HP::DNS.new when :lb Fog::HP::LB.new when :network Fog::HP::Network.new when :storage Fog::Logger.warning("HP[:storage] is deprecated, use Storage[:hp] instead") Fog::Storage.new(:provider => 'HP') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::HP.services end end end fog-1.19.0/lib/fog/bin/rackspace.rb0000644000004100000410000000476012261242551016766 0ustar www-datawww-dataclass Rackspace < Fog::Bin class << self def class_for(key) case key when :auto_scale Fog::Rackspace::AutoScale when :block_storage Fog::Rackspace::BlockStorage when :cdn Fog::CDN::Rackspace when :compute Fog::Compute::Rackspace when :compute_v2 Fog::Compute::RackspaceV2 when :storage Fog::Storage::Rackspace when :load_balancers Fog::Rackspace::LoadBalancers when :dns Fog::DNS::Rackspace when :identity Fog::Rackspace::Identity when :databases Fog::Rackspace::Databases when :monitoring Fog::Rackspace::Monitoring when :queues Fog::Rackspace::Queues else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :auto_scale Fog::Rackspace::AutoScale.new when :cdn Fog::Logger.warning("Rackspace[:cdn] is not recommended, use CDN[:rackspace] for portability") Fog::CDN.new(:provider => 'Rackspace') when :compute Fog::Logger.warning("Rackspace[:compute] is not recommended, use Compute[:rackspace] for portability") Fog::Compute.new(:provider => 'Rackspace') when :compute_v2 Fog::Logger.warning("Rackspace[:compute] is not recommended, use Compute[:rackspace] for portability") Fog::Compute.new(:provider => 'Rackspace', :version => 'v2') when :dns Fog::DNS.new(:provider => 'Rackspace') when :load_balancers Fog::Rackspace::LoadBalancers.new when :storage Fog::Logger.warning("Rackspace[:storage] is not recommended, use Storage[:rackspace] for portability") Fog::Storage.new(:provider => 'Rackspace') when :identity Fog::Logger.warning("Rackspace[:identity] is not recommended, use Identity[:rackspace] for portability") Fog::Identity.new(:provider => 'Rackspace') when :databases Fog::Rackspace::Databases.new when :block_storage Fog::Rackspace::BlockStorage.new when :monitoring Fog::Rackspace::Monitoring.new when :queues Fog::Rackspace::Queues.new else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Rackspace.services end end end fog-1.19.0/lib/fog/bin/ibm.rb0000644000004100000410000000127712261242551015601 0ustar www-datawww-dataclass IBM < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::IBM when :storage Fog::Storage::IBM else raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Compute.new(:provider => 'IBM') when :storage Fog::Storage.new(:provider => 'Storage') else raise ArgumentError, "Unrecognized service: #{service}" end end @@connections[service] end def services Fog::IBM.services end end end fog-1.19.0/lib/fog/bin/terremark.rb0000644000004100000410000000131012261242551017012 0ustar www-datawww-dataclass Terremark < Fog::Bin class << self def available? Fog::Terremark::VCLOUD_OPTIONS.all? {|requirement| Fog.credentials.include?(requirement)} end def terremark_service(service) case service when :vcloud Fog::Terremark::Vcloud else raise "Unsupported Terremark Service" end end def [](service) @@connections ||= Hash.new do |hash, key| credentials = Fog.credentials.reject do |k,v| case key when :vcloud !Fog::Terremark::VCLOUD_OPTIONS.include?(k) end end hash[key] = terremark_service(key).new(credentials) end @@connections[service] end end end fog-1.19.0/lib/fog/bin/bluebox.rb0000644000004100000410000000167712261242551016476 0ustar www-datawww-dataclass Bluebox < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Bluebox when :dns Fog::DNS::Bluebox when :blb Fog::Bluebox::BLB else raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("Bluebox[:compute] is not recommended, use Compute[:bluebox] for portability") Fog::Compute.new(:provider => 'Bluebox') when :dns Fog::Logger.warning("Bluebox[:dns] is not recommended, use DNS[:bluebox] for portability") Fog::DNS.new(:provider => 'Bluebox') else raise ArgumentError, "Unrecognized service: #{service}" end end @@connections[service] end def services Fog::Bluebox.services end end end fog-1.19.0/lib/fog/bin/clodo.rb0000644000004100000410000000130012261242551016115 0ustar www-datawww-dataclass Clodo < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Clodo else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Formatador.display_line("[yellow][WARN] Clodo[:compute] is deprecated, use Compute[:clodo] instead[/]") Fog::Compute.new(:provider => 'Clodo') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Clodo.services end end end fog-1.19.0/lib/fog/bin/zerigo.rb0000644000004100000410000000124512261242551016324 0ustar www-datawww-dataclass Zerigo < Fog::Bin class << self def class_for(key) case key when :dns Fog::DNS::Zerigo else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :dns Fog::Logger.warning("Zerigo[:dns] is not recommended, use DNS[:zerigo] for portability") Fog::DNS.new(:provider => 'Zerigo') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Zerigo.services end end end fog-1.19.0/lib/fog/bin/ecloud.rb0000644000004100000410000000146612261242551016305 0ustar www-datawww-dataclass Ecloud < Fog::Bin class << self def available? Fog::Ecloud::ECLOUD_OPTIONS.all? {|requirement| Fog.credentials.include?(requirement)} end def class_for(key) case key when :compute Fog::Compute::Ecloud else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("Ecloud[:compute] is not recommended, use Compute[:ecloud] for portability") Fog::Compute.new(:provider => 'Ecloud') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Ecloud.services end end end fog-1.19.0/lib/fog/bin/stormondemand.rb0000644000004100000410000000135512261242551017701 0ustar www-datawww-dataclass StormOnDemand < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::StormOnDemand else raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("StormOnDemand[:compute] is not recommended, use Compute[:stormondemand] for portability") Fog::Compute.new(:provider => 'StormOnDemand') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::StormOnDemand.services end end endfog-1.19.0/lib/fog/bin/google.rb0000644000004100000410000000432212261242551016300 0ustar www-datawww-datamodule Google # deviates from other bin stuff to accomodate gem class << self def class_for(key) case key when :compute Fog::Compute::Google when :storage Fog::Storage::Google else raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :storage Fog::Logger.warning("Google[:storage] is not recommended, use Storage[:google] for portability") Fog::Storage.new(:provider => 'Google') when :compute Fog::Logger.warning("Google[:compute] is not recommended, use Compute[:google] for portability") Fog::Compute.new(:provider => 'Google') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def account @@connections[:compute].account end def services Fog::Google.services end # based off of virtual_box.rb def available? # Make sure the gem we use is enabled. availability = if Gem::Specification.respond_to?(:find_all_by_name) !Gem::Specification.find_all_by_name('google-api-client').empty? # newest rubygems else !Gem.source_index.find_name('google-api-client').empty? # legacy end # Then make sure we have all of the requirements for service in services begin service = self.class_for(service) availability &&= service.requirements.all? { |requirement| Fog.credentials.include?(requirement) } rescue ArgumentError => e Fog::Logger.warning(e.message) availability = false rescue => e availability = false end end if availability for service in services for collection in self.class_for(service).collections unless self.respond_to?(collection) self.class_eval <<-EOS, __FILE__, __LINE__ def self.#{collection} self[:#{service}].#{collection} end EOS end end end end availability end end end fog-1.19.0/lib/fog/bin/cloudstack.rb0000644000004100000410000000114112261242551017154 0ustar www-datawww-dataclass Cloudstack < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Cloudstack else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Compute.new(:provider => 'Cloudstack') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Cloudstack.services end end end fog-1.19.0/lib/fog/bin/glesys.rb0000644000004100000410000000127712261242551016340 0ustar www-datawww-dataclass Glesys < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Glesys else raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("Glesys[:compute] is not recommended, use Compute[:glesys] for portability") Fog::Compute.new(:provider => 'Glesys') else raise ArgumentError, "Unrecognized service: #{service}" end end @@connections[service] end def services Fog::Glesys.services end end end fog-1.19.0/lib/fog/bin/vmfusion.rb0000644000004100000410000000302012261242551016664 0ustar www-datawww-datamodule Vmfusion # deviates from other bin stuff to accomodate gem class << self def class_for(key) case key when :compute Fog::Compute::Vmfusion else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("Vmfusion[:compute] is not recommended, use Compute[:vmfusion] for portability") Fog::Compute.new(:provider => 'Vmfusion') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def available? begin availability=true unless Gem::Specification::find_by_name("fission").nil? rescue Gem::LoadError availability=false rescue availability_gem=Gem.available?("fission") end if availability for service in services for collection in self.class_for(service).collections unless self.respond_to?(collection) self.class_eval <<-EOS, __FILE__, __LINE__ def self.#{collection} self[:#{service}].#{collection} end EOS end end end end availability end def collections services.map {|service| self[service].collections}.flatten.sort_by {|service| service.to_s} end def services Fog::Vmfusion.services end end end fog-1.19.0/lib/fog/bin/local.rb0000644000004100000410000000127612261242551016123 0ustar www-datawww-dataclass Local < Fog::Bin class << self def class_for(key) case key when :storage Fog::Storage::Local else raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :storage Fog::Logger.warning("Local[:storage] is not recommended, use Storage[:local] for portability") Fog::Storage.new(:provider => 'Local') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Local.services end end end fog-1.19.0/lib/fog/bin/dnsmadeeasy.rb0000644000004100000410000000130212261242551017314 0ustar www-datawww-dataclass DNSMadeEasy < Fog::Bin class << self def class_for(key) case key when :dns Fog::DNS::DNSMadeEasy else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :dns Fog::Logger.warning("DNSMadeEasy[:dns] is not recommended, use DNS[:dnsmadeeasy] for portability") Fog::DNS.new(:provider => 'DNSMadeEasy') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::DNSMadeEasy.services end end end fog-1.19.0/lib/fog/bin/bare_metal_cloud.rb0000644000004100000410000000136412261242551020310 0ustar www-datawww-dataclass BareMetalCloud < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::BareMetalCloud else raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("BareMetalCloud[:compute] is not recommended, use Compute[:baremetalcloud] for portability") Fog::Compute.new(:provider => 'BareMetalCloud') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::BareMetalCloud.services end end end fog-1.19.0/lib/fog/bin/linode.rb0000644000004100000410000000161712261242551016302 0ustar www-datawww-dataclass Linode < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Linode when :dns Fog::DNS::Linode else raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("Linode[:compute] is not recommended, use Compute[:linode] for portability") Fog::Compute.new(:provider => 'Linode') when :dns Fog::Logger.warning("Linode[:dns] is not recommended, use DNS[:linode] for portability") Fog::DNS.new(:provider => 'Linode') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Linode.services end end end fog-1.19.0/lib/fog/bin/openvz.rb0000644000004100000410000000130312261242551016341 0ustar www-datawww-dataclass Openvz < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Openvz else raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("Openvz[:compute] is not recommended, use Compute[:openvz] for portability") Fog::Compute.new(:provider => 'Openvz') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Openvz.services end end end fog-1.19.0/lib/fog/bin/joyent.rb0000644000004100000410000000127412261242551016337 0ustar www-datawww-dataclass Joyent < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Joyent else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("Joyent[:compute] is not recommended, use Compute[:joyent] for portability") Fog::Compute.new(:provider => 'Joyent') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Joyent.services end end end fog-1.19.0/lib/fog/bin/serverlove.rb0000644000004100000410000000132412261242551017217 0ustar www-datawww-dataclass Serverlove < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Serverlove else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("Serverlove[:compute] is not recommended, use Compute[:serverlove] for portability") Fog::Compute.new(:provider => 'Serverlove') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Serverlove.services end end end fog-1.19.0/lib/fog/bin/dynect.rb0000644000004100000410000000105712261242551016314 0ustar www-datawww-dataclass Dynect < Fog::Bin class << self def class_for(key) case key when :dns Fog::DNS::Dynect else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :dns Fog::DNS.new(:provider => 'Dynect') else raise ArgumentError, "Unrecognized service: #{service}" end end @@connections[service] end def services [:dns] end end end fog-1.19.0/lib/fog/bin/xenserver.rb0000644000004100000410000000131612261242551017045 0ustar www-datawww-dataclass XenServer < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::XenServer else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("XenServer[:compute] is not recommended, use Compute[:xenserver] for portability") Fog::Compute.new(:provider => 'XenServer') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::XenServer.services end end end fog-1.19.0/lib/fog/bin/openstack.rb0000644000004100000410000000457412261242551017024 0ustar www-datawww-dataclass OpenStack < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::OpenStack when :identity Fog::Identity::OpenStack when :image Fog::Image::OpenStack when :network Fog::Network::OpenStack when :storage Fog::Storage::OpenStack when :volume Fog::Volume::OpenStack when :metering Fog::Metering::OpenStack when :orchestration Fog::Orchestration::OpenStack else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("OpenStack[:compute] is not recommended, use Compute[:openstack] for portability") Fog::Compute.new(:provider => 'OpenStack') when :identity Fog::Logger.warning("OpenStack[:identity] is not recommended, use Identity[:openstack] for portability") Fog::Identity.new(:provider => 'OpenStack') when :image Fog::Logger.warning("OpenStack[:image] is not recommended, use Image[:openstack] for portability") Fog::Image.new(:provider => 'OpenStack') when :network Fog::Logger.warning("OpenStack[:network] is not recommended, use Network[:openstack] for portability") Fog::Network.new(:provider => 'OpenStack') when :storage Fog::Logger.warning("OpenStack[:storage] is not recommended, use Storage[:openstack] for portability") Fog::Storage.new(:provider => 'OpenStack') when :volume Fog::Logger.warning("OpenStack[:volume] is not recommended, use Volume[:openstack] for portability") Fog::Volume.new(:provider => 'OpenStack') when :metering Fog::Logger.warning("OpenStack[:metering] is not recommended, use Metering[:openstack] for portability") Fog::Metering.new(:provider => 'OpenStack') when :orchestration Fog::Logger.warning("OpenStack[:orchestration] is not recommended, use Orchestration[:openstack] for portability") Fog::Orchestration.new(:provider => 'OpenStack') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::OpenStack.services end end end fog-1.19.0/lib/fog/bin/dnsimple.rb0000644000004100000410000000126012261242551016635 0ustar www-datawww-dataclass DNSimple < Fog::Bin class << self def class_for(key) case key when :dns Fog::DNS::DNSimple else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :dns Fog::Logger.warning("DNSimple[:dns] is not recommended, use DNS[:dnsimple] for portability") Fog::DNS.new(:provider => 'DNSimple') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::DNSimple.services end end end fog-1.19.0/lib/fog/bin/vcloud_director.rb0000644000004100000410000000116112261242551020211 0ustar www-datawww-dataclass VcloudDirector < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::VcloudDirector else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Compute.new(:provider => 'VcloudDirector') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::VcloudDirector.services end end end fog-1.19.0/lib/fog/bin/atmos.rb0000644000004100000410000000127112261242551016147 0ustar www-datawww-dataclass Atmos < Fog::Bin class << self def class_for(key) case key when :storage Fog::Storage::Atmos else raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :storage Fog::Logger.warning("Atmos[:storage] is not recommended, use Storage[:atmos] for portability") Fog::Storage.new(:provider => 'Atmos') else raise ArgumentError, "Unrecognized service: #{service}" end end @@connections[service] end def services Fog::Atmos.services end end end fog-1.19.0/lib/fog/bin/ninefold.rb0000644000004100000410000000166712261242551016633 0ustar www-datawww-dataclass Ninefold < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Ninefold when :storage Fog::Storage::Ninefold else raise ArgumentError, "Unsupported #{self} service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Logger.warning("Ninefold[:compute] is not recommended, use Compute[:ninefold] for portability") Fog::Compute.new(:provider => 'Ninefold') when :storage Fog::Logger.warning("Ninefold[:storage] is not recommended, use Storage[:ninefold] for portability") Fog::Storage.new(:provider => 'Ninefold') else raise ArgumentError, "Unrecognized service: #{service}" end end @@connections[service] end def services Fog::Ninefold.services end end end fog-1.19.0/lib/fog/bin/ovirt.rb0000644000004100000410000000121112261242551016161 0ustar www-datawww-dataclass Ovirt < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Ovirt else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Compute.new(:provider => 'Ovirt') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Ovirt.services end end end fog-1.19.0/lib/fog/bin/vsphere.rb0000644000004100000410000000112512261242551016476 0ustar www-datawww-dataclass Vsphere < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Vsphere else raise ArgumentError, "Unrecognized service: #{key}" end end def [](service) @@connections ||= Hash.new do |hash, key| hash[key] = case key when :compute Fog::Compute.new(:provider => 'Vsphere') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Vsphere.services end end end fog-1.19.0/lib/fog/brightbox.rb0000644000004100000410000000021512261242551016241 0ustar www-datawww-datarequire 'fog/core' module Fog module Brightbox extend Fog::Provider service(:compute, 'brightbox/compute', 'Compute') end end fog-1.19.0/lib/fog/voxel/0000755000004100000410000000000012261242552015064 5ustar www-datawww-datafog-1.19.0/lib/fog/voxel/requests/0000755000004100000410000000000012261242552016737 5ustar www-datawww-datafog-1.19.0/lib/fog/voxel/requests/compute/0000755000004100000410000000000012261242552020413 5ustar www-datawww-datafog-1.19.0/lib/fog/voxel/requests/compute/devices_list.rb0000644000004100000410000000075012261242552023417 0ustar www-datawww-datamodule Fog module Compute class Voxel class Real require 'fog/voxel/parsers/compute/devices_list' def devices_list(device_id = nil) options = { :parser => Fog::Parsers::Compute::Voxel::DevicesList.new, :verbosity => 'normal' } unless device_id.nil? options[:device_id] = device_id end request("voxel.devices.list", options) end end end end end fog-1.19.0/lib/fog/voxel/requests/compute/devices_power.rb0000644000004100000410000000074112261242552023600 0ustar www-datawww-datamodule Fog module Compute class Voxel class Real require 'fog/voxel/parsers/compute/basic' def devices_power(device_id, power_action) options = { :device_id => device_id, :parser => Fog::Parsers::Compute::Voxel::Basic.new, :power_action => power_action, :verbosity => 'normal' } request("voxel.devices.power", options) end end end end end fog-1.19.0/lib/fog/voxel/requests/compute/images_list.rb0000644000004100000410000000123312261242552023237 0ustar www-datawww-datamodule Fog module Compute class Voxel class Real require 'fog/voxel/parsers/compute/images_list' def images_list(image_id = nil) options = { :parser => Fog::Parsers::Compute::Voxel::ImagesList.new, :verbosity => 'compact' } unless image_id.nil? options[:verbosity] = 'extended' options[:image_id] = image_id end data = request("voxel.images.list", options) if data.body['stat'] == "ok" data else raise Fog::Compute::Voxel::NotFound end end end end end end fog-1.19.0/lib/fog/voxel/requests/compute/voxcloud_delete.rb0000644000004100000410000000062412261242552024127 0ustar www-datawww-datamodule Fog module Compute class Voxel class Real require 'fog/voxel/parsers/compute/voxcloud_delete' def voxcloud_delete(device_id) options = { :device_id => device_id, :parser => Fog::Parsers::Compute::Voxel::VoxcloudDelete.new } request("voxel.voxcloud.delete", options) end end end end end fog-1.19.0/lib/fog/voxel/requests/compute/voxcloud_status.rb0000644000004100000410000000076512261242552024216 0ustar www-datawww-datamodule Fog module Compute class Voxel class Real require 'fog/voxel/parsers/compute/voxcloud_status' def voxcloud_status(device_id = nil) options = { :parser => Fog::Parsers::Compute::Voxel::VoxcloudStatus.new, :verbosity => 'compact' } unless device_id.nil? options[:device_id] = device_id end request("voxel.voxcloud.status", options) end end end end end fog-1.19.0/lib/fog/voxel/requests/compute/voxcloud_create.rb0000644000004100000410000000074412261242552024133 0ustar www-datawww-datamodule Fog module Compute class Voxel class Real require 'fog/voxel/parsers/compute/voxcloud_create' def voxcloud_create(options) options[:parser] = Fog::Parsers::Compute::Voxel::VoxcloudCreate.new if options.has_key?(:password) options[:admin_password] = options[:password] options.delete(:password) end request("voxel.voxcloud.create", options) end end end end end fog-1.19.0/lib/fog/voxel/parsers/0000755000004100000410000000000012261242552016543 5ustar www-datawww-datafog-1.19.0/lib/fog/voxel/parsers/compute/0000755000004100000410000000000012261242552020217 5ustar www-datawww-datafog-1.19.0/lib/fog/voxel/parsers/compute/devices_list.rb0000644000004100000410000000746712261242552023237 0ustar www-datawww-datamodule Fog module Parsers module Compute module Voxel class DevicesList < Fog::Parsers::Base def reset @device = {} @response = { 'devices' => [] } @in_storage = false end def start_element(name, attrs = []) super case name when 'accessmethod' @access_method = { 'type' => attr_value('type', attrs) } when 'accessmethods' @device['access_methods'] = [] when 'device' @device = { 'id' => attr_value('id', attrs), 'label' => attr_value('label', attrs), 'status' => attr_value('status', attrs) } when 'err' @response['err'] = { 'code' => attr_value('code', attrs), 'msg' => attr_value('msg', attrs) } when 'cage', 'facility', 'rack', 'row', 'zone' @device['location'][name] = { 'id' => attr_value('id', attrs) } if code = attr_value('code', attrs) @device['location'][name]['code'] = code end when 'drive' @drive = { 'position' => attr_value('position', attrs) } when 'ipassignment' type = attr_value('type', attrs) @device['ipassignments'] = [] @device['ipassignments'] << { 'id' => attr_value('id', attrs), 'type' => attr_value('type', attrs), 'description' => attr_value('description', attrs), } when 'ipassignments' @device['ipassignments'] = {} when 'location' @device['location'] = {} when 'memory' @device['memory'] = { 'size' => attr_value('size', attrs).to_i } when 'model', 'type' @device[name] = { 'id' => attr_value('id', attrs) } when 'operating_system' @device['operating_system'] = {} when 'power_consumption' @device[name] = attr_value('unit', attrs) when 'processor' @device['processor'] = {} when 'rsp' @response['stat'] = attr_value('stat', attrs) when 'storage' @device['drives'] = [] end end def end_element(name) case name when 'access_method' @device['access_methods'] << @access_method when 'architecture' @device['operating_system'][name] = value.to_i when 'cage', 'facility', 'rack', 'row', 'zone' @device['location'][name]['value'] = value when 'cores' @device['processor'][name] = value.to_i when 'description' @device[name] = value when 'device' @response['devices'] << @device @device = {} when 'drive' @device['drives'] << @drive @drive = {} when 'cores' @device['processing_cores'] = value.to_i when 'ipassignment' @device['ipassignments'].last['value'] = value when 'model', 'type' @device[name]['value'] = value when 'name' @device['operating_system'][name] = value when 'position' @device['location'][name] = value when 'power_consumption' @device[name] = [value, @device[name]].join(' ') when 'size' @drive[name] = value.to_i when 'host', 'password', 'protocol', 'username' @access_method[name] = value end end end end end end end fog-1.19.0/lib/fog/voxel/parsers/compute/images_list.rb0000644000004100000410000000313612261242552023047 0ustar www-datawww-datamodule Fog module Parsers module Compute module Voxel class ImagesList < Fog::Parsers::Base def reset @image = {} @response = { 'images' => [] } end def start_element(name, attrs = []) super case name when 'err' @response['err'] = { 'code' => attr_value('code', attrs), 'msg' => attr_value('msg', attrs) } when 'size' @image['filesystem']['units'] = attr_value('units', attrs) when 'image' @image = { 'id' => attr_value('id', attrs).to_i, 'summary' => attr_value('summary', attrs) } when 'filesystem', 'operating_system' @image[name] = {} when 'rsp' @response['stat'] = attr_value('stat', attrs) end end def end_element(name) case name when 'architecture' @image['operating_system'][name] = value.to_i when 'admin_username', 'family', 'product_family', 'product_version', 'version' @image['operating_system'][name] = value when 'description' @image[name] = value when 'image' @response['images'] << @image @image = {} when 'size' @image['filesystem'][name] = value.to_i when 'type' @image['filesystem'][name] = value end end end end end end endfog-1.19.0/lib/fog/voxel/parsers/compute/voxcloud_delete.rb0000644000004100000410000000113212261242552023726 0ustar www-datawww-datamodule Fog module Parsers module Compute module Voxel class VoxcloudDelete < Fog::Parsers::Base def reset @response = {} end def start_element(name, attrs = []) super case name when 'rsp' @response['stat'] = attr_value('stat', attrs) when 'err' @response['err'] = { 'code' => attr_value('code', attrs), 'msg' => attr_value('msg', attrs) } end end end end end end end fog-1.19.0/lib/fog/voxel/parsers/compute/voxcloud_status.rb0000644000004100000410000000200212261242552024004 0ustar www-datawww-datamodule Fog module Parsers module Compute module Voxel class VoxcloudStatus < Fog::Parsers::Base def reset @response = { 'devices' => [] } @device = {} end def start_element(name, attrs = []) super case name when 'rsp' @response['stat'] = attr_value('stat', attrs) when 'err' @response['err'] = { 'code' => attr_value('code', attrs), 'msg' => attr_value('msg', attrs) } when 'device' @device = {} end end def end_element(name) case name when 'device' @response['devices'] << @device @device = {} when 'id', 'status' @device[name] = value when 'last_update' @device[name] = Time.at(value.to_i) end end end end end end end fog-1.19.0/lib/fog/voxel/parsers/compute/basic.rb0000644000004100000410000000112112261242552021620 0ustar www-datawww-datamodule Fog module Parsers module Compute module Voxel class Basic < Fog::Parsers::Base def reset @response = {} end def start_element(name, attrs = []) super case name when 'err' @response['err'] = { 'code' => attr_value('code', attrs), 'msg' => attr_value('msg', attrs) } when 'rsp' @response['stat'] = attr_value('stat', attrs) end end end end end end end fog-1.19.0/lib/fog/voxel/parsers/compute/voxcloud_create.rb0000644000004100000410000000154212261242552023734 0ustar www-datawww-datamodule Fog module Parsers module Compute module Voxel class VoxcloudCreate < Fog::Parsers::Base def reset @response = { 'device' => {} } end def start_element(name, attrs = []) super case name when 'err' @response['err'] = { 'code' => attr_value('code', attrs), 'msg' => attr_value('msg', attrs) } when 'rsp' @response['stat'] = attr_value('stat', attrs) end end def end_element(name) case name when 'id' @response['device'][name] = value when 'last_update' @response['device'][name] = Time.at(value.to_i) end end end end end end end fog-1.19.0/lib/fog/voxel/models/0000755000004100000410000000000012261242552016347 5ustar www-datawww-datafog-1.19.0/lib/fog/voxel/models/compute/0000755000004100000410000000000012261242552020023 5ustar www-datawww-datafog-1.19.0/lib/fog/voxel/models/compute/images.rb0000644000004100000410000000101712261242552021614 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/voxel/models/compute/image' module Fog module Compute class Voxel class Images < Fog::Collection model Fog::Compute::Voxel::Image def all data = service.images_list.body['images'] load(data) end def get(image_id) data = service.images_list(image_id).body['images'] if data.empty? nil else new(data.first) end end end end end end fog-1.19.0/lib/fog/voxel/models/compute/servers.rb0000644000004100000410000000135612261242552022046 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/voxel/models/compute/server' module Fog module Compute class Voxel class Servers < Fog::Collection model Fog::Compute::Voxel::Server def all data = service.devices_list.body['devices'].select {|device| device['type']['id'] == '3'} load(data) end def get(device_id) if device_id && server = service.devices_list(device_id).body['devices'] new(server.first) end rescue Fog::Service::Error => error if error.message == "The device_id passed in can't be matched to a valid device." nil else raise error end end end end end end fog-1.19.0/lib/fog/voxel/models/compute/server.rb0000644000004100000410000000342212261242552021657 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class Voxel class Server < Fog::Compute::Server identity :id attribute :name attribute :processing_cores attribute :image_id attribute :facility attribute :disk_size attribute :ip_assignments, :aliases => 'ipassignments' def initialize(attributes={}) self.image_id ||= '55' # Ubuntu 10.04 LTS 64bit super end def destroy requires :id service.voxcloud_delete(id) true end def image requires :image_id service.images.get(image_id) end def ready? self.state == 'SUCCEEDED' end def private_ip_address ip_assignments.select {|ip_assignment| ip_assignment['type'] == 'internal'}.first end def public_ip_address ip_assignments.select {|ip_assignment| ip_assignment['type'] == 'external'}.first end def reboot requires :id service.devices_power(id, :reboot) true end def state @state ||= service.voxcloud_status(id).body['devices'].first['status'] end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :name, :image_id, :processing_cores, :facility, :disk_size data = service.voxcloud_create({ :disk_size => disk_size, :facility => facility, :hostname => name, :image_id => image_id, :processing_cores => processing_cores }).body merge_attributes(data['device']) true end end end end end fog-1.19.0/lib/fog/voxel/models/compute/image.rb0000644000004100000410000000026412261242552021434 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Voxel class Image < Fog::Model identity :id attribute :summary end end end end fog-1.19.0/lib/fog/voxel/compute.rb0000644000004100000410000001051512261242552017067 0ustar www-datawww-datarequire 'fog/voxel' require 'fog/compute' module Fog module Compute class Voxel < Fog::Service requires :voxel_api_key, :voxel_api_secret recognizes :host, :port, :scheme, :persistent model_path 'fog/voxel/models/compute' model :image collection :images model :server collection :servers request_path 'fog/voxel/requests/compute' request :images_list request :devices_list request :devices_power request :voxcloud_create request :voxcloud_status request :voxcloud_delete class Mock include Collections def self.data @data ||= Hash.new do |hash, key| hash[key] = { :last_modified => { :servers => {}, :statuses => {}, :images => {} }, :servers => [], :statuses => {}, :images => [ {'id' => 1, 'name' => "CentOS 4, 32-bit, base install"}, {'id' => 2, 'name' => "CentOS 4, 64-bit, base install"}, {'id' => 3, 'name' => "CentOS 5, 32-bit, base install"}, {'id' => 4, 'name' => "CentOS 5, 64-bit, base install"}, {'id' => 7, 'name' => "Fedora 10, 32-bit, base install"}, {'id' => 8, 'name' => "Fedora 10, 64-bit, base install"}, {'id' => 10, 'name' => "OpenSUSE 11, 64-bit, base install"}, {'id' => 11, 'name' => "Debian 5.0 \"lenny\", 32-bit, base install"}, {'id' => 12, 'name' => "Debian 5.0 \"lenny\", 64-bit, base install"}, {'id' => 13, 'name' => "Ubuntu 8.04 \"Hardy\", 32-bit, base install"}, {'id' => 14, 'name' => "Ubuntu 8.04 \"Hardy\", 64-bit, base install"}, {'id' => 15, 'name' => "Voxel Server Environment (VSE), 32-bit, base install"}, {'id' => 16, 'name' => "Voxel Server Environment (VSE), 64-bit, base install"}, {'id' => 32, 'name' => "Pantheon Official Mercury Stack for Drupal (based on VSE/64)"}, {'id' => 55, 'name' => "Ubuntu 10.04 \"Lucid\", 64-bit, base install"} ] } end end def self.reset @data = nil end def initialize(options={}) @voxel_api_key = options[:voxel_api_key] end def data self.class.data[@voxel_api_key] end def reset_data self.class.data.delete(@voxel_api_key) end end class Real include Collections def initialize(options = {}) require 'time' require 'digest/md5' @voxel_api_key = options[:voxel_api_key] @voxel_api_secret = options[:voxel_api_secret] @connection_options = options[:connection_options] || {} @host = options[:host] || "api.voxel.net" @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @persistent = options[:persistent] || false @connection_options[:ssl_verify_peer] = false @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def request(method_name, options = {}) begin parser = options.delete(:parser) options.merge!({ :method => method_name, :timestamp => Time.now.xmlschema, :key => @voxel_api_key }) options[:api_sig] = create_signature(@voxel_api_secret, options) data = @connection.request( :method => "POST", :query => options, :parser => parser, :path => "/version/1.0/" ) unless data.body['stat'] == 'ok' raise Fog::Compute::Voxel::Error, "#{data.body['err']['msg']}" end data rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Compute::Voxel::NotFound.slurp(error) else error end end end def create_signature(secret, options) to_sign = options.keys.map { |k| k.to_s }.sort.map { |k| "#{k}#{options[k.to_sym]}" }.join("") Digest::MD5.hexdigest( secret + to_sign ) end end end end end fog-1.19.0/lib/fog/aws.rb0000644000004100000410000002410112261242551015043 0ustar www-datawww-datarequire 'fog/core' require 'fog/aws/credential_fetcher' require 'fog/aws/signaturev4' module Fog module AWS extend Fog::Provider service(:auto_scaling, 'aws/auto_scaling', 'AutoScaling') service(:beanstalk, 'aws/beanstalk', 'ElasticBeanstalk') service(:cdn, 'aws/cdn', 'CDN') service(:compute, 'aws/compute', 'Compute') service(:cloud_formation, 'aws/cloud_formation', 'CloudFormation') service(:cloud_watch, 'aws/cloud_watch', 'CloudWatch') service(:data_pipeline, 'aws/data_pipeline', 'DataPipeline') service(:dynamodb, 'aws/dynamodb', 'DynamoDB') service(:dns, 'aws/dns', 'DNS') service(:elasticache, 'aws/elasticache', 'Elasticache') service(:elb, 'aws/elb', 'ELB') service(:emr, 'aws/emr', 'EMR') service(:glacier, 'aws/glacier', 'Glacier') service(:iam, 'aws/iam', 'IAM') service(:rds, 'aws/rds', 'RDS') service(:redshift, 'aws/redshift', 'Redshift') service(:ses, 'aws/ses', 'SES') service(:simpledb, 'aws/simpledb', 'SimpleDB') service(:sns, 'aws/sns', 'SNS') service(:sqs, 'aws/sqs', 'SQS') service(:sts, 'aws/sts', 'STS') service(:storage, 'aws/storage', 'Storage') def self.indexed_param(key, values) params = {} unless key.include?('%d') key << '.%d' end [*values].each_with_index do |value, index| if value.respond_to?('keys') k = format(key, index + 1) value.each do | vkey, vvalue | params["#{k}.#{vkey}"] = vvalue end else params[format(key, index + 1)] = value end end params end def self.serialize_keys(key, value, options = {}) case value when Hash value.each do | k, v | options.merge!(serialize_keys("#{key}.#{k}", v)) end return options when Array value.each_with_index do | it, idx | options.merge!(serialize_keys("#{key}.member.#{(idx + 1)}", it)) end return options else return {key => value} end end def self.indexed_request_param(name, values) idx = -1 Array(values).inject({}) do |params, value| params["#{name}.#{idx += 1}"] = value params end end def self.indexed_filters(filters) params = {} filters.keys.each_with_index do |key, key_index| key_index += 1 params[format('Filter.%d.Name', key_index)] = key [*filters[key]].each_with_index do |value, value_index| value_index += 1 params[format('Filter.%d.Value.%d', key_index, value_index)] = value end end params end def self.escape(string) unless @unf_loaded_or_warned begin require('unf/normalizer') rescue LoadError Fog::Logger.warning("Unable to load the 'unf' gem. Your AWS strings may not be properly encoded.") end @unf_loaded_or_warned = true end string = defined?(::UNF::Normalizer) ? ::UNF::Normalizer.normalize(string, :nfc) : string string.gsub(/([^a-zA-Z0-9_.\-~]+)/) { "%" + $1.unpack("H2" * $1.bytesize).join("%").upcase } end def self.signed_params(params, options = {}) params.merge!({ 'AWSAccessKeyId' => options[:aws_access_key_id], 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => '2', 'Timestamp' => Time.now.utc.strftime("%Y-%m-%dT%H:%M:%SZ"), 'Version' => options[:version] }) params.merge!({ 'SecurityToken' => options[:aws_session_token] }) if options[:aws_session_token] body = '' for key in params.keys.sort unless (value = params[key]).nil? body << "#{key}=#{escape(value.to_s)}&" end end string_to_sign = "POST\n#{options[:host]}:#{options[:port]}\n#{options[:path]}\n" << body.chop signed_string = options[:hmac].sign(string_to_sign) body << "Signature=#{escape(Base64.encode64(signed_string).chomp!)}" body end class Mock def self.arn(vendor, account_id, path, region = nil) "arn:aws:#{vendor}:#{region}:#{account_id}:#{path}" end def self.availability_zone(region) "#{region}#{Fog::Mock.random_selection('abcd', 1)}" end def self.box_usage sprintf("%0.10f", rand / 100).to_f end def self.console_output # "[ 0.000000] Linux version 2.6.18-xenU-ec2-v1.2 (root@domU-12-31-39-07-51-82) (gcc version 4.1.2 20070626 (Red Hat 4.1.2-13)) #2 SMP Wed Aug 19 09:04:38 EDT 2009" Base64.decode64("WyAwLjAwMDAwMF0gTGludXggdmVyc2lvbiAyLjYuMTgteGVuVS1lYzItdjEu\nMiAocm9vdEBkb21VLTEyLTMxLTM5LTA3LTUxLTgyKSAoZ2NjIHZlcnNpb24g\nNC4xLjIgMjAwNzA2MjYgKFJlZCBIYXQgNC4xLjItMTMpKSAjMiBTTVAgV2Vk\nIEF1ZyAxOSAwOTowNDozOCBFRFQgMjAwOQ==\n") end def self.dns_name_for(ip_address) "ec2-#{ip_address.gsub('.','-')}.compute-1.amazonaws.com" end def self.private_dns_name_for(ip_address) "ip-#{ip_address.gsub('.','-')}.ec2.internal" end def self.image path = [] (rand(3) + 2).times do path << Fog::Mock.random_letters(rand(9) + 8) end { "imageOwnerId" => Fog::Mock.random_letters(rand(5) + 4), "blockDeviceMapping" => [], "productCodes" => [], "kernelId" => kernel_id, "ramdiskId" => ramdisk_id, "imageState" => "available", "imageId" => image_id, "architecture" => "i386", "isPublic" => true, "imageLocation" => path.join('/'), "imageType" => "machine", "rootDeviceType" => ["ebs","instance-store"][rand(2)], "rootDeviceName" => "/dev/sda1" } end def self.image_id "ami-#{Fog::Mock.random_hex(8)}" end def self.key_fingerprint fingerprint = [] 20.times do fingerprint << Fog::Mock.random_hex(2) end fingerprint.join(':') end def self.instance_id "i-#{Fog::Mock.random_hex(8)}" end def self.ip_address ip = [] 4.times do ip << Fog::Mock.random_numbers(rand(3) + 1).to_i.to_s # remove leading 0 end ip.join('.') end def self.private_ip_address ip_address.gsub(/^\d{1,3}\./,"10.") end def self.kernel_id "aki-#{Fog::Mock.random_hex(8)}" end def self.key_material OpenSSL::PKey::RSA.generate(1024).to_s end def self.owner_id Fog::Mock.random_numbers(12) end def self.ramdisk_id "ari-#{Fog::Mock.random_hex(8)}" end def self.request_id request_id = [] request_id << Fog::Mock.random_hex(8) 3.times do request_id << Fog::Mock.random_hex(4) end request_id << Fog::Mock.random_hex(12) request_id.join('-') end class << self alias :reserved_instances_id :request_id alias :reserved_instances_offering_id :request_id alias :sqs_message_id :request_id alias :sqs_sender_id :request_id end def self.reservation_id "r-#{Fog::Mock.random_hex(8)}" end def self.snapshot_id "snap-#{Fog::Mock.random_hex(8)}" end def self.volume_id "vol-#{Fog::Mock.random_hex(8)}" end def self.security_group_id "sg-#{Fog::Mock.random_hex(8)}" end def self.network_interface_id "eni-#{Fog::Mock.random_hex(8)}" end def self.internet_gateway_id "igw-#{Fog::Mock.random_hex(8)}" end def self.dhcp_options_id "dopt-#{Fog::Mock.random_hex(8)}" end def self.vpc_id "vpc-#{Fog::Mock.random_hex(8)}" end def self.subnet_id "subnet-#{Fog::Mock.random_hex(8)}" end def self.zone_id "zone-#{Fog::Mock.random_hex(8)}" end def self.change_id Fog::Mock.random_letters_and_numbers(14) end def self.nameservers [ 'ns-2048.awsdns-64.com', 'ns-2049.awsdns-65.net', 'ns-2050.awsdns-66.org', 'ns-2051.awsdns-67.co.uk' ] end def self.key_id(length=21) #Probably close enough Fog::Mock.random_selection('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',length) end def self.rds_address(db_name,region) "#{db_name}.#{Fog::Mock.random_letters(rand(12) + 4)}.#{region}.rds.amazonaws.com" end end def self.parse_security_group_options(group_name, options) options ||= Hash.new if group_name.is_a?(Hash) options = group_name elsif group_name if options.key?('GroupName') raise Fog::Compute::AWS::Error, 'Arguments specified both group_name and GroupName in options' end options = options.clone options['GroupName'] = group_name end name_specified = options.key?('GroupName') && !options['GroupName'].nil? group_id_specified = options.key?('GroupId') && !options['GroupId'].nil? unless name_specified || group_id_specified raise Fog::Compute::AWS::Error, 'Neither GroupName nor GroupId specified' end if name_specified && group_id_specified options.delete('GroupName') end options end module Errors def self.match_error(error) matcher = lambda {|s| s.match(/(?:.*(.*)<\/Code>)(?:.*(.*)<\/Message>)/m)} [error.message, error.response.body].each(&Proc.new {|s| match = matcher.call(s) return {:code => match[1].split('.').last, :message => match[2]} if match }) {} # we did not match the message or response body end end end end fog-1.19.0/lib/fog/cloudsigma/0000755000004100000410000000000012261242551016055 5ustar www-datawww-datafog-1.19.0/lib/fog/cloudsigma/connection.rb0000644000004100000410000001524012261242551020543 0ustar www-datawww-datarequire 'fog/cloudsigma/error' module Fog module CloudSigma module CloudSigmaConnection module Real def auth_header(type = :basic) case type when :basic unless @username and @password raise ArgumentError, 'Username and password required for basic auth' end {'Authorization' => 'Basic ' << Base64.encode64("#{@username}:#{@password}").gsub("\n", '')} else unless @username and @password raise ArgumentError, 'Username and password required for basic auth' end {'Authorization' => 'Basic ' << Base64.encode64("#{@username}:#{@password}").gsub("\n", '')} end end def setup_connection(options) @persistent = options[:persistent] || false @connection_options = options[:connection_options] || {} @connection_options[:ssl_verify_peer] = false @auth_type = options[:cloudsigma_auth_type] || :basic @username = options[:cloudsigma_username] @password = options[:cloudsigma_password] @scheme = options[:cloudsigma_scheme] || 'https' @host = options[:cloudsigma_host] || 'lvs.cloudsigma.com' @port = options[:cloudsigma_port] || '443' @api_path_prefix = options[:cloudsigma_api_path_prefix] || 'api' @api_version = options[:cloudsigma_api_version] || '2.0' @path_prefix = "#{@api_path_prefix}/#{@api_version}/" @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def request(params) params[:headers] = params.fetch(:headers, {}).merge(auth_header(@auth_type)) params[:headers]['Content-Type'] = 'application/json; charset=utf-8' req_path = params[:path] params[:path] = "#{@path_prefix}#{req_path}" params[:body] = Fog::JSON.encode(params[:body]) if params[:body] begin response = @connection.request(params) rescue Excon::Errors::HTTPStatusError => e e.response.data[:body] = Fog::JSON.decode(e.response[:body]) unless e.response[:body].empty? err = Fog::CloudSigma::Errors.slurp_http_status_error(e) raise err end response.body = Fog::JSON.decode(response.body) unless response.body.empty? response end def list_request(path, override_params={}) default_params = {:method => 'GET', :expects => 200, :query => {:limit => 0}} override_params[:path] = path params = default_params.merge(override_params) request(params) end def get_request(path, override_params={}) default_params = {:method => 'GET', :expects => 200} override_params[:path] = path params = default_params.merge(override_params) request(params) end def delete_request(path, override_params={}) default_params = {:method => 'DELETE', :expects => 204} override_params[:path] = path params = default_params.merge(override_params) request(params) end def create_request(path, data, override_params={}) default_params = {:method => 'POST', :expects => [200, 201, 202]} override_params[:path] = path override_params[:body] = data params = default_params.merge(override_params) request(params) end def update_request(path, data, override_params={}) default_params = {:method => 'PUT', :expects => [200, 202]} override_params[:path] = path override_params[:body] = data params = default_params.merge(override_params) request(params) end end module Mock def setup_connection(options) @username = options[:cloudsigma_username] @password = options[:cloudsigma_password] end def mock_get(obj_or_collection, status, key=nil) data = self.data[obj_or_collection] if key data = data[key] unless data raise Fog::CloudSigma::Errors::NotFound.new("Object with uuid #{key} does not exist", 'notexist') end end Excon::Response.new(:body => Fog::JSON.decode(Fog::JSON.encode(data)), :status => status) end def mock_list(collection, status) data_array = self.data[collection].values Excon::Response.new(:body => {'objects' => data_array}, :status => status) end def mock_update(data, obj_or_collection, status, key, &clean_before_update) data = Fog::JSON.decode(Fog::JSON.encode(data)) if key unless self.data[obj_or_collection][key] raise Fog::CloudSigma::Errors::NotFound.new("Object with uuid #{key} does not exist", 'notexist') end if clean_before_update new_data = clean_before_update.call(self.data[obj_or_collection][key], data) else new_data = self.data[obj_or_collection][key].merge(data) end self.data[obj_or_collection][key] = new_data else if clean_before_update new_data = clean_before_update.call(self.data[obj_or_collection], data) else new_data = self.data[obj_or_collection].merge(data) end self.data[obj_or_collection] = new_data end Excon::Response.new(:body => Fog::JSON.decode(Fog::JSON.encode(new_data)), :status => status) end def mock_delete(collection, status, key) self.data[collection].delete(key) Excon::Response.new(:body => '', :status => status) end def mock_create(collection, status, data, key, defaults={}, &clean_before_store) data_with_defaults = data.merge(defaults) {|k, oldval, newval| oldval == nil ? newval: oldval} if clean_before_store cleaned_data = clean_before_store.call(data_with_defaults) else cleaned_data = data_with_defaults end # Encode and decode into JSON so that the result is the same as the one returned and parsed from the API final_data = Fog::JSON.decode(Fog::JSON.encode(cleaned_data)) self.data[collection][key] = final_data # dup so that stored data is different instance from response data response_data = final_data.dup response = Excon::Response.new response.body = {'objects' => [response_data]} response.status = status response end end end end endfog-1.19.0/lib/fog/cloudsigma/requests/0000755000004100000410000000000012261242551017730 5ustar www-datawww-datafog-1.19.0/lib/fog/cloudsigma/requests/get_server.rb0000644000004100000410000000046312261242551022425 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def get_server(server_id) get_request("servers/#{server_id}/") end end class Mock def get_server(server_id) mock_get(:servers, 200, server_id) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/get_vlan.rb0000644000004100000410000000042712261242551022057 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def get_vlan(vlan) get_request("vlans/#{vlan}/") end end class Mock def get_vlan(vlan) mock_get(:vlans, 200, vlan) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/get_lib_volume.rb0000644000004100000410000000046412261242551023255 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def get_lib_volume(vol_id) get_request("libdrives/#{vol_id}/") end end class Mock def get_lib_volume(vol_id) mock_get(:libvolumes, 200, vol_id) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/clone_server.rb0000644000004100000410000000141012261242551022737 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def clone_server(server_id, clone_params={}) request(:path => "servers/#{server_id}/action/", :method => 'POST', :query => {:do => :clone}, :body => clone_params, :expects => [200, 202]) end end class Mock def clone_server(server_id, clone_params={}) server = self.data[:servers][server_id].dup uuid = self.class.random_uuid server['uuid'] = uuid self.data[:servers][uuid] = server response = Excon::Response.new response.status = 200 response.body = server response end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/delete_server.rb0000644000004100000410000000047712261242551023115 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def delete_server(server_id) delete_request("servers/#{server_id}/") end end class Mock def delete_server(server_id) mock_delete(:servers, 204, server_id) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/open_vnc.rb0000644000004100000410000000146112261242551022066 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def open_vnc(server_id) request(:path => "servers/#{server_id}/action/", :method => 'POST', :query => {:do => :open_vnc}, :expects => [200, 202]) end end class Mock def open_vnc(server_id) response = Excon::Response.new response.status = 200 host = @init_options[:cloudsigma_host] port = Fog::Mock.random_number(65000) vnc_url = "vnc://#{host}:#{port}" response.body = { 'action' => 'open_vnc', 'result' => 'success', 'uuid' => server_id, 'vnc_url' => vnc_url } response end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/clone_libvolume.rb0000644000004100000410000000140712261242551023435 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def clone_libvolume(vol_id, clone_params={}) request(:path => "libdrives/#{vol_id}/action/", :method => 'POST', :query => {:do => :clone}, :body => clone_params, :expects => [200, 202]) end end class Mock def clone_libvolume(vol_id, clone_params={}) volume = self.data[:libvolumes][vol_id].dup uuid = self.class.random_uuid volume['uuid'] = uuid self.data[:volumes][uuid] = volume response = Excon::Response.new response.status = 200 response.body = volume response end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/get_current_usage.rb0000644000004100000410000000036712261242551023770 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def get_current_usage get_request("currentusage/") end end class Mock def get_current_usage end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/stop_server.rb0000644000004100000410000000133012261242551022625 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def stop_server(server_id) request(:path => "servers/#{server_id}/action/", :method => 'POST', :query => {:do => :stop}, :expects => [200, 202]) end end class Mock def stop_server(server_id) server = self.data[:servers][server_id] server['status'] = 'stopped' response = Excon::Response.new response.status = 200 response.body = { 'action' => 'stop', 'result' => 'success', 'uuid' => server_id } response end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/create_volume.rb0000644000004100000410000000127212261242551023111 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def create_volume(data) create_request("drives/", data) end end class Mock def create_volume(data) uuid = self.class.random_uuid defaults = {'uuid' => uuid, 'status' => 'unmounted', 'tags' => [], 'mounted_on' => [], 'affinities' => [], 'licenses' => [], 'jobs' => [], 'allow_multimount' => false, } mock_create(:volumes, 202, data, uuid, defaults) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/delete_volume.rb0000644000004100000410000000046212261242551023110 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def delete_volume(vol_id) delete_request("drives/#{vol_id}/") end end class Mock def delete_volume(vol_id) mock_delete(:volumes, 204, vol_id) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/list_vlans.rb0000644000004100000410000000041212261242551022430 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def list_vlans list_request('vlans/detail/') end end class Mock def list_vlans mock_list(:vlans, 200) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/get_subscription.rb0000644000004100000410000000047712261242551023650 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def get_subscription(sub_id) get_request("subscriptions/#{sub_id}/") end end class Mock def get_subscription(sub_id) mock_get(:subscriptions, 200, sub_id) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/calculate_subscription_price.rb0000644000004100000410000000045412261242551026203 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def calculate_subscription_price(data) create_request("subscriptioncalculator/", data) end end class Mock def calculate_subscription_price(data) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/get_balance.rb0000644000004100000410000000041012261242551022474 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def get_balance get_request("balance/") end end class Mock def get_balance mock_get(:balance, 200) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/update_server.rb0000644000004100000410000000241512261242551023127 0ustar www-datawww-datarequire 'set' module Fog module Compute class CloudSigma class Real def update_server(server_id, data) update_request("servers/#{server_id}/", data) end end class Mock def update_server(server_id, data) mock_update(data, :servers, 200, server_id) do |old_data, new_data| old_nics = old_data['nics'] new_nics = new_data['nics'] old_nics_macs = old_nics.map { |nic| nic['mac'] }.compact new_nics_macs = new_nics.map { |nic| nic['mac'] }.compact newly_created_macs = Set.new(new_nics_macs) - old_nics_macs unless newly_created_macs.empty? mac_err = <<-EOS MAC(s) #{newly_created_macs.to_a} not specified on guest #{server_id}. Nic MACs are automatically assigned at creation time and cannot be changed. Do not specify MAC to create a new NIC or specify existing MAC to update existing NIC. EOS raise Fog::CloudSigma::Errors::RequestError.new(mac_err, 'permission') end new_nics.each { |nic| nic['mac'] ||= Fog::Compute::CloudSigma::Mock.random_mac } old_data.merge(new_data) end end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/close_vnc.rb0000644000004100000410000000120512261242551022226 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def close_vnc(server_id) request(:path => "servers/#{server_id}/action/", :method => 'POST', :query => {:do => :close_vnc}, :expects => [200, 202]) end end class Mock def close_vnc(server_id) response = Excon::Response.new response.status = 200 response.body = { 'action' => 'close_vnc', 'result' => 'success', 'uuid' => server_id, } response end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/start_server.rb0000644000004100000410000000142212261242551022777 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def start_server(server_id, start_params={}) request(:path => "servers/#{server_id}/action/", :method => 'POST', :query => {:do => :start}.merge!(start_params), :expects => [200, 202]) end end class Mock def start_server(server_id, start_params={}) server = self.data[:servers][server_id] server['status'] = 'running' response = Excon::Response.new response.status = 200 response.body = { 'action' => 'start', 'result' => 'success', 'uuid' => server_id } response end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/get_pricing.rb0000644000004100000410000000115512261242551022551 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def get_pricing(currency=nil, subscription=false) query = {:limit => 0} if currency query[:currency] = currency end if subscription query[:level] = 0 end request(:path => "pricing/", :method => 'GET', :expects => 200, :query => query) end end class Mock def get_pricing(currency=nil, subscription=false) mock_get(:pricing, 200) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/list_servers.rb0000644000004100000410000000042212261242551022777 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def list_servers list_request('servers/detail/') end end class Mock def list_servers mock_list(:servers, 200) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/list_ips.rb0000644000004100000410000000040212261242551022077 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def list_ips list_request('ips/detail/') end end class Mock def list_ips mock_list(:ips, 200) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/get_volume.rb0000644000004100000410000000044612261242551022427 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def get_volume(vol_id) get_request("drives/#{vol_id}/") end end class Mock def get_volume(vol_id) mock_get(:volumes, 200, vol_id) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/list_volumes.rb0000644000004100000410000000042112261242551022777 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def list_volumes list_request('drives/detail/') end end class Mock def list_volumes mock_list(:volumes, 200) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/create_server.rb0000644000004100000410000000141612261242551023110 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def create_server(data) create_request("servers/", data) end end class Mock def create_server(data) uuid = self.class.random_uuid defaults = {'uuid' => uuid, 'status' => 'stopped', 'smp' => 1, 'hv_relaxed' => false, 'hv_tsc' => false, 'enable_numa' => false, 'cpus_instead_of_cores' => false, 'drives' => [], 'nics' => [], 'tags' => [] } mock_create(:servers, 202, data, uuid, defaults) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/list_lib_volumes.rb0000644000004100000410000000043012261242551023625 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def list_lib_volumes list_request('libdrives/') end end class Mock def list_lib_volumes mock_list(:libvolumes, 200) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/extend_subscription.rb0000644000004100000410000000071212261242551024350 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def extend_subscription(sub_id, data) request(:path => "subscriptions/#{sub_id}/action/", :method => 'POST', :expects => [200, 202], :query => {:do => :extend}, :body=>data) end end class Mock def extend_subscription(sub_id, data) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/update_profile.rb0000644000004100000410000000045312261242551023261 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def update_profile(data) update_request("profile/", data) end end class Mock def update_profile(data) mock_update(data, :profile, 200) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/update_vlan.rb0000644000004100000410000000052612261242551022562 0ustar www-datawww-datarequire 'set' module Fog module Compute class CloudSigma class Real def update_vlan(vlan_id, data) update_request("vlans/#{vlan_id}/", data) end end class Mock def update_vlan(vlan_id, data) mock_update(data, :vlans, 200, vlan_id) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/create_subscription.rb0000644000004100000410000000247512261242551024334 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def create_subscription(data) create_request("subscriptions/", data) end end class Mock def create_subscription(data) if data[:period] != '1 month' || data[:start_time] || data[:end_time] raise Fog::Errors::MockNotImplemented.new('Currently only mocks for subscriptions with period 1 month from now are implemented as mock') end id = Fog::Mock.random_numbers(3).to_i defaults = {'id' => id, 'start_time' => DateTime.now, 'end_time' => DateTime.now + 30 * 24 * 60 *60, 'auto_renew' => false, 'amount' => 1.0} if data[:resource] == 'vlan' vlan_uuid = self.class.random_uuid self.data[:vlans][vlan_uuid] = {'uuid' => vlan_uuid, 'subscription' => {'id' => id}, 'servers' => [], 'meta' => {}, 'tags' => []} defaults['subscribed_object'] = vlan_uuid end mock_create(:subscriptions, 200, data, id, defaults) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/get_ip.rb0000644000004100000410000000040312261242551021521 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def get_ip(ip) request("ips/#{ip}/") end end class Mock def get_ip(ip) mock_get(:ips, 200, ip) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/update_volume.rb0000644000004100000410000000051312261242551023125 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def update_volume(vol_id, data) update_request("drives/#{vol_id}/", data) end end class Mock def update_volume(vol_id, data) mock_update(data, :volumes, 200, vol_id) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/clone_volume.rb0000644000004100000410000000137312261242551022750 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def clone_volume(vol_id, clone_params={}) request(:path => "drives/#{vol_id}/action/", :method => 'POST', :query => {:do => :clone}, :body => clone_params, :expects => [200, 202]) end end class Mock def clone_volume(vol_id, clone_params={}) volume = self.data[:volumes][vol_id].dup uuid = self.class.random_uuid volume['uuid'] = uuid self.data[:volumes][uuid] = volume response = Excon::Response.new response.status = 200 response.body = volume response end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/list_subscriptions.rb0000644000004100000410000000044312261242551024220 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def list_subscriptions list_request('subscriptions/') end end class Mock def list_subscriptions mock_list(:subscriptions, 200) end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/list_fwpolicies.rb0000644000004100000410000000043412261242551023455 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def list_fwpolicies list_request('fwpolicies/detail/') end end class Mock def list_fwpolicies Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/cloudsigma/requests/get_profile.rb0000644000004100000410000000041012261242551022547 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def get_profile get_request("profile/") end end class Mock def get_profile mock_get(:profile, 200) end end end end end fog-1.19.0/lib/fog/cloudsigma/nested_model.rb0000644000004100000410000000363712261242551021055 0ustar www-datawww-datamodule Fog module CloudSigma class CloudsigmaModel < Fog::Model class << self def model_attribute_array(name, model, options={}) attributes_key = options[:aliases] || name class_eval <<-EOS, __FILE__, __LINE__ def #{name} #{name}_attrs = attributes[:#{attributes_key}] || [] refreshed_#{name} = #{name}_attrs.map { |x| #{model}.new(x) } attributes[:#{attributes_key}] = refreshed_#{name}.map { |x| x.attributes } refreshed_#{name} end def #{name}=(new_#{name}) new_#{name} ||= [] attributes[:#{attributes_key}] = new_#{name}.map { |x| x.kind_of?(Hash) ? x : x.attributes} end EOS @attributes ||= [] @attributes |= [name] for new_alias in [*options[:aliases]] aliases[new_alias] = name end end def model_attribute(name, model, options={}) attributes_key = options[:aliases] || name class_eval <<-EOS, __FILE__, __LINE__ def #{name} #{name}_attrs = attributes[:#{attributes_key}] if #{name}_attrs refreshed_#{name} = #{name}_attrs ? #{model}.new(#{name}_attrs) : nil attributes[:#{attributes_key}] = refreshed_#{name}.attributes refreshed_#{name} else nil end end def #{name}=(new_#{name}) if new_#{name} attributes[:#{attributes_key}] = new_#{name}.kind_of?(Hash) ? new_#{name} : new_#{name}.attributes else nil end end EOS @attributes ||= [] @attributes |= [name] for new_alias in [*options[:aliases]] aliases[new_alias] = name end end end end end endfog-1.19.0/lib/fog/cloudsigma/docs/0000755000004100000410000000000012261242551017005 5ustar www-datawww-datafog-1.19.0/lib/fog/cloudsigma/docs/getting_started.md0000644000004100000410000000623612261242551022525 0ustar www-datawww-data# Getting Started with Fog on CloudSigma ## Requirements In order to use CloudSigma with Fog, you must use Fog version 1.12.0 or later. ## Setting credentials Fog uses `~/.fog` to store credentials. To add CloudSigma as your default provider, simply add the following: :default: :cloudsigma_username: user@example.com :cloudsigma_password: SomeRandomPassword :cloudsigma_host: zrh.cloudsigma.com Please note that you need to specify the host. If you're on the Zurich-based cloud, you will need to enter `zrh.cloudsigma.com` and if you're on the Las Vegas cloud, you'll need to enter `lvs.cloudsigma.com`. ## Creating a server You can of course interact with Fog directly from your Ruby application, but in this example, we'll simply use the `fog` CLI tool. In the example below, we'll first create a 5GB disk, then we create server with 2Ghz CPU and 2GB RAM. Finally we attach the drive and boot up the server. $ fog > cs = Compute[:CloudSigma] > drive = cs.volumes.create(:name => 'fog_drive', :size => '5368709120', :media => 'disk') > server = cs.servers.create(:name => 'fog_server', :cpu => '2000', :mem => '2147483648', :vnc_password => 'foobar') > server.mount_volume(drive.uuid) > server.update > server.start Now, this wasn't very useful by itself since the drive we created was just a blank drive (as a result it cannot boot). It does however illustrate a minimal work flow. To make this a bit more useful, let's try to attach an ISO image (in this case Ubuntu 12.04 LTS), and boot into the installer. To do this, we'll run the following commands (assuming you haven't closed the session from above). You can either upload your own installer image, or you can use one from the drives library. In either case, you need to pass the UUID for the drive. > server.stop > ubuntu_image_uuid = '41d848c2-44e4-4428-9406-84e95bb1288d' > server.unmount(drive.uuid) > server.mount_volume(ubuntu_image_uuid, 'ide', '0:0', 1) > server.mount_volume(drive.uuid, 'virtio', '0:0', 2) > server.update > server.start What this does is to stop the server, unmount the previous drive, then we attach the Ubuntu installation drive as an IDE device (on bus 0:0), with the boot order 1 (first). We then mount the system drive as Virtio device (on bus 0:0) with the boot order 2. Finally we push the changes to the server and start it. This will bring you into the Ubuntu installation. In order to actually run the installer, you need to open a VNC session to the server. This can be done bye issue the following command: > server.open_vnc That will print out the VNC URL, among with other data. You can simply pass the value of 'vnc_url' into your VNC client. When opening the session, you also need to provide the password, which we set to 'foobar' during the server creation. After you're done with the installation, you can unmount the Ubuntu installation disk by running the following command: > server.unmount(ubuntu_image_uuid) You might also want to close the VNC session to increase security. This can be done by running: > server.close_vnc That's it. You've now set up a fully working Ubuntu server on CloudSigma using fog. fog-1.19.0/lib/fog/cloudsigma/models/0000755000004100000410000000000012261242551017340 5ustar www-datawww-datafog-1.19.0/lib/fog/cloudsigma/models/vlan.rb0000644000004100000410000000117212261242551020626 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' module Fog module Compute class CloudSigma class VLAN < Fog::CloudSigma::CloudsigmaModel identity :uuid attribute :tags attribute :servers attribute :meta attribute :owner attribute :resource_uri, :type => :string attribute :subscription def update requires :identity data = attributes response = service.update_vlan(identity, data) new_attributes = response.body merge_attributes(new_attributes) end alias :save :update end end end end fog-1.19.0/lib/fog/cloudsigma/models/mountpoint.rb0000644000004100000410000000104212261242551022076 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class CloudSigma class MountPoint < Fog::Model attribute :device, :type => 'string' attribute :dev_channel, :type => 'string' attribute :drive attribute :boot_order, :type => 'integer' def drive drive = attributes[:drive] drive.kind_of?(Hash) ? drive['uuid'] : drive end def drive=(new_drive) attributes[:drive] = new_drive end alias :volume :drive end end end end fog-1.19.0/lib/fog/cloudsigma/models/volume.rb0000644000004100000410000000317212261242551021177 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' module Fog module Compute class CloudSigma class Volume < Fog::CloudSigma::CloudsigmaModel identity :uuid attribute :status, :type => :string attribute :jobs attribute :name, :type => :string attribute :tags attribute :media, :type => :string attribute :mounted_on attribute :owner attribute :meta attribute :allow_multimount, :type => :boolean attribute :licenses attribute :affinities, :type => :array attribute :size, :type => :integer attribute :resource_uri, :type => :string def save if persisted? update else create end end def create requires :name, :size, :media data = attributes response = service.create_volume(data) new_attributes = response.body['objects'].first merge_attributes(new_attributes) end def update requires :identity, :name, :size, :media data = attributes() response = service.update_volume(identity, data) new_attributes = response.body merge_attributes(new_attributes) end def destroy requires :identity service.delete_volume(identity) true end alias :delete :destroy def clone(clone_params={}) requires :identity response = service.clone_volume(identity, clone_params) self.class.new(response.body['objects'].first) end end end end endfog-1.19.0/lib/fog/cloudsigma/models/profile.rb0000644000004100000410000000277312261242551021336 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' module Fog module Compute class CloudSigma class Profile < Fog::CloudSigma::CloudsigmaModel identity :uuid attribute :last_name, :type => :string attribute :login_sms, :type => :boolean attribute :currency, :type => :string attribute :meta attribute :api_https_only, :type => :boolean attribute :first_name, :type => :string attribute :uuid, :type => :string attribute :title, :type => :string attribute :state, :type => :string attribute :email, :type => :string attribute :vat, :type => :string attribute :autotopup_amount, :type => :float attribute :reseller, :type => :string attribute :company, :type => :string attribute :key_auth, :type => :boolean attribute :phone, :type => :string attribute :address, :type => :string attribute :mailing_list, :type => :boolean attribute :town, :type => :string attribute :has_autotopup, :type => :boolean attribute :my_notes, :type => :string attribute :bank_reference, :type => :string attribute :language, :type => :string attribute :country, :type => :string attribute :postcode, :type => :string def save update end def update response = service.update_profile(attributes) self.attribute.merge!(response.body) self end end end end endfog-1.19.0/lib/fog/cloudsigma/models/ipconf.rb0000644000004100000410000000035212261242551021143 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' module Fog module Compute class CloudSigma class IPConf < Fog::CloudSigma::CloudsigmaModel attribute :ip attribute :conf, :type => :string end end end end fog-1.19.0/lib/fog/cloudsigma/models/rule.rb0000644000004100000410000000102612261242551020633 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' module Fog module Compute class CloudSigma class Rule < Fog::CloudSigma::CloudsigmaModel attribute :action, :type => :string attribute :comment, :type => :string attribute :direction, :type => :string attribute :dst_ip, :type => :string attribute :dst_port, :type => :integer attribute :ip_proto, :type => :string attribute :src_ip, :type => :string attribute :src_port, :type => :string end end end end fog-1.19.0/lib/fog/cloudsigma/models/ips.rb0000644000004100000410000000102112261242551020452 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/cloudsigma/models/ip' module Fog module Compute class CloudSigma class Ips < Fog::Collection model Fog::Compute::CloudSigma::IP def all resp = service.list_ips data = resp.body['objects'] load(data) end def get(ip) resp = service.get_ip(ip) data = resp.body new(data) rescue Fog::CloudSigma::Errors::NotFound return nil end end end end end fog-1.19.0/lib/fog/cloudsigma/models/servers.rb0000644000004100000410000000106312261242551021356 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/cloudsigma/models/server' module Fog module Compute class CloudSigma class Servers < Fog::Collection model Fog::Compute::CloudSigma::Server def all resp = service.list_servers data = resp.body['objects'] load(data) end def get(server_id) resp = service.get_server(server_id) data = resp.body new(data) rescue Fog::CloudSigma::Errors::NotFound return nil end end end end end fog-1.19.0/lib/fog/cloudsigma/models/balance.rb0000644000004100000410000000040512261242551021251 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' module Fog module Compute class CloudSigma class Balance < Fog::CloudSigma::CloudsigmaModel attribute :balance, :type => :float attribute :currency, :type => :string end end end end fog-1.19.0/lib/fog/cloudsigma/models/current_usage.rb0000644000004100000410000000105412261242551022533 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' require 'fog/cloudsigma/models/usage_record' module Fog module Compute class CloudSigma class CurrentUsage < Fog::CloudSigma::CloudsigmaModel model_attribute :cpu, UsageRecord model_attribute :hdd, UsageRecord model_attribute :ip, UsageRecord model_attribute :mem, UsageRecord model_attribute :sms, UsageRecord model_attribute :ssd, UsageRecord model_attribute :tx, UsageRecord model_attribute :vlan, UsageRecord end end end end fog-1.19.0/lib/fog/cloudsigma/models/fwpolicies.rb0000644000004100000410000000056312261242551022035 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/cloudsigma/models/fwpolicy' module Fog module Compute class CloudSigma class Fwpolicies < Fog::Collection model Fog::Compute::CloudSigma::FWPolicy def all resp = service.list_fwpolicies data = resp.body['objects'] load(data) end end end end end fog-1.19.0/lib/fog/cloudsigma/models/obj_ref.rb0000644000004100000410000000034312261242551021273 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class CloudSigma class ObjRef < Fog::Model attribute :uuid, :type => :string attribute :resource_uri, :type => :string end end end end fog-1.19.0/lib/fog/cloudsigma/models/lib_volume.rb0000644000004100000410000000262012261242551022022 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class CloudSigma class LibVolume < Fog::Model identity :uuid attribute :mounted_on, :type => :related attribute :licenses attribute :meta attribute :owner attribute :affinities attribute :image_format, :type => :string attribute :size, :type => :integer attribute :category attribute :image_type, :type => :string attribute :media, :type => :string attribute :state, :type => :string attribute :status, :type => :string attribute :jobs attribute :description, :type => :string attribute :tags attribute :favourite, :type => :boolean attribute :paid, :type => :boolean attribute :allow_multimount, :type => :boolean attribute :install_notes, :type => :string attribute :arch, :type => :string attribute :name, :type => :string attribute :url, :type => :string attribute :os, :type => :string attribute :resource_uri, :type => :string def reload requires :identity collection.get(identity) end def clone(clone_params={}) requires :identity response = service.clone_volume(identity, clone_params) self.class.new(response.body['objects'].first) end end end end endfog-1.19.0/lib/fog/cloudsigma/models/ip.rb0000644000004100000410000000104212261242551020272 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' module Fog module Compute class CloudSigma class IP < Fog::CloudSigma::CloudsigmaModel identity :uuid attribute :tags, :type => :array attribute :nameservers, :type => :array attribute :server, :type => :string attribute :netmask, :type => :integer attribute :meta attribute :owner attribute :subscription attribute :gateway, :type => :string attribute :resource_uri, :type => :string end end end end fog-1.19.0/lib/fog/cloudsigma/models/fwpolicy.rb0000644000004100000410000000075412261242551021527 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' require 'fog/core/collection' require 'fog/cloudsigma/models/rule' module Fog module Compute class CloudSigma class FWPolicy < Fog::CloudSigma::CloudsigmaModel identity :uuid attribute :name, :type => :string attribute :meta attribute :owner attribute :resource_uri, :type => :string attribute :servers, :type => :array model_attribute_array :rules, Rule end end end end fog-1.19.0/lib/fog/cloudsigma/models/nic.rb0000644000004100000410000000071512261242551020441 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/cloudsigma/nested_model' require 'fog/cloudsigma/models/ipconf' module Fog module Compute class CloudSigma class Nic < Fog::CloudSigma::CloudsigmaModel attribute :boot_order attribute :mac, :type => :string attribute :model, :type => :string attribute :vlan model_attribute :ip_v4_conf, IPConf model_attribute :ip_v6_conf, IPConf end end end end fog-1.19.0/lib/fog/cloudsigma/models/pricing.rb0000644000004100000410000000104712261242551021322 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' require 'fog/cloudsigma/models/price_record' module Fog module Compute class CloudSigma class Pricing < Fog::CloudSigma::CloudsigmaModel model_attribute :cpu, PriceRecord model_attribute :hdd, PriceRecord model_attribute :ip, PriceRecord model_attribute :mem, PriceRecord model_attribute :sms, PriceRecord model_attribute :ssd, PriceRecord model_attribute :tx, PriceRecord model_attribute :vlan, PriceRecord end end end endfog-1.19.0/lib/fog/cloudsigma/models/subscription.rb0000644000004100000410000000271712261242551022420 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' module Fog module Compute class CloudSigma class Subscription < Fog::CloudSigma::CloudsigmaModel identity :id attribute :status, :type => :string attribute :uuid, :type => :string attribute :resource, :type => :string attribute :auto_renew, :type => :boolean attribute :descendants attribute :start_time, :type => :time attribute :price, :type => :float attribute :period, :type => :string attribute :remaining, :type => :string attribute :amount, :type => :integer attribute :end_time, :type => :time attribute :discount_percent, :type => :float attribute :subscribed_object, :type => :string attribute :discount_amount, :type => :float def save create end def create requires :resource, :amount data = attributes response = service.create_subscription(data) new_attributes = response.body['objects'].first merge_attributes(new_attributes) end def extend(period=nil, end_time=nil) requires :identity data = {} if period data[:period] = period elsif end_time data[:end_time] = end_time end response = service.extend_subscription(identity, data) self.class.new(response.body) end end end end end fog-1.19.0/lib/fog/cloudsigma/models/volumes.rb0000644000004100000410000000105512261242551021360 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/cloudsigma/models/volume' module Fog module Compute class CloudSigma class Volumes < Fog::Collection model Fog::Compute::CloudSigma::Volume def all resp = service.list_volumes data = resp.body['objects'] load(data) end def get(vol_id) resp = service.get_volume(vol_id) data = resp.body new(data) rescue Fog::CloudSigma::Errors::NotFound return nil end end end end end fog-1.19.0/lib/fog/cloudsigma/models/price_calculation.rb0000644000004100000410000000053612261242551023351 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' require 'fog/cloudsigma/models/subscriptions' module Fog module Compute class CloudSigma class PriceCalculation < Fog::CloudSigma::CloudsigmaModel attribute :price, :type => :float model_attribute_array :subscriptions, Subscription, :aliases => 'objects' end end end end fog-1.19.0/lib/fog/cloudsigma/models/lib_volumes.rb0000644000004100000410000000107712261242551022212 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/cloudsigma/models/lib_volume' module Fog module Compute class CloudSigma class LibVolumes < Fog::Collection model Fog::Compute::CloudSigma::LibVolume def all resp = service.list_lib_volumes data = resp.body['objects'] load(data) end def get(vol_id) resp = service.get_lib_volume(vol_id) data = resp.body new(data) rescue Fog::CloudSigma::Errors::NotFound return nil end end end end end fog-1.19.0/lib/fog/cloudsigma/models/subscriptions.rb0000644000004100000410000000217112261242551022575 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/cloudsigma/models/subscription' module Fog module Compute class CloudSigma class Subscriptions < Fog::Collection model Fog::Compute::CloudSigma::Subscription def all resp = service.list_subscriptions data = resp.body['objects'] load(data) end def get(sub_id) resp = service.get_subscription(sub_id) data = resp.body new(data) rescue Fog::CloudSigma::Errors::NotFound return nil end def check_price(subscriptions_list) subscriptions_list = subscriptions_list.map {|s| s.kind_of?(Hash) ? s : s.attributes} resp = service.calculate_subscription_price(subscriptions_list) PriceCalculation.new(resp.body) end def create_multiple(subscriptions_list) subscriptions_list = subscriptions_list.map { |s| s.kind_of?(Hash) ? s : s.attributes } resp = service.create_subscription(subscriptions_list) resp.body['objects'].map { |s| Subscription.new(s) } end end end end end fog-1.19.0/lib/fog/cloudsigma/models/server.rb0000644000004100000410000001407512261242551021202 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' require 'fog/cloudsigma/models/mountpoint' require 'fog/cloudsigma/models/nic' module Fog module Compute class CloudSigma class Server < Fog::CloudSigma::CloudsigmaModel identity :uuid attribute :status, :type => :string attribute :vnc_password, :type => :string attribute :name, :type => :string attribute :cpus_instead_of_cores, :type => :boolean attribute :tags attribute :mem, :type => :integer attribute :enable_numa, :type => :boolean attribute :smp attribute :hv_relaxed, :type => :boolean attribute :hv_tsc, :type => :boolean attribute :meta attribute :owner attribute :runtime attribute :cpu, :type => :integer attribute :resource_uri, :type => :string model_attribute_array :volumes, MountPoint, :aliases => 'drives' model_attribute_array :nics, Nic def save if persisted? update else create end end def create requires :name, :cpu, :mem, :vnc_password data = attributes response = service.create_server(data) new_attributes = response.body['objects'].first merge_attributes(new_attributes) end def update requires :identity, :name, :cpu, :mem, :vnc_password data = attributes response = service.update_server(identity, data) new_attributes = response.body merge_attributes(new_attributes) end def destroy requires :identity service.delete_server(identity) true end alias :delete :destroy def start(start_params={}) requires :identity service.start_server(identity, start_params) end def stop requires :identity service.stop_server(identity) end def open_vnc requires :identity service.open_vnc(identity) end def close_vnc requires :identity service.close_vnc(identity) end def clone(clone_params={}) requires :identity response = service.clone_server(identity, clone_params) self.class.new(response.body) end def mount_volume(volume, device = 'virtio', dev_channel = nil, boot_order = nil) unless dev_channel specified_channels = self.volumes.map { |v| v.dev_channel }.sort if specified_channels controller, controller_channel = 0, 0 max_ctlr, max_chnl = case device when 'ide' [4, 2] else [1024, 5] end dev_channel = "#{controller}:#{controller_channel}" while specified_channels.include? dev_channel controller_channel += 1 if controller_channel >= max_chnl controller_channel = 0 controller += 1 if controller >= max_ctlr raise Fog::CloudSigma::Errors::Error.new("Max channel reached, cannot attach more") end end dev_channel = "#{controller}:#{controller_channel}" end else # no other channels specified dev_channel = '0:0' end end vol_id = volume.kind_of?(String) ? volume : volume.identity mountpoint_data = { 'drive' => vol_id, 'device' => device, 'dev_channel' => dev_channel, } if boot_order mountpoint_data['boot_order'] = boot_order end self.volumes = self.volumes << MountPoint.new(mountpoint_data) end def unmount_volume(volume_or_position) if volume_or_position.kind_of? Fixnum self.volumes.delete_at(volume_or_position) # assign to update attributes return self.volumes = self.volumes end vol_id = volume_or_position.kind_of?(String) ? volume_or_position : volume_or_position.identity self.volumes = self.volumes.reject do |v| if v.volume.kind_of? Hash v.volume['uuid'] == vol_id else v.volume == vol_id end end end def unmount_all_volumes self.volumes = [] end def add_nic(vlan=nil, ip_v4_conf=nil, ip_v6_conf=nil, model='virtio', boot_order=nil) nic_data = { 'model' => model, 'vlan' => vlan, 'ip_v4_conf' => ip_v4_conf, 'ip_v6_conf' => ip_v6_conf } if boot_order nic_data['boot_order'] = boot_order end self.nics = self.nics << Nic.new(nic_data) end def add_public_nic(ip_or_conf=:dhcp, model='virtio', boot_order=nil) case ip_or_conf when :dhcp add_nic(nil, {:conf => :dhcp}, nil, model, boot_order) when :manual add_nic(nil, {:conf => :manual}, nil, model, boot_order) else ip = ip_or_conf.kind_of?(String) ? ip_or_conf : ip_or_conf.identity add_nic(nil, {:conf => :static, :ip => ip}, nil, model, boot_order) end end def add_private_nic(vlan, model='virtio', boot_order=nil) vlan = vlan.kind_of?(String) ? vlan : vlan.identity add_nic(vlan, nil, nil, model, boot_order) end def remove_nic(mac_or_position) if mac_or_position.kind_of? Fixnum self.nics.delete_at(mac_or_position) # assign to update attributes return self.nics = self.nics end self.nics = self.nics.reject { |n| n.mac == mac_or_position } end def remove_all_nics self.nics = [] end end end end endfog-1.19.0/lib/fog/cloudsigma/models/usage_record.rb0000644000004100000410000000047012261242551022330 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' module Fog module Compute class CloudSigma class UsageRecord < Fog::CloudSigma::CloudsigmaModel attribute :burst, :type => :integer attribute :subscribed, :type => :integer attribute :using, :type => :integer end end end end fog-1.19.0/lib/fog/cloudsigma/models/price_record.rb0000644000004100000410000000212512261242551022325 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' require 'bigdecimal' module Fog module Compute class CloudSigma class PriceRecord < Fog::CloudSigma::CloudsigmaModel attribute :resource, :type => :string attribute :multiplier, :type => :integer attribute :price, :type => :string attribute :level, :type => :integer attribute :currency, :type => :string attribute :unit, :type => :string def price if attributes[:price] BigDecimal(attributes[:price]) else nil end end def price=(new_price) attributes[:price] = new_price.kind_of?(String) ? new_price : new_price.to_s('F') end # The base price of the resource. # This is the price for the base API unit which is byte for memory, data, etc. and MHz for CPU. # Also the price is per second for time based resource (basically everything except data transfer which is not # limited in time) def base_price price / multiplier end end end end endfog-1.19.0/lib/fog/cloudsigma/models/vlans.rb0000644000004100000410000000103712261242551021011 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/cloudsigma/models/vlan' module Fog module Compute class CloudSigma class Vlans < Fog::Collection model Fog::Compute::CloudSigma::VLAN def all resp = service.list_vlans data = resp.body['objects'] load(data) end def get(vlan) resp = service.get_vlan(vlan) data = resp.body new(data) rescue Fog::CloudSigma::Errors::NotFound return nil end end end end end fog-1.19.0/lib/fog/cloudsigma/error.rb0000644000004100000410000000227112261242551017535 0ustar www-datawww-datamodule Fog module CloudSigma module Errors class Error < Fog::Errors::Error attr_accessor :type, :error_point def initialize(message, type='n/a', error_point=nil) @type = type @error_point = error_point super(message) end end class NotFound < Error; end class RequestError < Error; end class ServerError < Error; end def self.slurp_http_status_error(error) error_class = case error.response[:status] when 404 NotFound when 500..599 ServerError when 400..499 RequestError else Error end new_error = error_class.new(error.response[:body].first['error_message'], error.response[:body].first['error_type'], error.response[:body].first['error_point']) new_error.set_backtrace(error.backtrace) new_error.verbose = error.message new_error end end end endfog-1.19.0/lib/fog/cloudsigma/mock_data.rb0000644000004100000410000000307512261242551020331 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Mock def self.mock_data { :volumes => {}, :servers => {}, :vlans => {}, :ips => {}, :profile => {:login_sms=>false, :town=>"", :postcode=>"", :reseller=>"", :has_autotopup=>false, :currency=>"CHF", :state=>"REGULAR", :uuid=>"6c2203a1-a2e6-433f-aeab-b976b8cd3d18", :company=>"", :api_https_only=>false, :my_notes=>"", :key_auth=>false, :email=>"MyFirstName.MyLasttName@MyCompany.com", :bank_reference=>"mmlastname278", :first_name=>"MyFirstName", :meta =>"", :phone=>"", :language=>"EN", :vat=>"", :last_name=>"MyLasttName", :title=>"", :mailing_list=>true, :autotopup_amount=>0.0, :country=>"", :address=>""}, :subscriptions => {}, :current_usage => {}, :balance => {:balance => 100, :currency => 'CHF'}, } end end end end endfog-1.19.0/lib/fog/cloudsigma/compute.rb0000644000004100000410000001261212261242551020060 0ustar www-datawww-datarequire 'fog/compute' require 'fog/cloudsigma/connection' module Fog module Compute class CloudSigma < Fog::Service requires :cloudsigma_password, :cloudsigma_username recognizes :cloudsigma_password, :cloudsigma_username, :cloudsigma_host model_path 'fog/cloudsigma/models' request_path 'fog/cloudsigma/requests' model :volume collection :volumes request :create_volume request :get_volume request :list_volumes request :update_volume request :delete_volume request :clone_volume model :lib_volume collection :lib_volumes request :get_lib_volume request :list_lib_volumes model :ipconf model :nic model :mountpoint model :server collection :servers request :create_server request :get_server request :list_servers request :update_server request :delete_server request :start_server request :stop_server request :open_vnc request :close_vnc request :clone_server model :ip collection :ips request :list_ips request :get_ip model :vlan collection :vlans request :list_vlans request :get_vlan request :update_vlan model :rule model :fwpolicy collection :fwpolicies request :list_fwpolicies model :subscription collection :subscriptions request :list_subscriptions request :get_subscription request :create_subscription request :extend_subscription model :price_calculation request :calculate_subscription_price model :profile request :get_profile request :update_profile model :balance request :get_balance model :current_usage request :get_current_usage model :pricing request :get_pricing module CommonMockAndReal def initialize(options={}) @init_options = options setup_connection(options) end def profile response = get_profile Profile.new(response.body) end def balance response = get_balance Balance.new(response.body) end def current_usage response = get_current_usage CurrentUsage.new(response.body['usage']) end def currency # Cache since currency does not change @currency ||= profile.currency end def pricing resp = get_princing(currency) resp.body['objects'] end def current_pricing_levels resp = get_pricing(currency) resp.body['current'] end def next_pricing_levels resp = get_pricing(currency) resp.body['next'] end def subscription_pricing resp = get_pricing(currency, true) current_levels = resp.body['current'] current_prices = resp.body['objects'] current_pricing_pairs = current_levels.map do |resource, level| price_for_resource_and_level = current_prices.detect do |price| price['resource'] == resource end price_for_resource_and_level ||= {} [resource, price_for_resource_and_level] end Pricing.new(Hash[current_pricing_pairs]) end def current_pricing resp = get_pricing(currency) current_levels = resp.body['current'] current_prices = resp.body['objects'] current_pricing_pairs = current_levels.map do |resource, level| price_for_resource_and_level = current_prices.detect do |price| price['level'] == level && price['resource'] == resource end price_for_resource_and_level ||= {} [resource, price_for_resource_and_level] end Pricing.new(Hash[current_pricing_pairs]) end def next_pricing resp = get_pricing(currency) current_levels = resp.body['next'] current_prices = resp.body['objects'] current_pricing_pairs = current_levels.map do |resource, level| price_for_resource_and_level = current_prices.detect do |price| price['level'] == level && price['resource'] == resource end price_for_resource_and_level ||= {} [resource, price_for_resource_and_level] end Pricing.new(Hash[current_pricing_pairs]) end end class Mock include Collections include CommonMockAndReal include Fog::CloudSigma::CloudSigmaConnection::Mock require 'fog/cloudsigma/mock_data' def self.data @data ||= Hash.new do |hash, key| hash[key] = mock_data end end def self.random_uuid # Insert '4' at 13th position and 'a' at 17th as per uuid4 spec hex = Fog::Mock.random_hex(30).insert(12,'4').insert(16, 'a') # Add dashes "#{hex[0...8]}-#{hex[8...12]}-#{hex[12...16]}-#{hex[16...20]}-#{hex[20..32]}" end def self.random_mac (0..5).map{Fog::Mock.random_hex(2)}.join(':') end def data self.class.data[:test] end end class Real include Collections include CommonMockAndReal include Fog::CloudSigma::CloudSigmaConnection::Real end end end end fog-1.19.0/lib/fog/dreamhost.rb0000644000004100000410000000026512261242551016244 0ustar www-datawww-datarequire(File.expand_path(File.join(File.dirname(__FILE__), 'core'))) module Fog module Dreamhost extend Fog::Provider service(:dns, 'dreamhost/dns', 'DNS') end end fog-1.19.0/lib/fog/aws/0000755000004100000410000000000012261242551014520 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/elasticache.rb0000644000004100000410000001461112261242551017315 0ustar www-datawww-datamodule Fog module AWS class Elasticache < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods class IdentifierTaken < Fog::Errors::Error; end class InvalidInstance < Fog::Errors::Error; end class AuthorizationAlreadyExists < Fog::Errors::Error; end requires :aws_access_key_id, :aws_secret_access_key recognizes :region, :host, :path, :port, :scheme, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at request_path 'fog/aws/requests/elasticache' request :create_cache_cluster request :delete_cache_cluster request :describe_cache_clusters request :modify_cache_cluster request :reboot_cache_cluster request :create_cache_parameter_group request :delete_cache_parameter_group request :describe_cache_parameter_groups request :modify_cache_parameter_group request :reset_cache_parameter_group request :describe_engine_default_parameters request :describe_cache_parameters request :describe_reserved_cache_nodes request :create_cache_security_group request :delete_cache_security_group request :describe_cache_security_groups request :authorize_cache_security_group_ingress request :revoke_cache_security_group_ingress request :describe_events model_path 'fog/aws/models/elasticache' model :cluster collection :clusters model :security_group collection :security_groups model :parameter_group collection :parameter_groups class Real include Fog::AWS::CredentialFetcher::ConnectionMethods def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) options[:region] ||= 'us-east-1' @host = options[:host] || "elasticache.#{options[:region]}.amazonaws.com" @path = options[:path] || '/' @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new( "#{@scheme}://#{@host}:#{@port}#{@path}", options[:persistent] ) end def reload @connection.reset end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) end def request(params) refresh_credentials_if_expired idempotent = params.delete(:idempotent) parser = params.delete(:parser) body = Fog::AWS.signed_params( params, { :aws_access_key_id => @aws_access_key_id, :aws_session_token => @aws_session_token, :hmac => @hmac, :host => @host, :path => @path, :port => @port, #:version => '2011-07-15' :version => '2012-11-15' } ) begin @connection.request({ :body => body, :expects => 200, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded' }, :idempotent => idempotent, :host => @host, :method => 'POST', :parser => parser }) rescue Excon::Errors::HTTPStatusError => error match = Fog::AWS::Errors.match_error(error) raise if match.empty? raise case match[:code] when 'CacheSecurityGroupNotFound', 'CacheParameterGroupNotFound', 'CacheClusterNotFound' Fog::AWS::Elasticache::NotFound.slurp(error, match[:message]) when 'CacheSecurityGroupAlreadyExists' Fog::AWS::Elasticache::IdentifierTaken.slurp(error, match[:message]) when 'InvalidParameterValue' Fog::AWS::Elasticache::InvalidInstance.slurp(error, match[:message]) else Fog::AWS::Elasticache::Error.slurp(error, "#{match[:code]} => #{match[:message]}") end end end end class Mock include Fog::AWS::CredentialFetcher::ConnectionMethods def self.data @data ||= Hash.new do |hash, region| hash[region] = Hash.new do |region_hash, key| region_hash[key] = { :clusters => {}, # cache cluster data, indexed by cluster ID :security_groups => {}, # security groups } end end end def self.reset @data = nil end def initialize(options={}) @aws_credentials_expire_at = Time::now + 20 setup_credentials(options) @region = options[:region] || 'us-east-1' unless ['ap-northeast-1', 'ap-southeast-1', 'eu-west-1', 'us-east-1', 'us-west-1', 'us-west-2', 'sa-east-1'].include?(@region) raise ArgumentError, "Unknown region: #{@region.inspect}" end end def region_data self.class.data[@region] end def data self.region_data[@aws_access_key_id] end def reset_data self.region_data.delete(@aws_access_key_id) end def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] end # returns an Array of (Mock) elasticache nodes, representated as Hashes def create_cache_nodes(cluster_id, num_nodes = 1, port = '11211') (1..num_nodes).map do |node_number| node_id = "%04d" % node_number { # each hash represents a cache cluster node "CacheNodeId" => node_id, "Port" => port, "ParameterGroupStatus" => "in-sync", "CacheNodeStatus" => "available", "CacheNodeCreateTime" => Time.now.utc.to_s, "Address" => "#{cluster_id}.#{node_id}.use1.cache.amazonaws.com" } end end end end end end fog-1.19.0/lib/fog/aws/cloud_formation.rb0000644000004100000410000001014412261242551020231 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class CloudFormation < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods requires :aws_access_key_id, :aws_secret_access_key recognizes :host, :path, :port, :scheme, :persistent, :region, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at request_path 'fog/aws/requests/cloud_formation' request :create_stack request :update_stack request :delete_stack request :describe_stack_events request :describe_stack_resources request :describe_stacks request :get_template request :validate_template request :list_stacks request :list_stack_resources class Mock def initialize(options={}) Fog::Mock.not_implemented end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to CloudFormation # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # cf = CloudFormation.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # # ==== Returns # * CloudFormation object with connection to AWS. def initialize(options={}) require 'fog/core/parser' @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} options[:region] ||= 'us-east-1' @host = options[:host] || "cloudformation.#{options[:region]}.amazonaws.com" @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end def reload @connection.reset end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) end def request(params) refresh_credentials_if_expired idempotent = params.delete(:idempotent) parser = params.delete(:parser) body = Fog::AWS.signed_params( params, { :aws_access_key_id => @aws_access_key_id, :aws_session_token => @aws_session_token, :hmac => @hmac, :host => @host, :path => @path, :port => @port, :version => '2010-05-15' } ) begin @connection.request({ :body => body, :expects => 200, :idempotent => idempotent, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded' }, :method => 'POST', :parser => parser }) rescue Excon::Errors::HTTPStatusError => error match = Fog::AWS::Errors.match_error(error) raise if match.empty? raise case match[:code] when 'NotFound', 'ValidationError' Fog::AWS::CloudFormation::NotFound.slurp(error, match[:message]) else Fog::AWS::CloudFormation::Error.slurp(error, "#{match[:code]} => #{match[:message]}") end end end end end end end fog-1.19.0/lib/fog/aws/emr.rb0000644000004100000410000001030612261242551015630 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class EMR < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods class IdentifierTaken < Fog::Errors::Error; end requires :aws_access_key_id, :aws_secret_access_key recognizes :region, :host, :path, :port, :scheme, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at request_path 'fog/aws/requests/emr' request :add_instance_groups request :add_job_flow_steps request :describe_job_flows request :modify_instance_groups request :run_job_flow request :set_termination_protection request :terminate_job_flows # model_path 'fog/aws/models/rds' # model :server # collection :servers # model :snapshot # collection :snapshots # model :parameter_group # collection :parameter_groups # # model :parameter # collection :parameters # # model :security_group # collection :security_groups class Mock def initialize(options={}) Fog::Mock.not_implemented end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to EMR # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # emr = EMR.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # * region<~String> - optional region to use. For instance, in 'eu-west-1', 'us-east-1' and etc. # # ==== Returns # * EMR object with connection to AWS. def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} options[:region] ||= 'us-east-1' @host = options[:host] || "elasticmapreduce.#{options[:region]}.amazonaws.com" @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) @region = options[:region] end def reload @connection.reset end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) end def request(params) refresh_credentials_if_expired idempotent = params.delete(:idempotent) parser = params.delete(:parser) body = Fog::AWS.signed_params( params, { :aws_access_key_id => @aws_access_key_id, :aws_session_token => @aws_session_token, :hmac => @hmac, :host => @host, :path => @path, :port => @port, :version => '2009-03-31' #'2010-07-28' } ) begin response = @connection.request({ :body => body, :expects => 200, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded' }, :idempotent => idempotent, :host => @host, :method => 'POST', :parser => parser }) rescue Excon::Errors::HTTPStatusError raise end response end end end end end fog-1.19.0/lib/fog/aws/sns.rb0000644000004100000410000000707112261242551015655 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class SNS < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods requires :aws_access_key_id, :aws_secret_access_key recognizes :host, :path, :port, :scheme, :persistent, :region, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at request_path 'fog/aws/requests/sns' request :add_permission request :confirm_subscription request :create_topic request :delete_topic request :get_topic_attributes request :list_subscriptions request :list_subscriptions_by_topic request :list_topics request :publish request :remove_permission request :set_topic_attributes request :subscribe request :unsubscribe class Mock def initialize(options={}) end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to SNS # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # sns = SNS.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # # ==== Returns # * SNS object with connection to AWS. def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} options[:region] ||= 'us-east-1' @host = options[:host] || "sns.#{options[:region]}.amazonaws.com" @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end def reload @connection.reset end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) end def request(params) refresh_credentials_if_expired idempotent = params.delete(:idempotent) parser = params.delete(:parser) body = AWS.signed_params( params, { :aws_access_key_id => @aws_access_key_id, :aws_session_token => @aws_session_token, :hmac => @hmac, :host => @host, :path => @path, :port => @port } ) response = @connection.request({ :body => body, :expects => 200, :idempotent => idempotent, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded' }, :host => @host, :method => 'POST', :parser => parser }) response end end end end end fog-1.19.0/lib/fog/aws/iam.rb0000644000004100000410000001710312261242551015615 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class IAM < Fog::Service class EntityAlreadyExists < Fog::AWS::IAM::Error; end class KeyPairMismatch < Fog::AWS::IAM::Error; end class LimitExceeded < Fog::AWS::IAM::Error; end class MalformedCertificate < Fog::AWS::IAM::Error; end class ValidationError < Fog::AWS::IAM::Error; end requires :aws_access_key_id, :aws_secret_access_key recognizes :host, :path, :port, :scheme, :persistent, :instrumentor, :instrumentor_name request_path 'fog/aws/requests/iam' request :add_user_to_group request :add_role_to_instance_profile request :create_access_key request :create_account_alias request :create_group request :create_instance_profile request :create_login_profile request :create_role request :create_user request :delete_access_key request :delete_account_alias request :delete_group request :delete_group_policy request :delete_instance_profile request :delete_login_profile request :delete_role request :delete_role_policy request :delete_server_certificate request :delete_signing_certificate request :delete_user request :delete_user_policy request :get_group request :get_group_policy request :get_instance_profile request :get_role_policy request :get_login_profile request :get_server_certificate request :get_role request :get_user request :get_user_policy request :list_access_keys request :list_account_aliases request :list_group_policies request :list_groups request :list_groups_for_user request :list_instance_profiles request :list_instance_profiles_for_role request :list_roles request :list_role_policies request :list_server_certificates request :list_signing_certificates request :list_user_policies request :list_users request :put_group_policy request :put_role_policy request :put_user_policy request :remove_role_from_instance_profile request :remove_user_from_group request :update_access_key request :update_group request :update_login_profile request :update_server_certificate request :update_signing_certificate request :update_user request :upload_server_certificate request :upload_signing_certificate model_path 'fog/aws/models/iam' model :user collection :users model :policy collection :policies model :access_key collection :access_keys model :role collection :roles class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = { :owner_id => Fog::AWS::Mock.owner_id, :server_certificates => {}, :access_keys => [{ "Status" => "Active", "AccessKeyId" => key }], :users => Hash.new do |uhash, ukey| uhash[ukey] = { :user_id => Fog::AWS::Mock.key_id, :path => '/', :arn => "arn:aws:iam::#{Fog::AWS::Mock.owner_id}:user/#{ukey}", :access_keys => [], :created_at => Time.now, :policies => {} } end, :groups => Hash.new do |ghash, gkey| ghash[gkey] = { :group_id => Fog::AWS::Mock.key_id, :arn => "arn:aws:iam::#{Fog::AWS::Mock.owner_id}:group/#{gkey}", :members => [], :created_at => Time.now, :policies => {} } end } end end def self.reset @data = nil end def self.server_certificate_id Fog::Mock.random_hex(16) end def initialize(options={}) @aws_access_key_id = options[:aws_access_key_id] end def data self.class.data[@aws_access_key_id] end def reset_data self.class.data.delete(@aws_access_key_id) end end class Real # Initialize connection to IAM # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # iam = IAM.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # # ==== Returns # * IAM object with connection to AWS. def initialize(options={}) require 'fog/core/parser' @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @connection_options = options[:connection_options] || {} @instrumentor = options[:instrumentor] @instrumentor_name = options[:instrumentor_name] || 'fog.aws.iam' @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) @host = options[:host] || 'iam.amazonaws.com' @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end def reload @connection.reset end private def request(params) idempotent = params.delete(:idempotent) parser = params.delete(:parser) body = Fog::AWS.signed_params( params, { :aws_access_key_id => @aws_access_key_id, :hmac => @hmac, :host => @host, :path => @path, :port => @port, :version => '2010-05-08' } ) if @instrumentor @instrumentor.instrument("#{@instrumentor_name}.request", params) do _request(body, idempotent, parser) end else _request(body, idempotent, parser) end end def _request(body, idempotent, parser) @connection.request({ :body => body, :expects => 200, :idempotent => idempotent, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded' }, :method => 'POST', :parser => parser }) rescue Excon::Errors::HTTPStatusError => error match = Fog::AWS::Errors.match_error(error) raise if match.empty? raise case match[:code] when 'CertificateNotFound', 'NoSuchEntity' Fog::AWS::IAM::NotFound.slurp(error, match[:message]) when 'EntityAlreadyExists', 'KeyPairMismatch', 'LimitExceeded', 'MalformedCertificate', 'ValidationError' Fog::AWS::IAM.const_get(match[:code]).slurp(error, match[:message]) else Fog::AWS::IAM::Error.slurp(error, "#{match[:code]} => #{match[:message]}") end end end end end end fog-1.19.0/lib/fog/aws/cdn.rb0000644000004100000410000001641612261242551015621 0ustar www-datawww-datarequire 'fog/aws' require 'fog/cdn' module Fog module CDN class AWS < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods requires :aws_access_key_id, :aws_secret_access_key recognizes :host, :path, :port, :scheme, :version, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at model_path 'fog/aws/models/cdn' model :distribution collection :distributions model :streaming_distribution collection :streaming_distributions request_path 'fog/aws/requests/cdn' request 'delete_distribution' request 'delete_streaming_distribution' request 'get_distribution' request 'get_distribution_list' request 'get_invalidation_list' request 'get_invalidation' request 'get_streaming_distribution' request 'get_streaming_distribution_list' request 'post_distribution' request 'post_streaming_distribution' request 'post_invalidation' request 'put_distribution_config' request 'put_streaming_distribution_config' class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = { :distributions => {}, :streaming_distributions => {}, :invalidations => {} } end end def self.reset @data = nil end def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) end def data self.class.data[@aws_access_key_id] end def reset_data self.class.data.delete(@aws_access_key_id) end def signature(params) "foo" end def setup_credentials(options={}) @aws_access_key_id = options[:aws_access_key_id] end def self.distribution_id random_id(14) end def self.generic_id random_id(14) end def self.domain_name "#{random_id(12).downcase}.cloudfront.net" end def self.random_id(length) Fog::Mock.random_selection("abcdefghijklmnopqrstuvwxyz0123456789", length).upcase end CDN_ERRORS = { :access_denies => {:code => 'AccessDenied',:msg => 'Access denied.',:status => 403}, :inappropriate_xml => {:code => 'InappropriateXML',:msg => 'The XML document you provided was well-formed and valid, but not appropriate for this operation.',:status => 400}, :internal_error => {:code => 'InternalError',:msg => 'We encountered an internal error. Please try again.',:status => 500}, :invalid_action => {:code => 'InvalidAction',:msg => 'The action specified is not valid.',:status => 400}, :invalid_argument => {:code => 'InvalidArgument',:msg => '%s', :status => 400}, :not_implemented => {:code => 'NotImplemented', :msg => 'Not implemented.',:status => 501}, :no_such_distribution => { :code => 'NoSuchDistribution', :msg => 'The specified distribution does not exist', :status => 404 }, :no_such_streaming_distribution => { :code => 'NoSuchStreamingDistribution', :msg => 'The specified streaming distribution does not exist', :status => 404 }, :no_such_invalidation => { :code => 'NoSuchInvalidation', :msg => 'The specified invalidation does not exist', :status => 404 }, :cname_exists => { :code => 'CNAMEAlreadyExists', :msg => 'One or more of the CNAMEs you provided are already associated with a different distribution', :status => 409 }, :illegal_update => { :code => 'IllegalUpdate', :msg => 'Origin and CallerReference cannot be updated.', :status => 400 }, :invalid_if_match_version => { :code => 'InvalidIfMatchVersion', :msg => 'The If-Match version is missing or not valid for the distribution.', :status => 400}, :distribution_not_disabled => { :code => 'DistributionNotDisabled', :msg => 'The distribution you are trying to delete has not been disabled.', :status => 409 }, } def self.error(code, argument = '') if error = CDN_ERRORS[code] raise_error(error[:status], error[:code], error[:msg] % argument) end end def self.raise_error(status, code, message='') response = Excon::Response.new response.status = status response.body = < Sender #{code} #{message}. #{Fog::AWS::Mock.request_id} EOF raise(Excon::Errors.status_error({:expects => 201}, response)) end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to Cloudfront # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # cdn = Fog::AWS::CDN.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # # ==== Returns # * cdn object with connection to aws. def initialize(options={}) require 'fog/core/parser' @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} @host = options[:host] || 'cloudfront.amazonaws.com' @path = options[:path] || '/' @persistent = options.fetch(:persistent, true) @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @version = options[:version] || '2010-11-01' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end def reload @connection.reset end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha1', @aws_secret_access_key) end def request(params, &block) refresh_credentials_if_expired params[:headers] ||= {} params[:headers]['Date'] = Fog::Time.now.to_date_header params[:headers]['x-amz-security-token'] = @aws_session_token if @aws_session_token params[:headers]['Authorization'] = "AWS #{@aws_access_key_id}:#{signature(params)}" params[:path] = "/#{@version}/#{params[:path]}" @connection.request(params, &block) end def signature(params) string_to_sign = params[:headers]['Date'] signed_string = @hmac.sign(string_to_sign) Base64.encode64(signed_string).chomp! end end end end end fog-1.19.0/lib/fog/aws/dynamodb.rb0000644000004100000410000001027012261242551016642 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class DynamoDB < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods requires :aws_access_key_id, :aws_secret_access_key recognizes :aws_session_token, :host, :path, :port, :scheme, :persistent, :region, :use_iam_profile, :aws_credentials_expire_at request_path 'fog/aws/requests/dynamodb' request :batch_get_item request :batch_write_item request :create_table request :delete_item request :delete_table request :describe_table request :get_item request :list_tables request :put_item request :query request :scan request :update_item request :update_table class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = { :domains => {} } end end def self.reset @data = nil end def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) end def data self.class.data[@aws_access_key_id] end def reset_data self.class.data.delete(@aws_access_key_id) end def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to DynamoDB # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # ddb = DynamoDB.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # # ==== Returns # * DynamoDB object with connection to aws def initialize(options={}) @use_iam_profile = options[:use_iam_profile] @region = options[:region] || 'us-east-1' setup_credentials(options) @connection_options = options[:connection_options] || {} @host = options[:host] || "dynamodb.#{@region}.amazonaws.com" @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || '443' @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @signer = Fog::AWS::SignatureV4.new(@aws_access_key_id, @aws_secret_access_key, @region, 'dynamodb') end def reload @connection.reset end def request(params) refresh_credentials_if_expired # defaults for all dynamodb requests params.merge!({ :expects => 200, :host => @host, :method => :post, :path => '/' }) # setup headers and sign with signature v4 date = Fog::Time.now params[:headers] = { 'Content-Type' => 'application/x-amz-json-1.0', 'Date' => date.to_iso8601_basic, 'Host' => @host, }.merge!(params[:headers]) params[:headers]['x-amz-security-token'] = @aws_session_token if @aws_session_token params[:headers]['Authorization'] = @signer.sign(params, date) response = @connection.request(params) unless response.body.empty? response.body = Fog::JSON.decode(response.body) end response end end end end end fog-1.19.0/lib/fog/aws/redshift.rb0000644000004100000410000001115712261242551016662 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class Redshift < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods requires :aws_access_key_id, :aws_secret_access_key recognizes :region, :host, :path, :port, :scheme, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at request_path 'fog/aws/requests/redshift' request :describe_clusters request :describe_cluster_parameter_groups request :describe_cluster_parameters request :describe_cluster_security_groups request :describe_cluster_snapshots request :describe_cluster_subnet_groups request :describe_cluster_versions request :describe_default_cluster_parameters request :describe_events request :describe_orderable_cluster_options request :describe_reserved_node_offerings request :describe_reserved_nodes request :describe_resize request :create_cluster request :create_cluster_parameter_group request :create_cluster_security_group request :create_cluster_snapshot request :create_cluster_subnet_group request :modify_cluster request :modify_cluster_parameter_group request :modify_cluster_subnet_group request :delete_cluster request :delete_cluster_parameter_group request :delete_cluster_security_group request :delete_cluster_snapshot request :delete_cluster_subnet_group request :authorize_cluster_security_group_ingress request :authorize_snapshot_access request :copy_cluster_snapshot request :purchase_reserved_node_offering request :reboot_cluster request :reset_cluster_parameter_group request :restore_from_cluster_snapshot request :revoke_cluster_security_group_ingress request :revoke_snapshot_access class Mock def initialize(options={}) Fog::Mock.not_implemented end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to Redshift # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # ses = SES.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # * region<~String> - optional region to use. For instance, 'us-east-1' and etc. # # ==== Returns # * Redshift object with connection to AWS. def initialize(options={}) @use_iam_profile = options[:use_iam_profile] @region = options[:region] || 'us-east-1' setup_credentials(options) @connection_options = options[:connection_options] || {} @host = options[:host] || "redshift.#{@region}.amazonaws.com" @version = '2012-12-01' @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @signer = Fog::AWS::SignatureV4.new( @aws_access_key_id, @aws_secret_access_key,@region,'redshift') end def request(params, &block) refresh_credentials_if_expired parser = params.delete(:parser) date = Fog::Time.now params[:headers]['Date'] = date.to_date_header params[:headers]['x-amz-date'] = date.to_iso8601_basic params[:headers]['Host'] = @host params[:headers]['x-amz-redshift-version'] = @version params[:headers]['x-amz-security-token'] = @aws_session_token if @aws_session_token params[:headers]['Authorization'] = @signer.sign params, date response = @connection.request(params.merge(:parser => parser), &block) response end end end end end fog-1.19.0/lib/fog/aws/auto_scaling.rb0000644000004100000410000002266712261242551017532 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class AutoScaling < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods class IdentifierTaken < Fog::Errors::Error; end class ResourceInUse < Fog::Errors::Error; end class ValidationError < Fog::Errors::Error; end requires :aws_access_key_id, :aws_secret_access_key recognizes :host, :path, :port, :scheme, :persistent, :region, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at, :instrumentor, :instrumentor_name request_path 'fog/aws/requests/auto_scaling' request :create_auto_scaling_group request :create_launch_configuration request :create_or_update_tags request :delete_auto_scaling_group request :delete_launch_configuration request :delete_notification_configuration request :delete_policy request :delete_scheduled_action request :delete_tags request :describe_adjustment_types request :describe_auto_scaling_groups request :describe_auto_scaling_instances request :describe_auto_scaling_notification_types request :describe_launch_configurations request :describe_metric_collection_types request :describe_notification_configurations request :describe_policies request :describe_scaling_activities request :describe_scaling_process_types request :describe_scheduled_actions request :describe_tags request :describe_termination_policy_types request :disable_metrics_collection request :enable_metrics_collection request :execute_policy request :put_notification_configuration request :put_scaling_policy request :put_scheduled_update_group_action request :resume_processes request :set_desired_capacity request :set_instance_health request :suspend_processes request :terminate_instance_in_auto_scaling_group request :update_auto_scaling_group model_path 'fog/aws/models/auto_scaling' model :activity collection :activities model :configuration collection :configurations model :group collection :groups model :instance collection :instances model :policy collection :policies ExpectedOptions = {} class Real include Fog::AWS::CredentialFetcher::ConnectionMethods attr_accessor :region # Initialize connection to AutoScaling # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # as = AutoScaling.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # # ==== Returns # * AutoScaling object with connection to AWS. def initialize(options={}) require 'fog/core/parser' @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} @instrumentor = options[:instrumentor] @instrumentor_name = options[:instrumentor_name] || 'fog.aws.auto_scaling' options[:region] ||= 'us-east-1' @region = options[:region] @host = options[:host] || "autoscaling.#{options[:region]}.amazonaws.com" @path = options[:path] || '/' @port = options[:port] || 443 @persistent = options[:persistent] || false @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end def reload @connection.reset end private def request(params) refresh_credentials_if_expired idempotent = params.delete(:idempotent) parser = params.delete(:parser) body = AWS.signed_params( params, { :aws_access_key_id => @aws_access_key_id, :aws_session_token => @aws_session_token, :hmac => @hmac, :host => @host, :path => @path, :port => @port, :version => '2011-01-01' } ) if @instrumentor @instrumentor.instrument("#{@instrumentor_name}.request", params) do _request(body, idempotent, parser) end else _request(body, idempotent, parser) end end def _request(body, idempotent, parser) begin @connection.request({ :body => body, :expects => 200, :idempotent => idempotent, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded' }, :method => 'POST', :parser => parser }) rescue Excon::Errors::HTTPStatusError => error match = Fog::AWS::Errors.match_error(error) raise if match.empty? raise case match[:code] when 'AlreadyExists' Fog::AWS::AutoScaling::IdentifierTaken.slurp(error, match[:message]) when 'ResourceInUse' Fog::AWS::AutoScaling::ResourceInUse.slurp(error, match[:message]) when 'ValidationError' Fog::AWS::AutoScaling::ValidationError.slurp(error, match[:message]) else Fog::AWS::AutoScaling::Error.slurp(error, "#{match[:code]} => #{match[:message]}") end end end def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) end end class Mock include Fog::AWS::CredentialFetcher::ConnectionMethods attr_accessor :region def self.data @data ||= Hash.new do |hash, region| owner_id = Fog::AWS::Mock.owner_id hash[region] = Hash.new do |region_hash, key| region_hash[key] = { :adjustment_types => [ 'ChangeInCapacity', 'ExactCapacity', 'PercentChangeInCapacity' ], :auto_scaling_groups => {}, :scaling_policies => {}, :health_states => [ 'Healthy', 'Unhealthy' ], :launch_configurations => {}, :metric_collection_types => { :granularities => [ '1Minute' ], :metrics => [ 'GroupMinSize', 'GroupMaxSize', 'GroupDesiredCapacity', 'GroupInServiceInstances', 'GroupPendingInstances', 'GroupTerminatingInstances', 'GroupTotalInstances' ] }, :notification_configurations => {}, :notification_types => [ 'autoscaling:EC2_INSTANCE_LAUNCH', 'autoscaling:EC2_INSTANCE_LAUNCH_ERROR', 'autoscaling:EC2_INSTANCE_TERMINATE', 'autoscaling:EC2_INSTANCE_TERMINATE_ERROR', 'autoscaling:TEST_NOTIFICATION' ], :owner_id => owner_id, :process_types => [ 'AZRebalance', 'AddToLoadBalancer', 'AlarmNotification', 'HealthCheck', 'Launch', 'ReplaceUnhealthy', 'ScheduledActions', 'Terminate' ], :termination_policy_types => [ 'ClosestToNextInstanceHour', 'Default', 'NewestInstance', 'OldestInstance', 'OldestLaunchConfiguration' ] } end end end def self.reset @data = nil end def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @region = options[:region] || 'us-east-1' unless ['ap-northeast-1', 'ap-southeast-1', 'ap-southeast-2', 'eu-west-1', 'sa-east-1', 'us-east-1', 'us-west-1', 'us-west-2'].include?(@region) raise ArgumentError, "Unknown region: #{@region.inspect}" end end def region_data self.class.data[@region] end def data self.region_data[@aws_access_key_id] end def reset_data self.region_data.delete(@aws_access_key_id) end def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] end end end end end fog-1.19.0/lib/fog/aws/sqs.rb0000644000004100000410000001137412261242551015661 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class SQS < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods requires :aws_access_key_id, :aws_secret_access_key recognizes :region, :host, :path, :port, :scheme, :persistent, :aws_session_token, :use_iam_profile, :aws_credentials_expire_at request_path 'fog/aws/requests/sqs' request :change_message_visibility request :create_queue request :delete_message request :delete_queue request :get_queue_attributes request :list_queues request :receive_message request :send_message request :set_queue_attributes class Mock def self.data @data ||= Hash.new do |hash, region| hash[region] = Hash.new do |region_hash, key| region_hash[key] = { :owner_id => Fog::AWS::Mock.owner_id, :queues => {} } end end end def self.reset @data = nil end def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @region = options[:region] || 'us-east-1' unless ['ap-northeast-1', 'ap-southeast-1', 'ap-southeast-2', 'eu-west-1', 'us-east-1', 'us-west-1', 'us-west-2', 'sa-east-1'].include?(@region) raise ArgumentError, "Unknown region: #{@region.inspect}" end end def data self.class.data[@region][@aws_access_key_id] end def reset_data self.class.data[@region].delete(@aws_access_key_id) end def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to SQS # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # sqs = SQS.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # * region<~String> - optional region to use. For instance, 'eu-west-1', 'us-east-1' and etc. # # ==== Returns # * SQS object with connection to AWS. def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} options[:region] ||= 'us-east-1' @host = options[:host] || "sqs.#{options[:region]}.amazonaws.com" @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end def reload @connection.reset end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) end def path_from_queue_url(queue_url) queue_url.split('.com', 2).last.sub(/^:[0-9]+/, '') end def request(params) refresh_credentials_if_expired idempotent = params.delete(:idempotent) parser = params.delete(:parser) path = params.delete(:path) body = AWS.signed_params( params, { :aws_access_key_id => @aws_access_key_id, :aws_session_token => @aws_session_token, :hmac => @hmac, :path => path || @path, :version => '2009-02-01' } ) args = { :body => body, :expects => 200, :idempotent => idempotent, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded' }, :host => @host, :method => 'POST', :parser => parser } args.merge!(:path => path) if path response = @connection.request(args) response end end end end end fog-1.19.0/lib/fog/aws/ses.rb0000644000004100000410000001147412261242551015646 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class SES < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods class InvalidParameterError < Fog::Errors::Error; end class MessageRejected < Fog::Errors::Error; end requires :aws_access_key_id, :aws_secret_access_key recognizes :region, :host, :path, :port, :scheme, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at request_path 'fog/aws/requests/ses' request :delete_verified_email_address request :verify_email_address request :verify_domain_identity request :get_send_quota request :get_send_statistics request :list_verified_email_addresses request :send_email request :send_raw_email class Mock def initialize(options={}) Fog::Mock.not_implemented end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to SES # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # ses = SES.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # * region<~String> - optional region to use. For instance, 'us-east-1' and etc. # # ==== Returns # * SES object with connection to AWS. def initialize(options={}) require 'fog/core/parser' @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} options[:region] ||= 'us-east-1' @host = options[:host] || "email.#{options[:region]}.amazonaws.com" @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end def reload @connection.reset end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) end def request(params) refresh_credentials_if_expired idempotent = params.delete(:idempotent) parser = params.delete(:parser) headers = { 'Content-Type' => 'application/x-www-form-urlencoded', 'Date' => Fog::Time.now.to_date_header, } headers['x-amz-security-token'] = @aws_session_token if @aws_session_token #AWS3-HTTPS AWSAccessKeyId=, Algorithm=HmacSHA256, Signature= headers['X-Amzn-Authorization'] = 'AWS3-HTTPS ' headers['X-Amzn-Authorization'] << 'AWSAccessKeyId=' << @aws_access_key_id headers['X-Amzn-Authorization'] << ', Algorithm=HmacSHA256' headers['X-Amzn-Authorization'] << ', Signature=' << Base64.encode64(@hmac.sign(headers['Date'])).chomp! body = '' for key in params.keys.sort unless (value = params[key]).nil? body << "#{key}=#{CGI.escape(value.to_s).gsub(/\+/, '%20')}&" end end body.chop! # remove trailing '&' begin response = @connection.request({ :body => body, :expects => 200, :headers => headers, :idempotent => idempotent, :host => @host, :method => 'POST', :parser => parser }) rescue Excon::Errors::HTTPStatusError => error match = Fog::AWS::Errors.match_error(error) raise if match.empty? raise case match[:code] when 'MessageRejected' Fog::AWS::SES::MessageRejected.slurp(error, match[:message]) when 'InvalidParameterValue' Fog::AWS::SES::InvalidParameterError.slurp(error, match[:message]) else Fog::AWS::SES::Error.slurp(error, "#{match[:code]} => #{match[:message]}") end end response end end end end end fog-1.19.0/lib/fog/aws/requests/0000755000004100000410000000000012261242551016373 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/sts/0000755000004100000410000000000012261242551017204 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/sts/assume_role.rb0000644000004100000410000000362412261242551022054 0ustar www-datawww-datamodule Fog module AWS class STS class Real require 'fog/aws/parsers/sts/assume_role' # Assume Role # # ==== Parameters # * role_session_name<~String> - An identifier for the assumed role. # * role_arn<~String> - The ARN of the role the caller is assuming. # * external_id<~String> - An optional unique identifier required by the assuming role's trust identity. # * policy<~String> - An optional JSON policy document # * duration<~Integer> - Duration (of seconds) for the assumed role credentials to be valid (default 3600) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Arn'<~String>: The ARN of the assumed role/user # * 'AccessKeyId'<~String>: The AWS access key of the temporary credentials for the assumed role # * 'SecretAccessKey'<~String>: The AWS secret key of the temporary credentials for the assumed role # * 'SessionToken'<~String>: The AWS session token of the temporary credentials for the assumed role # * 'Expiration'<~Time>: The expiration time of the temporary credentials for the assumed role # # ==== See Also # http://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html # def assume_role(role_session_name, role_arn, external_id=nil, policy=nil, duration=3600) request({ 'Action' => 'AssumeRole', 'RoleSessionName' => role_session_name, 'RoleArn' => role_arn, 'Policy' => policy && Fog::JSON.encode(policy), 'DurationSeconds' => duration, 'ExternalId' => external_id, :idempotent => true, :parser => Fog::Parsers::AWS::STS::AssumeRole.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/sts/get_session_token.rb0000644000004100000410000000067312261242551023261 0ustar www-datawww-datamodule Fog module AWS class STS class Real require 'fog/aws/parsers/sts/get_session_token' def get_session_token(duration=43200) request({ 'Action' => 'GetSessionToken', 'DurationSeconds' => duration, :idempotent => true, :parser => Fog::Parsers::AWS::STS::GetSessionToken.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/sts/get_federation_token.rb0000644000004100000410000000464412261242551023720 0ustar www-datawww-datamodule Fog module AWS class STS class Real require 'fog/aws/parsers/sts/get_session_token' # Get federation token # # ==== Parameters # * name<~String>: The name of the federated user. # Minimum length of 2. Maximum length of 32. # * policy<~String>: Optional policy that specifies the permissions # that are granted to the federated user # Minimum length of 1. Maximum length of 2048. # * duration<~Integer>: Optional duration, in seconds, that the session # should last. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'SessionToken'<~String> - # * 'SecretAccessKey'<~String> - # * 'Expiration'<~String> - # * 'AccessKeyId'<~String> - # * 'Arn'<~String> - # * 'FederatedUserId'<~String> - # * 'PackedPolicySize'<~String> - # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html def get_federation_token(name, policy, duration=43200) request({ 'Action' => 'GetFederationToken', 'Name' => name, 'Policy' => Fog::JSON.encode(policy), 'DurationSeconds' => duration, :idempotent => true, :parser => Fog::Parsers::AWS::STS::GetSessionToken.new }) end end class Mock def get_federation_token(name, policy, duration=43200) Excon::Response.new.tap do |response| response.status = 200 response.body = { 'SessionToken' => Fog::Mock.random_base64(580), 'SecretAccessKey' => Fog::Mock.random_base64(40), 'Expiration' => (DateTime.now + duration).strftime('%FT%TZ'), 'AccessKeyId' => Fog::AWS::Mock.key_id(20), 'Arn' => "arn:aws:sts::#{Fog::AWS::Mock.owner_id}:federated-user/#{name}", 'FederatedUserId' => "#{Fog::AWS::Mock.owner_id}:#{name}", 'PackedPolicySize' => Fog::Mock.random_numbers(2), 'RequestId' => Fog::AWS::Mock.request_id } end end end end end end fog-1.19.0/lib/fog/aws/requests/sqs/0000755000004100000410000000000012261242551017201 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/sqs/set_queue_attributes.rb0000644000004100000410000000326012261242551023774 0ustar www-datawww-datamodule Fog module AWS class SQS class Real require 'fog/aws/parsers/sqs/basic' # Get attributes of a queue # # ==== Parameters # * queue_url<~String> - Url of queue to get attributes for # * attribute_name<~String> - Name of attribute to set, keys in ['MaximumMessageSize', 'MessageRetentionPeriod', 'Policy', 'VisibilityTimeout'] # * attribute_value<~String> - Value to set for attribute # # ==== See Also # http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QuerySetQueueAttributes.html # def set_queue_attributes(queue_url, attribute_name, attribute_value) request({ 'Action' => 'SetQueueAttributes', 'Attribute.Name' => attribute_name, 'Attribute.Value' => attribute_value, :path => path_from_queue_url(queue_url), :parser => Fog::Parsers::AWS::SQS::Basic.new }) end end class Mock def set_queue_attributes(queue_url, attribute_name, attribute_value) Excon::Response.new.tap do |response| if (queue = data[:queues][queue_url]) response.status = 200 queue['Attributes'][attribute_name] = attribute_value response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end end end end end end end fog-1.19.0/lib/fog/aws/requests/sqs/delete_queue.rb0000644000004100000410000000240312261242551022173 0ustar www-datawww-datamodule Fog module AWS class SQS class Real require 'fog/aws/parsers/sqs/basic' # Delete a queue # # ==== Parameters # * queue_url<~String> - Url of queue to delete # # ==== See Also # http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryDeleteQueue.html # def delete_queue(queue_url) request({ 'Action' => 'DeleteQueue', :parser => Fog::Parsers::AWS::SQS::Basic.new, :path => path_from_queue_url(queue_url), }) end end class Mock def delete_queue(queue_url) Excon::Response.new.tap do |response| if (queue = data[:queues][queue_url]) response.status = 200 data[:queues].delete(queue_url) response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end end end end end end end fog-1.19.0/lib/fog/aws/requests/sqs/list_queues.rb0000644000004100000410000000207412261242551022073 0ustar www-datawww-datamodule Fog module AWS class SQS class Real require 'fog/aws/parsers/sqs/list_queues' # List queues # # ==== Parameters # * options<~Hash>: # * QueueNamePrefix<~String> - String used to filter results to only those with matching prefixes # # ==== See Also # http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryListQueues.html # def list_queues(options = {}) request({ 'Action' => 'ListQueues', :parser => Fog::Parsers::AWS::SQS::ListQueues.new }.merge!(options)) end end class Mock def list_queues(options = {}) Excon::Response.new.tap do |response| response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'QueueUrls' => data[:queues].keys } end end end end end end fog-1.19.0/lib/fog/aws/requests/sqs/create_queue.rb0000644000004100000410000000423212261242551022176 0ustar www-datawww-datamodule Fog module AWS class SQS class Real require 'fog/aws/parsers/sqs/create_queue' # Create a queue # # ==== Parameters # * name<~String> - Name of queue to create # * options<~Hash>: # * DefaultVisibilityTimeout<~String> - Time, in seconds, to hide a message after it has been received, in 0..43200, defaults to 30 # # ==== See Also # http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryCreateQueue.html # def create_queue(name, options = {}) request({ 'Action' => 'CreateQueue', 'QueueName' => name, :parser => Fog::Parsers::AWS::SQS::CreateQueue.new }.merge!(options)) end end class Mock def create_queue(name, options = {}) Excon::Response.new.tap do |response| response.status = 200 now = Time.now queue_url = "https://queue.amazonaws.com/#{data[:owner_id]}/#{name}" queue = { 'QueueName' => name, 'Attributes' => { 'VisibilityTimeout' => 30, 'ApproximateNumberOfMessages' => 0, 'ApproximateNumberOfMessagesNotVisible' => 0, 'CreatedTimestamp' => now, 'LastModifiedTimestamp' => now, 'QueueArn' => Fog::AWS::Mock.arn('sqs', 'us-east-1', data[:owner_id], name), 'MaximumMessageSize' => 8192, 'MessageRetentionPeriod' => 345600 }, :messages => {}, :receipt_handles => {} } data[:queues][queue_url] = queue unless data[:queues][queue_url] response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'QueueUrl' => queue_url } end end end end end end fog-1.19.0/lib/fog/aws/requests/sqs/receive_message.rb0000644000004100000410000000627412261242551022665 0ustar www-datawww-datamodule Fog module AWS class SQS class Real require 'fog/aws/parsers/sqs/receive_message' # Get a message from a queue (marks it as unavailable temporarily, but does not remove from queue, see delete_message) # # ==== Parameters # * queue_url<~String> - Url of queue to get message from # * options<~Hash>: # * Attributes<~Array> - List of attributes to return, in ['All', 'ApproximateFirstReceiveTimestamp', 'ApproximateReceiveCount', 'SenderId', 'SentTimestamp'], defaults to 'All' # * MaxNumberOfMessages<~Integer> - Maximum number of messages to return, defaults to 1 # * VisibilityTimeout<~Integer> - Duration, in seconds, to hide message from other receives. In 0..43200, defaults to visibility timeout for queue # # ==== See Also # http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryReceiveMessage.html # def receive_message(queue_url, options = {}) request({ 'Action' => 'ReceiveMessage', 'AttributeName' => 'All', :path => path_from_queue_url(queue_url), :parser => Fog::Parsers::AWS::SQS::ReceiveMessage.new }.merge!(options)) end end class Mock def receive_message(queue_url, options = {}) Excon::Response.new.tap do |response| if (queue = data[:queues][queue_url]) max_number_of_messages = options['MaxNumberOfMessages'] || 1 now = Time.now messages = [] queue[:messages].values.each do |m| message_id = m['MessageId'] invisible = if (received_handles = queue[:receipt_handles][message_id]) visibility_timeout = m['Attributes']['VisibilityTimeout'] || queue['Attributes']['VisibilityTimeout'] received_handles.any? { |handle, time| now < time + visibility_timeout } else false end unless invisible receipt_handle = Fog::Mock.random_base64(300) queue[:receipt_handles][message_id] ||= {} queue[:receipt_handles][message_id][receipt_handle] = now m['Attributes'].tap do |attrs| attrs['ApproximateFirstReceiveTimestamp'] ||= now attrs['ApproximateReceiveCount'] = (attrs['ApproximateReceiveCount'] || 0) + 1 end messages << m.merge({ 'ReceiptHandle' => receipt_handle }) break if messages.size >= max_number_of_messages end end response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'Message' => messages } response.status = 200 else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end end end end end end end fog-1.19.0/lib/fog/aws/requests/sqs/delete_message.rb0000644000004100000410000000335312261242551022500 0ustar www-datawww-datamodule Fog module AWS class SQS class Real require 'fog/aws/parsers/sqs/basic' # Delete a message from a queue # # ==== Parameters # * queue_url<~String> - Url of queue to delete message from # * receipt_handle<~String> - Token from previous recieve message # # ==== See Also # http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryDeleteMessage.html # def delete_message(queue_url, receipt_handle) request({ 'Action' => 'DeleteMessage', 'ReceiptHandle' => receipt_handle, :parser => Fog::Parsers::AWS::SQS::Basic.new, :path => path_from_queue_url(queue_url), }) end end class Mock def delete_message(queue_url, receipt_handle) Excon::Response.new.tap do |response| if (queue = data[:queues][queue_url]) message_id, _ = queue[:receipt_handles].find { |msg_id, receipts| receipts.has_key?(receipt_handle) } if message_id queue[:receipt_handles].delete(message_id) queue[:messages].delete(message_id) queue['Attributes']['LastModifiedTimestamp'] = Time.now end response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response.status = 200 else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end end end end end end end fog-1.19.0/lib/fog/aws/requests/sqs/send_message.rb0000644000004100000410000000402712261242551022166 0ustar www-datawww-datamodule Fog module AWS class SQS class Real require 'fog/aws/parsers/sqs/send_message' # Add a message to a queue # # ==== Parameters # * queue_url<~String> - Url of queue to add message to # * message<~String> - Message to add to queue # # ==== See Also # http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QuerySendMessage.html # def send_message(queue_url, message) request({ 'Action' => 'SendMessage', 'MessageBody' => message, :path => path_from_queue_url(queue_url), :parser => Fog::Parsers::AWS::SQS::SendMessage.new }) end end class Mock def send_message(queue_url, message) Excon::Response.new.tap do |response| if (queue = data[:queues][queue_url]) response.status = 200 now = Time.now message_id = Fog::AWS::Mock.sqs_message_id md5 = Digest::MD5.hexdigest(message) queue[:messages][message_id] = { 'MessageId' => message_id, 'Body' => message, 'MD5OfBody' => md5, 'Attributes' => { 'SenderId' => Fog::AWS::Mock.sqs_message_id, 'SentTimestamp' => now } } queue['Attributes']['LastModifiedTimestamp'] = now response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'MessageId' => message_id, 'MD5OfMessageBody' => md5 } else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end end end end end end end fog-1.19.0/lib/fog/aws/requests/sqs/get_queue_attributes.rb0000644000004100000410000000330512261242551023760 0ustar www-datawww-datamodule Fog module AWS class SQS class Real require 'fog/aws/parsers/sqs/get_queue_attributes' # Get attributes of a queue # # ==== Parameters # * queue_url<~String> - Url of queue to get attributes for # * attribute_name<~Array> - Name of attribute to return, in ['All', 'ApproximateNumberOfMessages', 'ApproximateNumberOfMessagesNotVisible', 'CreatedTimestamp', 'LastModifiedTimestamp', 'MaximumMessageSize', 'MessageRetentionPeriod', 'Policy', 'QueueArn', 'VisibilityTimeout'] # # ==== See Also # http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryGetQueueAttributes.html # def get_queue_attributes(queue_url, attribute_name) request({ 'Action' => 'GetQueueAttributes', 'AttributeName' => attribute_name, :path => path_from_queue_url(queue_url), :parser => Fog::Parsers::AWS::SQS::GetQueueAttributes.new }) end end class Mock def get_queue_attributes(queue_url, attribute_name) Excon::Response.new.tap do |response| if (queue = data[:queues][queue_url]) response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'Attributes' => queue['Attributes'] } else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end end end end end end end fog-1.19.0/lib/fog/aws/requests/sqs/change_message_visibility.rb0000644000004100000410000000407612261242551024735 0ustar www-datawww-datamodule Fog module AWS class SQS class Real require 'fog/aws/parsers/sqs/basic' # Change visibility timeout for a message # # ==== Parameters # * queue_url<~String> - Url of queue for message to update # * receipt_handle<~String> - Token from previous recieve message # * visibility_timeout<~Integer> - New visibility timeout in 0..43200 # # ==== See Also # http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryChangeMessageVisibility.html # def change_message_visibility(queue_url, receipt_handle, visibility_timeout) request({ 'Action' => 'ChangeMessageVisibility', 'ReceiptHandle' => receipt_handle, 'VisibilityTimeout' => visibility_timeout, :parser => Fog::Parsers::AWS::SQS::Basic.new, :path => path_from_queue_url(queue_url) }) end end class Mock def change_message_visibility(queue_url, receipt_handle, visibility_timeout) Excon::Response.new.tap do |response| if (queue = data[:queues][queue_url]) message_id, _ = queue[:receipt_handles].find { |message_id, receipts| receipts.has_key?(receipt_handle) } if message_id queue[:messages][message_id]['Attributes']['VisibilityTimeout'] = visibility_timeout response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response.status = 200 else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end end end end end end end fog-1.19.0/lib/fog/aws/requests/storage/0000755000004100000410000000000012261242551020037 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/storage/get_object_url.rb0000644000004100000410000000220712261242551023354 0ustar www-datawww-datamodule Fog module Storage class AWS module GetObjectUrl def get_object_url(bucket_name, object_name, expires, options = {}) unless bucket_name raise ArgumentError.new('bucket_name is required') end unless object_name raise ArgumentError.new('object_name is required') end signed_url(options.merge({ :bucket_name => bucket_name, :object_name => object_name, :method => 'GET' }), expires) end end class Real # Get an expiring object url from S3 # # @param bucket_name [String] Name of bucket containing object # @param object_name [String] Name of object to get expiring url for # @param expires [Time] An expiry time for this url # # @return [Excon::Response] response: # * body [String] - url for object # # @see http://docs.amazonwebservices.com/AmazonS3/latest/dev/S3_QSAuth.html include GetObjectUrl end class Mock # :nodoc:all include GetObjectUrl end end end end fog-1.19.0/lib/fog/aws/requests/storage/put_bucket_versioning.rb0000644000004100000410000000433312261242551024777 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Change versioning status for an S3 bucket # # @param bucket_name [String] name of bucket to modify # @param status [String] Status to change to in ['Enabled', 'Suspended'] # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketPUTVersioningStatus.html def put_bucket_versioning(bucket_name, status) data = <<-DATA #{status} DATA request({ :body => data, :expects => 200, :headers => {}, :bucket_name => bucket_name, :method => 'PUT', :query => {'versioning' => nil} }) end end class Mock def put_bucket_versioning(bucket_name, status) response = Excon::Response.new bucket = self.data[:buckets][bucket_name] if bucket if ['Enabled', 'Suspended'].include?(status) bucket[:versioning] = status response.status = 200 else response.status = 400 response.body = { 'Error' => { 'Code' => 'MalformedXML', 'Message' => 'The XML you provided was not well-formed or did not validate against our published schema', 'RequestId' => Fog::Mock.random_hex(16), 'HostId' => Fog::Mock.random_base64(65) } } raise(Excon::Errors.status_error({:expects => 200}, response)) end else response.status = 404 response.body = { 'Error' => { 'Code' => 'NoSuchBucket', 'Message' => 'The specified bucket does not exist', 'BucketName' => bucket_name, 'RequestId' => Fog::Mock.random_hex(16), 'HostId' => Fog::Mock.random_base64(65) } } raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/put_request_payment.rb0000644000004100000410000000243012261242551024500 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Change who pays for requests to an S3 bucket # # @param bucket_name [String] name of bucket to modify # @param payer [String] valid values are BucketOwner or Requester # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTrequestPaymentPUT.html def put_request_payment(bucket_name, payer) data = <<-DATA #{payer} DATA request({ :body => data, :expects => 200, :headers => {}, :bucket_name => bucket_name, :method => 'PUT', :query => {'requestPayment' => nil} }) end end class Mock # :nodoc:all def put_request_payment(bucket_name, payer) response = Excon::Response.new if bucket = self.data[:buckets][bucket_name] response.status = 200 bucket['Payer'] = payer else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/put_bucket_lifecycle.rb0000644000004100000410000000720412261242551024553 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Change lifecycle configuration for an S3 bucket # # @param bucket_name [String] name of bucket to set lifecycle configuration for # * lifecycle [Hash]: # * Rules [Array] object expire rules # * ID [String] Unique identifier for the rule # * Prefix [String] Prefix identifying one or more objects to which the rule applies # * Enabled [Boolean] if rule is currently being applied # * Expiration [Hash] Container for the object expiration rule. # * Days [Integer] lifetime, in days, of the objects that are subject to the rule # * Date [Date] Indicates when the specific rule take effect. # The date value must conform to the ISO 8601 format. The time is always midnight UTC. # * Transition [Hash] Container for the transition rule that describes when objects transition # to the Glacier storage class # * Days [Integer] lifetime, in days, of the objects that are subject to the rule # * Date [Date] Indicates when the specific rule take effect. # The date value must conform to the ISO 8601 format. The time is always midnight UTC. # * StorageClass [String] Indicates the Amazon S3 storage class to which you want the object # to transition to. # # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketPUTlifecycle.html # def put_bucket_lifecycle(bucket_name, lifecycle) builder = Nokogiri::XML::Builder.new do LifecycleConfiguration { lifecycle['Rules'].each do |rule| Rule { ID rule['ID'] Prefix rule['Prefix'] Status rule['Enabled'] ? 'Enabled' : 'Disabled' unless (rule['Expiration'] or rule['Transition']) Expiration { Days rule['Days'] } else if rule['Expiration'] if rule['Expiration']['Days'] Expiration { Days rule['Expiration']['Days'] } elsif rule['Expiration']['Date'] Expiration { Date rule['Expiration']['Date'].is_a?(Time) ? rule['Expiration']['Date'].utc.iso8601 : Time.parse(rule['Expiration']['Date']).utc.iso8601 } end end if rule['Transition'] Transition { if rule['Transition']['Days'] Days rule['Transition']['Days'] elsif rule['Transition']['Date'] Date rule['Transition']['Date'].is_a?(Time) ? time.utc.iso8601 : Time.parse(time).utc.iso8601 end StorageClass rule['Transition']['StorageClass'].nil? ? 'GLACIER' : rule['Transition']['StorageClass'] } end end } end } end body = builder.to_xml body.gsub! /<([^<>]+)\/>/, '<\1>' request({ :body => body, :expects => 200, :headers => {'Content-MD5' => Base64.encode64(Digest::MD5.digest(body)).chomp!, 'Content-Type' => 'application/xml'}, :bucket_name => bucket_name, :method => 'PUT', :query => {'lifecycle' => nil} }) end end end end end fog-1.19.0/lib/fog/aws/requests/storage/put_object.rb0000644000004100000410000001162312261242551022525 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Create an object in an S3 bucket # # @param bucket_name [String] Name of bucket to create object in # @param object_name [String] Name of object to create # @param data [File||String] File or String to create object from # @param options [Hash] # @option options Cache-Control [String] Caching behaviour # @option options Content-Disposition [String] Presentational information for the object # @option options Content-Encoding [String] Encoding of object data # @option options Content-Length [String] Size of object in bytes (defaults to object.read.length) # @option options Content-MD5 [String] Base64 encoded 128-bit MD5 digest of message # @option options Content-Type [String] Standard MIME type describing contents (defaults to MIME::Types.of.first) # @option options Expires [String] Cache expiry # @option options x-amz-acl [String] Permissions, must be in ['private', 'public-read', 'public-read-write', 'authenticated-read'] # @option options x-amz-storage-class [String] Default is 'STANDARD', set to 'REDUCED_REDUNDANCY' for non-critical, reproducable data # @option options x-amz-meta-#{name} Headers to be returned with object, note total size of request without body must be less than 8 KB. # # @return [Excon::Response] response: # * headers [Hash]: # * ETag [String] etag of new object # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectPUT.html def put_object(bucket_name, object_name, data, options = {}) data = Fog::Storage.parse_data(data) headers = data[:headers].merge!(options) request({ :body => data[:body], :expects => 200, :headers => headers, :bucket_name => bucket_name, :object_name => object_name, :idempotent => true, :method => 'PUT', }) end end class Mock # :nodoc:all def put_object(bucket_name, object_name, data, options = {}) acl = options['x-amz-acl'] || 'private' if !['private', 'public-read', 'public-read-write', 'authenticated-read'].include?(acl) raise Excon::Errors::BadRequest.new('invalid x-amz-acl') else self.data[:acls][:object][bucket_name] ||= {} self.data[:acls][:object][bucket_name][object_name] = self.class.acls(acl) end data = Fog::Storage.parse_data(data) unless data[:body].is_a?(String) data[:body] = data[:body].read end response = Excon::Response.new if (bucket = self.data[:buckets][bucket_name]) response.status = 200 object = { :body => data[:body], 'Content-Type' => options['Content-Type'] || data[:headers]['Content-Type'], 'ETag' => Digest::MD5.hexdigest(data[:body]), 'Key' => object_name, 'Last-Modified' => Fog::Time.now.to_date_header, 'Content-Length' => options['Content-Length'] || data[:headers]['Content-Length'], 'StorageClass' => options['x-amz-storage-class'] || 'STANDARD', 'VersionId' => bucket[:versioning] == 'Enabled' ? Fog::Mock.random_base64(32) : 'null' } for key, value in options case key when 'Cache-Control', 'Content-Disposition', 'Content-Encoding', 'Content-MD5', 'Expires', /^x-amz-meta-/ object[key] = value end end if bucket[:versioning] bucket[:objects][object_name] ||= [] # When versioning is suspended, putting an object will create a new 'null' version if the latest version # is a value other than 'null', otherwise it will replace the latest version. if bucket[:versioning] == 'Suspended' && bucket[:objects][object_name].first['VersionId'] == 'null' bucket[:objects][object_name].shift end bucket[:objects][object_name].unshift(object) else bucket[:objects][object_name] = [object] end response.headers = { 'Content-Length' => object['Content-Length'], 'Content-Type' => object['Content-Type'], 'ETag' => object['ETag'], 'Last-Modified' => object['Last-Modified'], } response.headers['x-amz-version-id'] = object['VersionId'] if object['VersionId'] != 'null' else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/acl_utils.rb0000644000004100000410000000426112261242551022346 0ustar www-datawww-datamodule Fog module Storage class AWS require 'fog/aws/parsers/storage/access_control_list' private def self.hash_to_acl(acl) data = "\n" if acl['Owner'] && (acl['Owner']['ID'] || acl['Owner']['DisplayName']) data << " \n" data << " #{acl['Owner']['ID']}\n" if acl['Owner']['ID'] data << " #{acl['Owner']['DisplayName']}\n" if acl['Owner']['DisplayName'] data << " \n" end grants = [acl['AccessControlList']].flatten.compact data << " \n" if grants.any? grants.each do |grant| data << " \n" grantee = grant['Grantee'] type = case when grantee.has_key?('ID') 'CanonicalUser' when grantee.has_key?('EmailAddress') 'AmazonCustomerByEmail' when grantee.has_key?('URI') 'Group' end data << " \n" case type when 'CanonicalUser' data << " #{grantee['ID']}\n" if grantee['ID'] data << " #{grantee['DisplayName']}\n" if grantee['DisplayName'] when 'AmazonCustomerByEmail' data << " #{grantee['EmailAddress']}\n" if grantee['EmailAddress'] when 'Group' data << " #{grantee['URI']}\n" if grantee['URI'] end data << " \n" data << " #{grant['Permission']}\n" data << " \n" end data << " \n" if grants.any? data << "" data end def self.acl_to_hash(acl_xml) parser = Fog::Parsers::Storage::AWS::AccessControlList.new Nokogiri::XML::SAX::Parser.new(parser).parse(acl_xml) parser.response end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_object_torrent.rb0000644000004100000410000000306612261242551024253 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Get torrent for an S3 object # # @param bucket_name [String] name of bucket containing object # @param object_name [String] name of object to get torrent for # # @return [Excon::Response] response: # * body [Hash]: # * AccessControlPolicy [Hash: # * Owner [Hash]: # * DisplayName [String] - Display name of object owner # * ID [String] - Id of object owner # * AccessControlList [Array]: # * Grant [Hash]: # * Grantee [Hash]: # * DisplayName [String] - Display name of grantee # * ID [String] - Id of grantee # * Permission [String] - Permission, in [FULL_CONTROL, WRITE, WRITE_ACP, READ, READ_ACP] # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectGETtorrent.html def get_object_torrent(bucket_name, object_name) unless bucket_name raise ArgumentError.new('bucket_name is required') end unless object_name raise ArgumentError.new('object_name is required') end request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :object_name => object_name, :idempotent => true, :method => 'GET', :query => {'torrent' => nil} }) end end end end end fog-1.19.0/lib/fog/aws/requests/storage/head_object.rb0000644000004100000410000000537012261242551022620 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Get headers for an object from S3 # # @param bucket_name [String] Name of bucket to read from # @param object_name [String] Name of object to read # @param options [Hash]: # @option options [String] If-Match Returns object only if its etag matches this value, otherwise returns 412 (Precondition Failed). # @option options [Time] If-Modified-Since Returns object only if it has been modified since this time, otherwise returns 304 (Not Modified). # @option options [String] If-None-Match Returns object only if its etag differs from this value, otherwise returns 304 (Not Modified) # @option options [Time] If-Unmodified-Since Returns object only if it has not been modified since this time, otherwise returns 412 (Precodition Failed). # @option options [String] Range Range of object to download # @option options [String] versionId specify a particular version to retrieve # # @return [Excon::Response] response: # * body [String] Contents of object # * headers [Hash]: # * Content-Length [String] - Size of object contents # * Content-Type [String] - MIME type of object # * ETag [String] - Etag of object # * Last-Modified - [String] Last modified timestamp for object # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectHEAD.html # def head_object(bucket_name, object_name, options={}) unless bucket_name raise ArgumentError.new('bucket_name is required') end unless object_name raise ArgumentError.new('object_name is required') end if version_id = options.delete('versionId') query = {'versionId' => version_id} end headers = {} headers['If-Modified-Since'] = Fog::Time.at(options['If-Modified-Since'].to_i).to_date_header if options['If-Modified-Since'] headers['If-Unmodified-Since'] = Fog::Time.at(options['If-Unmodified-Since'].to_i).to_date_header if options['If-Modified-Since'] headers.merge!(options) request({ :expects => 200, :headers => headers, :bucket_name => bucket_name, :object_name => object_name, :idempotent => true, :method => 'HEAD', :query => query }) end end class Mock # :nodoc:all def head_object(bucket_name, object_name, options = {}) response = get_object(bucket_name, object_name, options) response.body = nil response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_object_acl.rb0000644000004100000410000000535412261242551023317 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/access_control_list' # Get access control list for an S3 object # # @param bucket_name [String] name of bucket containing object # @param object_name [String] name of object to get access control list for # @param options [Hash] # @option options versionId [String] specify a particular version to retrieve # # @return [Excon::Response] response: # * body [Hash]: # * [AccessControlPolicy [Hash]: # * Owner [Hash]: # * DisplayName [String] - Display name of object owner # * ID [String] - Id of object owner # * AccessControlList [Array]: # * Grant [Hash]: # * Grantee [Hash]: # * DisplayName [String] - Display name of grantee # * ID [String] - Id of grantee # or # * URI [String] - URI of group to grant access for # * Permission [String] - Permission, in [FULL_CONTROL, WRITE, WRITE_ACP, READ, READ_ACP] # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectGETacl.html def get_object_acl(bucket_name, object_name, options = {}) unless bucket_name raise ArgumentError.new('bucket_name is required') end unless object_name raise ArgumentError.new('object_name is required') end query = {'acl' => nil} if version_id = options.delete('versionId') query['versionId'] = version_id end request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :object_name => object_name, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::AccessControlList.new, :query => query }) end end class Mock # :nodoc:all require 'fog/aws/requests/storage/acl_utils' def get_object_acl(bucket_name, object_name, options = {}) response = Excon::Response.new if acl = self.data[:acls][:object][bucket_name] && self.data[:acls][:object][bucket_name][object_name] response.status = 200 if acl.is_a?(String) response.body = Fog::Storage::AWS.acl_to_hash(acl) else response.body = acl end else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_service.rb0000644000004100000410000000274712261242551022675 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/get_service' # List information about S3 buckets for authorized user # # @return [Excon::Response] response: # * body [Hash]: # * Buckets [Hash]: # * Name [String] - Name of bucket # * CreationTime [Time] - Timestamp of bucket creation # * Owner [Hash]: # * DisplayName [String] - Display name of bucket owner # * ID [String] - Id of bucket owner # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTServiceGET.html # def get_service request({ :expects => 200, :headers => {}, :host => @host, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::GetService.new }) end end class Mock # :nodoc:all def get_service response = Excon::Response.new response.headers['Status'] = 200 buckets = self.data[:buckets].values.map do |bucket| bucket.reject do |key, value| !['CreationDate', 'Name'].include?(key) end end response.body = { 'Buckets' => buckets, 'Owner' => { 'DisplayName' => 'owner', 'ID' => 'some_id'} } response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/put_bucket_website.rb0000644000004100000410000000306112261242551024253 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Change website configuration for an S3 bucket # # @param bucket_name [String] name of bucket to modify # @param suffix [String] suffix to append to requests for the bucket # @param options [Hash] # @option options key [String] key to use for 4XX class errors # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketPUTwebsite.html def put_bucket_website(bucket_name, suffix, options = {}) data = <<-DATA #{suffix} DATA if options[:key] data << <<-DATA #{options[:key]} DATA end data << '' request({ :body => data, :expects => 200, :headers => {}, :bucket_name => bucket_name, :method => 'PUT', :query => {'website' => nil} }) end end class Mock # :nodoc:all def put_bucket_website(bucket_name, suffix, options = {}) response = Excon::Response.new if self.data[:buckets][bucket_name] response.status = 200 else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_bucket_cors.rb0000644000004100000410000000516712261242551023537 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/cors_configuration' # Gets the CORS configuration for an S3 bucket # # @param bucket_name [String] name of bucket to get access control list for # # @return [Excon::Response] response: # * body [Hash]: # * CORSConfiguration [Array]: # * CORSRule [Hash]: # * AllowedHeader [String] - Which headers are allowed in a pre-flight OPTIONS request through the Access-Control-Request-Headers header. # * AllowedMethod [String] - Identifies an HTTP method that the domain/origin specified in the rule is allowed to execute. # * AllowedOrigin [String] - One or more response headers that you want customers to be able to access from their applications (for example, from a JavaScript XMLHttpRequest object). # * ExposeHeader [String] - One or more headers in the response that you want customers to be able to access from their applications (for example, from a JavaScript XMLHttpRequest object). # * ID [String] - An optional unique identifier for the rule. The ID value can be up to 255 characters long. The IDs help you find a rule in the configuration. # * MaxAgeSeconds [Integer] - The time in seconds that your browser is to cache the preflight response for the specified resource. # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketGETcors.html def get_bucket_cors(bucket_name) unless bucket_name raise ArgumentError.new('bucket_name is required') end request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::CorsConfiguration.new, :query => {'cors' => nil} }) end end class Mock # :nodoc:all require 'fog/aws/requests/storage/cors_utils' def get_bucket_cors(bucket_name) response = Excon::Response.new if cors = self.data[:cors][:bucket][bucket_name] response.status = 200 if cors.is_a?(String) response.body = Fog::Storage::AWS.cors_to_hash(cors) else response.body = cors end else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_bucket_tagging.rb0000644000004100000410000000303012261242551024174 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/get_bucket_tagging' # Get tags for an S3 bucket # # @param bucket_name [String] name of bucket to get tags for # # @return [Excon::Response] response: # * body [Hash]: # * BucketTagging [Hash]: # * Key [String] - tag key # * Value [String] - tag value # @see http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETtagging.html def get_bucket_tagging(bucket_name) unless bucket_name raise ArgumentError.new('bucket_name is required') end request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::GetBucketTagging.new, :query => {'tagging' => nil} }) end end class Mock # :nodoc:all def get_bucket_tagging(bucket_name) response = Excon::Response.new if self.data[:buckets][bucket_name] && self.data[:bucket_tagging][bucket_name] response.status = 200 response.body = {'BucketTagging' => self.data[:bucket_tagging][bucket_name]} else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_bucket_acl.rb0000644000004100000410000000424612261242551023325 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/access_control_list' # Get access control list for an S3 bucket # # @param bucket_name [String] name of bucket to get access control list for # # @return [Excon::Response] response: # * body [Hash]: # * AccessControlPolicy [Hash]: # * Owner [Hash]: # * DisplayName [String] - Display name of object owner # * ID [String] - Id of object owner # * AccessControlList [Array]: # * Grant [Hash]: # * Grantee [Hash]: # * DisplayName [String] - Display name of grantee # * ID [String] - Id of grantee # or # * URI [String] - URI of group to grant access for # * Permission [String] - Permission, in [FULL_CONTROL, WRITE, WRITE_ACP, READ, READ_ACP] # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketGETacl.html def get_bucket_acl(bucket_name) unless bucket_name raise ArgumentError.new('bucket_name is required') end request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::AccessControlList.new, :query => {'acl' => nil} }) end end class Mock # :nodoc:all require 'fog/aws/requests/storage/acl_utils' def get_bucket_acl(bucket_name) response = Excon::Response.new if acl = self.data[:acls][:bucket][bucket_name] response.status = 200 if acl.is_a?(String) response.body = Fog::Storage::AWS.acl_to_hash(acl) else response.body = acl end else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/initiate_multipart_upload.rb0000644000004100000410000000401512261242551025637 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/initiate_multipart_upload' # Initiate a multipart upload to an S3 bucket # # @param bucket_name [String] Name of bucket to create object in # @param object_name [String] Name of object to create # @param options [Hash]: # @option options [String] Cache-Control Caching behaviour # @option options [String] Content-Disposition Presentational information for the object # @option options [String] Content-Encoding Encoding of object data # @option options [String] Content-MD5 Base64 encoded 128-bit MD5 digest of message (defaults to Base64 encoded MD5 of object.read) # @option options [String] Content-Type Standard MIME type describing contents (defaults to MIME::Types.of.first) # @option options [String] x-amz-acl Permissions, must be in ['private', 'public-read', 'public-read-write', 'authenticated-read'] # @option options [String] x-amz-meta-#{name} Headers to be returned with object, note total size of request without body must be less than 8 KB. # # @return [Excon::Response] response: # * body [Hash]: # * Bucket [String] - Bucket where upload was initiated # * Key [String] - Object key where the upload was initiated # * UploadId [String] - Id for initiated multipart upload # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadInitiate.html # def initiate_multipart_upload(bucket_name, object_name, options = {}) request({ :expects => 200, :headers => options, :bucket_name => bucket_name, :object_name => object_name, :method => 'POST', :parser => Fog::Parsers::Storage::AWS::InitiateMultipartUpload.new, :query => {'uploads' => nil} }) end end # Real end # Storage end # AWS end # Fog fog-1.19.0/lib/fog/aws/requests/storage/put_bucket_policy.rb0000644000004100000410000000125512261242551024113 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Change bucket policy for an S3 bucket # # @param bucket_name [String] name of bucket to modify # @param policy [Hash] policy document # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketPUTpolicy.html def put_bucket_policy(bucket_name, policy) request({ :body => Fog::JSON.encode(policy), :expects => 204, :headers => {}, :bucket_name => bucket_name, :method => 'PUT', :query => {'policy' => nil} }) end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_bucket_policy.rb0000644000004100000410000000163612261242551024065 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Get bucket policy for an S3 bucket # # @param bucket_name [String] name of bucket to get policy for # # @return [Excon::Response] response: # * body [Hash] - policy document # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketGETpolicy.html def get_bucket_policy(bucket_name) unless bucket_name raise ArgumentError.new('bucket_name is required') end response = request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :idempotent => true, :method => 'GET', :query => {'policy' => nil} }) response.body = Fog::JSON.decode(response.body) unless response.body.nil? end end end end end fog-1.19.0/lib/fog/aws/requests/storage/cors_utils.rb0000644000004100000410000000202312261242551022547 0ustar www-datawww-datamodule Fog module Storage class AWS require 'fog/aws/parsers/storage/cors_configuration' private def self.hash_to_cors(cors) data = "\n" [cors['CORSConfiguration']].flatten.compact.each do |rule| data << " \n" ['ID', 'MaxAgeSeconds'].each do |key| data << " <#{key}>#{rule[key]}\n" if rule[key] end ['AllowedOrigin', 'AllowedMethod', 'AllowedHeader', 'ExposeHeader'].each do |key| [rule[key]].flatten.compact.each do |value| data << " <#{key}>#{value}\n" end end data << " \n" end data << "" data end def self.cors_to_hash(cors_xml) parser = Fog::Parsers::Storage::AWS::CorsConfiguration.new Nokogiri::XML::SAX::Parser.new(parser).parse(cors_xml) parser.response end end end end fog-1.19.0/lib/fog/aws/requests/storage/put_object_url.rb0000644000004100000410000000231512261242551023405 0ustar www-datawww-datamodule Fog module Storage class AWS module PutObjectUrl def put_object_url(bucket_name, object_name, expires, headers = {}, options = {}) unless bucket_name raise ArgumentError.new('bucket_name is required') end unless object_name raise ArgumentError.new('object_name is required') end signed_url(options.merge({ :bucket_name => bucket_name, :object_name => object_name, :method => 'PUT', :headers => headers, }), expires) end end class Real # Get an expiring object url from S3 for putting an object # # @param bucket_name [String] Name of bucket containing object # @param object_name [String] Name of object to get expiring url for # @param expires [Time] An expiry time for this url # # @return [Excon::Response] response: # * body [String] url for object # # @see http://docs.amazonwebservices.com/AmazonS3/latest/dev/S3_QSAuth.html include PutObjectUrl end class Mock # :nodoc:all include PutObjectUrl end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_bucket_website.rb0000644000004100000410000000230412261242551024221 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/get_bucket_website' # Get website configuration for an S3 bucket # # # @param bucket_name [String] name of bucket to get website configuration for # # @return [Excon::Response] response: # * body [Hash]: # * IndexDocument [Hash]: # * Suffix [String] - Suffix appended when directory is requested # * ErrorDocument [Hash]: # * Key [String] - Object key to return for 4XX class errors # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketGETwebsite.html def get_bucket_website(bucket_name) unless bucket_name raise ArgumentError.new('bucket_name is required') end request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::GetBucketWebsite.new, :query => {'website' => nil} }) end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_bucket_location.rb0000644000004100000410000000315512261242551024374 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/get_bucket_location' # Get location constraint for an S3 bucket # # @param bucket_name [String] name of bucket to get location constraint for # # @return [Excon::Response] response: # * body [Hash]: # * LocationConstraint [String] - Location constraint of the bucket # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketGETlocation.html def get_bucket_location(bucket_name) request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::GetBucketLocation.new, :query => {'location' => nil} }) end end class Mock # :nodoc:all def get_bucket_location(bucket_name) response = Excon::Response.new if bucket = self.data[:buckets][bucket_name] location_constraint = case bucket['LocationConstraint'] when 'us-east-1' nil when 'eu-east-1' 'EU' else bucket['LocationConstraint'] end response.status = 200 response.body = {'LocationConstraint' => location_constraint } else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/list_parts.rb0000644000004100000410000000454612261242551022561 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/list_parts' # List parts for a multipart upload # # @param bucket_name [String] Name of bucket to list parts for # @param object_name [String] Name of object to list parts for # @param upload_id [String] upload id to list objects for # @param options [Hash] config arguments for list. Defaults to {}. # @option options max-parts [Integer] limits number of parts returned # @option options part-number-marker [String] limits parts to only those that appear lexicographically after this part number. # # @return [Excon::Response] response: # * body [Hash]: # * Bucket [string] Bucket where the multipart upload was initiated # * Initiator [Hash]: # * DisplayName [String] Display name of upload initiator # * ID [String] Id of upload initiator # * IsTruncated [Boolean] Whether or not the listing is truncated # * Key [String] Key where multipart upload was initiated # * MaxParts [String] maximum number of replies alllowed in response # * NextPartNumberMarker [String] last item in list, for further pagination # * Part [Array]: # * ETag [String] ETag of part # * LastModified [Timestamp] Last modified for part # * PartNumber [String] Part number for part # * Size [Integer] Size of part # * PartNumberMarker [String] Part number after which listing begins # * StorageClass [String] Storage class of object # * UploadId [String] upload id of upload containing part # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadListParts.html # def list_parts(bucket_name, object_name, upload_id, options = {}) options['uploadId'] = upload_id request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :object_name => object_name, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::ListParts.new, :query => options.merge!({'uploadId' => upload_id}) }) end end end end end fog-1.19.0/lib/fog/aws/requests/storage/sync_clock.rb0000644000004100000410000000101712261242551022512 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Sync clock against S3 to avoid skew errors # def sync_clock response = begin get_service rescue Excon::Errors::HTTPStatusError => error error.response end Fog::Time.now = Time.parse(response.headers['Date']) end end # Real class Mock # :nodoc:all def sync_clock true end end # Mock end # Storage end # AWS end # Fogfog-1.19.0/lib/fog/aws/requests/storage/get_object_http_url.rb0000644000004100000410000000157512261242551024422 0ustar www-datawww-datamodule Fog module Storage class AWS module GetObjectHttpUrl def get_object_http_url(bucket_name, object_name, expires, options = {}) get_object_url(bucket_name, object_name, expires, options.merge(:scheme => 'http')) end end class Real # Get an expiring object http url from S3 # # @param bucket_name [String] Name of bucket containing object # @param object_name [String] Name of object to get expiring url for # @param expires [Time] An expiry time for this url # # @return [Excon::Response] response: # * body [String] - url for object # # @see http://docs.amazonwebservices.com/AmazonS3/latest/dev/S3_QSAuth.html include GetObjectHttpUrl end class Mock # :nodoc:all include GetObjectHttpUrl end end end end fog-1.19.0/lib/fog/aws/requests/storage/put_bucket_tagging.rb0000644000004100000410000000275712261242551024244 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Change tag set for an S3 bucket # # @param bucket_name [String] name of bucket to modify # @param tags [Hash]: # * Key [String]: tag key # * Value [String]: tag value # # @see http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTtagging.html def put_bucket_tagging(bucket_name, tags) tagging = tags.map do |k,v| "#{k}#{v}" end.join("\n") data = <<-DATA #{tagging} DATA request({ :body => data, :expects => 204, :headers => {'Content-MD5' => Base64.encode64(Digest::MD5.digest(data)).chomp!, 'Content-Type' => 'application/xml'}, :bucket_name => bucket_name, :method => 'PUT', :query => {'tagging' => nil} }) end end class Mock # :nodoc:all def put_bucket_tagging(bucket_name, tags) response = Excon::Response.new if self.data[:buckets][bucket_name] self.data[:bucket_tagging][bucket_name] = tags response.status = 204 else response.status = 404 raise(Excon::Errors.status_error({:expects => 204}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/list_multipart_uploads.rb0000644000004100000410000000476112261242551025177 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/list_multipart_uploads' # List multipart uploads for a bucket # # @param [String] bucket_name Name of bucket to list multipart uploads for # @param [Hash] options config arguments for list. Defaults to {}. # @option options [String] key-marker limits parts to only those that appear lexicographically after this key. # @option options [Integer] max-uploads limits number of uploads returned # @option options [String] upload-id-marker limits uploads to only those that appear lexicographically after this upload id. # # @return [Excon::Response] response: # * body [Hash]: # * Bucket [String] Bucket where the multipart upload was initiated # * IsTruncated [Boolean] Whether or not the listing is truncated # * KeyMarker [String] first key in list, only upload ids after this lexographically will appear # * MaxUploads [Integer] Maximum results to return # * NextKeyMarker [String] last key in list, for further pagination # * NextUploadIdMarker [String] last key in list, for further pagination # * Upload [Hash]: # * Initiated [Time] Time when upload was initiated # * Initiator [Hash]: # * DisplayName [String] Display name of upload initiator # * ID [String] Id of upload initiator # * Key [String] Key where multipart upload was initiated # * Owner [Hash]: # * DisplayName [String] Display name of upload owner # * ID [String] Id of upload owner # * StorageClass [String] Storage class of object # * UploadId [String] upload id of upload containing part # * UploadIdMarker [String] first key in list, only upload ids after this lexographically will appear # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadListMPUpload.html # def list_multipart_uploads(bucket_name, options = {}) request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::ListMultipartUploads.new, :query => options.merge!({'uploads' => nil}) }) end end end end end fog-1.19.0/lib/fog/aws/requests/storage/delete_bucket.rb0000644000004100000410000000233712261242551023170 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Delete an S3 bucket # # @param bucket_name [String] name of bucket to delete # # @return [Excon::Response] response: # * status [Integer] - 204 # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketDELETE.html def delete_bucket(bucket_name) request({ :expects => 204, :headers => {}, :bucket_name => bucket_name, :method => 'DELETE' }) end end class Mock # :nodoc:all def delete_bucket(bucket_name) response = Excon::Response.new if self.data[:buckets][bucket_name].nil? response.status = 404 raise(Excon::Errors.status_error({:expects => 204}, response)) elsif self.data[:buckets][bucket_name] && !self.data[:buckets][bucket_name][:objects].empty? response.status = 409 raise(Excon::Errors.status_error({:expects => 204}, response)) else self.data[:buckets].delete(bucket_name) response.status = 204 end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/copy_object.rb0000644000004100000410000000714512261242551022673 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/copy_object' # Copy an object from one S3 bucket to another # # @param source_bucket_name [String] Name of source bucket # @param source_object_name [String] Name of source object # @param target_bucket_name [String] Name of bucket to create copy in # @param target_object_name [String] Name for new copy of object # # @param options [Hash]: # @option options [String] x-amz-metadata-directive Specifies whether to copy metadata from source or replace with data in request. Must be in ['COPY', 'REPLACE'] # @option options [String] x-amz-copy_source-if-match Copies object if its etag matches this value # @option options [Time] x-amz-copy_source-if-modified_since Copies object it it has been modified since this time # @option options [String] x-amz-copy_source-if-none-match Copies object if its etag does not match this value # @option options [Time] x-amz-copy_source-if-unmodified-since Copies object it it has not been modified since this time # @option options [String] x-amz-storage-class Default is 'STANDARD', set to 'REDUCED_REDUNDANCY' for non-critical, reproducable data # # # @return [Excon::Response] # * body [Hash]: # * ETag [String] - etag of new object # * LastModified [Time] - date object was last modified # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectCOPY.html # def copy_object(source_bucket_name, source_object_name, target_bucket_name, target_object_name, options = {}) headers = { 'x-amz-copy-source' => "/#{source_bucket_name}/#{CGI.escape(source_object_name)}" }.merge!(options) request({ :expects => 200, :headers => headers, :bucket_name => target_bucket_name, :object_name => target_object_name, :method => 'PUT', :parser => Fog::Parsers::Storage::AWS::CopyObject.new, }) end end class Mock # :nodoc:all def copy_object(source_bucket_name, source_object_name, target_bucket_name, target_object_name, options = {}) response = Excon::Response.new source_bucket = self.data[:buckets][source_bucket_name] source_object = source_bucket && source_bucket[:objects][source_object_name] && source_bucket[:objects][source_object_name].first target_bucket = self.data[:buckets][target_bucket_name] acl = options['x-amz-acl'] || 'private' if !['private', 'public-read', 'public-read-write', 'authenticated-read'].include?(acl) raise Excon::Errors::BadRequest.new('invalid x-amz-acl') else self.data[:acls][:object][target_bucket_name] ||= {} self.data[:acls][:object][target_bucket_name][target_object_name] = self.class.acls(acl) end if source_object && target_bucket response.status = 200 target_object = source_object.dup target_object.merge!({'Key' => target_object_name}) target_bucket[:objects][target_object_name] = [target_object] response.body = { 'ETag' => target_object['ETag'], 'LastModified' => Time.parse(target_object['Last-Modified']) } else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_bucket_versioning.rb0000644000004100000410000000407512261242551024751 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/get_bucket_versioning' # Get versioning status for an S3 bucket # # @param bucket_name [String] name of bucket to get versioning status for # # @return [Excon::Response] response: # * body [Hash]: # * VersioningConfiguration [Hash]: # * Status [String] - Versioning status in ['Enabled', 'Suspended', nil] # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketGETversioningStatus.html def get_bucket_versioning(bucket_name) unless bucket_name raise ArgumentError.new('bucket_name is required') end request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::GetBucketVersioning.new, :query => {'versioning' => nil} }) end end class Mock def get_bucket_versioning(bucket_name) response = Excon::Response.new bucket = self.data[:buckets][bucket_name] if bucket response.status = 200 if bucket[:versioning] response.body = { 'VersioningConfiguration' => { 'Status' => bucket[:versioning] } } else response.body = { 'VersioningConfiguration' => {} } end else response.status = 404 response.body = { 'Error' => { 'Code' => 'NoSuchBucket', 'Message' => 'The specified bucket does not exist', 'BucketName' => bucket_name, 'RequestId' => Fog::Mock.random_hex(16), 'HostId' => Fog::Mock.random_base64(65) } } raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_bucket_object_versions.rb0000644000004100000410000001654412261242551025770 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/get_bucket_object_versions' # List information about object versions in an S3 bucket # # @param bucket_name [String] name of bucket to list object keys from # @param options [Hash] config arguments for list # @option options delimiter [String] causes keys with the same string between the prefix value and the first occurence of delimiter to be rolled up # @option options key-marker [String] limits object keys to only those that appear lexicographically after its value. # @option options max-keys [Integer] limits number of object keys returned # @option options prefix [String] limits object keys to those beginning with its value. # @option options version-id-marker [String] limits object versions to only those that appear lexicographically after its value # # @return [Excon::Response] response: # * body [Hash]: # * Delimeter [String] - Delimiter specified for query # * KeyMarker [String] - Key marker specified for query # * MaxKeys [Integer] - Maximum number of keys specified for query # * Name [String] - Name of the bucket # * Prefix [String] - Prefix specified for query # * VersionIdMarker [String] - Version id marker specified for query # * IsTruncated [Boolean] - Whether or not this is the totality of the bucket # * Versions [Array]: # * DeleteMarker [Hash]: # * IsLatest [Boolean] - Whether or not this is the latest version # * Key [String] - Name of object # * LastModified [String]: Timestamp of last modification of object # * Owner [Hash]: # * DisplayName [String] - Display name of object owner # * ID [String] - Id of object owner # * VersionId [String] - The id of this version # or # * Version [Hash]: # * ETag [String]: Etag of object # * IsLatest [Boolean] - Whether or not this is the latest version # * Key [String] - Name of object # * LastModified [String]: Timestamp of last modification of object # * Owner [Hash]: # * DisplayName [String] - Display name of object owner # * ID [String] - Id of object owner # * Size [Integer] - Size of object # * StorageClass [String] - Storage class of object # * VersionId [String] - The id of this version # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketGETVersion.html def get_bucket_object_versions(bucket_name, options = {}) unless bucket_name raise ArgumentError.new('bucket_name is required') end request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::GetBucketObjectVersions.new, :query => {'versions' => nil}.merge!(options) }) end end class Mock def get_bucket_object_versions(bucket_name, options = {}) delimiter, key_marker, max_keys, prefix, version_id_marker = \ options['delimiter'], options['key-marker'], options['max-keys'],options['prefix'],options['version-id-marker'] unless bucket_name raise ArgumentError.new('bucket_name is required') end response = Excon::Response.new # Invalid arguments. if version_id_marker && !key_marker response.status = 400 response.body = { 'Error' => { 'Code' => 'InvalidArgument', 'Message' => 'A version-id marker cannot be specified without a key marker.', 'ArgumentValue' => version_id_marker, 'RequestId' => Fog::Mock.random_hex(16), 'HostId' => Fog::Mock.random_base64(65) } } # Valid case. # TODO: (nirvdrum 12/15/11) It's not clear to me how to actually use version-id-marker, so I didn't implement it below. elsif bucket = self.data[:buckets][bucket_name] # We need to order results by S3 key, but since our data store is key => [versions], we want to ensure the integrity # of the versions as well. So, sort the keys, then fetch the versions, and then combine them all as a sorted list by # flattening the results. contents = bucket[:objects].keys.sort.collect { |key| bucket[:objects][key] }.flatten.reject do |object| (prefix && object['Key'][0...prefix.length] != prefix) || (key_marker && object['Key'] <= key_marker) || (delimiter && object['Key'][(prefix ? prefix.length : 0)..-1].include?(delimiter) \ && common_prefixes << object['Key'].sub(/^(#{prefix}[^#{delimiter}]+.).*/, '\1')) end.map do |object| if object.has_key?(:delete_marker) tag_name = 'DeleteMarker' extracted_attrs = ['Key', 'VersionId'] else tag_name = 'Version' extracted_attrs = ['ETag', 'Key', 'StorageClass', 'VersionId'] end data = {} data[tag_name] = object.reject { |key, value| !extracted_attrs.include?(key) } data[tag_name].merge!({ 'LastModified' => Time.parse(object['Last-Modified']), 'Owner' => bucket['Owner'], 'IsLatest' => object == bucket[:objects][object['Key']].first }) data[tag_name]['Size'] = object['Content-Length'].to_i if tag_name == 'Version' data end max_keys = max_keys || 1000 size = [max_keys, 1000].min truncated_contents = contents[0...size] response.status = 200 response.body = { 'Versions' => truncated_contents, 'IsTruncated' => truncated_contents.size != contents.size, 'KeyMarker' => key_marker, 'VersionIdMarker' => version_id_marker, 'MaxKeys' => max_keys, 'Name' => bucket['Name'], 'Prefix' => prefix } if max_keys && max_keys < response.body['Versions'].length response.body['IsTruncated'] = true response.body['Versions'] = response.body['Versions'][0...max_keys] end # Missing bucket case. else response.status = 404 response.body = { 'Error' => { 'Code' => 'NoSuchBucket', 'Message' => 'The specified bucket does not exist', 'BucketName' => bucket_name, 'RequestId' => Fog::Mock.random_hex(16), 'HostId' => Fog::Mock.random_base64(65) } } raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/post_object_restore.rb0000644000004100000410000000363012261242551024444 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Restore an object from Glacier to its original S3 path # # @param bucket_name [String] Name of bucket containing object # @param object_name [String] Name of object to restore # @option days [Integer] Number of days to restore object for. Defaults to 100000 (a very long time) # # @return [Excon::Response] response: # * status [Integer] 200 (OK) Object is previously restored # * status [Integer] 202 (Accepted) Object is not previously restored # * status [Integer] 409 (Conflict) Restore is already in progress # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectPOSTrestore.html # def post_object_restore(bucket_name, object_name, days = 100000) raise ArgumentError.new('bucket_name is required') unless bucket_name raise ArgumentError.new('object_name is required') unless object_name data = '' + days.to_s + '' headers = {} headers['Content-MD5'] = Base64.encode64(Digest::MD5.digest(data)).strip headers['Content-Type'] = 'application/xml' headers['Date'] = Fog::Time.now.to_date_header request({ :headers => headers, :bucket_name => bucket_name, :expects => [200, 202, 409], :body => data, :method => 'POST', :query => {'restore' => nil}, :path => CGI.escape(object_name) }) end end class Mock # :nodoc:all def post_object_restore(bucket_name, object_name, days = 100000) response = get_object(bucket_name, object_name) response.body = nil response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_request_payment.rb0000644000004100000410000000254012261242551024451 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/get_request_payment' # Get configured payer for an S3 bucket # # @param bucket_name [String] name of bucket to get payer for # # @return [Excon::Response] response: # * body [Hash]: # * Payer [String] - Specifies who pays for download and requests # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTrequestPaymentGET.html def get_request_payment(bucket_name) request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::GetRequestPayment.new, :query => {'requestPayment' => nil} }) end end class Mock # :nodoc:all def get_request_payment(bucket_name) response = Excon::Response.new if bucket = self.data[:buckets][bucket_name] response.status = 200 response.body = { 'Payer' => bucket['Payer'] } else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_bucket_lifecycle.rb0000644000004100000410000000244712261242551024526 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/get_bucket_lifecycle' # Get bucket lifecycle configuration # # @param bucket_name [String] name of bucket to get lifecycle configuration for # # @return [Excon::Response] response: # * body [Hash]: # * Rules - object expire rules [Array]: # * ID [String] - Unique identifier for the rule # * Prefix [String] - Prefix identifying one or more objects to which the rule applies # * Enabled [Boolean] - if rule is currently being applied # * Days [Integer] - lifetime, in days, of the objects that are subject to the rule # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketGETlifecycle.html def get_bucket_lifecycle(bucket_name) request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::GetBucketLifecycle.new, :query => {'lifecycle' => nil} }) end end end end end fog-1.19.0/lib/fog/aws/requests/storage/complete_multipart_upload.rb0000644000004100000410000000376312261242551025652 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/complete_multipart_upload' # Complete a multipart upload # # @param [String] bucket_name Name of bucket to complete multipart upload for # @param [String] object_name Name of object to complete multipart upload for # @param [String] upload_id Id of upload to add part to # @param [Array] parts Array of etags as Strings for parts # # @return [Excon::Response] # * body [Hash]: (success) # * Bucket [String] - bucket of new object # * ETag [String] - etag of new object # * Key [String] - key of new object # * Location [String] - location of new object # * body [Hash]: (failure) # * Code [String] - Error status code # * Message [String] - Error description # # @note This request could fail and still return +200 OK+, so it's important that you check the response. # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadComplete.html # def complete_multipart_upload(bucket_name, object_name, upload_id, parts) data = "" parts.each_with_index do |part, index| data << "" data << "#{index + 1}" data << "#{part}" data << "" end data << "" request({ :body => data, :expects => 200, :headers => { 'Content-Length' => data.length }, :bucket_name => bucket_name, :object_name => object_name, :method => 'POST', :parser => Fog::Parsers::Storage::AWS::CompleteMultipartUpload.new, :query => {'uploadId' => upload_id} }) end end # Real end # Storage end # AWS end # Fog fog-1.19.0/lib/fog/aws/requests/storage/delete_object.rb0000644000004100000410000001023212261242551023152 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Delete an object from S3 # # @param bucket_name [String] Name of bucket containing object to delete # @param object_name [String] Name of object to delete # # @return [Excon::Response] response: # * status [Integer] - 204 # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectDELETE.html def delete_object(bucket_name, object_name, options = {}) if version_id = options.delete('versionId') path = "#{CGI.escape(object_name)}?versionId=#{CGI.escape(version_id)}" else path = CGI.escape(object_name) end headers = options request({ :expects => 204, :headers => headers, :bucket_name => bucket_name, :idempotent => true, :method => 'DELETE', :path => path }) end end class Mock # :nodoc:all def delete_object(bucket_name, object_name, options = {}) response = Excon::Response.new if bucket = self.data[:buckets][bucket_name] response.status = 204 version_id = options.delete('versionId') if bucket[:versioning] bucket[:objects][object_name] ||= [] if version_id version = bucket[:objects][object_name].find { |object| object['VersionId'] == version_id} # S3 special cases the 'null' value to not error out if no such version exists. if version || (version_id == 'null') bucket[:objects][object_name].delete(version) bucket[:objects].delete(object_name) if bucket[:objects][object_name].empty? response.headers['x-amz-delete-marker'] = 'true' if version[:delete_marker] response.headers['x-amz-version-id'] = version_id else response.status = 400 response.body = invalid_version_id_payload(version_id) raise(Excon::Errors.status_error({:expects => 200}, response)) end else delete_marker = { :delete_marker => true, 'Key' => object_name, 'VersionId' => bucket[:versioning] == 'Enabled' ? Fog::Mock.random_base64(32) : 'null', 'Last-Modified' => Fog::Time.now.to_date_header } # When versioning is suspended, a delete marker is placed if the last object ID is not the value 'null', # otherwise the last object is replaced. if bucket[:versioning] == 'Suspended' && bucket[:objects][object_name].first['VersionId'] == 'null' bucket[:objects][object_name].shift end bucket[:objects][object_name].unshift(delete_marker) response.headers['x-amz-delete-marker'] = 'true' response.headers['x-amz-version-id'] = delete_marker['VersionId'] end else if version_id && version_id != 'null' response.status = 400 response.body = invalid_version_id_payload(version_id) raise(Excon::Errors.status_error({:expects => 200}, response)) else bucket[:objects].delete(object_name) response.headers['x-amz-version-id'] = 'null' end end else response.status = 404 raise(Excon::Errors.status_error({:expects => 204}, response)) end response end private def invalid_version_id_payload(version_id) { 'Error' => { 'Code' => 'InvalidArgument', 'Message' => 'Invalid version id specified', 'ArgumentValue' => version_id, 'ArgumentName' => 'versionId', 'RequestId' => Fog::Mock.random_hex(16), 'HostId' => Fog::Mock.random_base64(65) } } end end end end end fog-1.19.0/lib/fog/aws/requests/storage/post_object_hidden_fields.rb0000644000004100000410000000366512261242551025552 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Get a hash of hidden fields for form uploading to S3, in the form {:field_name => :field_value} # Form should look like:
# These hidden fields should then appear, followed by a field named 'file' which is either a textarea or file input. # # @param options Hash: # @option options acl [String] access control list, in ['private', 'public-read', 'public-read-write', 'authenticated-read', 'bucket-owner-read', 'bucket-owner-full-control'] # @option options Cache-Control [String] same as REST header # @option options Content-Type [String] same as REST header # @option options Content-Disposition [String] same as REST header # @option options Content-Encoding [String] same as REST header # @option options Expires same as REST header # @option options key key for object, set to '${filename}' to use filename provided by user # @option options policy security policy for upload # @option options success_action_redirect url to redirct to upon success # @option options success_action_status status code to return on success, in [200, 201, 204] # @option options x-amz-security token devpay security token # @option options x-amz-meta... meta data tags # # @see http://docs.amazonwebservices.com/AmazonS3/latest/dev/HTTPPOSTForms.html # def post_object_hidden_fields(options = {}) if options['policy'] options['policy'] = Base64.encode64(Fog::JSON.encode(options['policy'])).gsub("\n", "") options['AWSAccessKeyId'] = @aws_access_key_id options['Signature'] = Base64.encode64(@hmac.sign(options['policy'])).gsub("\n", "") end options end end end end end fog-1.19.0/lib/fog/aws/requests/storage/delete_bucket_lifecycle.rb0000644000004100000410000000140312261242551025200 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Delete lifecycle configuration for a bucket # # @param bucket_name [String] name of bucket to delete lifecycle configuration from # # @return [Excon::Response] response: # * status [Integer] - 204 # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketDELETElifecycle.html def delete_bucket_lifecycle(bucket_name) request({ :expects => 204, :headers => {}, :bucket_name => bucket_name, :method => 'DELETE', :query => {'lifecycle' => nil} }) end end end end end fog-1.19.0/lib/fog/aws/requests/storage/put_bucket_logging.rb0000644000004100000410000000510212261242551024235 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Change logging status for an S3 bucket # # @param bucket_name [String] name of bucket to modify # @param logging_status [Hash]: # * Owner [Hash]: # * ID [String]: id of owner # * DisplayName [String]: display name of owner # * AccessControlList [Array]: # * Grantee [Hash]: # * DisplayName [String] Display name of grantee # * ID [String] Id of grantee # or # * EmailAddress [String] Email address of grantee # or # * URI [String] URI of group to grant access for # * Permission [String] Permission, in [FULL_CONTROL, WRITE, WRITE_ACP, READ, READ_ACP] # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketPUTlogging.html def put_bucket_logging(bucket_name, logging_status) if logging_status['LoggingEnabled'].empty? data = <<-DATA DATA else data = <<-DATA #{logging_status['LoggingEnabled']['TargetBucket']} #{logging_status['LoggingEnabled']['TargetBucket']} DATA acl['AccessControlList'].each do |grant| data << " " type = case grant['Grantee'].keys.sort when ['DisplayName', 'ID'] 'CanonicalUser' when ['EmailAddress'] 'AmazonCustomerByEmail' when ['URI'] 'Group' end data << " " for key, value in grant['Grantee'] data << " <#{key}>#{value}" end data << " " data << " #{grant['Permission']}" data << " " end data << <<-DATA DATA end request({ :body => data, :expects => 200, :headers => {}, :bucket_name => bucket_name, :method => 'PUT', :query => {'logging' => nil} }) end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_object_https_url.rb0000644000004100000410000000160312261242551024575 0ustar www-datawww-datamodule Fog module Storage class AWS module GetObjectHttpsUrl def get_object_https_url(bucket_name, object_name, expires, options = {}) get_object_url(bucket_name, object_name, expires, options.merge(:scheme => 'https')) end end class Real # Get an expiring object https url from S3 # # @param bucket_name [String] Name of bucket containing object # @param object_name [String] Name of object to get expiring url for # @param expires [Time] An expiry time for this url # # @return [Excon::Response] response: # * body [String] - url for object # # @see http://docs.amazonwebservices.com/AmazonS3/latest/dev/S3_QSAuth.html include GetObjectHttpsUrl end class Mock # :nodoc:all include GetObjectHttpsUrl end end end end fog-1.19.0/lib/fog/aws/requests/storage/delete_bucket_cors.rb0000644000004100000410000000131412261242551024210 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Deletes the cors configuration information set for the bucket. # # @param bucket_name [String] name of bucket to delete cors rules from # # @return [Excon::Response] response: # * status [Integer] - 204 # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketDELETEcors.html def delete_bucket_cors(bucket_name) request({ :expects => 204, :headers => {}, :bucket_name => bucket_name, :method => 'DELETE', :query => {'cors' => nil} }) end end end end end fog-1.19.0/lib/fog/aws/requests/storage/abort_multipart_upload.rb0000644000004100000410000000153512261242551025144 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # # Abort a multipart upload # # @param [String] bucket_name Name of bucket to abort multipart upload on # @param [String] object_name Name of object to abort multipart upload on # @param [String] upload_id Id of upload to add part to # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadAbort.html # def abort_multipart_upload(bucket_name, object_name, upload_id) request({ :expects => 204, :headers => {}, :bucket_name => bucket_name, :object_name => object_name, :method => 'DELETE', :query => {'uploadId' => upload_id} }) end end # Real end # Storage end # AWS end # Fog fog-1.19.0/lib/fog/aws/requests/storage/delete_bucket_policy.rb0000644000004100000410000000125312261242551024543 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Delete policy for a bucket # # @param bucket_name [String] name of bucket to delete policy from # # @return [Excon::Response] response: # * status [Integer] - 204 # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketDELETEpolicy.html def delete_bucket_policy(bucket_name) request({ :expects => 204, :headers => {}, :bucket_name => bucket_name, :method => 'DELETE', :query => {'policy' => nil} }) end end end end end fog-1.19.0/lib/fog/aws/requests/storage/put_bucket_acl.rb0000644000004100000410000000465212261242551023357 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/requests/storage/acl_utils' # Change access control list for an S3 bucket # # @param bucket_name [String] name of bucket to modify # @param acl [Hash] # * Owner [Hash]: # * ID [String]: id of owner # * DisplayName [String]: display name of owner # * AccessControlList [Array]: # * Grantee [Hash]: # * DisplayName [String] Display name of grantee # * ID [String] Id of grantee # or # * EmailAddress [String] Email address of grantee # or # * URI [String] URI of group to grant access for # * Permission [String] Permission, in [FULL_CONTROL, WRITE, WRITE_ACP, READ, READ_ACP] # * acl [String] Permissions, must be in ['private', 'public-read', 'public-read-write', 'authenticated-read'] # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketPUTacl.html def put_bucket_acl(bucket_name, acl) data = "" headers = {} if acl.is_a?(Hash) data = Fog::Storage::AWS.hash_to_acl(acl) else if !['private', 'public-read', 'public-read-write', 'authenticated-read'].include?(acl) raise Excon::Errors::BadRequest.new('invalid x-amz-acl') end headers['x-amz-acl'] = acl end headers['Content-MD5'] = Base64.encode64(Digest::MD5.digest(data)).strip headers['Content-Type'] = 'application/json' headers['Date'] = Fog::Time.now.to_date_header request({ :body => data, :expects => 200, :headers => headers, :bucket_name => bucket_name, :method => 'PUT', :query => {'acl' => nil} }) end end class Mock def put_bucket_acl(bucket_name, acl) if acl.is_a?(Hash) self.data[:acls][:bucket][bucket_name] = Fog::Storage::AWS.hash_to_acl(acl) else if !['private', 'public-read', 'public-read-write', 'authenticated-read'].include?(acl) raise Excon::Errors::BadRequest.new('invalid x-amz-acl') end self.data[:acls][:bucket][bucket_name] = acl end end end end end end fog-1.19.0/lib/fog/aws/requests/storage/put_bucket_cors.rb0000644000004100000410000000364112261242551023563 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/requests/storage/cors_utils' # Sets the cors configuration for your bucket. If the configuration exists, Amazon S3 replaces it. # # @param bucket_name [String] name of bucket to modify # @param cors [Hash] # * CORSConfiguration [Array]: # * ID [String]: A unique identifier for the rule. # * AllowedMethod [String]: An HTTP method that you want to allow the origin to execute. # * AllowedOrigin [String]: An origin that you want to allow cross-domain requests from. # * AllowedHeader [String]: Specifies which headers are allowed in a pre-flight OPTIONS request via the Access-Control-Request-Headers header. # * MaxAgeSeconds [String]: The time in seconds that your browser is to cache the preflight response for the specified resource. # * ExposeHeader [String]: One or more headers in the response that you want customers to be able to access from their applications. # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketPUTcors.html def put_bucket_cors(bucket_name, cors) data = Fog::Storage::AWS.hash_to_cors(cors) headers = {} headers['Content-MD5'] = Base64.encode64(Digest::MD5.digest(data)).strip headers['Content-Type'] = 'application/json' headers['Date'] = Fog::Time.now.to_date_header request({ :body => data, :expects => 200, :headers => headers, :bucket_name => bucket_name, :method => 'PUT', :query => {'cors' => nil} }) end end class Mock def put_bucket_cors(bucket_name, cors) self.data[:cors][:bucket][bucket_name] = Fog::Storage::AWS.hash_to_cors(cors) end end end end end fog-1.19.0/lib/fog/aws/requests/storage/delete_bucket_tagging.rb0000644000004100000410000000214012261242551024660 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Delete tagging for a bucket # # @param bucket_name [String] name of bucket to delete tagging from # # @return [Excon::Response] response: # * status [Integer] - 204 # # @see http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETEtagging.html def delete_bucket_tagging(bucket_name) request({ :expects => 204, :headers => {}, :bucket_name => bucket_name, :method => 'DELETE', :query => {'tagging' => nil} }) end end class Mock # :nodoc:all def delete_bucket_tagging(bucket_name) response = Excon::Response.new if self.data[:buckets][bucket_name] self.data[:bucket_tagging].delete(bucket_name) response.status = 204 else response.status = 404 raise(Excon::Errors.status_error({:expects => 204}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_bucket.rb0000644000004100000410000001133112261242551022477 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/get_bucket' # List information about objects in an S3 bucket # # @param bucket_name [String] name of bucket to list object keys from # @param options [Hash] config arguments for list. Defaults to {}. # @option options delimiter [String] causes keys with the same string between the prefix # value and the first occurence of delimiter to be rolled up # @option options marker [String] limits object keys to only those that appear # lexicographically after its value. # @option options max-keys [Integer] limits number of object keys returned # @option options prefix [String] limits object keys to those beginning with its value. # # @return [Excon::Response] response: # * body [Hash]: # * Delimeter [String] - Delimiter specified for query # * IsTruncated [Boolean] - Whether or not the listing is truncated # * Marker [String]- Marker specified for query # * MaxKeys [Integer] - Maximum number of keys specified for query # * Name [String] - Name of the bucket # * Prefix [String] - Prefix specified for query # * CommonPrefixes [Array] - Array of strings for common prefixes # * Contents [Array]: # * ETag [String] - Etag of object # * Key [String] - Name of object # * LastModified [String] - Timestamp of last modification of object # * Owner [Hash]: # * DisplayName [String] - Display name of object owner # * ID [String] - Id of object owner # * Size [Integer] - Size of object # * StorageClass [String] - Storage class of object # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketGET.html def get_bucket(bucket_name, options = {}) unless bucket_name raise ArgumentError.new('bucket_name is required') end request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::GetBucket.new, :query => options }) end end class Mock # :nodoc:all def get_bucket(bucket_name, options = {}) prefix, marker, delimiter, max_keys = \ options['prefix'], options['marker'], options['delimiter'], options['max-keys'] common_prefixes = [] unless bucket_name raise ArgumentError.new('bucket_name is required') end response = Excon::Response.new if bucket = self.data[:buckets][bucket_name] contents = bucket[:objects].values.collect(&:first).sort {|x,y| x['Key'] <=> y['Key']}.reject do |object| (prefix && object['Key'][0...prefix.length] != prefix) || (marker && object['Key'] <= marker) || (delimiter && object['Key'][(prefix ? prefix.length : 0)..-1].include?(delimiter) \ && common_prefixes << object['Key'].sub(/^(#{prefix}[^#{delimiter}]+.).*/, '\1')) || object.has_key?(:delete_marker) end.map do |object| data = object.reject {|key, value| !['ETag', 'Key', 'StorageClass'].include?(key)} data.merge!({ 'LastModified' => Time.parse(object['Last-Modified']), 'Owner' => bucket['Owner'], 'Size' => object['Content-Length'].to_i }) data end max_keys = max_keys || 1000 size = [max_keys, 1000].min truncated_contents = contents[0...size] response.status = 200 response.body = { 'CommonPrefixes' => common_prefixes.uniq, 'Contents' => truncated_contents, 'IsTruncated' => truncated_contents.size != contents.size, 'Marker' => marker, 'MaxKeys' => max_keys, 'Name' => bucket['Name'], 'Prefix' => prefix } if max_keys && max_keys < response.body['Contents'].length response.body['IsTruncated'] = true response.body['Contents'] = response.body['Contents'][0...max_keys] end else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/upload_part.rb0000644000004100000410000000276212261242551022705 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Upload a part for a multipart upload # # @param bucket_name [String] Name of bucket to add part to # @param object_name [String] Name of object to add part to # @param upload_id [String] Id of upload to add part to # @param part_number [String] Index of part in upload # @param data [File||String] Content for part # @param options [Hash] # @option options Content-MD5 [String] Base64 encoded 128-bit MD5 digest of message # # @return [Excon::Response] response # * headers [Hash]: # * ETag [String] etag of new object (will be needed to complete upload) # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadUploadPart.html # def upload_part(bucket_name, object_name, upload_id, part_number, data, options = {}) data = Fog::Storage.parse_data(data) headers = options headers['Content-Length'] = data[:headers]['Content-Length'] request({ :body => data[:body], :expects => 200, :idempotent => true, :headers => headers, :bucket_name => bucket_name, :object_name => object_name, :method => 'PUT', :query => {'uploadId' => upload_id, 'partNumber' => part_number} }) end end # Real end # Storage end # AWS end # Fog fog-1.19.0/lib/fog/aws/requests/storage/delete_bucket_website.rb0000644000004100000410000000131312261242551024703 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Delete website configuration for a bucket # # @param bucket_name [String] name of bucket to delete website configuration from # # @return [Excon::Response] response: # * status [Integer] - 204 # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketDELETEwebsite.html def delete_bucket_website(bucket_name) request({ :expects => 204, :headers => {}, :bucket_name => bucket_name, :method => 'DELETE', :query => {'website' => nil} }) end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_object.rb0000644000004100000410000001724712261242551022504 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Get an object from S3 # # @param bucket_name [String] Name of bucket to read from # @param object_name [String] Name of object to read # @param options [Hash] # @option options If-Match [String] Returns object only if its etag matches this value, otherwise returns 412 (Precondition Failed). # @option options If-Modified-Since [Time] Returns object only if it has been modified since this time, otherwise returns 304 (Not Modified). # @option options If-None-Match [String] Returns object only if its etag differs from this value, otherwise returns 304 (Not Modified) # @option options If-Unmodified-Since [Time] Returns object only if it has not been modified since this time, otherwise returns 412 (Precodition Failed). # @option options Range [String] Range of object to download # @option options versionId [String] specify a particular version to retrieve # @option options query[Hash] specify additional query string # # @return [Excon::Response] response: # * body [String]- Contents of object # * headers [Hash]: # * Content-Length [String] - Size of object contents # * Content-Type [String] - MIME type of object # * ETag [String] - Etag of object # * Last-Modified [String] - Last modified timestamp for object # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectGET.html def get_object(bucket_name, object_name, options = {}, &block) unless bucket_name raise ArgumentError.new('bucket_name is required') end unless object_name raise ArgumentError.new('object_name is required') end params = { :headers => {} } params[:query] = options.delete('query') || {} if version_id = options.delete('versionId') params[:query] = params[:query].merge({'versionId' => version_id}) end params[:headers].merge!(options) if options['If-Modified-Since'] params[:headers]['If-Modified-Since'] = Fog::Time.at(options['If-Modified-Since'].to_i).to_date_header end if options['If-Unmodified-Since'] params[:headers]['If-Unmodified-Since'] = Fog::Time.at(options['If-Unmodified-Since'].to_i).to_date_header end if block_given? params[:response_block] = Proc.new end request(params.merge!({ :expects => [ 200, 206 ], :bucket_name => bucket_name, :object_name => object_name, :idempotent => true, :method => 'GET', })) end end class Mock # :nodoc:all def get_object(bucket_name, object_name, options = {}, &block) version_id = options.delete('versionId') unless bucket_name raise ArgumentError.new('bucket_name is required') end unless object_name raise ArgumentError.new('object_name is required') end response = Excon::Response.new if (bucket = self.data[:buckets][bucket_name]) object = nil if bucket[:objects].has_key?(object_name) object = version_id ? bucket[:objects][object_name].find { |object| object['VersionId'] == version_id} : bucket[:objects][object_name].first end if (object && !object[:delete_marker]) if options['If-Match'] && options['If-Match'] != object['ETag'] response.status = 412 elsif options['If-Modified-Since'] && options['If-Modified-Since'] >= Time.parse(object['Last-Modified']) response.status = 304 elsif options['If-None-Match'] && options['If-None-Match'] == object['ETag'] response.status = 304 elsif options['If-Unmodified-Since'] && options['If-Unmodified-Since'] < Time.parse(object['Last-Modified']) response.status = 412 else response.status = 200 for key, value in object case key when 'Cache-Control', 'Content-Disposition', 'Content-Encoding', 'Content-Length', 'Content-MD5', 'Content-Type', 'ETag', 'Expires', 'Last-Modified', /^x-amz-meta-/ response.headers[key] = value end end response.headers['x-amz-version-id'] = object['VersionId'] if bucket[:versioning] body = object[:body] if options['Range'] # since AWS S3 itself does not support multiple range headers, we will use only the first ranges = byte_ranges(options['Range'], body.size) unless ranges.nil? || ranges.empty? response.status = 206 body = body[ranges.first] end end unless block_given? response.body = body else data = StringIO.new(body) remaining = data.length while remaining > 0 chunk = data.read([remaining, Excon::CHUNK_SIZE].min) block.call(chunk) remaining -= Excon::CHUNK_SIZE end end end elsif version_id && !object response.status = 400 response.body = { 'Error' => { 'Code' => 'InvalidArgument', 'Message' => 'Invalid version id specified', 'ArgumentValue' => version_id, 'ArgumentName' => 'versionId', 'RequestId' => Fog::Mock.random_hex(16), 'HostId' => Fog::Mock.random_base64(65) } } raise(Excon::Errors.status_error({:expects => 200}, response)) else response.status = 404 response.body = "...NoSuchKey<\/Code>..." raise(Excon::Errors.status_error({:expects => 200}, response)) end else response.status = 404 response.body = "...NoSuchBucket..." raise(Excon::Errors.status_error({:expects => 200}, response)) end response end private # === Borrowed from rack # Parses the "Range:" header, if present, into an array of Range objects. # Returns nil if the header is missing or syntactically invalid. # Returns an empty array if none of the ranges are satisfiable. def byte_ranges(http_range, size) # See return nil unless http_range ranges = [] http_range.split(/,\s*/).each do |range_spec| matches = range_spec.match(/bytes=(\d*)-(\d*)/) return nil unless matches r0,r1 = matches[1], matches[2] if r0.empty? return nil if r1.empty? # suffix-byte-range-spec, represents trailing suffix of file r0 = [size - r1.to_i, 0].max r1 = size - 1 else r0 = r0.to_i if r1.empty? r1 = size - 1 else r1 = r1.to_i return nil if r1 < r0 # backwards range is syntactically invalid r1 = size-1 if r1 >= size end end ranges << (r0..r1) if r0 <= r1 end ranges end end end end end fog-1.19.0/lib/fog/aws/requests/storage/put_bucket.rb0000644000004100000410000000475512261242551022544 0ustar www-datawww-datamodule Fog module Storage class AWS class Real # Create an S3 bucket # # @param bucket_name [String] name of bucket to create # @option options [Hash] config arguments for bucket. Defaults to {}. # @option options LocationConstraint [Symbol] sets the location for the bucket # @option options x-amz-acl [String] Permissions, must be in ['private', 'public-read', 'public-read-write', 'authenticated-read'] # # @return [Excon::Response] response: # * status [Integer] 200 # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketPUT.html # def put_bucket(bucket_name, options = {}) if location_constraint = options.delete('LocationConstraint') data = <<-DATA #{location_constraint} DATA else data = nil end request({ :expects => 200, :body => data, :headers => options, :idempotent => true, :bucket_name => bucket_name, :method => 'PUT' }) end end class Mock # :nodoc:all def put_bucket(bucket_name, options = {}) acl = options['x-amz-acl'] || 'private' if !['private', 'public-read', 'public-read-write', 'authenticated-read'].include?(acl) raise Excon::Errors::BadRequest.new('invalid x-amz-acl') else self.data[:acls][:bucket][bucket_name] = self.class.acls(acl) end response = Excon::Response.new response.status = 200 bucket = { :objects => {}, 'Name' => bucket_name, 'CreationDate' => Time.now, 'Owner' => { 'DisplayName' => 'owner', 'ID' => 'some_id'}, 'Payer' => 'BucketOwner' } if options['LocationConstraint'] bucket['LocationConstraint'] = options['LocationConstraint'] else bucket['LocationConstraint'] = nil end if !self.data[:buckets][bucket_name] || self.region == 'us-east-1' self.data[:buckets][bucket_name] = bucket else response.status = 409 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/storage/get_bucket_logging.rb0000644000004100000410000000323112261242551024205 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/get_bucket_logging' # Get logging status for an S3 bucket # # @param bucket_name [String] name of bucket to get logging status for # # @return [Excon::Response] response: # * body [Hash]: # * BucketLoggingStatus (will be empty if logging is disabled) [Hash]: # * LoggingEnabled [Hash]: # * TargetBucket [String] - bucket where logs are stored # * TargetPrefix [String] - prefix logs are stored with # * TargetGrants [Array]: # * Grant [Hash]: # * Grantee [Hash]: # * DisplayName [String] - Display name of grantee # * ID [String] - Id of grantee # or # * URI [String] - URI of group to grant access for # * Permission [String] - Permission, in [FULL_CONTROL, WRITE, WRITE_ACP, READ, READ_ACP] # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketGETlogging.html def get_bucket_logging(bucket_name) unless bucket_name raise ArgumentError.new('bucket_name is required') end request({ :expects => 200, :headers => {}, :bucket_name => bucket_name, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Storage::AWS::GetBucketLogging.new, :query => {'logging' => nil} }) end end end end end fog-1.19.0/lib/fog/aws/requests/storage/delete_multiple_objects.rb0000644000004100000410000001576412261242551025267 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/parsers/storage/delete_multiple_objects' # Delete multiple objects from S3 # @note For versioned deletes, options should include a version_ids hash, which # maps from filename to an array of versions. # The semantics are that for each (object_name, version) tuple, the # caller must insert the object_name and an associated version (if # desired), so for n versions, the object must be inserted n times. # # @param bucket_name [String] Name of bucket containing object to delete # @param object_names [Array] Array of object names to delete # # @return [Excon::Response] response: # * body [Hash]: # * DeleteResult [Array]: # * Deleted [Hash]: # * Key [String] - Name of the object that was deleted # * VersionId [String] - ID for the versioned onject in case of a versioned delete # * DeleteMarker [Boolean] - Indicates if the request accessed a delete marker # * DeleteMarkerVersionId [String] - Version ID of the delete marker accessed # * Error [Hash]: # * Key [String] - Name of the object that failed to be deleted # * VersionId [String] - ID of the versioned object that was attempted to be deleted # * Code [String] - Status code for the result of the failed delete # * Message [String] - Error description # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/multiobjectdeleteapi.html def delete_multiple_objects(bucket_name, object_names, options = {}) headers = options.dup data = "" data << "true" if headers.delete(:quiet) version_ids = headers.delete('versionId') object_names.each do |object_name| data << "" data << "#{CGI.escapeHTML(object_name)}" object_version = version_ids.nil? ? nil : version_ids[object_name] if object_version data << "#{CGI.escapeHTML(object_version)}" end data << "" end data << "" headers['Content-Length'] = data.length headers['Content-MD5'] = Base64.encode64(Digest::MD5.digest(data)). gsub("\n", '') request({ :body => data, :expects => 200, :headers => headers, :bucket_name => bucket_name, :method => 'POST', :parser => Fog::Parsers::Storage::AWS::DeleteMultipleObjects.new, :query => {'delete' => nil} }) end end class Mock # :nodoc:all def delete_multiple_objects(bucket_name, object_names, options = {}) headers = options.dup headers.delete(:quiet) response = Excon::Response.new if bucket = self.data[:buckets][bucket_name] response.status = 200 response.body = { 'DeleteResult' => [] } version_ids = headers.delete('versionId') object_names.each do |object_name| object_version = version_ids.nil? ? nil : version_ids[object_name] response.body['DeleteResult'] << delete_object_helper(bucket, object_name, object_version) end else response.status = 404 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end private def delete_object_helper(bucket, object_name, version_id) response = { 'Deleted' => {} } if bucket[:versioning] bucket[:objects][object_name] ||= [] if version_id version = bucket[:objects][object_name].find { |object| object['VersionId'] == version_id} # S3 special cases the 'null' value to not error out if no such version exists. if version || (version_id == 'null') bucket[:objects][object_name].delete(version) bucket[:objects].delete(object_name) if bucket[:objects][object_name].empty? response['Deleted'] = { 'Key' => object_name, 'VersionId' => version_id, 'DeleteMarker' => 'true', 'DeleteMarkerVersionId' => version_id } else response = delete_error_body(object_name, version_id, 'InvalidVersion', 'Invalid version ID specified') end else delete_marker = { :delete_marker => true, 'Key' => object_name, 'VersionId' => bucket[:versioning] == 'Enabled' ? Fog::Mock.random_base64(32) : 'null', 'Last-Modified' => Fog::Time.now.to_date_header } # When versioning is suspended, a delete marker is placed if the last object ID is not the value 'null', # otherwise the last object is replaced. if bucket[:versioning] == 'Suspended' && bucket[:objects][object_name].first['VersionId'] == 'null' bucket[:objects][object_name].shift end bucket[:objects][object_name].unshift(delete_marker) response['Deleted'] = { 'Key' => object_name, 'VersionId' => delete_marker['VersionId'], 'DeleteMarkerVersionId' => delete_marker['VersionId'], 'DeleteMarker' => 'true', } end else if version_id && version_id != 'null' response = delete_error_body(object_name, version_id, 'InvalidVersion', 'Invalid version ID specified') response = invalid_version_id_payload(version_id) else bucket[:objects].delete(object_name) response['Deleted'] = { 'Key' => object_name } end end response end def delete_error_body(key, version_id, message, code) { 'Error' => { 'Code' => code, 'Message' => message, 'VersionId' => version_id, 'Key' => key, } } end end end end end fog-1.19.0/lib/fog/aws/requests/storage/put_object_acl.rb0000644000004100000410000000560712261242551023351 0ustar www-datawww-datamodule Fog module Storage class AWS class Real require 'fog/aws/requests/storage/acl_utils' # Change access control list for an S3 object # # @param [String] bucket_name name of bucket to modify # @param [String] object_name name of object to get access control list for # @param [Hash] acl # * Owner [Hash] # * ID [String] id of owner # * DisplayName [String] display name of owner # * AccessControlList [Array] # * Grantee [Hash] # * DisplayName [String] Display name of grantee # * ID [String] Id of grantee # or # * EmailAddress [String] Email address of grantee # or # * URI [String] URI of group to grant access for # * Permission [String] Permission, in [FULL_CONTROL, WRITE, WRITE_ACP, READ, READ_ACP] # @param [String] acl Permissions, must be in ['private', 'public-read', 'public-read-write', 'authenticated-read'] # @param [Hash] options # @option options [String] versionId specify a particular version to retrieve # # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectPUTacl.html def put_object_acl(bucket_name, object_name, acl, options = {}) query = {'acl' => nil} if version_id = options.delete('versionId') query['versionId'] = version_id end data = "" headers = {} if acl.is_a?(Hash) data = Fog::Storage::AWS.hash_to_acl(acl) else if !['private', 'public-read', 'public-read-write', 'authenticated-read'].include?(acl) raise Excon::Errors::BadRequest.new('invalid x-amz-acl') end headers['x-amz-acl'] = acl end headers['Content-MD5'] = Base64.encode64(Digest::MD5.digest(data)).strip headers['Content-Type'] = 'application/json' headers['Date'] = Fog::Time.now.to_date_header request({ :body => data, :expects => 200, :headers => headers, :bucket_name => bucket_name, :object_name => object_name, :method => 'PUT', :query => query }) end end class Mock def put_object_acl(bucket_name, object_name, acl, options = {}) if acl.is_a?(Hash) self.data[:acls][:object][bucket_name][object_name] = Fog::Storage::AWS.hash_to_acl(acl) else if !['private', 'public-read', 'public-read-write', 'authenticated-read'].include?(acl) raise Excon::Errors::BadRequest.new('invalid x-amz-acl') end self.data[:acls][:object][bucket_name][object_name] = acl end end end end end end fog-1.19.0/lib/fog/aws/requests/emr/0000755000004100000410000000000012261242551017156 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/emr/set_termination_protection.rb0000644000004100000410000000240612261242551025157 0ustar www-datawww-datamodule Fog module AWS class EMR class Real require 'fog/aws/parsers/emr/set_termination_protection' # locks a job flow so the Amazon EC2 instances in the cluster cannot be terminated by user intervention. # http://docs.amazonwebservices.com/ElasticMapReduce/latest/API/API_SetTerminationProtection.html # ==== Parameters # * JobFlowIds <~String list> - list of strings that uniquely identify the job flows to protect # * TerminationProtected <~Boolean> - indicates whether to protect the job flow # # ==== Returns # * response<~Excon::Response>: # * body<~Hash> def set_termination_protection(is_protected, options={}) if job_ids = options.delete('JobFlowIds') options.merge!(Fog::AWS.serialize_keys('JobFlowIds', job_ids)) end request({ 'Action' => 'SetTerminationProtection', 'TerminationProtected' => is_protected, :parser => Fog::Parsers::AWS::EMR::SetTerminationProtection.new, }.merge(options)) end end class Mock def set_termination_protection(db_name, options={}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/emr/add_instance_groups.rb0000644000004100000410000000344412261242551023523 0ustar www-datawww-datamodule Fog module AWS class EMR class Real require 'fog/aws/parsers/emr/add_instance_groups' # adds an instance group to a running cluster # http://docs.amazonwebservices.com/ElasticMapReduce/latest/API/API_AddInstanceGroups.html # ==== Parameters # * JobFlowId <~String> - Job flow in which to add the instance groups # * InstanceGroups<~Array> - Instance Groups to add # * 'BidPrice'<~String> - Bid price for each Amazon EC2 instance in the instance group when launching nodes as Spot Instances, expressed in USD. # * 'InstanceCount'<~Integer> - Target number of instances for the instance group # * 'InstanceRole'<~String> - MASTER | CORE | TASK The role of the instance group in the cluster # * 'InstanceType'<~String> - The Amazon EC2 instance type for all instances in the instance group # * 'MarketType'<~String> - ON_DEMAND | SPOT Market type of the Amazon EC2 instances used to create a cluster node # * 'Name'<~String> - Friendly name given to the instance group. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def add_instance_groups(job_flow_id, options={}) if instance_groups = options.delete('InstanceGroups') options.merge!(Fog::AWS.indexed_param('InstanceGroups.member.%d', [*instance_groups])) end request({ 'Action' => 'AddInstanceGroups', 'JobFlowId' => job_flow_id, :parser => Fog::Parsers::AWS::EMR::AddInstanceGroups.new, }.merge(options)) end end class Mock def add_instance_groups(job_flow_id, options={}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/emr/terminate_job_flows.rb0000644000004100000410000000177312261242551023547 0ustar www-datawww-datamodule Fog module AWS class EMR class Real require 'fog/aws/parsers/emr/terminate_job_flows' # shuts a list of job flows down. # http://docs.amazonwebservices.com/ElasticMapReduce/latest/API/API_TerminateJobFlows.html # ==== Parameters # * JobFlowIds <~String list> - list of strings that uniquely identify the job flows to protect # # ==== Returns # * response<~Excon::Response>: # * body<~Hash> def terminate_job_flows(options={}) if job_ids = options.delete('JobFlowIds') options.merge!(Fog::AWS.serialize_keys('JobFlowIds', job_ids)) end request({ 'Action' => 'TerminateJobFlows', :parser => Fog::Parsers::AWS::EMR::TerminateJobFlows.new, }.merge(options)) end end class Mock def terminate_job_flows(db_name, options={}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/emr/run_job_flow.rb0000644000004100000410000001445112261242551022175 0ustar www-datawww-datamodule Fog module AWS class EMR class Real require 'fog/aws/parsers/emr/run_job_flow' # creates and starts running a new job flow # http://docs.amazonwebservices.com/ElasticMapReduce/latest/API/API_RunJobFlow.html # ==== Parameters # * AdditionalInfo <~String> - A JSON string for selecting additional features. # * BootstrapActions <~Array> - A list of bootstrap actions that will be run before Hadoop is started on the cluster nodes. # * 'Name'<~String> - The name of the bootstrap action # * 'ScriptBootstrapAction'<~Array> - The script run by the bootstrap action # * 'Args' <~Array> - A list of command line arguments to pass to the bootstrap action script # * 'Path' <~String> - Location of the script to run during a bootstrap action. Can be either a location in Amazon S3 or on a local file system. # * Instances <~Array> - A specification of the number and type of Amazon EC2 instances on which to run the job flow. # * 'Ec2KeyName'<~String> - Specifies the name of the Amazon EC2 key pair that can be used to ssh to the master node as the user called "hadoop. # * 'HadoopVersion'<~String> - "0.18" | "0.20" Specifies the Hadoop version for the job flow # * 'InstanceCount'<~Integer> - The number of Amazon EC2 instances used to execute the job flow # * 'InstanceGroups'<~Array> - Configuration for the job flow's instance groups # * 'BidPrice' <~String> - Bid price for each Amazon EC2 instance in the instance group when launching nodes as Spot Instances, expressed in USD. # * 'InstanceCount'<~Integer> - Target number of instances for the instance group # * 'InstanceRole'<~String> - MASTER | CORE | TASK The role of the instance group in the cluster # * 'InstanceType'<~String> - The Amazon EC2 instance type for all instances in the instance group # * 'MarketType'<~String> - ON_DEMAND | SPOT Market type of the Amazon EC2 instances used to create a cluster node # * 'Name'<~String> - Friendly name given to the instance group. # * 'KeepJobFlowAliveWhenNoSteps' <~Boolean> - Specifies whether the job flow should terminate after completing all steps # * 'MasterInstanceType'<~String> - The EC2 instance type of the master node # * 'Placement'<~Array> - Specifies the Availability Zone the job flow will run in # * 'AvailabilityZone' <~String> - The Amazon EC2 Availability Zone for the job flow. # * 'SlaveInstanceType'<~String> - The EC2 instance type of the slave nodes # * 'TerminationProtected'<~Boolean> - Specifies whether to lock the job flow to prevent the Amazon EC2 instances from being terminated by API call, user intervention, or in the event of a job flow error # * LogUri <~String> - Specifies the location in Amazon S3 to write the log files of the job flow. If a value is not provided, logs are not created # * Name <~String> - The name of the job flow # * Steps <~Array> - A list of steps to be executed by the job flow # * 'ActionOnFailure'<~String> - TERMINATE_JOB_FLOW | CANCEL_AND_WAIT | CONTINUE Specifies the action to take if the job flow step fails # * 'HadoopJarStep'<~Array> - Specifies the JAR file used for the job flow step # * 'Args'<~String list> - A list of command line arguments passed to the JAR file's main function when executed. # * 'Jar'<~String> - A path to a JAR file run during the step. # * 'MainClass'<~String> - The name of the main class in the specified Java file. If not specified, the JAR file should specify a Main-Class in its manifest file # * 'Properties'<~Array> - A list of Java properties that are set when the step runs. You can use these properties to pass key value pairs to your main function # * 'Key'<~String> - The unique identifier of a key value pair # * 'Value'<~String> - The value part of the identified key # * 'Name'<~String> - The name of the job flow step # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def run_job_flow(name, options={}) if bootstrap_actions = options.delete('BootstrapActions') options.merge!(Fog::AWS.serialize_keys('BootstrapActions', bootstrap_actions)) end if instances = options.delete('Instances') options.merge!(Fog::AWS.serialize_keys('Instances', instances)) end if steps = options.delete('Steps') options.merge!(Fog::AWS.serialize_keys('Steps', steps)) end request({ 'Action' => 'RunJobFlow', 'Name' => name, :parser => Fog::Parsers::AWS::EMR::RunJobFlow.new, }.merge(options)) end def run_hive(name, options={}) steps = [] steps << { 'Name' => 'Setup Hive', 'HadoopJarStep' => { 'Jar' => 's3://us-east-1.elasticmapreduce/libs/script-runner/script-runner.jar', 'Args' => ['s3://us-east-1.elasticmapreduce/libs/hive/hive-script', '--base-path', 's3://us-east-1.elasticmapreduce/libs/hive/', '--install-hive']}, 'ActionOnFailure' => 'TERMINATE_JOB_FLOW' } # To add a configuration step to the Hive flow, see the step below # steps << { # 'Name' => 'Install Hive Site Configuration', # 'HadoopJarStep' => { # 'Jar' => 's3://us-east-1.elasticmapreduce/libs/script-runner/script-runner.jar', # 'Args' => ['s3://us-east-1.elasticmapreduce/libs/hive/hive-script', '--base-path', 's3://us-east-1.elasticmapreduce/libs/hive/', '--install-hive-site', '--hive-site=s3://my.bucket/hive/hive-site.xml']}, # 'ActionOnFailure' => 'TERMINATE_JOB_FLOW' # } options['Steps'] = steps if not options['Instances'].nil? options['Instances']['KeepJobFlowAliveWhenNoSteps'] = true end run_job_flow name, options end end class Mock def run_job_flow(db_name, options={}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/emr/add_job_flow_steps.rb0000644000004100000410000000410012261242551023325 0ustar www-datawww-datamodule Fog module AWS class EMR class Real require 'fog/aws/parsers/emr/add_job_flow_steps' # adds new steps to a running job flow. # http://docs.amazonwebservices.com/ElasticMapReduce/latest/API/API_AddJobFlowSteps.html # ==== Parameters # * JobFlowId <~String> - A string that uniquely identifies the job flow # * Steps <~Array> - A list of steps to be executed by the job flow # * 'ActionOnFailure'<~String> - TERMINATE_JOB_FLOW | CANCEL_AND_WAIT | CONTINUE Specifies the action to take if the job flow step fails # * 'HadoopJarStep'<~Array> - Specifies the JAR file used for the job flow step # * 'Args'<~String list> - A list of command line arguments passed to the JAR file's main function when executed. # * 'Jar'<~String> - A path to a JAR file run during the step. # * 'MainClass'<~String> - The name of the main class in the specified Java file. If not specified, the JAR file should specify a Main-Class in its manifest file # * 'Properties'<~Array> - A list of Java properties that are set when the step runs. You can use these properties to pass key value pairs to your main function # * 'Key'<~String> - The unique identifier of a key value pair # * 'Value'<~String> - The value part of the identified key # * 'Name'<~String> - The name of the job flow step # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def add_job_flow_steps(job_flow_id, options={}) if steps = options.delete('Steps') options.merge!(Fog::AWS.serialize_keys('Steps', steps)) end request({ 'Action' => 'AddJobFlowSteps', 'JobFlowId' => job_flow_id, :parser => Fog::Parsers::AWS::EMR::AddJobFlowSteps.new, }.merge(options)) end end class Mock def add_job_flow_steps(db_name, options={}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/emr/describe_job_flows.rb0000644000004100000410000002020312261242551023324 0ustar www-datawww-datamodule Fog module AWS class EMR class Real require 'fog/aws/parsers/emr/describe_job_flows' # returns a list of job flows that match all of the supplied parameters. # http://docs.amazonwebservices.com/ElasticMapReduce/latest/API/API_DescribeJobFlows.html # ==== Parameters # * CreatedAfter <~DateTime> - Return only job flows created after this date and time # * CreatedBefore <~DateTime> - Return only job flows created before this date and time # * JobFlowIds <~String list> - Return only job flows whose job flow ID is contained in this list # * JobFlowStates <~String list> - RUNNING | WAITING | SHUTTING_DOWN | STARTING Return only job flows whose state is contained in this list # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * JobFlows <~Array> - A list of job flows matching the parameters supplied. # * AmiVersion <~String> - A list of bootstrap actions that will be run before Hadoop is started on the cluster nodes. # * 'BootstrapActions'<~Array> - A list of the bootstrap actions run by the job flow # * 'BootstrapConfig <~Array> - A description of the bootstrap action # * 'Name' <~String> - The name of the bootstrap action # * 'ScriptBootstrapAction' <~Array> - The script run by the bootstrap action. # * 'Args' <~String list> - A list of command line arguments to pass to the bootstrap action script. # * 'Path' <~String> - Location of the script to run during a bootstrap action. # * 'ExecutionStatusDetail'<~Array> - Describes the execution status of the job flow # * 'CreationDateTime <~DateTime> - The creation date and time of the job flow. # * 'EndDateTime <~DateTime> - The completion date and time of the job flow. # * 'LastStateChangeReason <~String> - Description of the job flow last changed state. # * 'ReadyDateTime <~DateTime> - The date and time when the job flow was ready to start running bootstrap actions. # * 'StartDateTime <~DateTime> - The start date and time of the job flow. # * 'State <~DateTime> - COMPLETED | FAILED | TERMINATED | RUNNING | SHUTTING_DOWN | STARTING | WAITING | BOOTSTRAPPING The state of the job flow. # * Instances <~Array> - A specification of the number and type of Amazon EC2 instances on which to run the job flow. # * 'Ec2KeyName'<~String> - Specifies the name of the Amazon EC2 key pair that can be used to ssh to the master node as the user called "hadoop. # * 'HadoopVersion'<~String> - "0.18" | "0.20" Specifies the Hadoop version for the job flow # * 'InstanceCount'<~Integer> - The number of Amazon EC2 instances used to execute the job flow # * 'InstanceGroups'<~Array> - Configuration for the job flow's instance groups # * 'BidPrice' <~String> - Bid price for each Amazon EC2 instance in the instance group when launching nodes as Spot Instances, expressed in USD. # * 'CreationDateTime' <~DateTime> - The date/time the instance group was created. # * 'EndDateTime' <~DateTime> - The date/time the instance group was terminated. # * 'InstanceGroupId' <~String> - Unique identifier for the instance group. # * 'InstanceRequestCount'<~Integer> - Target number of instances for the instance group # * 'InstanceRole'<~String> - MASTER | CORE | TASK The role of the instance group in the cluster # * 'InstanceRunningCount'<~Integer> - Actual count of running instances # * 'InstanceType'<~String> - The Amazon EC2 instance type for all instances in the instance group # * 'LastStateChangeReason'<~String> - Details regarding the state of the instance group # * 'Market'<~String> - ON_DEMAND | SPOT Market type of the Amazon EC2 instances used to create a cluster # * 'Name'<~String> - Friendly name for the instance group # * 'ReadyDateTime'<~DateTime> - The date/time the instance group was available to the cluster # * 'StartDateTime'<~DateTime> - The date/time the instance group was started # * 'State'<~String> - PROVISIONING | STARTING | BOOTSTRAPPING | RUNNING | RESIZING | ARRESTED | SHUTTING_DOWN | TERMINATED | FAILED | ENDED State of instance group # * 'KeepJobFlowAliveWhenNoSteps' <~Boolean> - Specifies whether the job flow should terminate after completing all steps # * 'MasterInstanceId'<~String> - The Amazon EC2 instance identifier of the master node # * 'MasterInstanceType'<~String> - The EC2 instance type of the master node # * 'MasterPublicDnsName'<~String> - The DNS name of the master node # * 'NormalizedInstanceHours'<~Integer> - An approximation of the cost of the job flow, represented in m1.small/hours. # * 'Placement'<~Array> - Specifies the Availability Zone the job flow will run in # * 'AvailabilityZone' <~String> - The Amazon EC2 Availability Zone for the job flow. # * 'SlaveInstanceType'<~String> - The EC2 instance type of the slave nodes # * 'TerminationProtected'<~Boolean> - Specifies whether to lock the job flow to prevent the Amazon EC2 instances from being terminated by API call, user intervention, or in the event of a job flow error # * LogUri <~String> - Specifies the location in Amazon S3 to write the log files of the job flow. If a value is not provided, logs are not created # * Name <~String> - The name of the job flow # * Steps <~Array> - A list of steps to be executed by the job flow # * 'ExecutionStatusDetail'<~Array> - Describes the execution status of the job flow # * 'CreationDateTime <~DateTime> - The creation date and time of the job flow. # * 'EndDateTime <~DateTime> - The completion date and time of the job flow. # * 'LastStateChangeReason <~String> - Description of the job flow last changed state. # * 'ReadyDateTime <~DateTime> - The date and time when the job flow was ready to start running bootstrap actions. # * 'StartDateTime <~DateTime> - The start date and time of the job flow. # * 'State <~DateTime> - COMPLETED | FAILED | TERMINATED | RUNNING | SHUTTING_DOWN | STARTING | WAITING | BOOTSTRAPPING The state of the job flow. # * StepConfig <~Array> - The step configuration # * 'ActionOnFailure'<~String> - TERMINATE_JOB_FLOW | CANCEL_AND_WAIT | CONTINUE Specifies the action to take if the job flow step fails # * 'HadoopJarStep'<~Array> - Specifies the JAR file used for the job flow step # * 'Args'<~String list> - A list of command line arguments passed to the JAR file's main function when executed. # * 'Jar'<~String> - A path to a JAR file run during the step. # * 'MainClass'<~String> - The name of the main class in the specified Java file. If not specified, the JAR file should specify a Main-Class in its manifest file # * 'Properties'<~Array> - A list of Java properties that are set when the step runs. You can use these properties to pass key value pairs to your main function # * 'Key'<~String> - The unique identifier of a key value pair # * 'Value'<~String> - The value part of the identified key # * 'Name'<~String> - The name of the job flow step def describe_job_flows(options={}) if job_ids = options.delete('JobFlowIds') options.merge!(Fog::AWS.serialize_keys('JobFlowIds', job_ids)) end if job_states = options.delete('JobFlowStates') options.merge!(Fog::AWS.serialize_keys('JobFlowStates', job_states)) end request({ 'Action' => 'DescribeJobFlows', :parser => Fog::Parsers::AWS::EMR::DescribeJobFlows.new, }.merge(options)) end end class Mock def describe_job_flows(db_name, options={}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/emr/modify_instance_groups.rb0000644000004100000410000000232712261242551024261 0ustar www-datawww-datamodule Fog module AWS class EMR class Real require 'fog/aws/parsers/emr/modify_instance_groups' # modifies the number of nodes and configuration settings of an instance group.. # http://docs.amazonwebservices.com/ElasticMapReduce/latest/API/API_ModifyInstanceGroups.html # ==== Parameters # * InstanceGroups <~InstanceGroupModifyConfig list> - Instance groups to change # * InstanceCount <~Integer> - Target size for instance group # * InstanceGroupId <~String> - Unique ID of the instance group to expand or shrink # # ==== Returns # * response<~Excon::Response>: # * body<~Hash> def modify_instance_groups(options={}) if job_ids = options.delete('InstanceGroups') options.merge!(Fog::AWS.serialize_keys('InstanceGroups', job_ids)) end request({ 'Action' => 'ModifyInstanceGroups', :parser => Fog::Parsers::AWS::EMR::ModifyInstanceGroups.new, }.merge(options)) end end class Mock def modify_instance_groups(options={}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/0000755000004100000410000000000012261242551021043 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/auto_scaling/create_auto_scaling_group.rb0000644000004100000410000001632112261242551026602 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Creates a new Auto Scaling group with the specified name. Once the # creation request is completed, the AutoScalingGroup is ready to be # used in other calls. # # ==== Parameters # * auto_scaling_group_name<~String> - The name of the Auto Scaling # group. # * availability_zones<~Array> - A list of availability zones for the # Auto Scaling group. # * launch_configuration_name<~String> - The name of the launch # configuration to use with the Auto Scaling group. # * max_size<~Integer> - The maximum size of the Auto Scaling group. # * min_size<~Integer> - The minimum size of the Auto Scaling group. # * options<~Hash>: # * 'DefaultCooldown'<~Integer> - The amount of time, in seconds, # after a scaling activity completes before any further trigger- # related scaling activities can start. # * 'DesiredCapacity'<~Integer> - The number of Amazon EC2 instances # that should be running in the group. # * 'HealthCheckGracePeriod'<~Integer> - Length of time in seconds # after a new Amazon EC2 instance comes into service that Auto # Scaling starts checking its health. # * 'HealthCheckType'<~String> - The service you want the health # status from, Amazon EC2 or Elastic Load Balancer. Valid values # are "EC2" or "ELB". # * 'LoadBalancerNames'<~Array> - A list of LoadBalancers to use. # * 'PlacementGroup'<~String> - Physical location of your cluster # placement group created in Amazon EC2. # * 'Tags'<~Array>: # * tag<~Hash>: # * 'Key'<~String> - The key of the tag. # * 'PropagateAtLaunch'<~Boolean> - Specifies whether the new tag # will be applied to instances launched after the tag is # created. The same behavior applies to updates: If you change # a tag, the changed tag will be applied to all instances # launched after you made the change. # * 'ResourceId'<~String>: The name of the AutoScaling group. # * 'ResourceType'<~String>: The kind of resource to which the # tag is applied. Currently, Auto Scaling supports the # auto-scaling-group resource type. # * 'Value'<~String>: The value of the tag. # * 'TerminationPolicies'<~Array> - A standalone termination policy # or a list of termination policies used to select the instance to # terminate. The policies are executed in the order that they are # listed. # * 'VPCZoneIdentifier'<~String> - A comma-separated list of subnet # identifiers of Amazon Virtual Private Clouds (Amazon VPCs). # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_CreateAutoScalingGroup.html # ExpectedOptions[:create_auto_scaling_group] = %w[DefaultCooldown DesiredCapacity HealthCheckGracePeriod HealthCheckType LoadBalancerNames PlacementGroup Tags TerminationPolicies VPCZoneIdentifier] def create_auto_scaling_group(auto_scaling_group_name, availability_zones, launch_configuration_name, max_size, min_size, options = {}) options.merge!(AWS.indexed_param('AvailabilityZones.member.%d', [*availability_zones])) options.delete('AvailabilityZones') if load_balancer_names = options.delete('LoadBalancerNames') options.merge!(AWS.indexed_param('LoadBalancerNames.member.%d', [*load_balancer_names])) end if tags = options.delete('Tags') tags.each_with_index do |(key, value), i| options["Tags.member.#{i+1}.Key"] = key.to_s # turns symbol into string options["Tags.member.#{i+1}.Value"] = value end end if termination_policies = options.delete('TerminationPolicies') options.merge!(AWS.indexed_param('TerminationPolicies.member.%d', [*termination_policies])) end request({ 'Action' => 'CreateAutoScalingGroup', 'AutoScalingGroupName' => auto_scaling_group_name, 'LaunchConfigurationName' => launch_configuration_name, 'MaxSize' => max_size, 'MinSize' => min_size, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }.merge!(options)) end end class Mock def create_auto_scaling_group(auto_scaling_group_name, availability_zones, launch_configuration_name, max_size, min_size, options = {}) unexpected_options = options.keys - ExpectedOptions[:create_auto_scaling_group] unless unexpected_options.empty? raise Fog::AWS::AutoScaling::ValidationError.new("Options #{unexpected_options.join(',')} should not be included in request") end if self.data[:auto_scaling_groups].has_key?(auto_scaling_group_name) raise Fog::AWS::AutoScaling::IdentifierTaken.new("AutoScalingGroup by this name already exists - A group with the name #{auto_scaling_group_name} already exists") end unless self.data[:launch_configurations].has_key?(launch_configuration_name) raise Fog::AWS::AutoScaling::ValidationError.new('Launch configuration name not found - null') end self.data[:auto_scaling_groups][auto_scaling_group_name] = { 'AutoScalingGroupARN' => Fog::AWS::Mock.arn('autoscaling', self.data[:owner_id], "autoScalingGroup:00000000-0000-0000-0000-000000000000:autoScalingGroupName/#{auto_scaling_group_name}", @region), 'AutoScalingGroupName' => auto_scaling_group_name, 'AvailabilityZones' => [*availability_zones], 'CreatedTime' => Time.now.utc, 'DefaultCooldown' => 300, 'DesiredCapacity' => 0, 'EnabledMetrics' => [], 'HealthCheckGracePeriod' => 0, 'HealthCheckType' => 'EC2', 'Instances' => [], 'LaunchConfigurationName' => launch_configuration_name, 'LoadBalancerNames' => [], 'MaxSize' => max_size, 'MinSize' => min_size, 'PlacementGroup' => nil, 'SuspendedProcesses' => [], 'Tags' => [], 'TerminationPolicies' => ['Default'], 'VPCZoneIdentifier' => nil }.merge!(options) response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/describe_policies.rb0000644000004100000410000001134212261242551025040 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/describe_policies' # Returns descriptions of what each policy does. This action supports # pagination. If the response includes a token, there are more records # available. To get the additional records, repeat the request with the # response token as the NextToken parameter. # # ==== Parameters # * options<~Hash>: # * 'AutoScalingGroupName'<~String> - The name of the Auto Scaling # group. # * 'MaxRecords'<~Integer> - The maximum number of policies that will # be described with each call. # * 'NextToken'<~String> - The token returned by a previous call to # indicate that there is more data available. # * PolicyNames<~Array> - A list of policy names or policy ARNs to be # described. If this list is omitted, all policy names are # described. If an auto scaling group name is provided, the results # are limited to that group.The list of requested policy names # cannot contain more than 50 items. If unknown policy names are # requested, they are ignored with no error. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribePoliciesResult'<~Hash>: # * 'ScalingPolicies'<~Array>: # * 'AdjustmentType'<~String> - Specifies whether the # adjustment is an absolute number or a percentage of the # current capacity. # * 'Alarms'<~Array>: # * 'AlarmARN'<~String> - The Amazon Resource Name (ARN) of # the alarm. # * 'AlarmName'<~String> - The name of the alarm. # * 'AutoScalingGroupName'<~String> - The name of the Auto # Scaling group associated with this scaling policy. # * 'Cooldown'<~Integer> - The amount of time, in seconds, # after a scaling activity completes before any further # trigger-related scaling activities can start. # * 'PolicyARN'<~String> - The Amazon Resource Name (ARN) of # the policy. # * 'PolicyName'<~String> - The name of the scaling policy. # * 'ScalingAdjustment'<~Integer> - The number associated with # the specified AdjustmentType. A positive value adds to the # current capacity and a negative value removes from the # current capacity. # * 'NextToken'<~String> - Acts as a paging mechanism for large # result sets. Set to a non-empty string if there are # additional results waiting to be returned. Pass this in to # subsequent calls to return additional results. # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DescribePolicies.html # def describe_policies(options = {}) if policy_names = options.delete('PolicyNames') options.merge!(AWS.indexed_param('PolicyNames.member.%d', [*policy_names])) end request({ 'Action' => 'DescribePolicies', :parser => Fog::Parsers::AWS::AutoScaling::DescribePolicies.new }.merge!(options)) end end class Mock def describe_policies(options = {}) results = { 'ScalingPolicies' => [] } policy_set = self.data[:scaling_policies] for opt_key, opt_value in options if opt_key == "PolicyNames" && opt_value != nil && opt_value != "" policy_set = policy_set.reject do |asp_name, asp_data| ![*options["PolicyNames"]].include?(asp_name) end elsif opt_key == "AutoScalingGroupName" && opt_value != nil && opt_value != "" policy_set = policy_set.reject do |asp_name, asp_data| options["AutoScalingGroupName"] != asp_data["AutoScalingGroupName"] end end end policy_set.each do |asp_name, asp_data| results['ScalingPolicies'] << { 'PolicyName' => asp_name }.merge!(asp_data) end response = Excon::Response.new response.status = 200 response.body = { 'DescribePoliciesResult' => results, 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/terminate_instance_in_auto_scaling_group.rb0000644000004100000410000000520212261242551031675 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/terminate_instance_in_auto_scaling_group' # Terminates the specified instance. Optionally, the desired group size # can be adjusted. # # ==== Parameters # * instance_id<~String> - The ID of the EC2 instance to be terminated. # * should_decrement_desired_capacity<~Boolean> - Specifies whether # (true) or not (false) terminating this instance should also # decrement the size of the AutoScalingGroup. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'TerminateGroupInAutoScalingInstanceResult'<~Hash>: # * 'ActivityId'<~String> - Specifies the ID of the activity. # * 'AutoScalingGroupName'<~String> - The name of the Auto # Scaling group. # * 'Cause'<~String> - Contains the reason the activity was # begun. # * 'Description'<~String> - Contains a friendly, more verbose # description of the scaling activity. # * 'EndTime'<~Time> - Provides the end time of this activity. # * 'Progress'<~Integer> - Specifies a value between 0 and 100 # that indicates the progress of the activity. # * 'StartTime'<~Time> - Provides the start time of this # activity. # * 'StatusCode'<~String> - Contains the current status of the # activity. # * 'StatusMessage'<~String> - Contains a friendly, more verbose # description of the activity status. # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_TerminateInstanceInAutoScalingGroup.html # def terminate_instance_in_auto_scaling_group(instance_id, should_decrement_desired_capacity) request({ 'Action' => 'TerminateInstanceInAutoScalingGroup', 'InstanceId' => instance_id, 'ShouldDecrementDesiredCapacity' => should_decrement_desired_capacity.to_s, :parser => Fog::Parsers::AWS::AutoScaling::TerminateInstanceInAutoScalingGroup.new }) end end class Mock def terminate_instance_in_auto_scaling_group(instance_id, should_decrement_desired_capacity) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/create_or_update_tags.rb0000644000004100000410000000414012261242551025712 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Creates new tags or updates existing tags for an Auto Scaling group. # # ==== Parameters # * tags<~Array>: # * tag<~Hash>: # * Key<~String> - The key of the tag. # * PropagateAtLaunch<~Boolean> - Specifies whether the new tag # will be applied to instances launched after the tag is created. # The same behavior applies to updates: If you change a tag, the # changed tag will be applied to all instances launched after you # made the change. # * ResourceId<~String> - The name of the Auto Scaling group. # * ResourceType<~String> - The kind of resource to which the tag # is applied. Currently, Auto Scaling supports the # auto-scaling-group resource type. # * Value<~String> - The value of the tag. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_CreateOrUpdateTags.html # def create_or_update_tags(tags) params = {} tags.each_with_index do |tag, i| tag.each do |key, value| params["Tags.member.#{i+1}.#{key}"] = value unless value.nil? end end request({ 'Action' => 'CreateOrUpdateTags', :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }.merge!(params)) end end class Mock def create_or_update_tags(tags) if tags.to_a.empty? raise Fog::AWS::AutoScaling::ValidationError.new("1 validation error detected: Value null at 'tags' failed to satisfy constraint: Member must not be null") end raise Fog::Mock::NotImplementedError end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/put_scheduled_update_group_action.rb0000644000004100000410000000550512261242551030340 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Creates a scheduled scaling action for a Auto Scaling group. If you # leave a parameter unspecified, the corresponding value remains # unchanged in the affected Auto Scaling group. # # ==== Parameters # * auto_scaling_group_name<~String> - The name or ARN of the Auto # Scaling Group. # * scheduled_action_name<~String> - Name of this scaling action. # * time<~Datetime> - The time for this action to start (deprecated: # use StartTime, EndTime and Recurrence). # * options<~Hash>: # * 'DesiredCapacity'<~Integer> - The number of EC2 instances that # should be running in this group. # * 'EndTime'<~DateTime> - The time for this action to end. # * 'MaxSize'<~Integer> - The maximum size for the Auto Scaling # group. # * 'MinSize'<~Integer> - The minimum size for the Auto Scaling # group. # * 'Recurrence'<~String> - The time when recurring future actions # will start. Start time is specified by the user following the # Unix cron syntax format. When StartTime and EndTime are specified # with Recurrence, they form the boundaries of when the recurring # action will start and stop. # * 'StartTime'<~DateTime> - The time for this action to start # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_PutScheduledUpdateGroupAction.html # def put_scheduled_update_group_action(auto_scaling_group_name, scheduled_action_name, time=nil, options = {}) # The 'Time' paramenter is now an alias for StartTime and needs to be identical if specified. time = options['StartTime'].nil? ? time : options['StartTime'] if !time.nil? time = time.class == Time ? time.utc.iso8601 : Time.parse(time).utc.iso8601 end request({ 'Action' => 'PutScheduledUpdateGroupAction', 'AutoScalingGroupName' => auto_scaling_group_name, 'ScheduledActionName' => scheduled_action_name, 'Time' => time, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }.merge!(options)) end end class Mock def put_scheduled_update_group_action(auto_scaling_group_name, scheduled_policy_name, time, options = {}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/put_notification_configuration.rb0000644000004100000410000000556412261242551027707 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/put_notification_configuration' # Creates a notification configuration for an Auto Scaling group. To # update an existing policy, overwrite the existing notification # configuration name and set the parameter(s) you want to change. # # ==== Parameters # * auto_scaling_group_name<~String> - The name of the Auto Scaling # group. # * notification_types<~Array> - The type of events that will trigger # the notification. # * topic_arn<~String> - The Amazon Resource Name (ARN) of the Amazon # Simple Notification Service (SNS) topic. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_PutNotificationConfiguration.html # def put_notification_configuration(auto_scaling_group_name, notification_types, topic_arn) params = AWS.indexed_param('NotificationTypes.member.%d', [*notification_types]) request({ 'Action' => 'PutNotificationConfiguration', 'AutoScalingGroupName' => auto_scaling_group_name, 'TopicARN' => topic_arn, :parser => Fog::Parsers::AWS::AutoScaling::PutNotificationConfiguration.new }.merge!(params)) end end class Mock def put_notification_configuration(auto_scaling_group_name, notification_types, topic_arn) unless self.data[:auto_scaling_groups].has_key?(auto_scaling_group_name) raise Fog::AWS::AutoScaling::ValidationError.new("AutoScalingGroup name not found - #{auto_scaling_group_name}") end if notification_types.to_a.empty? raise Fog::AWS::AutoScaling::ValidationError.new("1 validation error detected: Value null at 'notificationTypes' failed to satisfy constraint: Member must not be null") end invalid_types = notification_types.to_a - self.data[:notification_types] unless invalid_types.empty? raise Fog::AWS::AutoScaling::ValidationError.new(""#{invalid_types.first}" is not a valid Notification Type.") end self.data[:notification_configurations][auto_scaling_group_name] ||= {} self.data[:notification_configurations][auto_scaling_group_name][topic_arn] = notification_types.to_a.uniq response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/delete_scheduled_action.rb0000644000004100000410000000256612261242551026220 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Deletes a scheduled action previously created using the # put_scheduled_update_group_action. # # ==== Parameters # * auto_scaling_group_name<~String> - The name of the Auto Scaling # group. # * scheduled_action_name<~String> - The name of the action you want to # delete. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DeleteScheduledAction.html # def delete_scheduled_action(auto_scaling_group_name, scheduled_action_name) request({ 'Action' => 'DeleteScheduledAction', 'AutoScalingGroupName' => auto_scaling_group_name, 'ScheduledActionName' => scheduled_action_name, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }) end end class Mock def delete_scheduled_action(auto_scaling_group_name, scheduled_action_name) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/set_desired_capacity.rb0000644000004100000410000000716612261242551025551 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Adjusts the desired size of the AutoScalingGroup by initiating # scaling activities. When reducing the size of the group, it is not # possible to define which EC2 instances will be terminated. This # applies to any auto-scaling decisions that might result in # terminating instances. # # There are two common use cases for set_desired_capacity: one for # users of the Auto Scaling triggering system, and another for # developers who write their own triggering systems. Both use cases # relate to the concept of cooldown. # # In the first case, if you use the Auto Scaling triggering system, # set_desired_capacity changes the size of your Auto Scaling group # without regard to the cooldown period. This could be useful, for # example, if Auto Scaling did something unexpected for some reason. If # your cooldown period is 10 minutes, Auto Scaling would normally # reject requests to change the size of the group for that entire 10 # minute period. The set_desired_capacity command allows you to # circumvent this restriction and change the size of the group before # the end of the cooldown period. # # In the second case, if you write your own triggering system, you can # use set_desired_capacity to control the size of your Auto Scaling # group. If you want the same cooldown functionality that Auto Scaling # offers, you can configure set_desired_capacity to honor cooldown by # setting the HonorCooldown parameter to true. # # ==== Parameters # * auto_scaling_group_name<~String> - The name of the Auto Scaling # group. # * desired_capacity<~Integer> - The new capacity setting for the Auto # Scaling group. # * options<~Hash>: # * 'HonorCooldown'<~Boolean> - By default, set_desired_capacity # overrides any cooldown period. Set to true if you want Auto # Scaling to reject this request if the Auto Scaling group is in # cooldown. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_SetDesiredCapacity.html # def set_desired_capacity(auto_scaling_group_name, desired_capacity, options = {}) request({ 'Action' => 'SetDesiredCapacity', 'AutoScalingGroupName' => auto_scaling_group_name, 'DesiredCapacity' => desired_capacity, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }.merge!(options)) end end class Mock def set_desired_capacity(auto_scaling_group_name, desired_capacity, options = {}) unless self.data[:auto_scaling_groups].has_key?(auto_scaling_group_name) Fog::AWS::AutoScaling::ValidationError.new('AutoScalingGroup name not found - null') end self.data[:auto_scaling_groups][auto_scaling_group_name]['DesiredCapacity'] = desired_capacity response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/enable_metrics_collection.rb0000644000004100000410000000460212261242551026561 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Enables monitoring of group metrics for the Auto Scaling group # specified in auto_scaling_group_name. You can specify the list of # enabled metrics with the metrics parameter. # # Auto scaling metrics collection can be turned on only if the # instance_monitoring.enabled flag, in the Auto Scaling group's launch # configuration, is set to true. # # ==== Parameters # * 'AutoScalingGroupName'<~String>: The name or ARN of the Auto # Scaling group # * options<~Hash>: # * Granularity<~String>: The granularity to associate with the # metrics to collect. # * Metrics<~Array>: The list of metrics to collect. If no metrics # are specified, all metrics are enabled. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_EnableMetricsCollection.html # def enable_metrics_collection(auto_scaling_group_name, granularity, options = {}) if metrics = options.delete('Metrics') options.merge!(AWS.indexed_param('Metrics.member.%d', [*metrics])) end request({ 'Action' => 'EnableMetricsCollection', 'AutoScalingGroupName' => auto_scaling_group_name, 'Granularity' => granularity, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }.merge!(options)) end end class Mock def enable_metrics_collection(auto_scaling_group_name, granularity, options = {}) unless self.data[:auto_scaling_groups].has_key?(auto_scaling_group_name) Fog::AWS::AutoScaling::ValidationError.new("Group #{auto_scaling_group_name} not found") end unless self.data[:metric_collection_types][:granularities].include?(granularity) Fog::AWS::AutoScaling::ValidationError.new('Valid metrics granularity type is: [1Minute].') end Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/suspend_processes.rb0000644000004100000410000000417012261242551025141 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Suspends Auto Scaling processes for an Auto Scaling group. To suspend # specific process types, specify them by name with the # ScalingProcesses parameter. To suspend all process types, omit the # ScalingProcesses.member.N parameter. # # ==== Parameters # * 'AutoScalingGroupName'<~String> - The name or Amazon Resource Name # (ARN) of the Auto Scaling group. # * options<~Hash>: # * 'ScalingProcesses'<~Array> - The processes that you want to # suspend. To suspend all process types, omit this parameter. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_SuspendProcesses.html # def suspend_processes(auto_scaling_group_name, options = {}) if scaling_processes = options.delete('ScalingProcesses') options.merge!(AWS.indexed_param('ScalingProcesses.member.%d', [*scaling_processes])) end request({ 'Action' => 'SuspendProcesses', 'AutoScalingGroupName' => auto_scaling_group_name, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }.merge!(options)) end end class Mock def suspend_processes(auto_scaling_group_name, options = {}) unless self.data[:auto_scaling_groups].has_key?(auto_scaling_group_name) raise Fog::AWS::AutoScaling::ValidationError.new("AutoScalingGroup name not found - no such group: #{auto_scaling_group_name}") end response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/delete_policy.rb0000644000004100000410000000315012261242551024210 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Deletes a policy created by put_scaling_policy # # ==== Parameters # * auto_scaling_group_name<~String> - The name of the Auto Scaling # group. # * policy_name<~String> - The name or PolicyARN of the policy you want # to delete. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DeletePolicy.html # def delete_policy(auto_scaling_group_name, policy_name) request({ 'Action' => 'DeletePolicy', 'AutoScalingGroupName' => auto_scaling_group_name, 'PolicyName' => policy_name, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }) end end class Mock def delete_policy(auto_scaling_group_name, policy_name) unless self.data[:scaling_policies].delete(policy_name) raise Fog::AWS::AutoScaling::NotFound, "The scaling policy '#{policy_name}' does not exist." end response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/delete_launch_configuration.rb0000644000004100000410000000335612261242551027122 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Deletes the specified launch configuration. # # The specified launch configuration must not be attached to an Auto # Scaling group. Once this call completes, the launch configuration is # no longer available for use. # # ==== Parameters # * launch_configuration_name<~String> - The name of the launch # configuration. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DeleteLaunchConfiguration.html # def delete_launch_configuration(launch_configuration_name) request({ 'Action' => 'DeleteLaunchConfiguration', 'LaunchConfigurationName' => launch_configuration_name, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }) end end class Mock def delete_launch_configuration(launch_configuration_name) unless self.data[:launch_configurations].delete(launch_configuration_name) raise Fog::AWS::AutoScaling::NotFound, "The launch configuration '#{launch_configuration_name}' does not exist." end response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/execute_policy.rb0000644000004100000410000000261312261242551024413 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Runs the policy you create for your Auto Scaling group in # put_scaling_policy. # # ==== Parameters # * 'PolicyName'<~String> - The name or PolicyARN of the policy you # want to run. # * options<~Hash>: # * 'AutoScalingGroupName'<~String> - The name or ARN of the Auto # Scaling group. # * 'HonorCooldown'<~Boolean> - Set to true if you want Auto Scaling # to reject this request if the Auto Scaling group is in cooldown. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_ExecutePolicy.html # def execute_policy(policy_name, options = {}) request({ 'Action' => 'ExecutePolicy', 'PolicyName' => policy_name, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }.merge!(options)) end end class Mock def execute_policy(policy_name, options = {}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/create_launch_configuration.rb0000644000004100000410000001222012261242551027111 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Creates a new launch configuration. When created, the new launch # configuration is available for immediate use. # # ==== Parameters # * image_id<~String> - Unique ID of the Amazon Machine Image (AMI) # which was assigned during registration. # * instance_type<~String> - The instance type of the EC2 instance. # * launch_configuration_name<~String> - The name of the launch # configuration to create. # * options<~Hash>: # * 'BlockDeviceMappings'<~Array>: # * 'DeviceName'<~String> - The name of the device within Amazon # EC2. # * 'Ebs.SnapshotId'<~String> - The snapshot ID. # * 'Ebs.VolumeSize'<~Integer> - The volume size, in GigaBytes. # * 'VirtualName'<~String> - The virtual name associated with the # device. # * 'IamInstanceProfile'<~String> The name or the Amazon Resource # Name (ARN) of the instance profile associated with the IAM role # for the instance. # * 'InstanceMonitoring.Enabled'<~Boolean> - Enables detailed # monitoring, which is enabled by default. # * 'KernelId'<~String> - The ID of the kernel associated with the # Amazon EC2 AMI. # * 'KeyName'<~String> - The name of the Amazon EC2 key pair. # * 'RamdiskId'<~String> - The ID of the RAM disk associated with the # Amazon EC2 AMI. # * 'SecurityGroups'<~Array> - The names of the security groups with # which to associate Amazon EC2 or Amazon VPC instances. # * 'SpotPrice'<~String> - The maximum hourly price to be paid for # any Spot Instance launched to fulfill the request. Spot Instances # are launched when the price you specify exceeds the current Spot # market price. # * 'UserData'<~String> - The user data available to the launched # Amazon EC2 instances. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_CreateLaunchConfiguration.html # def create_launch_configuration(image_id, instance_type, launch_configuration_name, options = {}) if block_device_mappings = options.delete('BlockDeviceMappings') block_device_mappings.each_with_index do |mapping, i| for key, value in mapping options.merge!({ format("BlockDeviceMappings.member.%d.#{key}", i+1) => value }) end end end if security_groups = options.delete('SecurityGroups') options.merge!(AWS.indexed_param('SecurityGroups.member.%d', [*security_groups])) end if options['UserData'] options['UserData'] = Base64.encode64(options['UserData']) end request({ 'Action' => 'CreateLaunchConfiguration', 'ImageId' => image_id, 'InstanceType' => instance_type, 'LaunchConfigurationName' => launch_configuration_name, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }.merge!(options)) end end class Mock def create_launch_configuration(image_id, instance_type, launch_configuration_name, options = {}) if self.data[:launch_configurations].has_key?(launch_configuration_name) raise Fog::AWS::AutoScaling::IdentifierTaken.new("Launch Configuration by this name already exists - A launch configuration already exists with the name #{launch_configuration_name}") end self.data[:launch_configurations][launch_configuration_name] = { 'AssociatePublicIpAddress' => nil, 'BlockDeviceMappings' => [], 'CreatedTime' => Time.now.utc, 'IamInstanceProfile' => nil, 'ImageId' => image_id, 'InstanceMonitoring' => {'Enabled' => true}, 'InstanceType' => instance_type, 'KernelId' => nil, 'KeyName' => nil, 'LaunchConfigurationARN' => Fog::AWS::Mock.arn('autoscaling', self.data[:owner_id], "launchConfiguration:00000000-0000-0000-0000-000000000000:launchConfigurationName/#{launch_configuration_name}", @region), 'LaunchConfigurationName' => launch_configuration_name, 'RamdiskId' => nil, 'SecurityGroups' => [], 'UserData' => nil }.merge!(options) response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/describe_auto_scaling_notification_types.rb0000644000004100000410000000333712261242551031700 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/describe_auto_scaling_notification_types' # Returns a list of all notification types that are supported by Auto # Scaling. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeAutoScalingNotificationTypesResult'<~Hash>: # * 'AutoScalingNotificationTypes'<~Array>: # * 'notificationType'<~String> - A notification type. # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DescribeAutoScalingNotificationTypes.html # def describe_auto_scaling_notification_types() request({ 'Action' => 'DescribeAutoScalingNotificationTypes', :idempotent => true, :parser => Fog::Parsers::AWS::AutoScaling::DescribeAutoScalingNotificationTypes.new }) end end class Mock def describe_auto_scaling_notification_types() results = { 'AutoScalingNotificationTypes' => [], } self.data[:notification_types].each do |notification_type| results['AutoScalingNotificationTypes'] << notification_type end response = Excon::Response.new response.status = 200 response.body = { 'DescribeAutoScalingNotificationTypesResult' => results, 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/disable_metrics_collection.rb0000644000004100000410000000346612261242551026745 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Disables monitoring of group metrics for the Auto Scaling group # specified in AutoScalingGroupName. You can specify the list of # affected metrics with the Metrics parameter. # # ==== Parameters # * 'AutoScalingGroupName'<~String> - The name or ARN of the Auto # Scaling group. # * options<~Hash>: # * Metrics<~Array> - The list of metrics to disable. If no metrics # are specified, all metrics are disabled. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DisableMetricsCollection.html # def disable_metrics_collection(auto_scaling_group_name, options = {}) if metrics = options.delete('Metrics') options.merge!(AWS.indexed_param('Metrics.member.%d', [*metrics])) end request({ 'Action' => 'DisableMetricsCollection', 'AutoScalingGroupName' => auto_scaling_group_name, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }.merge!(options)) end end class Mock def disable_metrics_collection(auto_scaling_group_name, options = {}) unless self.data[:auto_scaling_groups].has_key?(auto_scaling_group_name) Fog::AWS::AutoScaling::ValidationError.new("Group #{auto_scaling_group_name} not found") end Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/delete_auto_scaling_group.rb0000644000004100000410000000377712261242551026614 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Deletes the specified auto scaling group if the group has no # instances and no scaling activities in progress. # # ==== Parameters # * auto_scaling_group_name<~String> - The name of the Auto Scaling # group. # * options<~Hash>: # * 'ForceDelete'<~Boolean> - Starting with API version 2011-01-01, # specifies that the Auto Scaling group will be deleted along with # all instances associated with the group, without waiting for all # instances to be terminated. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DeleteAutoScalingGroup.html # def delete_auto_scaling_group(auto_scaling_group_name, options = {}) request({ 'Action' => 'DeleteAutoScalingGroup', 'AutoScalingGroupName' => auto_scaling_group_name, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }.merge!(options)) end end class Mock def delete_auto_scaling_group(auto_scaling_group_name, options = {}) unless self.data[:auto_scaling_groups].delete(auto_scaling_group_name) raise Fog::AWS::AutoScaling::ValidationError, "The auto scaling group '#{auto_scaling_group_name}' does not exist." end self.data[:notification_configurations].delete(auto_scaling_group_name) response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/describe_metric_collection_types.rb0000644000004100000410000000365712261242551030165 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/describe_metric_collection_types' # Returns a list of metrics and a corresponding list of granularities # for each metric. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeMetricCollectionTypesResult'<~Hash>: # * 'Granularities'<~Array>: # * 'Granularity'<~String> - The granularity of a Metric. # * 'Metrics'<~Array>: # * 'Metric'<~String> - The name of a Metric. # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DescribeMetricCollectionTypes.html # def describe_metric_collection_types() request({ 'Action' => 'DescribeMetricCollectionTypes', :idempotent => true, :parser => Fog::Parsers::AWS::AutoScaling::DescribeMetricCollectionTypes.new }) end end class Mock def describe_metric_collection_types() results = { 'Granularities' => [], 'Metrics' => [] } self.data[:metric_collection_types][:granularities].each do |granularity| results['Granularities'] << { 'Granularity' => granularity } end self.data[:metric_collection_types][:metrics].each do |metric| results['Metrics'] << { 'Metric' => metric } end response = Excon::Response.new response.status = 200 response.body = { 'DescribeMetricCollectionTypesResult' => results, 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/delete_tags.rb0000644000004100000410000000407412261242551023655 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Removes the specified tags or a set of tags from a set of resources. # # ==== Parameters # * tags<~Array>: # * tag<~Hash>: # * Key<~String> - The key of the tag. # * PropagateAtLaunch<~Boolean> - Specifies whether the new tag # will be applied to instances launched after the tag is created. # The same behavior applies to updates: If you change a tag, the # changed tag will be applied to all instances launched after you # made the change. # * ResourceId<~String> - The name of the Auto Scaling group. # * ResourceType<~String> - The kind of resource to which the tag # is applied. Currently, Auto Scaling supports the # auto-scaling-group resource type. # * Value<~String> - The value of the tag. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DeleteTags.html # def delete_tags(tags) params = {} tags.each_with_index do |tag, i| tag.each do |key, value| params["Tags.member.#{i+1}.#{key}"] = value unless value.nil? end end request({ 'Action' => 'DeleteTags', :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }.merge!(params)) end end class Mock def delete_tags(tags) if tags.to_a.empty? raise Fog::AWS::AutoScaling::ValidationError.new("1 validation error detected: Value null at 'tags' failed to satisfy constraint: Member must not be null") end raise Fog::Mock::NotImplementedError end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/resume_processes.rb0000644000004100000410000000365412261242551024766 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Resumes Auto Scaling processes for an Auto Scaling group. # # ==== Parameters # * auto_scaling_group_name'<~String> - The name or Amazon Resource # Name (ARN) of the Auto Scaling group. # * options<~Hash>: # * 'ScalingProcesses'<~Array> - The processes that you want to # resume. To resume all process types, omit this parameter. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_ResumeProcesses.html # def resume_processes(auto_scaling_group_name, options = {}) if scaling_processes = options.delete('ScalingProcesses') options.merge!(AWS.indexed_param('ScalingProcesses.member.%d', [*scaling_processes])) end request({ 'Action' => 'ResumeProcesses', 'AutoScalingGroupName' => auto_scaling_group_name, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }.merge!(options)) end end class Mock def resume_processes(auto_scaling_group_name, options = {}) unless self.data[:auto_scaling_groups].has_key?(auto_scaling_group_name) raise Fog::AWS::AutoScaling::ValidationError.new("AutoScalingGroup name not found - no such group: #{auto_scaling_group_name}") end response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/update_auto_scaling_group.rb0000644000004100000410000001061312261242551026617 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Updates the configuration for the specified AutoScalingGroup. # # The new settings are registered upon the completion of this call. Any # launch configuration settings take effect on any triggers after this # call returns. Triggers that are currently in progress aren't # affected. # # ==== Parameters # * auto_scaling_group_name<~String> - The name of the Auto Scaling # group. # * options<~Hash>: # * 'AvailabilityZones'<~Array> - Availability zones for the group. # * 'DefaultCooldown'<~Integer> - The amount of time, in seconds, # after a scaling activity completes before any further trigger- # related scaling activities can start # * 'DesiredCapacity'<~Integer> - The desired capacity for the Auto # Scaling group. # * 'HealthCheckGracePeriod'<~Integer> - The length of time that Auto # Scaling waits before checking an instance's health status.The # grace period begins when an instance comes into service. # * 'HealthCheckType'<~String> - The service of interest for the # health status check, either "EC2" for Amazon EC2 or "ELB" for # Elastic Load Balancing. # * 'LaunchConfigurationName'<~String> - The name of the launch # configuration. # * 'MaxSize'<~Integer> - The maximum size of the Auto Scaling group. # * 'MinSize'<~Integer> - The minimum size of the Auto Scaling group. # * 'PlacementGroup'<~String> - The name of the cluster placement # group, if applicable. # * 'TerminationPolicies'<~Array> - A standalone termination policy # or a list of termination policies used to select the instance to # terminate. The policies are executed in the order that they are # listed. # * 'VPCZoneIdentifier'<~String> - The subnet identifier for the # Amazon VPC connection, if applicable. You can specify several # subnets in a comma-separated list. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_UpdateAutoScalingGroup.html # ExpectedOptions[:update_auto_scaling_group] = %w[AvailabilityZones DefaultCooldown DesiredCapacity HealthCheckGracePeriod HealthCheckType LaunchConfigurationName MaxSize MinSize PlacementGroup TerminationPolicies VPCZoneIdentifier] def update_auto_scaling_group(auto_scaling_group_name, options = {}) if availability_zones = options.delete('AvailabilityZones') options.merge!(AWS.indexed_param('AvailabilityZones.member.%d', [*availability_zones])) end if termination_policies = options.delete('TerminationPolicies') options.merge!(AWS.indexed_param('TerminationPolicies.member.%d', [*termination_policies])) end request({ 'Action' => 'UpdateAutoScalingGroup', 'AutoScalingGroupName' => auto_scaling_group_name, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }.merge!(options)) end end class Mock def update_auto_scaling_group(auto_scaling_group_name, options = {}) unexpected_options = options.keys - ExpectedOptions[:update_auto_scaling_group] unless unexpected_options.empty? raise Fog::AWS::AutoScaling::ValidationError.new("Options #{unexpected_options.join(',')} should not be included in request") end unless self.data[:auto_scaling_groups].has_key?(auto_scaling_group_name) raise Fog::AWS::AutoScaling::ValidationError.new('AutoScalingGroup name not found - null') end self.data[:auto_scaling_groups][auto_scaling_group_name].merge!(options) response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/describe_launch_configurations.rb0000644000004100000410000001206512261242551027620 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/describe_launch_configurations' # Returns a full description of the launch configurations given the # specified names. # # If no names are specified, then the full details of all launch # configurations are returned. # # ==== Parameters # * options<~Hash>: # * 'LaunchConfigurationNames'<~Array> - A list of launch # configuration names. # * 'MaxRecords'<~Integer> - The maximum number of launch # configurations. # * 'NextToken'<~String> - The token returned by a previous call to # indicate that there is more data available. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeLaunchConfigurationsResponse'<~Hash>: # * 'LaunchConfigurations'<~Array>: # * launchconfiguration'<~Hash>: # * 'BlockDeviceMappings'<~Array>: # * blockdevicemapping<~Hash>: # * 'DeviceName'<~String> - The name of the device within # EC2. # * 'Ebs'<~Hash>: # * 'SnapshotId'<~String> - The snapshot ID # * 'VolumeSize'<~Integer> - The volume size, in # GigaBytes. # * 'VirtualName'<~String> - The virtual name associated # with the device. # * 'CreatedTime'<~Time> - Provides the creation date and # time for this launch configuration. # * 'ImageId'<~String> - Provides the unique ID of the Amazon # Machine Image (AMI) that was assigned during # registration. # * 'InstanceMonitoring'<~Hash>: # * 'Enabled'<~Boolean> - If true, instance monitoring is # enabled. # * 'InstanceType'<~String> - Specifies the instance type of # the EC2 instance. # * 'KernelId'<~String> - Provides the ID of the kernel # associated with the EC2 AMI. # * 'KeyName'<~String> - Provides the name of the EC2 key # pair. # * 'LaunchConfigurationARN'<~String> - The launch # configuration's Amazon Resource Name (ARN). # * 'LaunchConfigurationName'<~String> - Specifies the name # of the launch configuration. # * 'RamdiskId'<~String> - Provides ID of the RAM disk # associated with the EC2 AMI. # * 'SecurityGroups'<~Array> - A description of the security # groups to associate with the EC2 instances. # * 'UserData'<~String> - The user data available to the # launched EC2 instances. # * 'NextToken'<~String> - Acts as a paging mechanism for large # result sets. Set to a non-empty string if there are # additional results waiting to be returned. Pass this in to # subsequent calls to return additional results. # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DescribeLaunchConfigurations.html # def describe_launch_configurations(options = {}) if launch_configuration_names = options.delete('LaunchConfigurationNames') options.merge!(AWS.indexed_param('LaunchConfigurationNames.member.%d', [*launch_configuration_names])) end request({ 'Action' => 'DescribeLaunchConfigurations', :parser => Fog::Parsers::AWS::AutoScaling::DescribeLaunchConfigurations.new }.merge!(options)) end end class Mock def describe_launch_configurations(options = {}) launch_configuration_names = options.delete('LaunchConfigurationNames') # even a nil object will turn into an empty array lc = [*launch_configuration_names] launch_configurations = if lc.any? lc.map do |lc_name| l_conf = self.data[:launch_configurations].find { |name, data| name == lc_name } #raise Fog::AWS::AutoScaling::NotFound unless l_conf l_conf[1].dup if l_conf end.compact else self.data[:launch_configurations].map { |lc, values| values.dup } end response = Excon::Response.new response.status = 200 response.body = { 'DescribeLaunchConfigurationsResult' => { 'LaunchConfigurations' => launch_configurations }, 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/delete_notification_configuration.rb0000644000004100000410000000444312261242551030334 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Deletes notifications created by put_notification_configuration. # # ==== Parameters # * auto_scaling_group_name<~String> - The name of the Auto Scaling # group. # * topic_arn<~String> - The Amazon Resource Name (ARN) of the Amazon # Simple Notification Service (SNS) topic. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DeleteNotificationConfiguration.html # def delete_notification_configuration(auto_scaling_group_name, topic_arn) request({ 'Action' => 'DeleteNotificationConfiguration', 'AutoScalingGroupName' => auto_scaling_group_name, 'TopicARN' => topic_arn, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }) end end class Mock def delete_notification_configuration(auto_scaling_group_name, topic_arn) unless self.data[:notification_configurations].has_key?(auto_scaling_group_name) raise Fog::AWS::AutoScaling::ValidationError.new('AutoScalingGroup name not found - %s' % auto_scaling_group_name) end unless self.data[:notification_configurations][auto_scaling_group_name].has_key?(topic_arn) raise Fog::AWS::AutoScaling::ValidationError.new("Notification Topic '#{topic_arn}' doesn't exist for '#{self.data[:owner_id]}'") end self.data[:notification_configurations][auto_scaling_group_name].delete(topic_arn) if self.data[:notification_configurations][auto_scaling_group_name].empty? self.data[:notification_configurations].delete(auto_scaling_group_name) end response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/describe_notification_configurations.rb0000644000004100000410000000604712261242551031037 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/describe_notification_configurations' # Returns a list of notification actions associated with Auto Scaling # groups for specified events. # # ==== Parameters # * options<~Hash>: # * 'AutoScalingGroupNames'<~String> - The name of the Auto Scaling # group. # * 'MaxRecords'<~Integer> - The maximum number of records to return. # * 'NextToken'<~String> - A string that is used to mark the start of # the next batch of returned results for pagination. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeNotificationConfigurationsResult'<~Hash>: # * 'NotificationConfigurations'<~Array>: # * notificationConfiguration<~Hash>: # * 'AutoScalingGroupName'<~String> - Specifies the Auto # Scaling group name. # * 'NotificationType'<~String> - The types of events for an # action to start. # * 'TopicARN'<~String> - The Amazon Resource Name (ARN) of the # Amazon Simple Notification Service (SNS) topic. # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DescribeNotificationConfigurations.html # def describe_notification_configurations(options = {}) if auto_scaling_group_names = options.delete('AutoScalingGroupNames') options.merge!(AWS.indexed_param('AutoScalingGroupNames.member.%d', [*auto_scaling_group_names])) end request({ 'Action' => 'DescribeNotificationConfigurations', :parser => Fog::Parsers::AWS::AutoScaling::DescribeNotificationConfigurations.new }.merge!(options)) end end class Mock def describe_notification_configurations(options = {}) results = { 'NotificationConfigurations' => [] } (options['AutoScalingGroupNames']||self.data[:notification_configurations].keys).each do |asg_name| (self.data[:notification_configurations][asg_name]||{}).each do |topic_arn, notification_types| notification_types.each do |notification_type| results['NotificationConfigurations'] << { 'AutoScalingGroupName' => asg_name, 'NotificationType' => notification_type, 'TopicARN' => topic_arn, } end end end response = Excon::Response.new response.status = 200 response.body = { 'DescribeNotificationConfigurationsResult' => results, 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/set_instance_health.rb0000644000004100000410000000343512261242551025401 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/basic' # Sets the health status of an instance. # # ==== Parameters # * health_status<~String> - The health status of the instance. # "Healthy" means that the instance is healthy and should remain in # service. "Unhealthy" means that the instance is unhealthy. Auto # Scaling should terminate and replace it. # * instance_id<~String> - The identifier of the EC2 instance. # * options<~Hash>: # * 'ShouldRespectGracePeriod'<~Boolean> - If true, this call should # respect the grace period associated with the group. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_SetInstanceHealth.html # def set_instance_health(health_status, instance_id, options = {}) request({ 'Action' => 'SetInstanceHealth', 'HealthStatus' => health_status, 'InstanceId' => instance_id, :parser => Fog::Parsers::AWS::AutoScaling::Basic.new }.merge!(options)) end end class Mock def set_instance_health(health_status, instance_id, options = {}) unless self.data[:health_states].include?(health_status) raise Fog::AWS::AutoScaling::ValidationError.new('Valid instance health states are: [#{self.data[:health_states].join(", ")}].') end Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/describe_termination_policy_types.rb0000644000004100000410000000315412261242551030367 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/describe_termination_policy_types' # Returns a list of all termination policies supported by Auto Scaling. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeTerminationPolicyTypesResult'<~Hash>: # * 'TerminationPolicyTypes'<~Array>: # * terminationtype<~String>: # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DescribeTerminationPolicyTypes.html # def describe_termination_policy_types() request({ 'Action' => 'DescribeTerminationPolicyTypes', :idempotent => true, :parser => Fog::Parsers::AWS::AutoScaling::DescribeTerminationPolicyTypes.new }) end end class Mock def describe_termination_policy_types() results = { 'TerminationPolicyTypes' => [] } self.data[:termination_policy_types].each do |termination_policy_type| results['TerminationPolicyTypes'] << termination_policy_type end response = Excon::Response.new response.status = 200 response.body = { 'DescribeTerminationPolicyTypesResult' => results, 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/describe_scaling_process_types.rb0000644000004100000410000000320212261242551027627 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/describe_scaling_process_types' # Returns scaling process types for use in the resume_processes and # suspend_processes actions. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeScalingProcessTypesResult'<~Hash>: # * 'Processes'<~Array>: # * processtype<~Hash>: # * 'ProcessName'<~String> - The name of a process. # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DescribeScalingProcessTypes.html # def describe_scaling_process_types() request({ 'Action' => 'DescribeScalingProcessTypes', :idempotent => true, :parser => Fog::Parsers::AWS::AutoScaling::DescribeScalingProcessTypes.new }) end end class Mock def describe_scaling_process_types() results = { 'Processes' => [] } self.data[:process_types].each do |process_type| results['Processes'] << { 'ProcessName' => process_type } end response = Excon::Response.new response.status = 200 response.body = { 'DescribeScalingProcessTypesResult' => results, 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/describe_auto_scaling_instances.rb0000644000004100000410000001007712261242551027754 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/describe_auto_scaling_instances' # Returns a description of each Auto Scaling instance in the # instance_ids list. If a list is not provided, the service returns the # full details of all instances. # # This action supports pagination by returning a token if there are # more pages to retrieve. To get the next page, call this action again # with the returned token as the NextToken parameter. # # ==== Parameters # * options<~Hash>: # * 'InstanceIds'<~Array> - The list of Auto Scaling instances to # describe. If this list is omitted, all auto scaling instances are # described. The list of requested instances cannot contain more # than 50 items. If unknown instances are requested, they are # ignored with no error. # * 'MaxRecords'<~Integer> - The aximum number of Auto Scaling # instances to be described with each call. # * 'NextToken'<~String> - The token returned by a previous call to # indicate that there is more data available. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeAutoScalingInstancesResponse'<~Hash>: # * 'AutoScalingInstances'<~Array>: # * autoscalinginstancedetails<~Hash>: # * 'AutoScalingGroupName'<~String> - The name of the Auto # Scaling Group associated with this instance. # * 'AvailabilityZone'<~String> - The availability zone in # which this instance resides. # * 'HealthStatus'<~String> - The health status of this # instance. "Healthy" means that the instance is healthy # and should remain in service. "Unhealthy" means that the # instance is unhealthy. Auto Scaling should terminate and # replace it. # * 'InstanceId'<~String> - The instance's EC2 instance ID. # * 'LaunchConfigurationName'<~String> - The launch # configuration associated with this instance. # * 'LifecycleState'<~String> - The life cycle state of this # instance. # * 'NextToken'<~String> - Acts as a paging mechanism for large # result sets. Set to a non-empty string if there are # additional results waiting to be returned. Pass this in to # subsequent calls to return additional results. # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DescribeAutoScalingInstances.html # def describe_auto_scaling_instances(options = {}) if instance_ids = options.delete('InstanceIds') options.merge!(AWS.indexed_param('InstanceIds.member.%d', [*instance_ids])) end request({ 'Action' => 'DescribeAutoScalingInstances', :parser => Fog::Parsers::AWS::AutoScaling::DescribeAutoScalingInstances.new }.merge!(options)) end end class Mock def describe_auto_scaling_instances(options = {}) results = { 'AutoScalingInstances' => [] } self.data[:auto_scaling_groups].each do |asg_name, asg_data| asg_data['Instances'].each do |instance| results['AutoScalingInstances'] << { 'AutoScalingGroupName' => asg_name }.merge!(instance) end end response = Excon::Response.new response.status = 200 response.body = { 'DescribeAutoScalingInstancesResult' => results, 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/describe_tags.rb0000644000004100000410000000550312261242551024171 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/describe_tags' # Lists the Auto Scaling group tags. # # ==== Parameters # * options<~Hash>: # * tag<~Hash>: # * Key<~String> - The key of the tag. # * PropagateAtLaunch<~Boolean> - Specifies whether the new tag # will be applied to instances launched after the tag is created. # The same behavior applies to updates: If you change a tag, # changed tag will be applied to all instances launched after you # made the change. # * ResourceId<~String> - The name of the Auto Scaling group. # * ResourceType<~String> - The kind of resource to which the tag # is applied. Currently, Auto Scaling supports the # auto-scaling-group resource type. # * Value<~String> - The value of the tag. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeTagsResult'<~Hash>: # * 'NextToken'<~String> - A string used to mark the start of the # next batch of returned results. # * 'Tags'<~Hash>: # * tagDescription<~Hash>: # * 'Key'<~String> - The key of the tag. # * 'PropagateAtLaunch'<~Boolean> - Specifies whether the new # tag will be applied to instances launched after the tag # is created. The same behavior applies to updates: If you # change a tag, the changed tag will be applied to all # instances launched after you made the change. # * 'ResourceId'<~String> - The name of the Auto Scaling # group. # * 'ResourceType'<~String> - The kind of resource to which # the tag is applied. Currently, Auto Scaling supports the # auto-scaling-group resource type. # * 'Value'<~String> - The value of the tag. # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DescribeTags.html # def describe_tags(options={}) if filters = options.delete('Filters') options.merge!(Fog::AWS.indexed_filters(filters)) end request({ 'Action' => 'DescribeTags', :parser => Fog::Parsers::AWS::AutoScaling::DescribeTags.new }.merge!(options)) end end class Mock def describe_tags(options={}) raise Fog::Mock::NotImplementedError end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/describe_scheduled_actions.rb0000644000004100000410000001001212261242551026702 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/describe_scheduled_actions' # List all the actions scheduled for your Auto Scaling group that # haven't been executed. To see a list of action already executed, see # the activity record returned in describe_scaling_activities. # # ==== Parameters # * options<~Hash>: # * 'AutoScalingGroupName'<~String> - The name of the Auto Scaling # group. # * 'EndTime'<~Time> - The latest scheduled start time to return. If # scheduled action names are provided, this field will be ignored. # * 'MaxRecords'<~Integer> - The maximum number of scheduled actions # to return. # * 'NextToken'<~String> - The token returned by a previous call to # indicate that there is more data available. # * 'ScheduledActionNames'<~Array> - A list of scheduled actions to # be described. If this list is omitted, all scheduled actions are # described. The list of requested scheduled actions cannot contain # more than 50 items. If an auto scaling group name is provided, # the results are limited to that group. If unknown scheduled # actions are requested, they are ignored with no error. # * 'StartTime'<~Time> - The earliest scheduled start time to return. # If scheduled action names are provided, this field will be # ignored. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeScheduledActionsResponse'<~Hash>: # * 'ScheduledUpdateGroupActions'<~Array>: # * scheduledupdatesroupAction<~Hash>: # * 'AutoScalingGroupName'<~String> - The name of the Auto # Scaling group to be updated. # * 'DesiredCapacity'<~Integer> -The number of instances you # prefer to maintain in your Auto Scaling group. # * 'EndTime'<~Time> - The time for this action to end. # * 'MaxSize'<~Integer> - The maximum size of the Auto Scaling # group. # * 'MinSize'<~Integer> - The minimum size of the Auto Scaling # group. # * 'Recurrence'<~String> - The time when recurring future # actions will start. Start time is specified by the user # following the Unix cron syntax format. # * 'ScheduledActionARN'<~String> - The Amazon Resource Name # (ARN) of this scheduled action. # * 'StartTime'<~Time> - The time for this action to start. # * 'Time'<~Time> - The time that the action is scheduled to # occur. This value can be up to one month in the future. # * 'NextToken'<~String> - Acts as a paging mechanism for large # result sets. Set to a non-empty string if there are # additional results waiting to be returned. Pass this in to # subsequent calls to return additional results. # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DescribeScheduledActions.html # def describe_scheduled_actions(options = {}) if scheduled_action_names = options.delete('ScheduledActionNames') options.merge!(AWS.indexed_param('ScheduledActionNames.member.%d', [*scheduled_action_names])) end request({ 'Action' => 'DescribeScheduledActions', :parser => Fog::Parsers::AWS::AutoScaling::DescribeScheduledActions.new }.merge!(options)) end end class Mock def describe_scheduled_actions(options = {}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/describe_adjustment_types.rb0000644000004100000410000000310712261242551026633 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/describe_adjustment_types' # Returns policy adjustment types for use in the put_scaling_policy # action. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeAdjustmentTypesResponse'<~Hash>: # * 'AdjustmentTypes'<~Array>: # * 'AdjustmentType'<~String> - A policy adjustment type. # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DescribeAdjustmentTypes.html # def describe_adjustment_types() request({ 'Action' => 'DescribeAdjustmentTypes', :idempotent => true, :parser => Fog::Parsers::AWS::AutoScaling::DescribeAdjustmentTypes.new }) end end class Mock def describe_adjustment_types() results = { 'AdjustmentTypes' => [] } self.data[:adjustment_types].each do |adjustment_type| results['AdjustmentTypes'] << { 'AdjustmentType' => adjustment_type } end response = Excon::Response.new response.status = 200 response.body = { 'DescribeAdjustmentTypesResult' => results, 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/describe_scaling_activities.rb0000644000004100000410000000745112261242551027103 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/describe_scaling_activities' # Returns the scaling activities for the specified Auto Scaling group. # # If the specified activity_ids list is empty, all the activities from # the past six weeks are returned. Activities are sorted by completion # time. Activities still in progress appear first on the list. # # This action supports pagination. If the response includes a token, # there are more records available. To get the additional records, # repeat the request with the response token as the NextToken # parameter. # # ==== Parameters # * options<~Hash>: # * 'ActivityIds'<~Array> - A list containing the activity IDs of the # desired scaling activities. If this list is omitted, all # activities are described. If an AutoScalingGroupName is provided, # the results are limited to that group. The list of requested # activities cannot contain more than 50 items. If unknown # activities are requested, they are ignored with no error. # * 'AutoScalingGroupName'<~String> - The name of the Auto Scaling # group. # * 'MaxRecords'<~Integer> - The maximum number of scaling activities # to return. # * 'NextToken'<~String> - The token returned by a previous call to # indicate that there is more data available. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeScalingActivitiesResponse'<~Hash>: # * 'Activities'<~Array>: # * 'ActivityId'<~String> - Specifies the ID of the activity. # * 'AutoScalingGroupName'<~String> - The name of the Auto # Scaling group. # * 'Cause'<~String> - Contins the reason the activity was # begun. # * 'Description'<~String> - Contains a friendly, more verbose # description of the scaling activity. # * 'EndTime'<~Time> - Provides the end time of this activity. # * 'Progress'<~Integer> - Specifies a value between 0 and 100 # that indicates the progress of the activity. # * 'StartTime'<~Time> - Provides the start time of this # activity. # * 'StatusCode'<~String> - Contains the current status of the # activity. # * 'StatusMessage'<~String> - Contains a friendly, more # verbose description of the activity status. # * 'NextToken'<~String> - Acts as a paging mechanism for large # result sets. Set to a non-empty string if there are # additional results waiting to be returned. Pass this in to # subsequent calls to return additional results. # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DescribeScalingActivities.html # def describe_scaling_activities(options = {}) if activity_ids = options.delete('ActivityIds') options.merge!(AWS.indexed_param('ActivityIds.member.%d', [*activity_ids])) end request({ 'Action' => 'DescribeScalingActivities', :parser => Fog::Parsers::AWS::AutoScaling::DescribeScalingActivities.new }.merge!(options)) end end class Mock def describe_scaling_activities(options = {}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/describe_auto_scaling_groups.rb0000644000004100000410000001503512261242551027303 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/describe_auto_scaling_groups' # Returns a full description of each Auto Scaling group in the given # list. This includes all Amazon EC2 instances that are members of the # group. If a list of names is not provided, the service returns the # full details of all Auto Scaling groups. # # This action supports pagination by returning a token if there are # more pages to retrieve. To get the next page, call this action again # with the returned token as the NextToken parameter. # # ==== Parameters # * options<~Hash>: # * 'AutoScalingGroupNames'<~Array> - A list of Auto Scaling group # names. # * 'MaxRecords'<~Integer> - The maximum number of records to return. # * 'NextToken'<~String> - A string that marks the start of the next # batch of returned results. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeAutoScalingGroupsResponse'<~Hash>: # * 'AutoScalingGroups'<~Array>: # * 'AutoScalingGroup'<~Hash>: # * 'AutoScalingGroupARN'<~String> - The Amazon Resource Name # (ARN) of the Auto Scaling group. # * 'AutoScalingGroupName'<~String> - Specifies the name of # the group. # * 'AvailabilityZones'<~Array> - Contains a list of # availability zones for the group. # * 'CreatedTime'<~Time> - Specifies the date and time the # Auto Scaling group was created. # * 'DefaultCooldown'<~Integer> - The number of seconds after # a scaling activity completes before any further scaling # activities can start. # * 'DesiredCapacity'<~Integer> - Specifies the desired # capacity of the Auto Scaling group. # * 'EnabledMetrics'<~Array>: # * enabledmetric<~Hash>: # * 'Granularity'<~String> - The granularity of the # enabled metric. # * 'Metrics'<~String> - The name of the enabled metric. # * 'HealthCheckGracePeriod'<~Integer>: The length of time # that Auto Scaling waits before checking an instance's # health status. The grace period begins when an instance # comes into service. # * 'HealthCheckType'<~String>: The service of interest for # the health status check, either "EC2" for Amazon EC2 or # "ELB" for Elastic Load Balancing. # * 'Instances'<~Array>: # * instance<~Hash>: # * 'AvailabilityZone'<~String>: Availability zone # associated with this instance. # * 'HealthStatus'<~String>: The instance's health # status. # * 'InstanceId'<~String>: Specifies the EC2 instance ID. # * 'LaunchConfigurationName'<~String>: The launch # configuration associated with this instance. # * 'LifecycleState'<~String>: Contains a description of # the current lifecycle state. # * 'LaunchConfigurationName'<~String> - Specifies the name # of the associated launch configuration. # * 'LoadBalancerNames'<~Array> - A list of load balancers # associated with this Auto Scaling group. # * 'MaxSize'<~Integer> - The maximum size of the Auto # Scaling group. # * 'MinSize'<~Integer> - The minimum size of the Auto # Scaling group. # * 'PlacementGroup'<~String> - The name of the cluster # placement group, if applicable. # * 'SuspendedProcesses'<~Array>: # * suspendedprocess'<~Hash>: # * 'ProcessName'<~String> - The name of the suspended # process. # * 'SuspensionReason'<~String> - The reason that the # process was suspended. # * 'TerminationPolicies'<~Array> - A standalone termination # policy or a list of termination policies for this Auto # Scaling group. # * 'VPCZoneIdentifier'<~String> - The subnet identifier for # the Amazon VPC connection, if applicable. You can specify # several subnets in a comma-separated list. # * 'NextToken'<~String> - A string that marks the start of the # next batch of returned results. # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_DescribeAutoScalingGroups.html # def describe_auto_scaling_groups(options = {}) if auto_scaling_group_names = options.delete('AutoScalingGroupNames') options.merge!(AWS.indexed_param('AutoScalingGroupNames.member.%d', [*auto_scaling_group_names])) end request({ 'Action' => 'DescribeAutoScalingGroups', :parser => Fog::Parsers::AWS::AutoScaling::DescribeAutoScalingGroups.new }.merge!(options)) end end class Mock def describe_auto_scaling_groups(options = {}) results = { 'AutoScalingGroups' => [] } asg_set = self.data[:auto_scaling_groups] if !options["AutoScalingGroupNames"].nil? asg_set = asg_set.reject do |asg_name, asg_data| ![*options["AutoScalingGroupNames"]].include?(asg_name) end end asg_set.each do |asg_name, asg_data| results['AutoScalingGroups'] << { 'AutoScalingGroupName' => asg_name }.merge!(asg_data) end response = Excon::Response.new response.status = 200 response.body = { 'DescribeAutoScalingGroupsResult' => results, 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/auto_scaling/put_scaling_policy.rb0000644000004100000410000000726312261242551025267 0ustar www-datawww-datamodule Fog module AWS class AutoScaling class Real require 'fog/aws/parsers/auto_scaling/put_scaling_policy' # Creates or updates a policy for an Auto Scaling group. To update an # existing policy, use the existing policy name and set the # parameter(s) you want to change. Any existing parameter not changed # in an update to an existing policy is not changed in this update # request. # # ==== Parameters # * adjustment_type<~String> - Specifies whether the scaling_adjustment # is an absolute number or a percentage of the current capacity. # * auto_scaling_group_name<~String> - The name or ARN of the Auto # Scaling group. # * policy_name<~String> - The name of the policy you want to create or # update. # * scaling_adjustment<~Integer> - The number of instances by which to # scale. AdjustmentType determines the interpretation of this number # (e.g., as an absolute number or as a percentage of the existing # Auto Scaling group size). A positive increment adds to the current # capacity and a negative value removes from the current capacity. # * options<~Hash>: # * 'CoolDown'<~Integer> - The amount of time, in seconds, after a # scaling activity completes before any further trigger-related # scaling activities can start # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'PutScalingPolicyResult'<~Hash>: # * 'PolicyARN'<~String> - A policy's Amazon Resource Name (ARN). # # ==== See Also # http://docs.amazonwebservices.com/AutoScaling/latest/APIReference/API_PutScalingPolicy.html # def put_scaling_policy(adjustment_type, auto_scaling_group_name, policy_name, scaling_adjustment, options = {}) request({ 'Action' => 'PutScalingPolicy', 'AdjustmentType' => adjustment_type, 'AutoScalingGroupName' => auto_scaling_group_name, 'PolicyName' => policy_name, 'ScalingAdjustment' => scaling_adjustment, :parser => Fog::Parsers::AWS::AutoScaling::PutScalingPolicy.new }.merge!(options)) end end class Mock def put_scaling_policy(adjustment_type, auto_scaling_group_name, policy_name, scaling_adjustment, options = {}) unless self.data[:auto_scaling_groups].has_key?(auto_scaling_group_name) raise Fog::AWS::AutoScaling::ValidationError.new('Auto Scaling Group name not found - null') end self.data[:scaling_policies][policy_name] = { 'AdjustmentType' => adjustment_type, 'Alarms' => [], 'AutoScalingGroupName' => auto_scaling_group_name, 'Cooldown' => 0, 'MinAdjustmentStep' => 0, 'PolicyARN' => Fog::AWS::Mock.arn('autoscaling', self.data[:owner_id], "scalingPolicy:00000000-0000-0000-0000-000000000000:autoScalingGroupName/#{auto_scaling_group_name}:policyName/#{policy_name}", self.region), 'PolicyName' => policy_name, 'ScalingAdjustment' => scaling_adjustment }.merge!(options) response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/redshift/0000755000004100000410000000000012261242551020203 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/redshift/describe_reserved_node_offerings.rb0000644000004100000410000000360612261242551027263 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/describe_reserved_node_offerings' # ==== Parameters # # @param [Hash] options # * :reserved_node_offering_id - (String) # The unique identifier for the offering. # * :max_records - (Integer) # The maximum number of records to include in the response. If more than the # MaxRecords value is available, a marker is included in the response so that the # following results can be retrieved. Constrained between [20,100]. Default is 100. # * :marker - (String) # The marker returned from a previous request. If this parameter is specified, the # response includes records beyond the marker only, up to MaxRecords. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeReservedNodeOfferings.html def describe_reserved_node_offerings(options = {}) reserved_node_offering_id = options[:reserved_node_offering_id] marker = options[:marker] max_records = options[:max_records] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :get, :query => {}, :parser => Fog::Parsers::Redshift::AWS::DescribeReservedNodeOfferings.new } params[:query]['Action'] = 'DescribeReservedNodeOfferings' params[:query]['ReservedNodeOfferingId'] = reserved_node_offering_id if reserved_node_offering_id params[:query]['Marker'] = marker if marker params[:query]['MaxRecords'] = max_records if max_records request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/describe_cluster_security_groups.rb0000644000004100000410000000416112261242551027401 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/describe_cluster_security_groups' # ==== Parameters # # @param [Hash] options # * :cluster_security_group_name - (String) # The name of a cluster security group for which you are requesting details. You # can specify either the Marker parameter or a ClusterSecurityGroupName parameter, # but not both. Example: securitygroup1 # * :max_records - (Integer) # The maximum number of records to include in the response. If more than the # MaxRecords value is available, a marker is included in the response so that the # following results can be retrieved. Constrained between [20,100]. Default is 100. # * :marker - (String) # The marker returned from a previous request. If this parameter is specified, the # response includes records beyond the marker only, up to MaxRecords. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeClusterSecurityGroups.html def describe_cluster_security_groups(options = {}) cluster_security_group_name = options[:cluster_security_group_name] marker = options[:marker] max_records = options[:max_records] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :get, :query => {}, :parser => Fog::Parsers::Redshift::AWS::DescribeClusterSecurityGroups.new } params[:query]['Action'] = 'DescribeClusterSecurityGroups' params[:query]['ClusterSecurityGroupName'] = cluster_security_group_name if cluster_security_group_name params[:query]['Marker'] = marker if marker params[:query]['MaxRecords'] = max_records if max_records request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/create_cluster_security_group.rb0000644000004100000410000000302112261242551026673 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/create_cluster_security_group' # ==== Parameters # # @param [Hash] options # * :cluster_security_group_name - (String) # The name of a cluster security group for which you are requesting details. You # can specify either the Marker parameter or a ClusterSecurityGroupName parameter, # but not both. Example: securitygroup1 # * :description - required - (String) # A description for the security group. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_CreateClusterSecurityGroup.html def create_cluster_security_group(options = {}) cluster_security_group_name = options[:cluster_security_group_name] description = options[:description] path = "/" params = { :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::CreateClusterSecurityGroup.new } params[:query]['Action'] = 'CreateClusterSecurityGroup' params[:query]['ClusterSecurityGroupName'] = cluster_security_group_name if cluster_security_group_name params[:query]['Description'] = description if description request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/describe_cluster_versions.rb0000644000004100000410000000463612261242551026012 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/describe_cluster_versions' # ==== Parameters # # @param [Hash] options # * :cluster_parameter_group_family - (String) # The name of a specific cluster parameter group family to return details for. # Constraints: Must be 1 to 255 alphanumeric characters. First character must be # a letter, and cannot end with a hyphen or contain two consecutive hyphens. # * :cluster_version - (String) # The specific cluster version to return. Example: 1.0 # * :max_records - (Integer) # The maximum number of records to include in the response. If more than the # MaxRecords value is available, a marker is included in the response so that the # following results can be retrieved. Constrained between [20,100]. Default is 100. # * :marker - (String) # The marker returned from a previous request. If this parameter is specified, the # response includes records beyond the marker only, up to MaxRecords. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeClusterVersions.html def describe_cluster_versions(options = {}) cluster_version = options[:cluster_version] cluster_parameter_group_family = options[:cluster_parameter_group_family] marker = options[:marker] max_records = options[:max_records] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :get, :query => {}, :parser => Fog::Parsers::Redshift::AWS::DescribeClusterVersions.new } params[:query]['Action'] = 'DescribeClusterVersions' params[:query]['ClusterVersion'] = cluster_version if cluster_version params[:query]['ClusterParameterGroupFamily'] = cluster_parameter_group_family if cluster_parameter_group_family params[:query]['Marker'] = marker if marker params[:query]['MaxRecords'] = max_records if max_records request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/modify_cluster.rb0000644000004100000410000001544612261242551023572 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/cluster' # ==== Parameters # # @param [Hash] options # * :cluster_identifier - required - (String) # A unique identifier for the cluster. You use this identifier to refer to the cluster # for any subsequent cluster operations such as deleting or modifying. Must be unique # for all clusters within an AWS account. Example: myexamplecluster # * :allow_version_upgrade - (Boolean) # If `true` , upgrades can be applied during the maintenance window to the Amazon # Redshift engine that is running on the cluster. Default: `true` # * :automated_snapshot_retention_period - (Integer) # Number of days that automated snapshots are retained. If the value is 0, automated # snapshots are disabled. Default: 1 Constraints: Must be a value from 0 to 35. # * :cluster_parameter_group_name - (String) # The name of the parameter group to be associated with this cluster. Default: The # default Amazon Redshift cluster parameter group. Constraints: Must be 1 to 255 # alphanumeric characters or hyphens. First character must be a letter. Cannot end # with a hyphen or contain two consecutive hyphens. # * :cluster_security_groups - (Array) # A list of security groups to be associated with this cluster. Default: The default # cluster security group for Amazon Redshift. # * :cluster_type - (String) # Type of the cluster. When cluster type is specified as single-node, the NumberOfNodes # parameter is not required. multi-node, the NumberOfNodes parameter is required. Valid # Values: multi-node | single-node Default: multi-node # * :cluster_version - (String) # The version of the Amazon Redshift engine software that you want to deploy on the # cluster. The version selected runs on all the nodes in the cluster. Constraints: # Only version 1.0 is currently available. Example: 1.0 # * :master_user_password - required - (String) # The password associated with the master user account for the cluster that is being # created. Constraints: Must be between 8 and 64 characters in length. Must contain at # least one uppercase letter. Must contain at least one lowercase letter. Must contain # one number. # * :node_type - required - (String) # The node type to be provisioned. Valid Values: dw.hs1.xlarge | dw.hs1.8xlarge. # * :number_of_nodes - (Integer) # The number of compute nodes in the cluster. This parameter is required when the # ClusterType parameter is specified as multi-node. If you don't specify this parameter, # you get a single-node cluster. When requesting a multi-node cluster, you must specify # the number of nodes that you want in the cluster. Default: 1 Constraints: Value must # be at least 1 and no more than 100. # * :preferred_maintenance_window - (String) # The weekly time range (in UTC) during which automated cluster maintenance can occur. # Format: ddd:hh24:mi-ddd:hh24:mi Default: A 30-minute window selected at random from # an 8-hour block of time per region, occurring on a random day of the week. # Constraints: Minimum 30-minute window. # * :vpc_security_group_ids - (Array) # A list of Virtual Private Cloud (VPC) security groups to be associated with the # cluster. Default: The default VPC security group is associated with the cluster. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_CreateCluster.html def modify_cluster(options = {}) cluster_identifier = options[:cluster_identifier] cluster_type = options[:cluster_type] node_type = options[:node_type] master_user_password = options[:master_user_password] preferred_maintenance_window = options[:preferred_maintenance_window] cluster_parameter_group_name = options[:cluster_parameter_group_name] automated_snapshot_retention_period = options[:automated_snapshot_retention_period] cluster_version = options[:cluster_version] allow_version_upgrade = options[:allow_version_upgrade] number_of_nodes = options[:number_of_nodes] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::Cluster.new } if cluster_security_groups = options.delete(:ClusterSecurityGroups) params[:query].merge!(Fog::AWS.indexed_param('ClusterSecurityGroups.member.%d', [*cluster_security_groups])) end if vpc_security_group_ids = options.delete(:VpcSecurityGroupIds) params[:query].merge!(Fog::AWS.indexed_param('VpcSecurityGroupIds.member.%d', [*vpc_security_group_ids])) end params[:query]['Action'] = 'ModifyCluster' params[:query]['ClusterIdentifier'] = cluster_identifier if cluster_identifier params[:query]['ClusterParameterGroupName'] = cluster_parameter_group_name if cluster_parameter_group_name params[:query]['ClusterType'] = cluster_type if cluster_type params[:query]['NodeType'] = node_type if node_type params[:query]['MasterUserPassword'] = master_user_password if master_user_password params[:query]['PreferredMaintenanceWindow'] = preferred_maintenance_window if preferred_maintenance_window params[:query]['AutomatedSnapshotRetentionPeriod'] = automated_snapshot_retention_period if automated_snapshot_retention_period params[:query]['ClusterVersion'] = cluster_version if cluster_version params[:query]['AllowVersionUpgrade'] = allow_version_upgrade if allow_version_upgrade params[:query]['NumberOfNodes'] = number_of_nodes if number_of_nodes params[:query]['ClusterSecurityGroups'] = cluster_security_groups if cluster_security_groups params[:query]['VpcSecurityGroupIds'] = vpc_security_group_ids if vpc_security_group_ids request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/modify_cluster_parameter_group.rb0000644000004100000410000000275612261242551027046 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/update_cluster_parameter_group_parser' # ==== Parameters # # @param [Hash] options # * :parameter_group_name - required - (String) # The name of the parameter group to be deleted. Constraints: Must be the name of an # existing cluster parameter group. Cannot delete a default cluster parameter group. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_ModifyClusterParameterGroup.html def modify_cluster_parameter_group(options = {}) parameter_group_name = options[:parameter_group_name] path = "/" params = { :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::UpdateClusterParameterGroupParser.new } params[:query]['Action'] = 'ModifyClusterParameterGroup' params[:query]['ParameterGroupName'] = parameter_group_name if parameter_group_name if options['Parameters'] options['Parameters'].keys.each_with_index do |name, index| params[:query].merge!({ "Parameters.member.#{index+1}.#{name}" => options['Parameters'][name] }) end end request(params) end end end end end fog-1.19.0/lib/fog/aws/requests/redshift/describe_cluster_subnet_groups.rb0000644000004100000410000000355712261242551027042 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/describe_cluster_subnet_groups' # ==== Parameters # # @param [Hash] options # * :cluster_subnet_group_name - (String) # The name of the cluster subnet group for which information is requested. # * :max_records - (Integer) # The maximum number of records to include in the response. If more than the # MaxRecords value is available, a marker is included in the response so that the # following results can be retrieved. Constrained between [20,100]. Default is 100. # * :marker - (String) # The marker returned from a previous request. If this parameter is specified, the # response includes records beyond the marker only, up to MaxRecords. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeClusterSubnetGroups.html def describe_cluster_subnet_groups(cluster_subnet_group_name=nil, marker=nil,max_records=nil) path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :get, :query => {}, :parser => Fog::Parsers::Redshift::AWS::DescribeClusterSubnetGroups.new } params[:query]['Action'] = 'DescribeClusterSubnetGroups' params[:query]['ClusterSubnetGroupName'] = cluster_subnet_group_name if cluster_subnet_group_name params[:query]['Marker'] = marker if marker params[:query]['MaxRecords'] = max_records if max_records request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/create_cluster_snapshot.rb0000644000004100000410000000322312261242551025453 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/cluster_snapshot' # ==== Parameters # # @param [Hash] options # * :snapshot_identifier - required - (String) # A unique identifier for the snapshot that you are requesting. This identifier # must be unique for all snapshots within the AWS account. Constraints: Cannot be # null, empty, or blank Must contain from 1 to 255 alphanumeric characters or # hyphens First character must be a letter Cannot end with a hyphen or contain two # consecutive hyphens Example: my-snapshot-id # * :cluster_identifier - required - (String) # The cluster identifier for which you want a snapshot. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_CreateClusterSnapshot.html def create_cluster_snapshot(options = {}) snapshot_identifier = options[:snapshot_identifier] cluster_identifier = options[:cluster_identifier] path = "/" params = { :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::ClusterSnapshot.new } params[:query]['Action'] = 'CreateClusterSnapshot' params[:query]['SnapshotIdentifier'] = snapshot_identifier if snapshot_identifier params[:query]['ClusterIdentifier'] = cluster_identifier if cluster_identifier request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/authorize_cluster_security_group_ingress.rb0000644000004100000410000000512212261242551031200 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/revoke_cluster_security_group_ingress' # ==== Parameters # # @param [Hash] options # * :cluster_security_group_name - required - (String) # The name of the security Group from which to revoke the ingress rule. # * :cidrip - (String) # The IP range for which to revoke access. This range must be a valid Classless # Inter-Domain Routing (CIDR) block of IP addresses. If CIDRIP is specified, # EC2SecurityGroupName and EC2SecurityGroupOwnerId cannot be provided. # * :ec2_security_group_name - (String) # The name of the EC2 Security Group whose access is to be revoked. If # EC2SecurityGroupName is specified, EC2SecurityGroupOwnerId must also be # provided and CIDRIP cannot be provided. # * :ec2_security_group_owner_id - (String) # The AWS account number of the owner of the security group specified in the # EC2SecurityGroupName parameter. The AWS access key ID is not an acceptable # value. If EC2SecurityGroupOwnerId is specified, EC2SecurityGroupName must # also be provided. and CIDRIP cannot be provided. Example: 111122223333 # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_AuthorizeClusterSecurityGroupIngress.html def authorize_cluster_security_group_ingress(options = {}) cluster_security_group_name = options[:cluster_security_group_name] cidrip = options[:cidrip] ec2_security_group_name = options[:ec2_security_group_name] ec2_security_group_owner_id = options[:ec2_security_group_owner_id] path = "/" params = { :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::RevokeClusterSecurityGroupIngress.new } params[:query]['Action'] = 'AuthorizeClusterSecurityGroupIngress' params[:query]['ClusterSecurityGroupName'] = cluster_security_group_name if cluster_security_group_name params[:query]['CIDRIP'] = cidrip if cidrip params[:query]['EC2SecurityGroupName'] = ec2_security_group_name if ec2_security_group_name params[:query]['EC2SecurityGroupOwnerId'] = ec2_security_group_owner_id if ec2_security_group_owner_id request(params) end end end end end fog-1.19.0/lib/fog/aws/requests/redshift/delete_cluster_security_group.rb0000644000004100000410000000174012261242551026700 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real # ==== Parameters # # @param [Hash] options # * :cluster_security_group_name - required - (String) # The name of the cluster security group to be deleted. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DeleteClusterSecurityGroup.html def delete_cluster_security_group(options = {}) cluster_security_group_name = options[:cluster_security_group_name] path = "/" params = { :headers => {}, :path => path, :method => :put, :query => {} } params[:query]['Action'] = 'DeleteClusterSecurityGroup' params[:query]['ClusterSecurityGroupName'] = cluster_security_group_name if cluster_security_group_name request(params) end end end end end fog-1.19.0/lib/fog/aws/requests/redshift/revoke_cluster_security_group_ingress.rb0000644000004100000410000000500612261242551030462 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/revoke_cluster_security_group_ingress' # ==== Parameters # # @param [Hash] options # * :cluster_security_group_name - required - (String) # The name of the security Group from which to revoke the ingress rule. # * :cidrip - (String) # The IP range for which to revoke access. This range must be a valid Classless # Inter-Domain Routing (CIDR) block of IP addresses. If CIDRIP is specified, # EC2SecurityGroupName and EC2SecurityGroupOwnerId cannot be provided. # * :ec2_security_group_name - (String) # The name of the EC2 Security Group whose access is to be revoked. If # EC2SecurityGroupName is specified, EC2SecurityGroupOwnerId must also be # provided and CIDRIP cannot be provided. # * :ec2_security_group_owner_id - (String) # The AWS account number of the owner of the security group specified in the # EC2SecurityGroupName parameter. The AWS access key ID is not an acceptable # value. If EC2SecurityGroupOwnerId is specified, EC2SecurityGroupName must # also be provided. and CIDRIP cannot be provided. Example: 111122223333 # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_RevokeClusterSecurityGroupIngress.html def revoke_cluster_security_group_ingress(options = {}) cluster_security_group_name = options[:cluster_security_group_name] cidrip = options[:cidrip] ec2_security_group_name = options[:ec2_security_group_name] ec2_security_group_owner_id = options[:ec2_security_group_owner_id] path = "/" params = { :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::RevokeClusterSecurityGroupIngress.new } params[:query]['Action'] = 'RevokeClusterSecurityGroupIngress' params[:query]['ClusterSecurityGroupName'] = cluster_security_group_name if cluster_security_group_name params[:query]['CIDRIP'] = cidrip if cidrip params[:query]['EC2SecurityGroupName'] = ec2_security_group_name if ec2_security_group_name params[:query]['EC2SecurityGroupOwnerId'] = ec2_security_group_owner_id if ec2_security_group_owner_id request(params) end end end end end fog-1.19.0/lib/fog/aws/requests/redshift/describe_events.rb0000644000004100000410000001030712261242551023675 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/describe_events' # ==== Parameters # # @param [Hash] options # * :source_identifier - (String) # The identifier of the event source for which events will be returned. If this # parameter is not specified, then all sources are included in the response. # Constraints: If SourceIdentifier is supplied, SourceType must also be provided. # Specify a cluster identifier when SourceType is cluster. Specify a cluster security # group name when SourceType is cluster-security-group. Specify a cluster parameter # group name when SourceType is cluster-parameter-group. Specify a cluster snapshot # identifier when SourceType is cluster-snapshot. # * :source_type - (String) # The event source to retrieve events for. If no value is specified, all events are # returned. Constraints: If SourceType is supplied, SourceIdentifier must also be # provided. Specify cluster when SourceIdentifier is a cluster identifier. Specify # cluster-security-group when SourceIdentifier is a cluster security group name. Specify # cluster-parameter-group when SourceIdentifier is a cluster parameter group name. Specify # cluster-snapshot when SourceIdentifier is a cluster snapshot identifier. Valid values # include: cluster, cluster-parameter-group, cluster-security-group, cluster-snapshot # * :start_time - (String<) # The beginning of the time interval to retrieve events for, specified in ISO 8601 # format. Example: 2009-07-08T18:00Z # * :end_time - (String<) # The end of the time interval for which to retrieve events, specified in ISO 8601 # format. Example: 2009-07-08T18:00Z # * :duration - (Integer) # The number of minutes prior to the time of the request for which to retrieve events. # For example, if the request is sent at 18:00 and you specify a duration of 60, then # only events which have occurred after 17:00 will be returned. Default: 60 # * :max_records - (Integer) # The maximum number of records to include in the response. If more than the # MaxRecords value is available, a marker is included in the response so that the # following results can be retrieved. Constrained between [20,100]. Default is 100. # * :marker - (String) # The marker returned from a previous request. If this parameter is specified, the # response includes records beyond the marker only, up to MaxRecords. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeEvents.html def describe_events(options = {}) source_identifier = options[:source_identifier] source_type = options[:source_type] start_time = options[:start_time] end_time = options[:end_time] duration = options[:duration] marker = options[:marker] max_records = options[:max_records] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :get, :query => {}, :parser => Fog::Parsers::Redshift::AWS::DescribeEvents.new } params[:query]['Action'] = 'DescribeEvents' params[:query]['SourceIdentifier'] = source_identifier if source_identifier params[:query]['SourceType'] = source_type if source_type params[:query]['StartTime'] = start_time if start_time params[:query]['EndTime'] = end_time if end_time params[:query]['Duration'] = duration if duration params[:query]['Marker'] = marker if marker params[:query]['MaxRecords'] = max_records if max_records request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/delete_cluster_subnet_group.rb0000644000004100000410000000240012261242551026323 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real # ==== Parameters # # @param [Hash] options # * :cluster_subnet_group_name - required - (String) # The name for the subnet group. Amazon Redshift stores the value as a lowercase string. # Constraints: Must contain no more than 255 alphanumeric characters or hyphens. Must not # be "Default". Must be unique for all subnet groups that are created by your AWS account. # Example: examplesubnetgroup # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DeleteClusterSubnetGroup.html def delete_cluster_subnet_group(options = {}) cluster_subnet_group_name = options[:cluster_subnet_group_name] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :delete, :query => {} } params[:query]['Action'] = 'DeleteClusterSubnetGroup' params[:query]['ClusterSubnetGroupName'] = cluster_subnet_group_name if cluster_subnet_group_name request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/purchase_reserved_node_offering.rb0000644000004100000410000000262312261242551027130 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/purchase_reserved_node_offering' # ==== Parameters # # @param [Hash] options # * :reserved_node_offering_id - required - (String) # The unique identifier of the reserved node offering you want to purchase. # * :node_count - (Integer) # The number of reserved nodes you want to purchase. Default: 1 # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_PurchaseReservedNodeOffering.html def purchase_reserved_node_offering(options = {}) reserved_node_offering_id = options[:reserved_node_offering_id] node_count = options[:node_count] path = "/" params = { :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::PurchaseReservedNodeOffering.new } params[:query]['Action'] = 'PurchaseReservedNodeOffering' params[:query]['ReservedNodeOfferingId'] = reserved_node_offering_id if reserved_node_offering_id params[:query]['NodeCount'] = node_count if node_count request(params) end end end end end fog-1.19.0/lib/fog/aws/requests/redshift/create_cluster_subnet_group.rb0000644000004100000410000000371212261242551026333 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/cluster_subnet_group_parser' # ==== Parameters # # @param [Hash] options # * :cluster_subnet_group_name - required - (String) # The name for the subnet group. Amazon Redshift stores the value as a lowercase string. # Constraints: Must contain no more than 255 alphanumeric characters or hyphens. Must not # be "Default". Must be unique for all subnet groups that are created by your AWS account. # Example: examplesubnetgroup # * :description - required - (String) # A description of the parameter group. # * :subnet_ids - required - (Array<) # An array of VPC subnet IDs. A maximum of 20 subnets can be modified in a single request. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_CreateClusterSubnetGroup.html def create_cluster_subnet_group(options = {}) cluster_subnet_group_name = options[:cluster_subnet_group_name] description = options[:description] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::ClusterSubnetGroupParser.new } if subnet_ids = options.delete(:subnet_ids) params[:query].merge!(Fog::AWS.indexed_param('SubnetIds.member.%d', [*subnet_ids])) end params[:query]['Action'] = 'CreateClusterSubnetGroup' params[:query]['ClusterSubnetGroupName'] = cluster_subnet_group_name if cluster_subnet_group_name params[:query]['Description'] = description if description request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/describe_clusters.rb0000644000004100000410000000367612261242551024250 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/describe_clusters' # ==== Parameters # # @param [Hash] options # * :cluster_identifier - (String) # The unique identifier of a cluster whose properties you are requesting. # This parameter isn't case sensitive. The default is that all clusters # defined for an account are returned. # * :max_records - (Integer) # The maximum number of records to include in the response. If more than the # MaxRecords value is available, a marker is included in the response so that the # following results can be retrieved. Constrained between [20,100]. Default is 100. # * :marker - (String) # The marker returned from a previous request. If this parameter is specified, the # response includes records beyond the marker only, up to MaxRecords. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeClusters.html def describe_clusters(options = {}) cluster_identifier = options[:cluster_identifier] marker = options[:marker] max_records = options[:max_records] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :get, :query => {}, :parser => Fog::Parsers::Redshift::AWS::DescribeClusters.new } params[:query]['Action'] = 'DescribeClusters' params[:query]['ClusterIdentifier'] = cluster_identifier if cluster_identifier params[:query]['MaxRecords'] = max_records if max_records params[:query]['Marker'] = marker if marker request(params) end end end end end fog-1.19.0/lib/fog/aws/requests/redshift/delete_cluster_snapshot.rb0000644000004100000410000000333512261242551025456 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/cluster_snapshot' # ==== Parameters # # @param [Hash] options # * :snapshot_identifier - required - (String) # A unique identifier for the snapshot that you are requesting. This identifier # must be unique for all snapshots within the AWS account. Constraints: Cannot be # null, empty, or blank Must contain from 1 to 255 alphanumeric characters or # hyphens First character must be a letter Cannot end with a hyphen or contain two # consecutive hyphens Example: my-snapshot-id # * :snapshot_cluster_identifier - required - (String) # The cluster identifier for which you want a snapshot. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_CreateClusterSnapshot.html def delete_cluster_snapshot(options = {}) snapshot_identifier = options[:snapshot_identifier] snapshot_cluster_identifier = options[:snapshot_cluster_identifier] path = "/" params = { :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::ClusterSnapshot.new } params[:query]['Action'] = 'DeleteClusterSnapshot' params[:query]['SnapshotIdentifier'] = snapshot_identifier if snapshot_identifier params[:query]['SnapshotClusterIdentifier'] = snapshot_cluster_identifier if snapshot_cluster_identifier request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/describe_resize.rb0000644000004100000410000000232312261242551023671 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/describe_resize' # ==== Parameters # # @param [Hash] options # * :cluster_identifier - required - (String) # The unique identifier of a cluster whose resize progress you are requesting. # This parameter isn't case-sensitive. By default, resize operations for all # clusters defined for an AWS account are returned. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeResize.html def describe_resize(options = {}) cluster_identifier = options[:cluster_identifier] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :get, :query => {}, :parser => Fog::Parsers::Redshift::AWS::DescribeResize.new } params[:query]['Action'] = 'DescribeResize' params[:query]['ClusterIdentifier'] = cluster_identifier if cluster_identifier request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/delete_cluster_parameter_group.rb0000644000004100000410000000204612261242551027011 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real # ==== Parameters # # @param [Hash] options # * :parameter_group_name - required - (String) # The name of the parameter group to be deleted. Constraints: Must be the name of an # existing cluster parameter group. Cannot delete a default cluster parameter group. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DeleteClusterParameterGroup.html def delete_cluster_parameter_group(options = {}) parameter_group_name = options[:parameter_group_name] path = "/" params = { :headers => {}, :path => path, :method => :put, :query => {} } params[:query]['Action'] = 'DeleteClusterParameterGroup' params[:query]['ParameterGroupName'] = parameter_group_name if parameter_group_name request(params) end end end end end fog-1.19.0/lib/fog/aws/requests/redshift/revoke_snapshot_access.rb0000644000004100000410000000327212261242551025267 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/cluster_snapshot' # ==== Parameters # # @param [Hash] options # * :snapshot_identifier - required - (String) # The identifier of the snapshot that the account can no longer access. # * :snapshot_cluster_identifier - (String) # * :account_with_restore_access - required - (String) # The identifier of the AWS customer account that can no longer restore the specified snapshot. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_RevokeSnapshotAccess.html def revoke_snapshot_access(options = {}) snapshot_identifier = options[:snapshot_identifier] snapshot_cluster_identifier = options[:snapshot_cluster_identifier] account_with_restore_access = options[:account_with_restore_access] path = "/" params = { :expects => 200, :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::ClusterSnapshot.new } params[:query]['Action'] = 'RevokeSnapshotAccess' params[:query]['SnapshotIdentifier'] = snapshot_identifier if snapshot_identifier params[:query]['SnapshotClusterIdentifier'] = snapshot_cluster_identifier if snapshot_cluster_identifier params[:query]['AccountWithRestoreAccess'] = account_with_restore_access if account_with_restore_access request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/describe_orderable_cluster_options.rb0000644000004100000410000000447712261242551027657 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/describe_orderable_cluster_options' # ==== Parameters # # @param [Hash] options # * :cluster_version - (String) # The version filter value. Specify this parameter to show only the available # offerings matching the specified version. Default: All versions. Constraints: # Must be one of the version returned from DescribeClusterVersions. # * :node_type - (String) # The node type filter value. Specify this parameter to show only the available # offerings matching the specified node type. # * :max_records - (Integer) # The maximum number of records to include in the response. If more than the # MaxRecords value is available, a marker is included in the response so that the # following results can be retrieved. Constrained between [20,100]. Default is 100. # * :marker - (String) # The marker returned from a previous request. If this parameter is specified, the # response includes records beyond the marker only, up to MaxRecords. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeOrderableClusterOptions.html def describe_orderable_cluster_options(options = {}) cluster_version = options[:cluster_version] node_type = options[:node_type] marker = options[:marker] max_records = options[:max_records] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :get, :query => {}, :parser => Fog::Parsers::Redshift::AWS::DescribeOrderableClusterOptions.new } params[:query]['Action'] = 'DescribeOrderableClusterOptions' params[:query]['ClusterVersion'] = cluster_version if cluster_version params[:query]['NodeType'] = node_type if node_type params[:query]['Marker'] = marker if marker params[:query]['MaxRecords'] = max_records if max_records request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/reset_cluster_parameter_group.rb0000644000004100000410000000524212261242551026672 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/update_cluster_parameter_group_parser' # ==== Parameters # # @param [Hash] options # * :parameter_group_name - required - (String) The name of the cluster parameter group to be reset. # * :reset_all_parameters - (Boolean) If true , all parameters in the specified parameter group will be reset to their default values. Default: true # * :parameters - (Array<) An array of names of parameters to be reset. If ResetAllParameters option is not used, then at least one parameter name must be supplied. Constraints: A maximum of 20 parameters can be reset in a single request. # * :parameter_name - (String) The name of the parameter. # * :parameter_value - (String) The value of the parameter. # * :description - (String) A description of the parameter. # * :source - (String) The source of the parameter value, such as "engine-default" or "user". # * :data_type - (String) The data type of the parameter. # * :allowed_values - (String) The valid range of values for the parameter. # * :is_modifiable - (Boolean) If true , the parameter can be modified. Some parameters have security or operational implications that prevent them from being changed. # * :minimum_engine_version - (String) The earliest engine version to which the parameter can apply. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_ResetClusterParameterGroup.html def reset_cluster_parameter_group(options = {}) parameter_group_name = options[:parameter_group_name] reset_all_parameters = options[:reset_all_parameters] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::UpdateClusterParameterGroupParser.new } if options['Parameters'] options['Parameters'].keys.each_with_index do |name, index| params[:query].merge!({ "Parameters.member.#{index+1}.#{name}" => options['Parameters'][name] }) end end params[:query]['Action'] = 'ResetClusterSubnetGroup' params[:query]['ParameterGroupName'] = parameter_group_name if parameter_group_name params[:query]['ResetAllParameters'] = reset_all_parameters if reset_all_parameters request(params) end end end end end fog-1.19.0/lib/fog/aws/requests/redshift/describe_reserved_nodes.rb0000644000004100000410000000343512261242551025404 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/describe_reserved_nodes' # ==== Parameters # # @param [Hash] options # * :reserved_node_id - (String) # The unique identifier for the node reservation. # * :max_records - (Integer) # The maximum number of records to include in the response. If more than the # MaxRecords value is available, a marker is included in the response so that the # following results can be retrieved. Constrained between [20,100]. Default is 100. # * :marker - (String) # The marker returned from a previous request. If this parameter is specified, the # response includes records beyond the marker only, up to MaxRecords. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeReservedNodes.html def describe_reserved_nodes(options = {}) reserved_node_id = options[:reserved_node_id] marker = options[:marker] max_records = options[:max_records] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :get, :query => {}, :parser => Fog::Parsers::Redshift::AWS::DescribeReservedNodes.new } params[:query]['Action'] = 'DescribeReservedNodes' params[:query]['ReservedNodeId'] = reserved_node_id if reserved_node_id params[:query]['Marker'] = marker if marker params[:query]['MaxRecords'] = max_records if max_records request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/describe_cluster_snapshots.rb0000644000004100000410000000721412261242551026157 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/describe_cluster_snapshots' # ==== Parameters # # @param [Hash] options # * :cluster_identifier - (String) # The identifier of the cluster for which information about snapshots is requested. # * :snapshot_identifier - (String) # The snapshot identifier of the snapshot about which to return information. # * :snapshot_type - (String) # The type of snapshots for which you are requesting information. By default, # snapshots of all types are returned. Valid Values: automated | manual # * :start_time - (String) # A value that requests only snapshots created at or after the specified time. # The time value is specified in ISO 8601 format. For more information about # ISO 8601, go to the ISO8601 Wikipedia page. Example: 2012-07-16T18:00:00Z # * :end_time - (String) # A time value that requests only snapshots created at or before the specified # time. The time value is specified in ISO 8601 format. For more information # about ISO 8601, go to the ISO8601 Wikipedia page. Example: 2012-07-16T18:00:00Z # * :owner_account - (String) # The AWS customer account used to create or copy the snapshot. Use this field to # filter the results to snapshots owned by a particular account. To describe snapshots # you own, either specify your AWS customer account, or do not specify the parameter. # * :max_records - (Integer) # The maximum number of records to include in the response. If more than the # MaxRecords value is available, a marker is included in the response so that the # following results can be retrieved. Constrained between [20,100]. Default is 100. # * :marker - (String) # The marker returned from a previous request. If this parameter is specified, the # response includes records beyond the marker only, up to MaxRecords. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeClusterSnapshots.html def describe_cluster_snapshots(options = {}) cluster_identifier = options[:cluster_identifier] snapshot_identifier = options[:snapshot_identifier] start_time = options[:start_time] end_time = options[:end_time] owner_account = options[:owner_account] marker = options[:marker] max_records = options[:max_records] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :get, :query => {}, :parser => Fog::Parsers::Redshift::AWS::DescribeClusterSnapshots.new } params[:query]['Action'] = 'DescribeClusterSnapshots' params[:query]['ClusterIdentifier'] = cluster_identifier if cluster_identifier params[:query]['SnapshotIdentifier'] = snapshot_identifier if snapshot_identifier params[:query]['start_time'] = start_time if start_time params[:query]['end_time'] = end_time if end_time params[:query]['OwnerAccount'] = owner_account if owner_account params[:query]['Marker'] = marker if marker params[:query]['MaxRecords'] = max_records if max_records request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/restore_from_cluster_snapshot.rb0000644000004100000410000001031512261242551026716 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/cluster' # ==== Parameters # # @param [Hash] options # * :cluster_identifier - required - (String) # The identifier of the cluster that will be created from restoring the snapshot. # Constraints: Must contain from 1 to 63 alphanumeric characters or hyphens. # Alphabetic characters must be lowercase. First character must be a letter. Cannot # end with a hyphen or contain two consecutive hyphens. Must be unique for all # clusters within an AWS account. # * :snapshot_identifier - required - (String) # The name of the snapshot from which to create the new cluster. This parameter # isn't case sensitive. Example: my-snapshot-id # * :snapshot_cluster_identifier - (String) # * :port - (Integer) # The port number on which the cluster accepts connections. Default: The same port # as the original cluster. Constraints: Must be between 1115 and 65535. # * :availability_zone - (String) # The Amazon EC2 Availability Zone in which to restore the cluster. Default: A # random, system-chosen Availability Zone. Example: us-east-1a # * :allow_version_upgrade - (Boolean) # If true , upgrades can be applied during the maintenance window to the Amazon # Redshift engine that is running on the cluster. Default: true # * :cluster_subnet_group_name - (String) # The name of the subnet group where you want to cluster restored. A snapshot of # cluster in VPC can be restored only in VPC. Therefore, you must provide subnet # group name where you want the cluster restored. # * :publicly_accessible - (Boolean) # If true , the cluster can be accessed from a public network. # * :owner_account - (String) # The AWS customer account used to create or copy the snapshot. Required if you are # restoring a snapshot you do not own, optional if you own the snapshot. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_RestoreFromClusterSnapshot.html def restore_from_cluster_snapshot(options = {}) cluster_identifier = options[:cluster_identifier] snapshot_identifier = options[:snapshot_identifier] snapshot_cluster_identifier = options[:snapshot_cluster_identifier] port = options[:port] availability_zone = options[:availability_zone] allow_version_upgrade = options[:allow_version_upgrade] cluster_subnet_group_name = options[:cluster_subnet_group_name] publicly_accessible = options[:publicly_accessible] owner_account = options[:owner_account] path = "/" params = { :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::Cluster.new } params[:query]['Action'] = 'RestoreFromClusterSnapshot' params[:query]['ClusterIdentifier'] = cluster_identifier if cluster_identifier params[:query]['SnapshotIdentifier'] = snapshot_identifier if snapshot_identifier params[:query]['SnapshotClusterIdentifier'] = snapshot_cluster_identifier if snapshot_cluster_identifier params[:query]['Port'] = port if port params[:query]['AvailabilityZone'] = availability_zone if availability_zone params[:query]['AllowVersionUpgrade'] = allow_version_upgrade if allow_version_upgrade params[:query]['ClusterSubnetGroupName'] = cluster_subnet_group_name if cluster_subnet_group_name params[:query]['PubliclyAccessible'] = publicly_accessible if publicly_accessible params[:query]['OwnerAccount'] = owner_account if owner_account request(params) end end end end end fog-1.19.0/lib/fog/aws/requests/redshift/describe_default_cluster_parameters.rb0000644000004100000410000000376312261242551030011 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/describe_default_cluster_parameters' # ==== Parameters # # @param [Hash] options # * :parameter_group_family - required - (String) # The name of a cluster parameter group family for which to return details. # * :max_records - (Integer) # The maximum number of records to include in the response. If more than the # MaxRecords value is available, a marker is included in the response so that the # following results can be retrieved. Constrained between [20,100]. Default is 100. # * :marker - (String) # The marker returned from a previous request. If this parameter is specified, the # response includes records beyond the marker only, up to MaxRecords. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeDefaultClusterParameters.html def describe_default_cluster_parameters(options = {}) parameter_group_family = options[:parameter_group_family] source = options[:source] marker = options[:marker] max_records = options[:max_records] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :get, :query => {}, :parser => Fog::Parsers::Redshift::AWS::DescribeDefaultClusterParameters.new } params[:query]['Action'] = 'DescribeDefaultClusterParameters' params[:query]['ParameterGroupFamily'] = parameter_group_family if parameter_group_family params[:query]['Marker'] = marker if marker params[:query]['MaxRecords'] = max_records if max_records request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/authorize_snapshot_access.rb0000644000004100000410000000324512261242551026006 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/cluster_snapshot' # ==== Parameters # # @param [Hash] options # * :snapshot_identifier - required - (String) # The identifier of the snapshot the account is authorized to restore. # * :snapshot_cluster_identifier - (String) # * :account_with_restore_access - required - (String) # The identifier of the AWS customer account authorized to restore the specified snapshot. # # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_CopyClusterSnapshot.html def authorize_snapshot_access(options = {}) snapshot_identifier = options[:snapshot_identifier] snapshot_cluster_identifier = options[:snapshot_cluster_identifier] account_with_restore_access = options[:account_with_restore_access] path = "/" params = { :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::ClusterSnapshot.new } params[:query]['Action'] = 'AuthorizeSnapshotAccess' params[:query]['SnapshotIdentifier'] = snapshot_identifier if snapshot_identifier params[:query]['SnapshotClusterIdentifier'] = snapshot_cluster_identifier if snapshot_cluster_identifier params[:query]['AccountWithRestoreAccess'] = account_with_restore_access if account_with_restore_access request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/describe_cluster_parameter_groups.rb0000644000004100000410000000361412261242551027514 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/describe_cluster_parameter_groups' # ==== Parameters # # @param [Hash] options # * :parameter_group_name (String) # The name of a cluster parameter group for which to return details. # * :max_records - (Integer) # The maximum number of records to include in the response. If more than the # MaxRecords value is available, a marker is included in the response so that the # following results can be retrieved. Constrained between [20,100]. Default is 100. # * :marker - (String) # The marker returned from a previous request. If this parameter is specified, the # response includes records beyond the marker only, up to MaxRecords. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeClusterParameterGroups.html def describe_cluster_parameter_groups(options = {}) parameter_group_name = options[:parameter_group_name] marker = options[:marker] max_records = options[:max_records] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :get, :query => {}, :parser => Fog::Parsers::Redshift::AWS::DescribeClusterParameterGroups.new } params[:query]['Action'] = 'DescribeClusterParameterGroups' params[:query]['ParameterGroupName'] = parameter_group_name if parameter_group_name params[:query]['Marker'] = marker if marker params[:query]['MaxRecords'] = max_records if max_records request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/describe_cluster_parameters.rb0000644000004100000410000000453712261242551026305 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/describe_cluster_parameters' # ==== Parameters # # @param [Hash] options # * :parameter_group_name - required - (String) # The name of a cluster parameter group for which to return details. # * :source - (String) # The parameter types to return. Specify user to show parameters that are # different form the default. Similarly, specify engine-default to show parameters # that are the same as the default parameter group. Default: All parameter types # returned. Valid Values: user | engine-default # * :max_records - (Integer) # The maximum number of records to include in the response. If more than the # MaxRecords value is available, a marker is included in the response so that the # following results can be retrieved. Constrained between [20,100]. Default is 100. # * :marker - (String) # The marker returned from a previous request. If this parameter is specified, the # response includes records beyond the marker only, up to MaxRecords. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeClusterParameters.html def describe_cluster_parameters(options = {}) parameter_group_name = options[:parameter_group_name] source = options[:source] marker = options[:marker] max_records = options[:max_records] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :get, :query => {}, :parser => Fog::Parsers::Redshift::AWS::DescribeClusterParameters.new } params[:query]['Action'] = 'DescribeClusterParameters' params[:query]['ParameterGroupName'] = parameter_group_name if parameter_group_name params[:query]['Source'] = source if source params[:query]['Marker'] = marker if marker params[:query]['MaxRecords'] = max_records if max_records request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/reboot_cluster.rb0000644000004100000410000000235112261242551023564 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/cluster' # ==== Parameters # # @param [Hash] options # * :cluster_identifier - required - (String) # A unique identifier for the cluster. You use this identifier to refer to the cluster # for any subsequent cluster operations such as deleting or modifying. Must be unique # for all clusters within an AWS account. Example: myexamplecluster # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DeleteCluster.html def reboot_cluster(options = {}) cluster_identifier = options[:cluster_identifier] path = "/" params = { :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::Cluster.new } params[:query]['Action'] = 'RebootCluster' params[:query]['ClusterIdentifier'] = cluster_identifier if cluster_identifier request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/create_cluster_parameter_group.rb0000644000004100000410000000501112261242551027005 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/create_cluster_parameter_group' # ==== Parameters # # @param [Hash] options # * :parameter_group_name - required - (String) # The name of the cluster parameter group. Constraints: Must be 1 to 255 alphanumeric # characters or hyphens First character must be a letter. Cannot end with a hyphen or # contain two consecutive hyphens. Must be unique within your AWS account. This value # is stored as a lower-case string. # * :parameter_group_family - required - (String) # The Amazon Redshift engine version to which the cluster parameter group applies. The # cluster engine version determines the set of parameters. To get a list of valid parameter # group family names, you can call DescribeClusterParameterGroups. By default, Amazon # Redshift returns a list of all the parameter groups that are owned by your AWS account, # including the default parameter groups for each Amazon Redshift engine version. The # parameter group family names associated with the default parameter groups provide you # the valid values. For example, a valid family name is "redshift-1.0". # * :description - required - (String) # A description of the parameter group. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_CreateClusterParameterGroup.html def create_cluster_parameter_group(options = {}) parameter_group_name = options[:parameter_group_name] parameter_group_family = options[:parameter_group_family] description = options[:description] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::CreateClusterParameterGroup.new } params[:query]['Action'] = 'CreateClusterParameterGroup' params[:query]['ParameterGroupName'] = parameter_group_name if parameter_group_name params[:query]['ParameterGroupFamily'] = parameter_group_family if parameter_group_family params[:query]['Description'] = description if description request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/create_cluster.rb0000644000004100000410000002327512261242551023545 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/cluster' # ==== Parameters # # @param [Hash] options # * :db_name - (String) # The name of the first database to be created when the cluster is created. To create # additional databases after the cluster is created, connect to the cluster with a SQL # client and use SQL commands to create a database. Default: dev Constraints: Must # contain 1 to 64 alphanumeric characters. Must contain only lowercase letters. # * :cluster_identifier - required - (String) # A unique identifier for the cluster. You use this identifier to refer to the cluster # for any subsequent cluster operations such as deleting or modifying. Must be unique # for all clusters within an AWS account. Example: myexamplecluster # * :cluster_type - (String) # Type of the cluster. When cluster type is specified as single-node, the NumberOfNodes # parameter is not required. multi-node, the NumberOfNodes parameter is required. Valid # Values: multi-node | single-node Default: multi-node # * :node_type - required - (String) # The node type to be provisioned. Valid Values: dw.hs1.xlarge | dw.hs1.8xlarge. # * :master_username - required - (String) # The user name associated with the master user account for the cluster that is being # created. Constraints: Must be 1 - 128 alphanumeric characters. First character must # be a letter. Cannot be a reserved word. # * :master_user_password - required - (String) # The password associated with the master user account for the cluster that is being # created. Constraints: Must be between 8 and 64 characters in length. Must contain at # least one uppercase letter. Must contain at least one lowercase letter. Must contain # one number. # * :cluster_security_groups - (Array) # A list of security groups to be associated with this cluster. Default: The default # cluster security group for Amazon Redshift. # * :vpc_security_group_ids - (Array) # A list of Virtual Private Cloud (VPC) security groups to be associated with the # cluster. Default: The default VPC security group is associated with the cluster. # * :cluster_subnet_group_name - (String) # The name of a cluster subnet group to be associated with this cluster. If this # parameter is not provided the resulting cluster will be deployed outside virtual # private cloud (VPC). # * :availability_zone - (String) # The EC2 Availability Zone (AZ) in which you want Amazon Redshift to provision the # cluster. Default: A random, system-chosen Availability Zone in the region that is # specified by the endpoint. Example: us-east-1d Constraint: The specified # Availability Zone must be in the same region as the current endpoint. # * :preferred_maintenance_window - (String) # The weekly time range (in UTC) during which automated cluster maintenance can occur. # Format: ddd:hh24:mi-ddd:hh24:mi Default: A 30-minute window selected at random from # an 8-hour block of time per region, occurring on a random day of the week. # Constraints: Minimum 30-minute window. # * :cluster_parameter_group_name - (String) # The name of the parameter group to be associated with this cluster. Default: The # default Amazon Redshift cluster parameter group. Constraints: Must be 1 to 255 # alphanumeric characters or hyphens. First character must be a letter. Cannot end # with a hyphen or contain two consecutive hyphens. # * :automated_snapshot_retention_period - (Integer) # Number of days that automated snapshots are retained. If the value is 0, automated # snapshots are disabled. Default: 1 Constraints: Must be a value from 0 to 35. # * :port - (Integer) # The port number on which the cluster accepts incoming connections. Default: 5439 # Valid Values: 1150-65535 # * :cluster_version - (String) # The version of the Amazon Redshift engine software that you want to deploy on the # cluster. The version selected runs on all the nodes in the cluster. Constraints: # Only version 1.0 is currently available. Example: 1.0 # * :allow_version_upgrade - (Boolean) # If `true` , upgrades can be applied during the maintenance window to the Amazon # Redshift engine that is running on the cluster. Default: `true` # * :number_of_nodes - (Integer) # The number of compute nodes in the cluster. This parameter is required when the # ClusterType parameter is specified as multi-node. If you don't specify this parameter, # you get a single-node cluster. When requesting a multi-node cluster, you must specify # the number of nodes that you want in the cluster. Default: 1 Constraints: Value must # be at least 1 and no more than 100. # * :publicly_accessible - (Boolean) # If `true` , the cluster can be accessed from a public network. # * :encrypted - (Boolean) # If `true` , the data in cluster is encrypted at rest. Default: `false` # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_CreateCluster.html def create_cluster(options = {}) db_name = options[:db_name] cluster_identifier = options[:cluster_identifier] cluster_type = options[:cluster_type] node_type = options[:node_type] master_username = options[:master_username] master_user_password = options[:master_user_password] cluster_subnet_group_name = options[:cluster_subnet_group_name] availability_zone = options[:availability_zone] preferred_maintenance_window = options[:preferred_maintenance_window] cluster_parameter_group_name = options[:cluster_parameter_group_name] automated_snapshot_retention_period = options[:automated_snapshot_retention_period] port = options[:port] cluster_version = options[:cluster_version] allow_version_upgrade = options[:allow_version_upgrade] number_of_nodes = options[:number_of_nodes] publicly_accessible = options[:publicly_accessible] encrypted = options[:encrypted] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::Cluster.new } if cluster_security_groups = options.delete(:ClusterSecurityGroups) params[:query].merge!(Fog::AWS.indexed_param('ClusterSecurityGroups.member.%d', [*cluster_security_groups])) end if vpc_security_group_ids = options.delete(:VpcSecurityGroupIds) params[:query].merge!(Fog::AWS.indexed_param('VpcSecurityGroupIds.member.%d', [*vpc_security_group_ids])) end params[:query]['Action'] = 'CreateCluster' params[:query]['DBName'] = db_name if db_name params[:query]['ClusterIdentifier'] = cluster_identifier if cluster_identifier params[:query]['ClusterType'] = cluster_type if cluster_type params[:query]['NodeType'] = node_type if node_type params[:query]['MasterUsername'] = master_username if master_username params[:query]['MasterUserPassword'] = master_user_password if master_user_password params[:query]['ClusterSecurityGroups'] = cluster_security_groups if cluster_security_groups params[:query]['VpcSecurityGroupIds'] = vpc_security_group_ids if vpc_security_group_ids params[:query]['ClusterSubnetGroupName'] = cluster_subnet_group_name if cluster_subnet_group_name params[:query]['AvailabilityZone'] = availability_zone if availability_zone params[:query]['PreferredMaintenanceWindow'] = preferred_maintenance_window if preferred_maintenance_window params[:query]['ClusterParameterGroupName'] = cluster_parameter_group_name if cluster_parameter_group_name params[:query]['AutomatedSnapshotRetentionPeriod'] = automated_snapshot_retention_period if automated_snapshot_retention_period params[:query]['Port'] = port if port params[:query]['ClusterVersion'] = cluster_version if cluster_version params[:query]['AllowVersionUpgrade'] = allow_version_upgrade if allow_version_upgrade params[:query]['NumberOfNodes'] = number_of_nodes if number_of_nodes params[:query]['PubliclyAccessible'] = publicly_accessible if publicly_accessible params[:query]['Encrypted'] = encrypted if encrypted request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/delete_cluster.rb0000644000004100000410000000506112261242551023535 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/cluster' # ==== Parameters # # @param [Hash] options # * :cluster_identifier - required - (String) # A unique identifier for the cluster. You use this identifier to refer to the cluster # for any subsequent cluster operations such as deleting or modifying. Must be unique # for all clusters within an AWS account. Example: myexamplecluster # * :skip_final_cluster_snapshot - (Boolean) # Determines whether a final snapshot of the cluster is created before Amazon Redshift # deletes the cluster. If `true` , a final cluster snapshot is not created. If `false`, # a final cluster snapshot is created before the cluster is deleted. The # FinalClusterSnapshotIdentifier parameter must be specified if SkipFinalClusterSnapshot # is `false` . Default: `false` # * :final_cluster_snapshot_identifier - (String) # The identifier of the final snapshot that is to be created immediately before deleting # the cluster. If this parameter is provided, SkipFinalClusterSnapshot must be `false`. # Constraints: Must be 1 to 255 alphanumeric characters. First character must be a letter # Cannot end with a hyphen or contain two consecutive hyphens. # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_DeleteCluster.html def delete_cluster(options = {}) cluster_identifier = options[:cluster_identifier] final_cluster_snapshot_identifier = options[:final_cluster_snapshot_identifier] skip_final_cluster_snapshot = options[:skip_final_cluster_snapshot] path = "/" params = { :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::Cluster.new } params[:query]['Action'] = 'DeleteCluster' params[:query]['ClusterIdentifier'] = cluster_identifier if cluster_identifier params[:query]['FinalClusterSnapshotIdentifier'] = final_cluster_snapshot_identifier if final_cluster_snapshot_identifier params[:query]['SkipFinalClusterSnapshot'] = skip_final_cluster_snapshot if skip_final_cluster_snapshot request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/redshift/copy_cluster_snapshot.rb0000644000004100000410000000412312261242551025162 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/cluster_snapshot' # ==== Parameters # # @param [Hash] options # * :source_snapshot_identifier - required - (String) # The identifier for the source snapshot. Constraints: Must be the identifier for # a valid automated snapshot whose state is "available". # * :source_snapshot_cluster_identifier - (String) # * :target_snapshot_identifier - required - (String) # The identifier given to the new manual snapshot. Constraints: Cannot be null, # empty, or blank. Must contain from 1 to 255 alphanumeric characters or hyphens. # First character must be a letter. Cannot end with a hyphen or contain two # consecutive hyphens. Must be unique for the AWS account that is making the request. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_CopyClusterSnapshot.html def copy_cluster_snapshot(options = {}) source_snapshot_identifier = options[:source_snapshot_identifier] source_snapshot_cluster_identifier = options[:source_snapshot_cluster_identifier] target_snapshot_identifier = options[:target_snapshot_identifier] path = "/" params = { :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::ClusterSnapshot.new } params[:query]['Action'] = 'CopyClusterSnapshot' params[:query]['SourceSnapshotIdentifier'] = source_snapshot_identifier if source_snapshot_identifier params[:query]['SourceSnapshotClusterIdentifier'] = source_snapshot_cluster_identifier if source_snapshot_cluster_identifier params[:query]['TargetSnapshotIdentifier'] = target_snapshot_identifier if target_snapshot_identifier request(params) end end end end end fog-1.19.0/lib/fog/aws/requests/redshift/modify_cluster_subnet_group.rb0000644000004100000410000000371212261242551026357 0ustar www-datawww-datamodule Fog module AWS class Redshift class Real require 'fog/aws/parsers/redshift/cluster_subnet_group_parser' # ==== Parameters # # @param [Hash] options # * :cluster_subnet_group_name - required - (String) # The name for the subnet group. Amazon Redshift stores the value as a lowercase string. # Constraints: Must contain no more than 255 alphanumeric characters or hyphens. Must not # be "Default". Must be unique for all subnet groups that are created by your AWS account. # Example: examplesubnetgroup # * :description - required - (String) # A description of the parameter group. # * :subnet_ids - required - (Array<) # An array of VPC subnet IDs. A maximum of 20 subnets can be modified in a single request. # # ==== See Also # http://docs.aws.amazon.com/redshift/latest/APIReference/API_ModifyClusterSubnetGroup.html def modify_cluster_subnet_group(options = {}) cluster_subnet_group_name = options[:cluster_subnet_group_name] description = options[:description] path = "/" params = { :idempotent => true, :headers => {}, :path => path, :method => :put, :query => {}, :parser => Fog::Parsers::Redshift::AWS::ClusterSubnetGroupParser.new } if subnet_ids = options.delete(:subnet_ids) params[:query].merge!(Fog::AWS.indexed_param('SubnetIds.member.%d', [*subnet_ids])) end params[:query]['Action'] = 'ModifyClusterSubnetGroup' params[:query]['ClusterSubnetGroupName'] = cluster_subnet_group_name if cluster_subnet_group_name params[:query]['Description'] = description if description request(params) end end end end endfog-1.19.0/lib/fog/aws/requests/beanstalk/0000755000004100000410000000000012261242551020337 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/beanstalk/create_application_version.rb0000644000004100000410000000330212261242551026255 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/create_application_version' # Creates an application version for the specified application. # # ==== Options # * ApplicationName<~String>: The name of the application. If no application is found with this name, # and AutoCreateApplication is false, returns an InvalidParameterValue error. # * AutoCreateApplication<~Boolean>: If true, create the application if it doesn't exist. # * Description<~String>: Describes this version. # * SourceBundle<~Hash>: The Amazon S3 bucket and key that identify the location of the source bundle # for this version. Use keys 'S3Bucket' and 'S3Key' to describe location. # * VersionLabel<~String>: A label identifying this version. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_CreateApplicationVersion.html # def create_application_version(options={}) if source_bundle = options.delete('SourceBundle') # flatten hash options.merge!({ 'SourceBundle.S3Bucket' => source_bundle['S3Bucket'], 'SourceBundle.S3Key' => source_bundle['S3Key'] }) end request({ 'Operation' => 'CreateApplicationVersion', :parser => Fog::Parsers::AWS::ElasticBeanstalk::CreateApplicationVersion.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/swap_environment_cnames.rb0000644000004100000410000000140012261242551025603 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/empty' # Swaps the CNAMEs of two environments. # # ==== Options # * EnvironmentId # * EnvironmentName # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_SwapEnvironmentCNAMEs.html # def swap_environment_cnames(options={}) request({ 'Operation' => 'SwapEnvironmentCNAMEs', :parser => Fog::Parsers::AWS::ElasticBeanstalk::Empty.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/check_dns_availability.rb0000644000004100000410000000145612261242551025345 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/check_dns_availability' # Checks if the specified CNAME is available. # # ==== Options # * CNAMEPrefix<~String>: The prefix used when this CNAME is reserved # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_CheckDNSAvailability.html # def check_dns_availability(options) request({ 'Operation' => 'CheckDNSAvailability', :parser => Fog::Parsers::AWS::ElasticBeanstalk::CheckDNSAvailability.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/create_application.rb0000644000004100000410000000162612261242551024517 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/create_application' # Creates an application that has one configuration template named default and no application versions. # # ==== Options # * ApplicationName<~String>: The name of the application. # * Description<~String>: Describes the application. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_CreateApplication.html # def create_application(options={}) request({ 'Operation' => 'CreateApplication', :parser => Fog::Parsers::AWS::ElasticBeanstalk::CreateApplication.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/describe_application_versions.rb0000644000004100000410000000245112261242551026761 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/describe_application_versions' # Returns descriptions for existing application versions. # # ==== Options # * ApplicationName<~String>: If specified, AWS Elastic Beanstalk restricts the returned descriptions to # only include ones that are associated with the specified application. # * VersionLabels<~Array>: If specified, restricts the returned descriptions to only include ones that have # the specified version labels. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_DescribeApplicationVersions.html # def describe_application_versions(options={}) if version_labels = options.delete('VersionLabels') options.merge!(AWS.indexed_param('VersionLabels.member.%d', [*version_labels])) end request({ 'Operation' => 'DescribeApplicationVersions', :parser => Fog::Parsers::AWS::ElasticBeanstalk::DescribeApplicationVersions.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/delete_environment_configuration.rb0000644000004100000410000000217312261242551027504 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/empty' # Deletes the draft configuration associated with the running environment. # # ==== Options # * application_name<~String>: The name of the application the environment is associated with. # * environment_name<~String>: The name of the environment to delete the draft configuration from. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_DeleteConfigurationTemplate.html # def delete_environment_configuration(application_name, environment_name) options = { 'ApplicationName' => application_name, 'EnvironmentName' => environment_name } request({ 'Operation' => 'DeleteEnvironmentConfiguration', :parser => Fog::Parsers::AWS::ElasticBeanstalk::Empty.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/restart_app_server.rb0000644000004100000410000000136712261242551024605 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/empty' # Returns AWS resources for this environment. # # ==== Options # * EnvironmentId # * EnvironmentName # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_RestartAppServer.html # def restart_app_server(options={}) request({ 'Operation' => 'RestartAppServer', :parser => Fog::Parsers::AWS::ElasticBeanstalk::Empty.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/update_application.rb0000644000004100000410000000175612261242551024542 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/update_application' # Updates the specified application to have the specified properties. # # ==== Options # * ApplicationName<~String>: The name of the application to update. If no such application is found, # UpdateApplication returns an InvalidParameterValue error. # * Description<~String>: A new description for the application. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_UpdateApplication.html # def update_application(options) request({ 'Operation' => 'UpdateApplication', :parser => Fog::Parsers::AWS::ElasticBeanstalk::UpdateApplication.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/delete_application_version.rb0000644000004100000410000000242412261242551026260 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/empty' # Deletes the specified version from the specified application. # # ==== Options # * application_name<~String>: The name of the application to delete releases from. # * version_label<~String>: The label of the version to delete. # * delete_source_bundle<~Boolean>: Indicates whether to delete the associated source bundle from Amazon S3. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_DeleteApplication.html # def delete_application_version(application_name, version_label, delete_source_bundle = nil) options = { 'ApplicationName' => application_name, 'VersionLabel' => version_label } options['DeleteSourceBundle'] = delete_source_bundle unless delete_source_bundle.nil? request({ 'Operation' => 'DeleteApplicationVersion', :parser => Fog::Parsers::AWS::ElasticBeanstalk::Empty.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/describe_environment_resources.rb0000644000004100000410000000151312261242551027162 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/describe_environment_resources' # Returns AWS resources for this environment. # # ==== Options # * EnvironmentId # * EnvironmentName # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_DescribeEnvironmentResources.html # def describe_environment_resources(options={}) request({ 'Operation' => 'DescribeEnvironmentResources', :parser => Fog::Parsers::AWS::ElasticBeanstalk::DescribeEnvironmentResources.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/describe_events.rb0000644000004100000410000000165712261242551024041 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/describe_events' # Returns list of event descriptions matching criteria up to the last 6 weeks. # # ==== Options # * ApplicationName<~String>: If specified, AWS Elastic Beanstalk restricts the returned descriptions # to include only those that are associated with this application. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_DescribeEnvironments.html # def describe_events(options={}) request({ 'Operation' => 'DescribeEvents', :parser => Fog::Parsers::AWS::ElasticBeanstalk::DescribeEvents.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/update_configuration_template.rb0000644000004100000410000000261612261242551026775 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/update_configuration_template' # Updates the specified configuration template to have the specified properties or configuration option values. # # ==== Options # * ApplicationName<~String>: If specified, AWS Elastic Beanstalk restricts the returned descriptions # to include only those that are associated with this application. # * VersionLabel<~String>: # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_CreateConfigurationTemplate.html # def update_configuration_template(options={}) if option_settings = options.delete('OptionSettings') options.merge!(AWS.indexed_param('OptionSettings.member.%d', [*option_settings])) end if options_to_remove = options.delete('OptionsToRemove') options.merge!(AWS.indexed_param('OptionsToRemove.member.%d', [*options_to_remove])) end request({ 'Operation' => 'UpdateConfigurationTemplate', :parser => Fog::Parsers::AWS::ElasticBeanstalk::UpdateConfigurationTemplate.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/terminate_environment.rb0000644000004100000410000000203412261242551025277 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/terminate_environment' # Terminates the specified environment. # # ==== Options # * EnvironmentId<~String>: The ID of the environment to terminate. # * EnvironmentName<~String>: The name of the environment to terminate. # * TerminateResources<~Boolean>: Indicates whether the associated AWS resources should shut down when the # environment is terminated # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_TerminateEnvironment.html # def terminate_environment(options={}) request({ 'Operation' => 'TerminateEnvironment', :parser => Fog::Parsers::AWS::ElasticBeanstalk::TerminateEnvironment.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/list_available_solution_stacks.rb0000644000004100000410000000136212261242551027145 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/list_available_solution_stacks' # Checks if the specified CNAME is available. # # ==== Options # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_CheckDNSAvailability.html # def list_available_solution_stacks() request({ 'Operation' => 'ListAvailableSolutionStacks', :parser => Fog::Parsers::AWS::ElasticBeanstalk::ListAvailableSolutionStacks.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/delete_application.rb0000644000004100000410000000160212261242551024510 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/empty' # Deletes the specified application along with all associated versions and configurations. # # ==== Options # * application_name<~String>: The name of the application to delete. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_DeleteApplication.html # def delete_application(application_name) options = { 'ApplicationName' => application_name } request({ 'Operation' => 'DeleteApplication', :parser => Fog::Parsers::AWS::ElasticBeanstalk::Empty.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/describe_configuration_options.rb0000644000004100000410000000370312261242551027151 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/describe_configuration_options' # Describes the configuration options that are used in a particular configuration template or environment, # or that a specified solution stack defines. The description includes the values the options, # their default values, and an indication of the required action on a running environment # if an option value is changed. # # ==== Options # * ApplicationName<~String>: The name of the application associated with the configuration template or # environment. Only needed if you want to describe the configuration options associated with either the # configuration template or environment. # * EnvironmentName<~String>: The name of the environment whose configuration options you want to describe. # * Options<~Array>: If specified, restricts the descriptions to only the specified options. # * SolutionStackName<~String>: The name of the solution stack whose configuration options you want to describe. # * TemplateName<~String>: The name of the configuration template whose configuration options you want to describe. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_DescribeConfigurationOptions.html # def describe_configuration_options(options={}) if option_filters = options.delete('Options') options.merge!(AWS.indexed_param('Options.member.%d', [*option_filters])) end request({ 'Operation' => 'DescribeConfigurationOptions', :parser => Fog::Parsers::AWS::ElasticBeanstalk::DescribeConfigurationOptions.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/create_storage_location.rb0000644000004100000410000000134512261242551025546 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/create_storage_location' # Creates the Amazon S3 storage location for the account. # # ==== Options # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_CreateStorageLocation.html # def create_storage_location() request({ 'Operation' => 'CreateStorageLocation', :parser => Fog::Parsers::AWS::ElasticBeanstalk::CreateStorageLocation.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/describe_applications.rb0000644000004100000410000000206012261242551025210 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/describe_applications' # Returns the descriptions of existing applications. # # ==== Options # * application_names<~Array>: If specified, AWS Elastic Beanstalk restricts the returned descriptions # to only include those with the specified names. # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_DescribeApplications.html # def describe_applications(application_names=[]) options = {} options.merge!(AWS.indexed_param('ApplicationNames.member.%d', [*application_names])) request({ 'Operation' => 'DescribeApplications', :parser => Fog::Parsers::AWS::ElasticBeanstalk::DescribeApplications.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/validate_configuration_settings.rb0000644000004100000410000000234412261242551027327 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/validate_configuration_settings' # Updates the specified configuration template to have the specified properties or configuration option values. # # ==== Options # * ApplicationName<~String>: If specified, AWS Elastic Beanstalk restricts the returned descriptions # to include only those that are associated with this application. # * VersionLabel<~String>: # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_CreateConfigurationTemplate.html # def validate_configuration_settings(options={}) if option_settings = options.delete('OptionSettings') options.merge!(AWS.indexed_param('OptionSettings.member.%d', [*option_settings])) end request({ 'Operation' => 'ValidateConfigurationSettings', :parser => Fog::Parsers::AWS::ElasticBeanstalk::ValidateConfigurationSettings.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/create_configuration_template.rb0000644000004100000410000000476312261242551026763 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/create_configuration_template' # Creates a configuration template. Templates are associated with a specific application and are used to # deploy different versions of the application with the same configuration settings. # # ==== Options # * ApplicationName<~String>: The name of the application to associate with this configuration template. # If no application is found with this name, AWS Elastic Beanstalk returns an InvalidParameterValue error. # * Description<~String>: Describes this configuration. # * EnvironmentId<~String>: The ID of the environment used with this configuration template. # * OptionSettings<~Hash>: If specified, AWS Elastic Beanstalk sets the specified configuration option # to the requested value. The new value overrides the value obtained from the solution stack or the # source configuration template. # * SolutionStackName<~String>: The name of the solution stack used by this configuration. The solution # stack specifies the operating system, architecture, and application server for a configuration template. # It determines the set of configuration options as well as the possible and default values. # * SourceConfiguration<~String>: If specified, AWS Elastic Beanstalk uses the configuration values from the # specified configuration template to create a new configuration. # * TemplateName<~String>: The name of the configuration template. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_CreateConfigurationTemplate.html # def create_configuration_template(options={}) if option_settings = options.delete('OptionSettings') options.merge!(AWS.indexed_param('OptionSettings.member.%d', [*option_settings])) end if option_settings = options.delete('SourceConfiguration') options.merge!(AWS.serialize_keys('SourceConfiguration', option_settings)) end request({ 'Operation' => 'CreateConfigurationTemplate', :parser => Fog::Parsers::AWS::ElasticBeanstalk::CreateConfigurationTemplate.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/update_environment.rb0000644000004100000410000000312512261242551024573 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/update_environment' # Updates the environment description, deploys a new application version, updates the configuration settings # to an entirely new configuration template, or updates select configuration option values in # the running environment. # # ==== Options # * ApplicationName<~String>: If specified, AWS Elastic Beanstalk restricts the returned descriptions # to include only those that are associated with this application. # * EnvironmentIds # * EnvironmentNames # * IncludeDeleted # * IncludedDeletedBackTo # * VersionLabel<~String>: # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_CreateEnvironment.html # def update_environment(options={}) if option_settings = options.delete('OptionSettings') options.merge!(AWS.indexed_param('OptionSettings.member.%d', [*option_settings])) end if options_to_remove = options.delete('OptionsToRemove') options.merge!(AWS.indexed_param('OptionsToRemove.member.%d', [*options_to_remove])) end request({ 'Operation' => 'UpdateEnvironment', :parser => Fog::Parsers::AWS::ElasticBeanstalk::UpdateEnvironment.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/update_application_version.rb0000644000004100000410000000201212261242551026271 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/update_application_version' # Updates the specified application version to have the specified properties. # # ==== Options # * ApplicationName<~String>: The name of the application associated with this version. # * VersionLabel<~String>: The name of the version to update. # * Description<~String>: A new description for this release. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_UpdateApplicationVersion.html # def update_application_version(options) request({ 'Operation' => 'UpdateApplicationVersion', :parser => Fog::Parsers::AWS::ElasticBeanstalk::UpdateApplicationVersion.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/describe_environments.rb0000644000004100000410000000264212261242551025257 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/describe_environments' # Returns descriptions for existing environments. # # ==== Options # * ApplicationName<~String>: If specified, AWS Elastic Beanstalk restricts the returned descriptions # to include only those that are associated with this application. # * EnvironmentIds # * EnvironmentNames # * IncludeDeleted # * IncludedDeletedBackTo # * VersionLabel<~String>: # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_DescribeEnvironments.html # def describe_environments(options={}) if environment_ids = options.delete('EnvironmentIds') options.merge!(AWS.indexed_param('EnvironmentIds.member.%d', [*environment_ids])) end if environment_names = options.delete('EnvironmentNames') options.merge!(AWS.indexed_param('EnvironmentNames.member.%d', [*environment_names])) end request({ 'Operation' => 'DescribeEnvironments', :parser => Fog::Parsers::AWS::ElasticBeanstalk::DescribeEnvironments.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/request_environment_info.rb0000644000004100000410000000141112261242551026010 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/empty' # Returns AWS resources for this environment. # # ==== Options # * EnvironmentId # * EnvironmentName # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_RequestEnvironmentInfo.html # def request_environment_info(options={}) request({ 'Operation' => 'RequestEnvironmentInfo', :parser => Fog::Parsers::AWS::ElasticBeanstalk::Empty.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/describe_configuration_settings.rb0000644000004100000410000000226712261242551027322 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/describe_configuration_settings' # Returns a description of the settings for the specified configuration set, that is, either a configuration # template or the configuration set associated with a running environment. # # ==== Options # * ApplicationName<~String>: The application for the environment or configuration template. # * EnvironmentName<~String>: The name of the environment to describe. # * TemplateName<~String>: The name of the configuration template to describe. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_DescribeConfigurationSettings.html # def describe_configuration_settings(options={}) request({ 'Operation' => 'DescribeConfigurationSettings', :parser => Fog::Parsers::AWS::ElasticBeanstalk::DescribeConfigurationSettings.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/retrieve_environment_info.rb0000644000004100000410000000146212261242551026153 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/retrieve_environment_info' # Returns AWS resources for this environment. # # ==== Options # * EnvironmentId # * EnvironmentName # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_RetrieveEnvironmentInfo.html # def retrieve_environment_info(options={}) request({ 'Operation' => 'RetrieveEnvironmentInfo', :parser => Fog::Parsers::AWS::ElasticBeanstalk::RetrieveEnvironmentInfo.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/rebuild_environment.rb0000644000004100000410000000156612261242551024746 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/empty' # Deletes and recreates all of the AWS resources (for example: the Auto Scaling group, load balancer, etc.) # for a specified environment and forces a restart. # # ==== Options # * EnvironmentId # * EnvironmentName # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_RebuildEnvironment.html # def rebuild_environment(options={}) request({ 'Operation' => 'RebuildEnvironment', :parser => Fog::Parsers::AWS::ElasticBeanstalk::Empty.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/create_environment.rb0000644000004100000410000000524512261242551024561 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/create_environment' # Launches an environment for the specified application using the specified configuration. # # ==== Options # * ApplicationName<~String>: If specified, AWS Elastic Beanstalk restricts the returned descriptions # to include only those that are associated with this application. # * CNAMEPrefix<~String>: If specified, the environment attempts to use this value as the prefix for the CNAME. # If not specified, the environment uses the environment name. # * Description<~String>: Describes this environment. # * EnvironmentName<~String>: A unique name for the deployment environment. Used in the application URL. # * OptionSettings<~Array>: If specified, AWS Elastic Beanstalk sets the specified configuration options to # the requested value in the configuration set for the new environment. These override the values obtained # from the solution stack or the configuration template. # * OptionsToRemove<~Array>: A list of custom user-defined configuration options to remove from the # configuration set for this new environment. # * SolutionStackName<~String>: This is an alternative to specifying a configuration name. If specified, # AWS Elastic Beanstalk sets the configuration values to the default values associated with the # specified solution stack. # * TemplateName<~String>: The name of the configuration template to use in deployment. If no configuration # template is found with this name, AWS Elastic Beanstalk returns an InvalidParameterValue error. # * VersionLabel<~String>: The name of the application version to deploy. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_CreateEnvironment.html # def create_environment(options={}) if option_settings = options.delete('OptionSettings') options.merge!(AWS.indexed_param('OptionSettings.member.%d', [*option_settings])) end if options_to_remove = options.delete('OptionsToRemove') options.merge!(AWS.indexed_param('OptionsToRemove.member.%d', [*options_to_remove])) end request({ 'Operation' => 'CreateEnvironment', :parser => Fog::Parsers::AWS::ElasticBeanstalk::CreateEnvironment.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/beanstalk/delete_configuration_template.rb0000644000004100000410000000210312261242551026744 0ustar www-datawww-datamodule Fog module AWS class ElasticBeanstalk class Real require 'fog/aws/parsers/beanstalk/empty' # Deletes the specified configuration template. # # ==== Options # * application_name<~String>: The name of the application to delete the configuration template from. # * template_name<~String>: The name of the configuration template to delete. # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/elasticbeanstalk/latest/api/API_DeleteConfigurationTemplate.html # def delete_configuration_template(application_name, template_name) options = { 'ApplicationName' => application_name, 'TemplateName' => template_name } request({ 'Operation' => 'DeleteConfigurationTemplate', :parser => Fog::Parsers::AWS::ElasticBeanstalk::Empty.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_watch/0000755000004100000410000000000012261242551020667 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/cloud_watch/disable_alarm_actions.rb0000644000004100000410000000161012261242551025511 0ustar www-datawww-datamodule Fog module AWS class CloudWatch class Real require 'fog/aws/parsers/cloud_watch/disable_alarm_actions' # Disables actions for the specified alarms # ==== Options # * AlarmNames<~Array>: The names of the alarms to disable actions for # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_DisableAlarmActions.html # def disable_alarm_actions(alarm_names) options = {} options.merge!(AWS.indexed_param('AlarmNames.member.%d', [*alarm_names])) request({ 'Action' => 'DisableAlarmActions', :parser => Fog::Parsers::AWS::CloudWatch::DisableAlarmActions.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_watch/get_metric_statistics.rb0000644000004100000410000000431512261242551025613 0ustar www-datawww-datamodule Fog module AWS class CloudWatch class Real require 'fog/aws/parsers/cloud_watch/get_metric_statistics' # Fetch datapoints for a metric. At most 1440 datapoints will be returned, the most datapoints that can be queried is 50850 # StartTime is capped to 2 weeks ago # ==== Options # * Namespace<~String>: the namespace of the metric # * MetricName<~String>: the name of the metric # * StartTime<~Datetime>: when to start fetching datapoints from (inclusive) # * EndTime<~Datetime>: used to determine the last datapoint to fetch (exclusive) # * Period<~Integer>: Granularity, in seconds of the returned datapoints. Must be a multiple of 60, and at least 60 # * Statistics<~Array>: An array of up to 5 strings, which name the statistics to return # * Unit<~String>: The unit for the metric # * Dimensions<~Array>: a list of dimensions to filter against (optional) # Name : The name of the dimension # Value : The value to filter against # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html # def get_metric_statistics(options={}) %w{Statistics StartTime EndTime Period MetricName Namespace}.each do |required_parameter| raise ArgumentError, "Must provide #{required_parameter}" unless options.has_key?(required_parameter) end statistics = options.delete 'Statistics' options.merge!(AWS.indexed_param('Statistics.member.%d', [*statistics])) if dimensions = options.delete('Dimensions') options.merge!(AWS.indexed_param('Dimensions.member.%d.Name', dimensions.collect {|dimension| dimension['Name']})) options.merge!(AWS.indexed_param('Dimensions.member.%d.Value', dimensions.collect {|dimension| dimension['Value']})) end request({ 'Action' => 'GetMetricStatistics', :parser => Fog::Parsers::AWS::CloudWatch::GetMetricStatistics.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_watch/put_metric_data.rb0000644000004100000410000000612112261242551024360 0ustar www-datawww-datamodule Fog module AWS class CloudWatch class Real require 'fog/aws/parsers/cloud_watch/put_metric_data' # Publishes one or more data points to CloudWatch. A new metric is created if necessary # ==== Options # * Namespace<~String>: the namespace of the metric data # * MetricData<~Array>: the datapoints to publish of the metric # * MetricName<~String>: the name of the metric # * Timestamp<~String>: the timestamp for the data point. If omitted defaults to the time at which the data is received by CloudWatch # * Unit<~String>: the unit # * Value<~Double> the value for the metric # * StatisticValues<~Hash>: # * Maximum<~Double>: the maximum value of the sample set # * Sum<~Double>: the sum of the values of the sample set # * SampleCount<~Double>: the number of samples used for the statistic set # * Minimum<~Double>: the minimum value of the sample set # * Dimensions<~Array>: the dimensions for the metric. From 0 to 10 may be included # * Name<~String> # * Value<~String> # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_PutMetricData.html # def put_metric_data(namespace, metric_data) options = {'Namespace' => namespace} #first index the dimensions for any of the datums that have dimensions metric_data.collect! do |metric_datum| if dimensions = metric_datum.delete('Dimensions') metric_datum.merge!(AWS.indexed_param('Dimensions.member.%d.Name', dimensions.collect {|dimension| dimension['Name']})) metric_datum.merge!(AWS.indexed_param('Dimensions.member.%d.Value', dimensions.collect {|dimension| dimension['Value']})) end metric_datum end #then flatten out an hashes in the metric_data array metric_data.collect! { |metric_datum| flatten_hash(metric_datum) } #then index the metric_data array options.merge!(AWS.indexed_param('MetricData.member.%d', [*metric_data])) #then finally flatten out an hashes in the overall options array options = flatten_hash(options) request({ 'Action' => 'PutMetricData', :parser => Fog::Parsers::AWS::CloudWatch::PutMetricData.new }.merge(options)) end private def flatten_hash(starting) finishing = {} starting.each do |top_level_key, top_level_value| if top_level_value.is_a?(Hash) nested_hash = top_level_value nested_hash.each do |nested_key, nested_value| finishing["#{top_level_key}.#{nested_key}"] = nested_value end else finishing[top_level_key] = top_level_value end end return finishing end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_watch/list_metrics.rb0000644000004100000410000000422212261242551023715 0ustar www-datawww-datamodule Fog module AWS class CloudWatch class Real require 'fog/aws/parsers/cloud_watch/list_metrics' # List availabe metrics # # ==== Options # * Dimensions<~Array>: a list of dimensions to filter against, # Name : The name of the dimension # Value : The value to filter against # * MetricName<~String>: The name of the metric to filter against # * Namespace<~String>: The namespace to filter against # * NextToken<~String> The token returned by a previous call to indicate that there is more data available # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_ListMetrics.html # def list_metrics(options={}) if dimensions = options.delete('Dimensions') options.merge!(AWS.indexed_param('Dimensions.member.%d.Name', dimensions.collect {|dimension| dimension['Name']})) options.merge!(AWS.indexed_param('Dimensions.member.%d.Value', dimensions.collect {|dimension| dimension['Value']})) end request({ 'Action' => 'ListMetrics', :parser => Fog::Parsers::AWS::CloudWatch::ListMetrics.new }.merge(options)) end end class Mock def list_metrics(options={}) body = case options["NextToken"] when nil { "ListMetricsResult" => { "Metrics" => (0...500).map{ {} }, "NextToken" => '1' }} when "1" { "ListMetricsResult" => { "Metrics" => (0...500).map{ {} }, "NextToken" => '2' }} when "2" { "ListMetricsResult" => { "Metrics" => (0...1).map{ {} } }} end Excon::Response.new.tap do |response| response.body = body response.status = 200 end end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_watch/delete_alarms.rb0000644000004100000410000000264712261242551024026 0ustar www-datawww-datamodule Fog module AWS class CloudWatch class Real require 'fog/aws/parsers/cloud_watch/delete_alarms' # Delete a list of alarms # ==== Options # * AlarmNames<~Array>: A list of alarms to be deleted # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/index.html?API_DeleteAlarms.html # def delete_alarms(alarm_names) options = {} options.merge!(AWS.indexed_param('AlarmNames.member.%d', [*alarm_names])) request({ 'Action' => 'DeleteAlarms', :parser => Fog::Parsers::AWS::CloudWatch::DeleteAlarms.new }.merge(options)) end end class Mock def delete_alarms(alarm_names) [*alarm_names].each do |alarm_name| unless data[:metric_alarms].has_key?(alarm_name) raise Fog::AWS::AutoScaling::NotFound, "The alarm '#{alarm_name}' does not exist." end end [*alarm_names].each { |alarm_name| data[:metric_alarms].delete(alarm_name) } response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_watch/describe_alarms_for_metric.rb0000644000004100000410000000277712261242551026561 0ustar www-datawww-datamodule Fog module AWS class CloudWatch class Real require 'fog/aws/parsers/cloud_watch/describe_alarms_for_metric' # Retrieves all alarms for a single metric # ==== Options # * Dimensions<~Array>: a list of dimensions to filter against # Name : The name of the dimension # Value : The value to filter against # * MetricName<~String>: The name of the metric # * Namespace<~String>: The namespace of the metric # * Period<~Integer>: The period in seconds over which the statistic is applied # * Statistics<~String>: The statistic for the metric # * Unit<~String> The unit for the metric # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_DescribeAlarms.html # def describe_alarms_for_metric(options) if dimensions = options.delete('Dimensions') options.merge!(AWS.indexed_param('Dimensions.member.%d.Name', dimensions.collect {|dimension| dimension['Name']})) options.merge!(AWS.indexed_param('Dimensions.member.%d.Value', dimensions.collect {|dimension| dimension['Value']})) end request({ 'Action' => 'DescribeAlarmsForMetric', :parser => Fog::Parsers::AWS::CloudWatch::DescribeAlarmsForMetric.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_watch/set_alarm_state.rb0000644000004100000410000000201712261242551024363 0ustar www-datawww-datamodule Fog module AWS class CloudWatch class Real require 'fog/aws/parsers/cloud_watch/set_alarm_state' # Temporarily sets the state of an alarm # ==== Options # * AlarmName<~String>: The names of the alarm # * StateReason<~String>: The reason that this alarm is set to this specific state (in human-readable text format) # * StateReasonData<~String>: The reason that this alarm is set to this specific state (in machine-readable JSON format) # * StateValue<~String>: The value of the state # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_SetAlarmState.html # def set_alarm_state(options) request({ 'Action' => 'SetAlarmState', :parser => Fog::Parsers::AWS::CloudWatch::SetAlarmState.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_watch/enable_alarm_actions.rb0000644000004100000410000000160112261242551025334 0ustar www-datawww-datamodule Fog module AWS class CloudWatch class Real require 'fog/aws/parsers/cloud_watch/enable_alarm_actions' # Enables actions for the specified alarms # ==== Options # * AlarmNames<~Array>: The names of the alarms to enable actions for # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_EnableAlarmActions.html # def enable_alarm_actions(alarm_names) options = {} options.merge!(AWS.indexed_param('AlarmNames.member.%d', [*alarm_names])) request({ 'Action' => 'EnableAlarmActions', :parser => Fog::Parsers::AWS::CloudWatch::EnableAlarmActions.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_watch/put_metric_alarm.rb0000644000004100000410000001057612261242551024554 0ustar www-datawww-datamodule Fog module AWS class CloudWatch class Real require 'fog/aws/parsers/cloud_watch/put_metric_alarm' # Creates or updates an alarm and associates it with the specified Amazon CloudWatch metric # ==== Options # * ActionsEnabled<~Boolean>: Indicates whether or not actions should be executed during any changes to the alarm's state # * AlarmActions<~Array>: A list of actions to execute # * AlarmDescription<~String>: The description for the alarm # * AlarmName<~String> The unique name for the alarm # * ComparisonOperator<~String>: The arithmetic operation to use for comparison # * Dimensions<~Array>: a list of dimensions to filter against, # Name : The name of the dimension # Value : The value to filter against # * EvaluationPeriods<~Integer>: The number of periods over which data is compared to the specified threshold # * InsufficientDataActions<~Array>: A list of actions to execute # * MetricName<~String>: The name for the alarm's associated metric # * Namespace<~String>: The namespace for the alarm's associated metric # * OKActions<~Array>: A list of actions to execute # * Period<~Integer>: The period in seconds over which the specified statistic is applied # * Statistic<~String>: The statistic to apply to the alarm's associated metric # * Threshold<~Double>: The value against which the specified statistic is compared # * Unit<~String>: The unit for the alarm's associated metric # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_PutMetricAlarm.html # def put_metric_alarm(options) if dimensions = options.delete('Dimensions') options.merge!(AWS.indexed_param('Dimensions.member.%d.Name', dimensions.collect {|dimension| dimension['Name']})) options.merge!(AWS.indexed_param('Dimensions.member.%d.Value', dimensions.collect {|dimension| dimension['Value']})) end if alarm_actions = options.delete('AlarmActions') options.merge!(AWS.indexed_param('AlarmActions.member.%d', [*alarm_actions])) end if insufficient_data_actions = options.delete('InsufficientDataActions') options.merge!(AWS.indexed_param('InsufficientDataActions.member.%d', [*insufficient_data_actions])) end if ok_actions = options.delete('OKActions') options.merge!(AWS.indexed_param('OKActions.member.%d', [*ok_actions])) end request({ 'Action' => 'PutMetricAlarm', :parser => Fog::Parsers::AWS::CloudWatch::PutMetricAlarm.new }.merge(options)) end end class Mock require 'fog/aws/parsers/cloud_watch/put_metric_alarm' # See: Fog::AWS::CloudWatch::Real.put_metric_alarm() # def put_metric_alarm(options) supported_actions = [ "InsufficientDataActions", "OKActions", "AlarmActions" ] found_actions = options.keys.select {|key| supported_actions.include? key } if found_actions.empty? raise Fog::Compute::AWS::Error.new("The request must contain at least one of #{supported_actions.join(", ")}'") end requirements = [ "AlarmName", "ComparisonOperator", "EvaluationPeriods", "Namespace", "Period", "Statistic", "Threshold" ] requirements.each do |req| unless options.has_key?(req) raise Fog::Compute::AWS::Error.new("The request must contain a the parameter '%s'" % req) end end data[:metric_alarms][options['AlarmName']] = { 'AlarmARN' => "arn:aws:cloudwatch:eu-west-1:000000000000:metricAlarm:00000000-0000-0000-0000-000000000000:alarmName/#{options['AlarmName']}", 'ActionsEnabled' => false, 'AlarmActions' => [], 'AlarmConfigurationUpdatedTimestamp' => Time.now.utc.strftime("%Y-%m-%dT%H:%M:%SZ"), 'Dimensions' => [], 'OKActions' => [], }.merge!(options) response = Excon::Response.new response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id } response end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_watch/describe_alarms.rb0000644000004100000410000000405412261242551024336 0ustar www-datawww-datamodule Fog module AWS class CloudWatch class Real require 'fog/aws/parsers/cloud_watch/describe_alarms' # Retrieves alarms with the specified names # ==== Options # * ActionPrefix<~String>: The action name prefix # * AlarmNamePrefix<~String>: The alarm name prefix. # AlarmNames cannot be specified if this parameter is specified # * AlarmNames<~Array>: A list of alarm names to retrieve information for. # * MaxRecords<~Integer>: The maximum number of alarm descriptions to retrieve # * NextToken<~String>: The token returned by a previous call to indicate that there is more data available # * NextToken<~String> The token returned by a previous call to indicate that there is more data available # * StateValue<~String>: The state value to be used in matching alarms # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_DescribeAlarms.html # def describe_alarms(options={}) if alarm_names = options.delete('AlarmNames') options.merge!(AWS.indexed_param('AlarmNames.member.%d', [*alarm_names])) end request({ 'Action' => 'DescribeAlarms', :parser => Fog::Parsers::AWS::CloudWatch::DescribeAlarms.new }.merge(options)) end end class Mock def describe_alarms(options={}) results = { 'MetricAlarms' => [] } data[:metric_alarms].each do |alarm_name, alarm_data| results['MetricAlarms'] << { 'AlarmName' => alarm_name }.merge!(alarm_data) end response = Excon::Response.new response.status = 200 response.body = { 'DescribeAlarmsResult' => results, 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_watch/describe_alarm_history.rb0000644000004100000410000000230412261242551025730 0ustar www-datawww-datamodule Fog module AWS class CloudWatch class Real require 'fog/aws/parsers/cloud_watch/describe_alarm_history' # Retrieves history for the specified alarm # ==== Options # * AlarmName<~String>: The name of the alarm # * EndDate<~DateTime>: The ending date to retrieve alarm history # * HistoryItemType<~String>: The type of alarm histories to retrieve # * MaxRecords<~Integer>: The maximum number of alarm history records to retrieve # * NextToken<~String> The token returned by a previous call to indicate that there is more data available # * StartData<~DateTime>: The starting date to retrieve alarm history # # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/index.html?API_DescribeAlarmHistory.html # def describe_alarm_history(options={}) request({ 'Action' => 'DescribeAlarmHistory', :parser => Fog::Parsers::AWS::CloudWatch::DescribeAlarmHistory.new }.merge(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/0000755000004100000410000000000012261242551020001 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/glacier/set_vault_notification_configuration.rb0000644000004100000410000000242612261242551030035 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # Set a vault's notification configuration # # ==== Parameters # * name<~String> Name of the vault # * SnsTopic<~String> ARN of the topic to notify # * events<~Array> Events you wish to receive. Valid events are ArchiveRetrievalCompleted, InventoryRetrievalCompleted # * options<~Hash> # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-vault-notifications-put.html # def set_vault_notification_configuration(name,sns_topic, events, options={}) account_id = options['account_id'] || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(name)}/notification-configuration" request( :expects => 204, :idempotent => true, :headers => {}, :method => :put, :path => path, :body => Fog::JSON.encode('SNSTopic' => sns_topic, 'Events' => events) ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/create_archive.rb0000644000004100000410000000257612261242551023304 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # Upload an archive # # ==== Parameters # * name<~String> Name of the vault to upload to # * body<~String> The data to upload # * options<~Hash> # * description<~String> - The archive description # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-archive-post.html # def create_archive(vault_name, body, options={}) account_id = options['account_id'] || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(vault_name)}/archives" headers = { 'Content-Length' => body.bytesize.to_s, 'x-amz-content-sha256' => Digest::SHA256.hexdigest(body), 'x-amz-sha256-tree-hash' => Fog::AWS::Glacier::TreeHash.digest(body) } headers['x-amz-archive-description'] = Fog::AWS.escape(options['description']) if options['description'] request( :expects => 201, :headers => headers, :method => :post, :path => path, :body => body ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/initiate_job.rb0000644000004100000410000000301512261242551022765 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # This operation initates a multipart upload of an archive to a vault # # ==== Parameters # * name<~String> The vault name # * job_specification<~Hash> A specification of the job # * Type<~String> The job type. Mandatory. Values: archive-retrieval, inventory-retrieval # * Description<~String> The job description # * ArchiveId<~String> The id of the archive to retrieve (only for Type==archive-retrieval) # * Format<~String> The format to return (only for inventory retrieval). Values: CSV, JSON # * SNSTopic ARN of a topic to publish to when the job is complete # * options<~Hash> # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-initiate-job-post.html # def initiate_job(name, job_specification, options={}) account_id = options['account_id'] || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(name)}/jobs" request({ :expects => 202, :headers => {}, :method => 'POST', :path => path, :body => Fog::JSON.encode(job_specification) }) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/list_vaults.rb0000644000004100000410000000211512261242551022676 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # This operation lists all vaults owned by the calling user’s account. # # ==== Parameters # * options<~Hash> # * limit<~Integer> - The maximum number of items returned in the response. (default 1000) # * marker<~String> - marker used for pagination # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-vaults-get.html # def list_vaults(options={}) account_id = options.delete('account_id') || '-' path = "/#{account_id}/vaults" request( :expects => 200, :idempotent => true, :headers => {}, :method => 'GET', :path => path, :query => options ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/delete_archive.rb0000644000004100000410000000201012261242551023262 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # Delete an archive # # ==== Parameters # * name<~String> Name of the vault to delete # * options<~Hash> # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-vault-delete.html # def delete_archive(name,archive_id,options={}) account_id = options['account_id'] || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(name)}/archives/#{archive_id}" request( :expects => 204, :idempotent => true, :headers => {}, :method => :delete, :path => path ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/create_vault.rb0000644000004100000410000000201412261242551023001 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # This operation creates a new vault with the specified name. . # # ==== Parameters # * name<~String> 1-255 characters. must be unique within a region for an AWS account # * options<~Hash> # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-vault-put.html # def create_vault(name,options={}) account_id = options['account_id'] || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(name)}" request(options.merge({ :expects => 201, :idempotent => true, :headers => {}, :method => :put, :path => path, })) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/initiate_multipart_upload.rb0000644000004100000410000000250212261242551025600 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # This operation initates a multipart upload of an archive to a vault # # ==== Parameters # * name<~String> The vault name # * part_size<~Integer> The part size to use. Must be a power of 2 multiple of 1MB (1,2,4,8,16,...) # * options<~Hash> # * description<~String> - The archive description # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-multipart-initiate-upload.html # def initiate_multipart_upload(name, part_size, options={}) account_id = options['account_id'] || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(name)}/multipart-uploads" headers = {'x-amz-part-size' => part_size.to_s} headers['x-amz-archive-description'] = Fog::AWS.escape(options['description']) if options['description'] request( :expects => 201, :headers => headers, :method => 'POST', :path => path ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/list_parts.rb0000644000004100000410000000241112261242551022510 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # lists the parts of an archive that have been uploaded in a specific multipart upload # # ==== Parameters # * name<~String> Name of the vault # * upload_id<~String> The id of the upload # * options<~Hash> # * limit<~Integer> - The maximum number of items returned in the response. (default 1000) # * marker<~String> - marker used for pagination # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-multipart-list-parts.html # def list_parts(vault_name, upload_id, options={}) account_id = options.delete('account_id') || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(vault_name)}/multipart-uploads/#{Fog::AWS.escape(upload_id)}" request( :expects => 200, :idempotent => true, :headers => {}, :method => :get, :path => path, :query => options ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/list_multipart_uploads.rb0000644000004100000410000000223712261242551025135 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # lists in-progress multipart uploads for the specified vault # # ==== Parameters # * name<~String> Name of the vault # * options<~Hash> # * limit<~Integer> - The maximum number of items returned in the response. (default 1000) # * marker<~String> - marker used for pagination # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-multipart-list-uploads.html # def list_multipart_uploads(vault_name, options={}) account_id = options.delete('account_id') || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(vault_name)}/multipart-uploads" request( :expects => 200, :idempotent => true, :headers => {}, :method => :get, :path => path, :query => options ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/delete_vault.rb0000644000004100000410000000210412261242551023000 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # Delete a vault. Amazon Glacier will delete a vault only if there are no archives in the vault as per the last inventory # and there have been no writes to the vault since the last inventory # # ==== Parameters # * name<~String> Name of the vault to delete # * options<~Hash> # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-vault-delete.html # def delete_vault(name,options={}) account_id = options['account_id'] || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(name)}" request( :expects => 204, :idempotent => true, :headers => {}, :method => :delete, :path => path ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/delete_vault_notification_configuration.rb0000644000004100000410000000174212261242551030504 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # Delete vault's notification configuration # # ==== Parameters # * name<~String> Name of the vault # * options<~Hash> # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-vault-notifications-delete.html # def delete_vault_notification_configuration(name,options={}) account_id = options['account_id'] || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(name)}/notification-configuration" request( :expects => 204, :idempotent => true, :headers => {}, :method => :delete, :path => path ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/complete_multipart_upload.rb0000644000004100000410000000247612261242551025614 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # Complete an upload # # ==== Parameters # * name<~String> Name of the vault to upload to # * upload_id<~String> The id of the upload to complete # * total_size<~Integer> The total archive size # * tree_hash<~String> the treehash for the archive # * options<~Hash> # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-multipart-complete-upload.html # def complete_multipart_upload(vault_name, upload_id, total_size, tree_hash, options={}) account_id = options['account_id'] || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(vault_name)}/multipart-uploads/#{upload_id}" headers = { 'x-amz-archive-size' => total_size.to_s, 'x-amz-sha256-tree-hash' => tree_hash } request( :expects => 201, :idempotent => true, :headers => headers, :method => :post, :path => path ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/list_jobs.rb0000644000004100000410000000250412261242551022317 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # lists in-progress and recently jobs for the specified vault # # ==== Parameters # * name<~String> Name of the vault # * options<~Hash> # * completed<~Boolean>Specifies the state of the jobs to return. You can specify true or false # * statuscode<~String> Filter returned jobs by status (InProgress, Succeeded, or Failed) # * limit<~Integer> - The maximum number of items returned in the response. (default 1000) # * marker<~String> - marker used for pagination # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # ==== See Also #http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-jobs-get.html # def list_jobs(vault_name, options={}) account_id = options.delete('account_id') || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(vault_name)}/jobs" request( :expects => 200, :idempotent => true, :headers => {}, :method => :get, :path => path, :query => options ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/abort_multipart_upload.rb0000644000004100000410000000203512261242551025102 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # Abort an upload # # ==== Parameters # * name<~String> Name of the vault to upload to # * upload_id<~String> The id of the upload to complete # * options<~Hash> # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-multipart-abort-upload.html # def abort_multipart_upload(vault_name, upload_id, options={}) account_id = options['account_id'] || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(vault_name)}/multipart-uploads/#{upload_id}" request( :expects => 204, :idempotent => true, :headers => {}, :method => :delete, :path => path ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/get_job_output.rb0000644000004100000410000000245012261242551023360 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # Get the output from a job # # ==== Parameters # * name<~String> Name of the vault # * job_id<~String> The id of the job # * options<~Hash> # * Range<~Range> The range to retrieve # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # * response_block<~Proc> Proc to use for streaming the response # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-job-output-get.html # def get_job_output(vault_name, job_id, options={}) account_id = options.delete('account_id') || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(vault_name)}/jobs/#{job_id}/output" headers = {} if range = options.delete('Range') headers['Range'] = "bytes=#{range.begin}-#{range.end}" end request( options.merge( :expects => [200,206], :idempotent => true, :headers => headers, :method => :get, :path => path )) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/upload_part.rb0000644000004100000410000000300012261242551022631 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # Upload an archive # # ==== Parameters # * name<~String> Name of the vault to upload to # * uploadId<~String> Id of the upload # * body<~String> The data to upload # * offset<~Integer> The offset of the data within the archive # * hash<~String> The tree hash for this part # * options<~Hash> # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-upload-part.html # def upload_part(vault_name, upload_id, body, offset, hash, options={}) account_id = options['account_id'] || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(vault_name)}/multipart-uploads/#{Fog::AWS.escape(upload_id)}" headers = { 'Content-Length' => body.bytesize.to_s, 'Content-Range' => "bytes #{offset}-#{offset+body.bytesize-1}/*", 'x-amz-content-sha256' => Digest::SHA256.hexdigest(body), 'x-amz-sha256-tree-hash' => hash } request( :expects => 204, :idempotent => true, :headers => headers, :method => :put, :path => path, :body => body ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/get_vault_notification_configuration.rb0000644000004100000410000000176312261242551030024 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # Get a vault's notification configuration # # ==== Parameters # * name<~String> Name of the vault # * options<~Hash> # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-vault-notifications-get.html # def get_vault_notification_configuration(name,options={}) account_id = options['account_id'] || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(name)}/notification-configuration" request( :expects => 200, :idempotent => true, :headers => {}, :method => :get, :path => path ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/describe_vault.rb0000644000004100000410000000166512261242551023331 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # This operation returns information about a vault # # ==== Parameters # * name<~String> Vault name # * options<~Hash> # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-vault-get.html # def describe_vault(name,options={}) account_id = options['account_id'] || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(name)}" request( :expects => 200, :idempotent => true, :headers => {}, :method => :get, :path => path ) end end end end end fog-1.19.0/lib/fog/aws/requests/glacier/describe_job.rb0000644000004100000410000000173312261242551022744 0ustar www-datawww-datamodule Fog module AWS class Glacier class Real # Complete an upload # # ==== Parameters # * name<~String> Name of the vault # * job_id<~String> The id of the job # * options<~Hash> # * account_id<~String> - The AWS account id. Defaults to the account owning the credentials making the request # ==== Returns # * response<~Excon::Response>: # # ==== See Also # http://docs.amazonwebservices.com/amazonglacier/latest/dev/api-describe-job-get.html # def describe_job(vault_name, job_id, options={}) account_id = options['account_id'] || '-' path = "/#{account_id}/vaults/#{Fog::AWS.escape(vault_name)}/jobs/#{job_id}" request( :expects => 200, :idempotent => true, :headers => {}, :method => :get, :path => path ) end end end end end fog-1.19.0/lib/fog/aws/requests/ses/0000755000004100000410000000000012261242551017165 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/ses/delete_verified_email_address.rb0000644000004100000410000000143712261242551025512 0ustar www-datawww-datamodule Fog module AWS class SES class Real require 'fog/aws/parsers/ses/delete_verified_email_address' # Delete an existing verified email address # # ==== Parameters # * email_address<~String> - Email Address to be removed # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def delete_verified_email_address(email_address) request({ 'Action' => 'DeleteVerifiedEmailAddress', 'EmailAddress' => email_address, :parser => Fog::Parsers::AWS::SES::DeleteVerifiedEmailAddress.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/ses/list_verified_email_addresses.rb0000644000004100000410000000135112261242551025546 0ustar www-datawww-datamodule Fog module AWS class SES class Real require 'fog/aws/parsers/ses/list_verified_email_addresses' # Returns a list containing all of the email addresses that have been verified # # ==== Parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'VerifiedEmailAddresses' <~Array> # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def list_verified_email_addresses request({ 'Action' => 'ListVerifiedEmailAddresses', :parser => Fog::Parsers::AWS::SES::ListVerifiedEmailAddresses.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/ses/get_send_statistics.rb0000644000004100000410000000164312261242551023560 0ustar www-datawww-datamodule Fog module AWS class SES class Real require 'fog/aws/parsers/ses/get_send_statistics' # Returns the user's current activity limits. # # ==== Parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'GetSendStatisticsResult'<~Hash> # * 'SendDataPoints' <~Array> # * 'Bounces' <~String> # * 'Complaints' <~String> # * 'DeliveryAttempts' <~String> # * 'Rejects' <~String> # * 'Timestamp' <~String> # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def get_send_statistics request({ 'Action' => 'GetSendStatistics', :parser => Fog::Parsers::AWS::SES::GetSendStatistics.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/ses/send_raw_email.rb0000644000004100000410000000246312261242551022470 0ustar www-datawww-datamodule Fog module AWS class SES class Real require 'fog/aws/parsers/ses/send_raw_email' # Send a raw email # # ==== Parameters # * RawMessage <~String> - The message to be sent. # * Options <~Hash> # * Source <~String> - The sender's email address. Takes precenence over Return-Path if specified in RawMessage # * Destinations <~Array> - All destinations for this email. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'MessageId'<~String> - Id of message # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def send_raw_email(raw_message, options = {}) params = {} if options.has_key?('Destinations') params.merge!(Fog::AWS.indexed_param('Destinations.member', [*options['Destinations']])) end if options.has_key?('Source') params['Source'] = options['Source'] end request({ 'Action' => 'SendRawEmail', 'RawMessage.Data' => Base64.encode64(raw_message.to_s).chomp!, :parser => Fog::Parsers::AWS::SES::SendRawEmail.new }.merge(params)) end end end end end fog-1.19.0/lib/fog/aws/requests/ses/verify_domain_identity.rb0000644000004100000410000000162312261242551024260 0ustar www-datawww-datamodule Fog module AWS class SES class Real require 'fog/aws/parsers/ses/verify_domain_identity' # Verifies a domain. This action returns a verification authorization # token which must be added as a DNS TXT record to the domain. # # ==== Parameters # * domain<~String> - The domain to be verified # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'VerificationToken'<~String> - Verification token # * 'RequestId'<~String> - Id of request def verify_domain_identity(domain) request({ 'Action' => 'VerifyDomainIdentity', 'Domain' => domain, :parser => Fog::Parsers::AWS::SES::VerifyDomainIdentity.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/ses/send_email.rb0000644000004100000410000000527712261242551021625 0ustar www-datawww-datamodule Fog module AWS class SES class Real require 'fog/aws/parsers/ses/send_email' # Send an email # # ==== Parameters # * Source <~String> - The sender's email address # * Destination <~Hash> - The destination for this email, composed of To:, From:, and CC: fields. # * BccAddresses <~Array> - The BCC: field(s) of the message. # * CcAddresses <~Array> - The CC: field(s) of the message. # * ToAddresses <~Array> - The To: field(s) of the message. # * Message <~Hash> - The message to be sent. # * Body <~Hash> # * Html <~Hash> # * Charset <~String> # * Data <~String> # * Text <~Hash> # * Charset <~String> # * Data <~String> # * Subject <~Hash> # * Charset <~String> # * Data <~String> # * options <~Hash>: # * ReplyToAddresses <~Array> - The reply-to email address(es) for the message. If the recipient replies to the message, each reply-to address will receive the reply. # * ReturnPath <~String> - The email address to which bounce notifications are to be forwarded. If the message cannot be delivered to the recipient, then an error message will be returned from the recipient's ISP; this message will then be forwarded to the email address specified by the ReturnPath parameter. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'MessageId'<~String> - Id of message # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def send_email(source, destination, message, options = {}) params = { 'Source' => source } for key, values in destination params.merge!(Fog::AWS.indexed_param("Destination.#{key}.member", [*values])) end for key, value in message['Subject'] params["Message.Subject.#{key}"] = value end for type, data in message['Body'] for key, value in data params["Message.Body.#{type}.#{key}"] = value end end if options.has_key?('ReplyToAddresses') params.merge!(Fog::AWS.indexed_param("ReplyToAddresses.member", [*options['ReplyToAddresses']])) end if options.has_key?('ReturnPath') params['ReturnPath'] = options['ReturnPath'] end request({ 'Action' => 'SendEmail', :parser => Fog::Parsers::AWS::SES::SendEmail.new }.merge(params)) end end end end end fog-1.19.0/lib/fog/aws/requests/ses/verify_email_address.rb0000644000004100000410000000151012261242551023667 0ustar www-datawww-datamodule Fog module AWS class SES class Real require 'fog/aws/parsers/ses/verify_email_address' # Verifies an email address. This action causes a confirmation email message to be sent to the specified address. # # ==== Parameters # * email_address<~String> - The email address to be verified # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def verify_email_address(email_address) request({ 'Action' => 'VerifyEmailAddress', 'EmailAddress' => email_address, :parser => Fog::Parsers::AWS::SES::VerifyEmailAddress.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/ses/get_send_quota.rb0000644000004100000410000000141412261242551022513 0ustar www-datawww-datamodule Fog module AWS class SES class Real require 'fog/aws/parsers/ses/get_send_quota' # Returns the user's current activity limits. # # ==== Parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'GetSendQuotaResult'<~Hash> # * 'Max24HourSend' <~String> # * 'MaxSendRate' <~String> # * 'SentLast24Hours' <~String> # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def get_send_quota request({ 'Action' => 'GetSendQuota', :parser => Fog::Parsers::AWS::SES::GetSendQuota.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/dns/0000755000004100000410000000000012261242551017157 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/dns/list_resource_record_sets.rb0000644000004100000410000001036112261242551024763 0ustar www-datawww-datamodule Fog module DNS class AWS class Real require 'fog/aws/parsers/dns/list_resource_record_sets' # list your resource record sets # # ==== Parameters # * zone_id<~String> - # * options<~Hash> # * type<~String> - # * name<~String> - # * identifier<~String> - # * max_items<~Integer> - # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResourceRecordSet'<~Array>: # * 'Name'<~String> - # * 'Type'<~String> - # * 'TTL'<~Integer> - # * 'AliasTarget'<~Hash> - # * 'HostedZoneId'<~String> - # * 'DNSName'<~String> - # * 'ResourceRecords'<~Array> # * 'Value'<~String> - # * 'IsTruncated'<~String> - # * 'MaxItems'<~String> - # * 'NextRecordName'<~String> # * 'NextRecordType'<~String> # * 'NextRecordIdentifier'<~String> # * status<~Integer> - 201 when successful def list_resource_record_sets(zone_id, options = {}) # AWS methods return zone_ids that looks like '/hostedzone/id'. Let the caller either use # that form or just the actual id (which is what this request needs) zone_id = zone_id.sub('/hostedzone/', '') parameters = {} options.each do |option, value| case option when :type, :name, :identifier parameters[option] = "#{value}" when :max_items parameters['maxitems'] = "#{value}" end end request({ :query => parameters, :parser => Fog::Parsers::DNS::AWS::ListResourceRecordSets.new, :expects => 200, :method => 'GET', :path => "hostedzone/#{zone_id}/rrset" }) end end class Mock def list_resource_record_sets(zone_id, options = {}) maxitems = [options[:max_items]||100,100].min response = Excon::Response.new zone = self.data[:zones][zone_id] if zone.nil? response.status = 404 response.body = "\nSenderNoSuchHostedZoneNo hosted zone found with ID: #{zone_id}#{Fog::AWS::Mock.request_id}" raise(Excon::Errors.status_error({:expects => 200}, response)) end if options[:type] records = zone[:records][options[:type]].values else records = zone[:records].values.map{|r| r.values}.flatten end # sort for pagination records.sort! { |a,b| a[:name].gsub(zone[:name],"") <=> b[:name].gsub(zone[:name],"") } if options[:name] name = options[:name].gsub(zone[:name],"") records = records.select{|r| r[:name].gsub(zone[:name],"") >= name } require 'pp' end next_record = records[maxitems] records = records[0, maxitems] truncated = !next_record.nil? response.status = 200 response.body = { 'ResourceRecordSets' => records.map do |r| if r[:alias_target] record = { 'AliasTarget' => { 'HostedZoneId' => r[:alias_target][:hosted_zone_id], 'DNSName' => r[:alias_target][:dns_name] } } else record = { 'TTL' => r[:ttl] } end { 'ResourceRecords' => r[:resource_records], 'Name' => r[:name], 'Type' => r[:type] }.merge(record) end, 'MaxItems' => maxitems, 'IsTruncated' => truncated } if truncated response.body['NextRecordName'] = next_record[:name] response.body['NextRecordType'] = next_record[:type] end response end end end end end fog-1.19.0/lib/fog/aws/requests/dns/list_hosted_zones.rb0000644000004100000410000000511112261242551023241 0ustar www-datawww-datamodule Fog module DNS class AWS class Real require 'fog/aws/parsers/dns/list_hosted_zones' # Describe all or specified instances # # ==== Parameters # * options<~Hash> # * marker<~String> - Indicates where to begin in your list of hosted zones. # * max_items<~Integer> - The maximum number of hosted zones to be included in the response body # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'HostedZones'<~Array>: # * 'HostedZone'<~Hash>: # * 'Id'<~String> - # * 'Name'<~String> - # * 'CallerReference'<~String> # * 'Comment'<~String> - # * 'Marker'<~String> - # * 'MaxItems'<~Integer> - # * 'IsTruncated'<~String> - # * 'NextMarket'<~String> # * status<~Integer> - 200 when successful def list_hosted_zones(options = {}) parameters = {} options.each do |option, value| case option when :marker parameters[option] = value when :max_items parameters[:maxitems] = value end end request({ :query => parameters, :parser => Fog::Parsers::DNS::AWS::ListHostedZones.new, :expects => 200, :method => 'GET', :path => "hostedzone" }) end end class Mock def list_hosted_zones(options = {}) maxitems = [options[:max_items]||100,100].min if options[:marker].nil? start = 0 else start = self.data[:zones].find_index {|z| z[:id] == options[:marker]} end zones = self.data[:zones].values[start, maxitems] next_zone = self.data[:zones].values[start + maxitems] truncated = !next_zone.nil? response = Excon::Response.new response.status = 200 response.body = { 'HostedZones' => zones.map do |z| { 'Id' => z[:id], 'Name' => z[:name], 'CallerReference' => z[:reference], 'Comment' => z[:comment], } end, 'Marker' => options[:marker].to_s, 'MaxItems' => maxitems, 'IsTruncated' => truncated } if truncated response.body['NextMarker'] = next_zone[:id] end response end end end end end fog-1.19.0/lib/fog/aws/requests/dns/get_hosted_zone.rb0000644000004100000410000000422512261242551022667 0ustar www-datawww-datamodule Fog module DNS class AWS class Real require 'fog/aws/parsers/dns/get_hosted_zone' # retrieve information about a hosted zone # # ==== Parameters # * zone_id<~String> - The ID of the hosted zone # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'HostedZone'<~Hash>: # * 'Id'<~String> - # * 'Name'<~String> - # * 'CallerReference'<~String> # * 'Comment'<~String> - # * 'NameServers'<~Array> # * 'NameServer'<~String> # * status<~Integer> - 200 when successful def get_hosted_zone(zone_id) # AWS methods return zone_ids that looks like '/hostedzone/id'. Let the caller either use # that form or just the actual id (which is what this request needs) zone_id = zone_id.sub('/hostedzone/', '') request({ :expects => 200, :parser => Fog::Parsers::DNS::AWS::GetHostedZone.new, :method => 'GET', :path => "hostedzone/#{zone_id}" }) end end class Mock def get_hosted_zone(zone_id) response = Excon::Response.new if (zone = self.data[:zones][zone_id]) response.status = 200 response.body = { 'HostedZone' => { 'Id' => zone[:id], 'Name' => zone[:name], 'CallerReference' => zone[:reference], 'Comment' => zone[:comment] }, 'NameServers' => Fog::AWS::Mock.nameservers } response else response.status = 404 response.body = "SenderNoSuchHostedZoneThe specified hosted zone does not exist.#{Fog::AWS::Mock.request_id}" raise(Excon::Errors.status_error({:expects => 200}, response)) end end end end end end fog-1.19.0/lib/fog/aws/requests/dns/delete_hosted_zone.rb0000644000004100000410000000453412261242551023355 0ustar www-datawww-datamodule Fog module DNS class AWS class Real require 'fog/aws/parsers/dns/delete_hosted_zone' # Delete a hosted zone # # ==== Parameters # * zone_id<~String> - # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ChangeInfo'<~Hash> - # * 'Id'<~String> The ID of the request # * 'Status'<~String> The current state of the hosted zone # * 'SubmittedAt'<~String> The date and time the change was made # * status<~Integer> - 200 when successful def delete_hosted_zone(zone_id) # AWS methods return zone_ids that looks like '/hostedzone/id'. Let the caller either use # that form or just the actual id (which is what this request needs) zone_id = zone_id.sub('/hostedzone/', '') request({ :expects => 200, :parser => Fog::Parsers::DNS::AWS::DeleteHostedZone.new, :method => 'DELETE', :path => "hostedzone/#{zone_id}" }) end end class Mock require 'time' def delete_hosted_zone(zone_id) response = Excon::Response.new key = [zone_id, "/hostedzone/#{zone_id}"].find{|k| !self.data[:zones][k].nil?} if key change = { :id => Fog::AWS::Mock.change_id, :status => 'INSYNC', :submitted_at => Time.now.utc.iso8601 } self.data[:changes][change[:id]] = change response.status = 200 response.body = { 'ChangeInfo' => { 'Id' => change[:id], 'Status' => change[:status], 'SubmittedAt' => change[:submitted_at] } } self.data[:zones].delete(key) response else response.status = 404 response.body = "SenderNoSuchHostedZoneThe specified hosted zone does not exist.#{Fog::AWS::Mock.request_id}" raise(Excon::Errors.status_error({:expects => 200}, response)) end end end end end end fog-1.19.0/lib/fog/aws/requests/dns/create_hosted_zone.rb0000644000004100000410000001073212261242551023353 0ustar www-datawww-datamodule Fog module DNS class AWS class Real require 'fog/aws/parsers/dns/create_hosted_zone' # Creates a new hosted zone # # ==== Parameters # * name<~String> - The name of the domain. Must be a fully-specified domain that ends with a period # * options<~Hash> # * caller_ref<~String> - unique string that identifies the request & allows failed # calls to be retried without the risk of executing the operation twice # * comment<~String> - # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'HostedZone'<~Hash>: # * 'Id'<~String> - # * 'Name'<~String> - # * 'CallerReference'<~String> # * 'Comment'<~String> - # * 'ChangeInfo'<~Hash> - # * 'Id'<~String> # * 'Status'<~String> # * 'SubmittedAt'<~String> # * 'NameServers'<~Array> # * 'NameServer'<~String> # * status<~Integer> - 201 when successful def create_hosted_zone(name, options = {}) optional_tags = '' if options[:caller_ref] optional_tags += "#{options[:caller_ref]}" else #make sure we have a unique call reference caller_ref = "ref-#{rand(1000000).to_s}" optional_tags += "#{caller_ref}" end if options[:comment] optional_tags += "#{options[:comment]}" end request({ :body => %Q{#{name}#{optional_tags}}, :parser => Fog::Parsers::DNS::AWS::CreateHostedZone.new, :expects => 201, :method => 'POST', :path => "hostedzone" }) end end class Mock require 'time' def create_hosted_zone(name, options = {}) # Append a trailing period to the name if absent. name = name + "." unless name.end_with?(".") response = Excon::Response.new if list_hosted_zones.body['HostedZones'].find_all {|z| z['Name'] == name}.size < self.data[:limits][:duplicate_domains] response.status = 201 if options[:caller_ref] caller_ref = options[:caller_ref] else #make sure we have a unique call reference caller_ref = "ref-#{rand(1000000).to_s}" end zone_id = "/hostedzone/#{Fog::AWS::Mock.zone_id}" self.data[:zones][zone_id] = { :id => zone_id, :name => name, :reference => caller_ref, :comment => options[:comment], :records => {} } change = { :id => Fog::AWS::Mock.change_id, :status => 'PENDING', :submitted_at => Time.now.utc.iso8601 } self.data[:changes][change[:id]] = change response.body = { 'HostedZone' => { 'Id' => zone_id, 'Name' => name, 'CallerReference' => caller_ref, 'Comment' => options[:comment] }, 'ChangeInfo' => { 'Id' => change[:id], 'Status' => change[:status], 'SubmittedAt' => change[:submitted_at] }, 'NameServers' => Fog::AWS::Mock.nameservers } response else response.status = 400 response.body = "DelegationSetNotAvailableAmazon Route 53 allows some duplication, but Amazon Route 53 has a maximum threshold of duplicated domains. This error is generated when you reach that threshold. In this case, the error indicates that too many hosted zones with the given domain name exist. If you want to create a hosted zone and Amazon Route 53 generates this error, contact Customer Support.#{Fog::AWS::Mock.request_id}" raise(Excon::Errors.status_error({:expects => 200}, response)) end end end end end end fog-1.19.0/lib/fog/aws/requests/dns/change_resource_record_sets.rb0000644000004100000410000002336412261242551025244 0ustar www-datawww-datamodule Fog module DNS class AWS class Real require 'fog/aws/parsers/dns/change_resource_record_sets' # Use this action to create or change your authoritative DNS information for a zone # http://docs.amazonwebservices.com/Route53/latest/DeveloperGuide/RRSchanges.html#RRSchanges_API # # ==== Parameters # * zone_id<~String> - ID of the zone these changes apply to # * options<~Hash> # * comment<~String> - Any comments you want to include about the change. # * change_batch<~Array> - The information for a change request # * changes<~Hash> - # * action<~String> - 'CREATE' or 'DELETE' # * name<~String> - This must be a fully-specified name, ending with a final period # * type<~String> - A | AAAA | CNAME | MX | NS | PTR | SOA | SPF | SRV | TXT # * ttl<~Integer> - Time-to-live value - omit if using an alias record # * resource_records<~Array> - Omit if using an alias record # * alias_target<~Hash> - Information about the domain to which you are redirecting traffic (Alias record sets only) # * dns_name<~String> - The Elastic Load Balancing domain to which you want to reroute traffic # * hosted_zone_id<~String> - The ID of the hosted zone that contains the Elastic Load Balancing domain to which you want to reroute traffic # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ChangeInfo'<~Hash> # * 'Id'<~String> - The ID of the request # * 'Status'<~String> - status of the request - PENDING | INSYNC # * 'SubmittedAt'<~String> - The date and time the change was made # * status<~Integer> - 200 when successful # # ==== Examples # # Example changing a CNAME record: # # change_batch_options = [ # { # :action => "DELETE", # :name => "foo.example.com.", # :type => "CNAME", # :ttl => 3600, # :resource_records => [ "baz.example.com." ] # }, # { # :action => "CREATE", # :name => "foo.example.com.", # :type => "CNAME", # :ttl => 3600, # :resource_records => [ "bar.example.com." ] # } # ] # # change_resource_record_sets("ABCDEFGHIJKLMN", change_batch_options) # def change_resource_record_sets(zone_id, change_batch, options = {}) # AWS methods return zone_ids that looks like '/hostedzone/id'. Let the caller either use # that form or just the actual id (which is what this request needs) zone_id = zone_id.sub('/hostedzone/', '') optional_tags = '' options.each do |option, value| case option when :comment optional_tags += "#{value}" end end #build XML if change_batch.count > 0 changes = "#{optional_tags}" change_batch.each do |change_item| action_tag = %Q{#{change_item[:action]}} name_tag = %Q{#{change_item[:name]}} type_tag = %Q{#{change_item[:type]}} # TTL must be omitted if using an alias record ttl_tag = '' ttl_tag += %Q{#{change_item[:ttl]}} unless change_item[:alias_target] weight_tag = '' set_identifier_tag = '' region_tag = '' if change_item[:set_identifier] set_identifier_tag += %Q{#{change_item[:set_identifier]}} if change_item[:weight] # Weighted Record weight_tag += %Q{#{change_item[:weight]}} elsif change_item[:region] # Latency record region_tag += %Q{#{change_item[:region]}} end end resource_records = change_item[:resource_records] || [] resource_record_tags = '' resource_records.each do |record| resource_record_tags += %Q{#{record}} end # ResourceRecords must be omitted if using an alias record resource_tag = '' resource_tag += %Q{#{resource_record_tags}} if resource_records.any? alias_target_tag = '' if change_item[:alias_target] # Accept either underscore or camel case for hash keys. dns_name = change_item[:alias_target][:dns_name] || change_item[:alias_target][:DNSName] hosted_zone_id = change_item[:alias_target][:hosted_zone_id] || change_item[:alias_target][:HostedZoneId] || AWS.hosted_zone_for_alias_target(dns_name) alias_target_tag += %Q{#{hosted_zone_id}#{dns_name}} end change_tags = %Q{#{action_tag}#{name_tag}#{type_tag}#{set_identifier_tag}#{weight_tag}#{region_tag}#{ttl_tag}#{resource_tag}#{alias_target_tag}} changes += change_tags end changes += '' end body = %Q{#{changes}} request({ :body => body, :parser => Fog::Parsers::DNS::AWS::ChangeResourceRecordSets.new, :expects => 200, :method => 'POST', :path => "hostedzone/#{zone_id}/rrset" }) end end class Mock def change_resource_record_sets(zone_id, change_batch, options = {}) response = Excon::Response.new errors = [] if (zone = self.data[:zones][zone_id]) response.status = 200 change_id = Fog::AWS::Mock.change_id change_batch.each do |change| case change[:action] when "CREATE" if zone[:records][change[:type]].nil? zone[:records][change[:type]] = {} end if zone[:records][change[:type]][change[:name]].nil? # raise change.to_s if change[:resource_records].nil? zone[:records][change[:type]][change[:name]] = if change[:alias_target] record = { :alias_target => change[:alias_target] } else record = { :ttl => change[:ttl].to_s, } end zone[:records][change[:type]][change[:name]] = { :change_id => change_id, :resource_records => change[:resource_records] || [], :name => change[:name], :type => change[:type] }.merge(record) else errors << "Tried to create resource record set #{change[:name]}. type #{change[:type]}, but it already exists" end when "DELETE" if zone[:records][change[:type]].nil? || zone[:records][change[:type]].delete(change[:name]).nil? errors << "Tried to delete resource record set #{change[:name]}. type #{change[:type]}, but it was not found" end end end if errors.empty? change = { :id => change_id, :status => 'PENDING', :submitted_at => Time.now.utc.iso8601 } self.data[:changes][change[:id]] = change response.body = { 'Id' => change[:id], 'Status' => change[:status], 'SubmittedAt' => change[:submitted_at] } response else response.status = 400 response.body = "#{errors.map {|e| "#{e}"}.join()}" raise(Excon::Errors.status_error({:expects => 200}, response)) end else response.status = 404 response.body = "NoSuchHostedZoneA hosted zone with the specified hosted zone ID does not exist.#{Fog::AWS::Mock.request_id}" raise(Excon::Errors.status_error({:expects => 200}, response)) end end end def self.hosted_zone_for_alias_target(dns_name) k = elb_hosted_zone_mapping.keys.find do |k| dns_name =~ /\A.+\.#{k}\.elb\.amazonaws\.com\.?\z/ end elb_hosted_zone_mapping[k] end def self.elb_hosted_zone_mapping @elb_hosted_zone_mapping ||= { "ap-northeast-1" => "Z2YN17T5R711GT", "ap-southeast-1" => "Z1WI8VXHPB1R38", "ap-southeast-2" => "Z2999QAZ9SRTIC", "eu-west-1" => "Z3NF1Z3NOM5OY2", "sa-east-1" => "Z2ES78Y61JGQKS", "us-east-1" => "Z3DZXE0Q79N41H", "us-west-1" => "Z1M58G0W56PQJA", "us-west-2" => "Z33MTJ483KN6FU", } end end end end fog-1.19.0/lib/fog/aws/requests/dns/get_change.rb0000644000004100000410000000420112261242551021565 0ustar www-datawww-datamodule Fog module DNS class AWS class Real require 'fog/aws/parsers/dns/get_change' # returns the current state of a change request # # ==== Parameters # * change_id<~String> # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Id'<~String> # * 'Status'<~String> # * 'SubmittedAt'<~String> # * status<~Integer> - 200 when successful def get_change(change_id) # AWS methods return change_ids that looks like '/change/id'. Let the caller either use # that form or just the actual id (which is what this request needs) change_id = change_id.sub('/change/', '') request({ :expects => 200, :parser => Fog::Parsers::DNS::AWS::GetChange.new, :method => 'GET', :path => "change/#{change_id}" }) end end class Mock def get_change(change_id) response = Excon::Response.new # find the record with matching change_id # records = data[:zones].values.map{|z| z[:records].values.map{|r| r.values}}.flatten change = self.data[:changes][change_id] if change response.status = 200 submitted_at = Time.parse(change[:submitted_at]) response.body = { 'Id' => change[:id], # set as insync after some time 'Status' => (submitted_at + Fog::Mock.delay) < Time.now ? 'INSYNC' : change[:status], 'SubmittedAt' => change[:submitted_at] } response else response.status = 404 response.body = "SenderNoSuchChangeCould not find resource with ID: #{change_id}#{Fog::AWS::Mock.request_id}" raise(Excon::Errors.status_error({:expects => 200}, response)) end end end end end end fog-1.19.0/lib/fog/aws/requests/elb/0000755000004100000410000000000012261242551017135 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/elb/enable_availability_zones_for_load_balancer.rb0000644000004100000410000000414312261242551030356 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/enable_availability_zones_for_load_balancer' # Enable an availability zone for an existing ELB # # ==== Parameters # * availability_zones<~Array> - List of availability zones to enable on ELB # * lb_name<~String> - Load balancer to enable availability zones on # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'EnableAvailabilityZonesForLoadBalancerResult'<~Hash>: # * 'AvailabilityZones'<~Array> - array of strings describing instances currently enabled def enable_availability_zones_for_load_balancer(availability_zones, lb_name) params = Fog::AWS.indexed_param('AvailabilityZones.member', [*availability_zones]) request({ 'Action' => 'EnableAvailabilityZonesForLoadBalancer', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::EnableAvailabilityZonesForLoadBalancer.new }.merge!(params)) end alias :enable_zones :enable_availability_zones_for_load_balancer end class Mock def enable_availability_zones_for_load_balancer(availability_zones, lb_name) raise Fog::AWS::ELB::NotFound unless load_balancer = self.data[:load_balancers][lb_name] response = Excon::Response.new response.status = 200 load_balancer['AvailabilityZones'] << availability_zones load_balancer['AvailabilityZones'].flatten!.uniq! response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'EnableAvailabilityZonesForLoadBalancerResult' => { 'AvailabilityZones' => load_balancer['AvailabilityZones'] } } response end alias :enable_zones :enable_availability_zones_for_load_balancer end end end end fog-1.19.0/lib/fog/aws/requests/elb/create_load_balancer_policy.rb0000644000004100000410000000642312261242551025137 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/empty' # Create Elastic Load Balancer Policy # # ==== Parameters # * lb_name<~String> - The name associated with the LoadBalancer for which the policy is being created. This name must be unique within the client AWS account. # * attributes<~Hash> - A list of attributes associated with the policy being created. # * 'AttributeName'<~String> - The name of the attribute associated with the policy. # * 'AttributeValue'<~String> - The value of the attribute associated with the policy. # * name<~String> - The name of the LoadBalancer policy being created. The name must be unique within the set of policies for this LoadBalancer. # * type_name<~String> - The name of the base policy type being used to create this policy. To get the list of policy types, use the DescribeLoadBalancerPolicyTypes action. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def create_load_balancer_policy(lb_name, name, type_name, attributes = {}) params = {} attribute_name = [] attribute_value = [] attributes.each do |name, value| attribute_name.push(name) attribute_value.push(value) end params.merge!(Fog::AWS.indexed_param('PolicyAttributes.member.%d.AttributeName', attribute_name)) params.merge!(Fog::AWS.indexed_param('PolicyAttributes.member.%d.AttributeValue', attribute_value)) request({ 'Action' => 'CreateLoadBalancerPolicy', 'LoadBalancerName' => lb_name, 'PolicyName' => name, 'PolicyTypeName' => type_name, :parser => Fog::Parsers::AWS::ELB::Empty.new }.merge!(params)) end end class Mock def create_load_balancer_policy(lb_name, name, type_name, attributes = {}) if load_balancer = self.data[:load_balancers][lb_name] raise Fog::AWS::ELB::DuplicatePolicyName, name if policy = load_balancer['Policies']['Proper'].find { |p| p['PolicyName'] == name } raise Fog::AWS::ELB::PolicyTypeNotFound, type_name unless policy_type = self.data[:policy_types].find { |pt| pt['PolicyTypeName'] == type_name } response = Excon::Response.new attributes = attributes.map do |key, value| if key == "CookieExpirationPeriod" && !value value = 0 end {"AttributeName" => key, "AttributeValue" => value.to_s} end load_balancer['Policies']['Proper'] << { 'PolicyAttributeDescriptions' => attributes, 'PolicyName' => name, 'PolicyTypeName' => type_name } response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response else raise Fog::AWS::ELB::NotFound end end end end end end fog-1.19.0/lib/fog/aws/requests/elb/set_load_balancer_listener_ssl_certificate.rb0000644000004100000410000000524412261242551030240 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/empty' # Sets the certificate that terminates the specified listener's SSL # connections. The specified certificate replaces any prior certificate # that was used on the same LoadBalancer and port. # # ==== Parameters # * lb_name<~String> - Name of the ELB # * load_balancer_port<~Integer> - The external port of the LoadBalancer # with which this policy has to be associated. # * ssl_certificate_id<~String> - ID of the SSL certificate chain to use # example: arn:aws:iam::322191361670:server-certificate/newCert # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def set_load_balancer_listener_ssl_certificate(lb_name, load_balancer_port, ssl_certificate_id) request({ 'Action' => 'SetLoadBalancerListenerSSLCertificate', 'LoadBalancerName' => lb_name, 'LoadBalancerPort' => load_balancer_port, 'SSLCertificateId' => ssl_certificate_id, :parser => Fog::Parsers::AWS::ELB::Empty.new }) end end class Mock def set_load_balancer_listener_ssl_certificate(lb_name, load_balancer_port, ssl_certificate_id) raise Fog::AWS::ELB::NotFound unless load_balancer = self.data[:load_balancers][lb_name] certificate_ids = Fog::AWS::IAM::Mock.data[@aws_access_key_id][:server_certificates].map {|n, c| c['Arn'] } if !certificate_ids.include? ssl_certificate_id raise Fog::AWS::IAM::NotFound.new('CertificateNotFound') end response = Excon::Response.new unless listener = load_balancer['ListenerDescriptions'].find { |listener| listener['Listener']['LoadBalancerPort'] == load_balancer_port } response.status = 400 response.body = "ListenerNotFoundLoadBalancer does not have a listnener configured at the given port.#{Fog::AWS::Mock.request_id}" raise Excon::Errors.status_error({:expects => 200}, response) end listener['Listener']['SSLCertificateId'] = ssl_certificate_id response.status = 200 response.body = { "ResponseMetadata" => { "RequestId" => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/elb/describe_load_balancer_policies.rb0000644000004100000410000000534112261242551025762 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/describe_load_balancer_policies' # Describe all or specified load balancer policies # # ==== Parameters # * lb_name<~String> - The mnemonic name associated with the LoadBalancer. If no name is specified, the operation returns the attributes of either all the sample policies pre-defined by Elastic Load Balancing or the specified sample polices. # * names<~Array> - The names of LoadBalancer policies you've created or Elastic Load Balancing sample policy names. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeLoadBalancerPoliciesResult'<~Hash>: # * 'PolicyDescriptions'<~Array> # * 'PolicyAttributeDescriptions'<~Array> # * 'AttributeName'<~String> - The name of the attribute associated with the policy. # * 'AttributeValue'<~String> - The value of the attribute associated with the policy. # * 'PolicyName'<~String> - The name mof the policy associated with the LoadBalancer. # * 'PolicyTypeName'<~String> - The name of the policy type. def describe_load_balancer_policies(lb_name = nil, names = []) params = Fog::AWS.indexed_param('PolicyNames.member', [*names]) request({ 'Action' => 'DescribeLoadBalancerPolicies', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::DescribeLoadBalancerPolicies.new }.merge!(params)) end end class Mock def describe_load_balancer_policies(lb_name = nil, names = []) if lb_name raise Fog::AWS::ELB::NotFound unless load_balancer = self.data[:load_balancers][lb_name] names = [*names] policies = if names.any? names.map do |name| raise Fog::AWS::ELB::PolicyNotFound unless policy = load_balancer['Policies']['Proper'].find { |p| p['PolicyName'] == name } policy.dup end.compact else load_balancer['Policies']['Proper'] end else policies = [] end response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'DescribeLoadBalancerPoliciesResult' => { 'PolicyDescriptions' => policies } } response end end end end end fog-1.19.0/lib/fog/aws/requests/elb/delete_load_balancer_listeners.rb0000644000004100000410000000305612261242551025646 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/empty' # Delet Elastic Load Balancer Listeners # # ==== Parameters # * lb_name<~String> - Name for the new ELB -- must be unique # * load_balancer_ports<~Array> - Array of client port numbers of the LoadBalancerListeners to remove # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def delete_load_balancer_listeners(lb_name, load_balancer_ports) params = Fog::AWS.indexed_param('LoadBalancerPorts.member.%d', load_balancer_ports) request({ 'Action' => 'DeleteLoadBalancerListeners', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::Empty.new }.merge!(params)) end end class Mock def delete_load_balancer_listeners(lb_name, load_balancer_ports) raise Fog::AWS::ELB::NotFound unless load_balancer = self.data[:load_balancers][lb_name] response = Excon::Response.new response.status = 200 load_balancer['ListenerDescriptions'].delete_if { |listener| load_balancer_ports.include? listener['Listener']['LoadBalancerPort'] } response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/elb/describe_load_balancers.rb0000644000004100000410000001611512261242551024257 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/describe_load_balancers' # Describe all or specified load balancers # # ==== Parameters # * options<~Hash> # * 'LoadBalancerNames'<~Array> - List of load balancer names to describe, defaults to all # * 'Marker' - Indicates where to begin in your list of load balancers # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeLoadBalancersResult'<~Hash>: # * 'LoadBalancerDescriptions'<~Array> # * 'AvailabilityZones'<~Array> - list of availability zones covered by this load balancer # * 'BackendServerDescriptions'<~Array>: # * 'InstancePort'<~Integer> - the port on which the back-end server is listening # * 'PolicyNames'<~Array> - list of policy names enabled for the back-end server # * 'CanonicalHostedZoneName'<~String> - name of the Route 53 hosted zone associated with the load balancer # * 'CanonicalHostedZoneNameID'<~String> - ID of the Route 53 hosted zone associated with the load balancer # * 'CreatedTime'<~Time> - time load balancer was created # * 'DNSName'<~String> - external DNS name of load balancer # * 'HealthCheck'<~Hash>: # * 'HealthyThreshold'<~Integer> - number of consecutive health probe successes required before moving the instance to the Healthy state # * 'Timeout'<~Integer> - number of seconds after which no response means a failed health probe # * 'Interval'<~Integer> - interval (in seconds) between health checks of an individual instance # * 'UnhealthyThreshold'<~Integer> - number of consecutive health probe failures that move the instance to the unhealthy state # * 'Target'<~String> - string describing protocol type, port and URL to check # * 'Instances'<~Array> - list of instances that the load balancer balances between # * 'ListenerDescriptions'<~Array> # * 'PolicyNames'<~Array> - list of policies enabled # * 'Listener'<~Hash>: # * 'InstancePort'<~Integer> - port on instance that requests are sent to # * 'Protocol'<~String> - transport protocol used for routing in [TCP, HTTP] # * 'LoadBalancerPort'<~Integer> - port that load balancer listens on for requests # * 'LoadBalancerName'<~String> - name of load balancer # * 'Policies'<~Hash>: # * 'LBCookieStickinessPolicies'<~Array> - list of Load Balancer Generated Cookie Stickiness policies for the LoadBalancer # * 'AppCookieStickinessPolicies'<~Array> - list of Application Generated Cookie Stickiness policies for the LoadBalancer # * 'OtherPolicies'<~Array> - list of policy names other than the stickiness policies # * 'SourceSecurityGroup'<~Hash>: # * 'GroupName'<~String> - Name of the source security group to use with inbound security group rules # * 'OwnerAlias'<~String> - Owner of the source security group # * 'NextMarker'<~String> - Marker to specify for next page def describe_load_balancers(options = {}) unless options.is_a?(Hash) Fog::Logger.deprecation("describe_load_balancers with #{options.class} is deprecated, use all('LoadBalancerNames' => []) instead [light_black](#{caller.first})[/]") options = { 'LoadBalancerNames' => [options].flatten } end if names = options.delete('LoadBalancerNames') options.update(Fog::AWS.indexed_param('LoadBalancerNames.member', [*names])) end request({ 'Action' => 'DescribeLoadBalancers', :parser => Fog::Parsers::AWS::ELB::DescribeLoadBalancers.new }.merge!(options)) end end class Mock def describe_load_balancers(options = {}) unless options.is_a?(Hash) Fog::Logger.deprecation("describe_load_balancers with #{options.class} is deprecated, use all('LoadBalancerNames' => []) instead [light_black](#{caller.first})[/]") options = { 'LoadBalancerNames' => [options].flatten } end lb_names = options['LoadBalancerNames'] || [] lb_names = [*lb_names] load_balancers = if lb_names.any? lb_names.map do |lb_name| lb = self.data[:load_balancers].find { |name, data| name == lb_name } raise Fog::AWS::ELB::NotFound unless lb lb[1].dup end.compact else self.data[:load_balancers].map { |lb, values| values.dup } end marker = options.fetch('Marker', 0).to_i if load_balancers.count - marker > 400 next_marker = marker + 400 load_balancers = load_balancers[marker...next_marker] else next_marker = nil end response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'DescribeLoadBalancersResult' => { 'LoadBalancerDescriptions' => load_balancers.map do |lb| lb['Instances'] = lb['Instances'].map { |i| i['InstanceId'] } lb['Policies'] = lb['Policies']['Proper'].inject({'AppCookieStickinessPolicies' => [], 'LBCookieStickinessPolicies' => [], 'OtherPolicies' => []}) { |m, policy| case policy['PolicyTypeName'] when 'AppCookieStickinessPolicyType' cookie_name = policy['PolicyAttributeDescriptions'].detect{|h| h['AttributeName'] == 'CookieName'}['AttributeValue'] m['AppCookieStickinessPolicies'] << { 'PolicyName' => policy['PolicyName'], 'CookieName' => cookie_name } when 'LBCookieStickinessPolicyType' cookie_expiration_period = policy['PolicyAttributeDescriptions'].detect{|h| h['AttributeName'] == 'CookieExpirationPeriod'}['AttributeValue'].to_i lb_policy = { 'PolicyName' => policy['PolicyName'] } lb_policy['CookieExpirationPeriod'] = cookie_expiration_period if cookie_expiration_period > 0 m['LBCookieStickinessPolicies'] << lb_policy else m['OtherPolicies'] << policy['PolicyName'] end m } lb['BackendServerDescriptions'] = lb.delete('BackendServerDescriptionsRemote') lb end } } if next_marker response.body['DescribeLoadBalancersResult']['NextMarker'] = next_marker.to_s end response end end end end end fog-1.19.0/lib/fog/aws/requests/elb/configure_health_check.rb0000644000004100000410000000472112261242551024131 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/configure_health_check' # Enables the client to define an application healthcheck for the instances. # See http://docs.amazonwebservices.com/ElasticLoadBalancing/latest/APIReference/index.html?API_ConfigureHealthCheck.html # # ==== Parameters # * lb_name<~String> - Name of the ELB # * health_check<~Hash> - A hash of parameters describing the health check # * 'HealthyThreshold'<~Integer> - Specifies the number of consecutive # health probe successes required before moving the instance to the Healthy state. # * 'Interval'<~Integer> - Specifies the approximate interval, in seconds, # between health checks of an individual instance. # * 'Target'<~String> - Specifies the instance being checked. # The protocol is either TCP or HTTP. The range of valid ports is one (1) through 65535. # * 'Timeout'<~Integer> - Specifies the amount of time, in seconds, # during which no response means a failed health probe. # * 'UnhealthyThreshold'<~Integer> - Specifies the number of consecutive # health probe failures required before moving the instance to the Unhealthy state. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def configure_health_check(lb_name, health_check) params = {'LoadBalancerName' => lb_name} health_check.each {|key, value| params["HealthCheck.#{key}"] = value } request({ 'Action' => 'ConfigureHealthCheck', :parser => Fog::Parsers::AWS::ELB::ConfigureHealthCheck.new }.merge!(params)) end end class Mock def configure_health_check(lb_name, health_check) if load_balancer = self.data[:load_balancers][lb_name] response = Excon::Response.new response.status = 200 load_balancer['HealthCheck'] = health_check response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'ConfigureHealthCheckResult' => { 'HealthCheck' => load_balancer['HealthCheck'] } } response else raise Fog::AWS::ELB::NotFound end end end end end end fog-1.19.0/lib/fog/aws/requests/elb/describe_instance_health.rb0000644000004100000410000000454212261242551024460 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/describe_instance_health' # Get health status for one or more instances on an existing ELB # # ==== Parameters # * lb_name<~String> - Load balancer to check instances health on # * instance_ids<~Array> - Optional list of instance IDs to check # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeInstanceHealthResult'<~Hash>: # * 'InstanceStates'<~Array> - array of hashes describing instance health # * 'Description'<~String> # * 'State'<~String> # * 'InstanceId'<~String> # * 'ReasonCode'<~String> def describe_instance_health(lb_name, instance_ids = []) params = Fog::AWS.indexed_param('Instances.member.%d.InstanceId', [*instance_ids]) request({ 'Action' => 'DescribeInstanceHealth', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::DescribeInstanceHealth.new }.merge!(params)) end end class Mock def describe_instance_health(lb_name, instance_ids = []) raise Fog::AWS::ELB::NotFound unless load_balancer = self.data[:load_balancers][lb_name] instance_ids = [*instance_ids] instance_ids = load_balancer['Instances'].collect { |i| i['InstanceId'] } unless instance_ids.any? data = instance_ids.map do |id| unless Fog::Compute::AWS::Mock.data[@region][@aws_access_key_id][:instances][id] raise Fog::AWS::ELB::InvalidInstance end { 'Description' => "", 'InstanceId' => id, 'ReasonCode' => "", 'State' => 'OutOfService' } end response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'DescribeInstanceHealthResult' => { 'InstanceStates' => data } } response end end end end end fog-1.19.0/lib/fog/aws/requests/elb/delete_load_balancer.rb0000644000004100000410000000260112261242551023551 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/delete_load_balancer' # Delete an existing Elastic Load Balancer # # Note that this API call, as defined by Amazon, is idempotent. # That is, it will not return an error if you try to delete an # ELB that does not exist. # # ==== Parameters # * lb_name<~String> - Name of the ELB to be deleted # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'DeleteLoadBalancerResponse'<~nil> # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def delete_load_balancer(lb_name) request({ 'Action' => 'DeleteLoadBalancer', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::DeleteLoadBalancer.new }) end end class Mock def delete_load_balancer(lb_name) response = Excon::Response.new response.status = 200 self.data[:load_balancers].delete(lb_name) response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'DeleteLoadBalancerResult' => nil } response end end end end end fog-1.19.0/lib/fog/aws/requests/elb/register_instances_with_load_balancer.rb0000644000004100000410000000440712261242551027243 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/register_instances_with_load_balancer' # Register an instance with an existing ELB # # ==== Parameters # * instance_ids<~Array> - List of instance IDs to associate with ELB # * lb_name<~String> - Load balancer to assign instances to # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'RegisterInstancesWithLoadBalancerResult'<~Hash>: # * 'Instances'<~Array> - array of hashes describing instances currently enabled # * 'InstanceId'<~String> def register_instances_with_load_balancer(instance_ids, lb_name) params = Fog::AWS.indexed_param('Instances.member.%d.InstanceId', [*instance_ids]) request({ 'Action' => 'RegisterInstancesWithLoadBalancer', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::RegisterInstancesWithLoadBalancer.new }.merge!(params)) end alias :register_instances :register_instances_with_load_balancer end class Mock def register_instances_with_load_balancer(instance_ids, lb_name) raise Fog::AWS::ELB::NotFound unless load_balancer = self.data[:load_balancers][lb_name] instance_ids = [*instance_ids] instances = instance_ids.map do |instance| raise Fog::AWS::ELB::InvalidInstance unless Fog::Compute::AWS::Mock.data[@region][@aws_access_key_id][:instances][instance] {'InstanceId' => instance} end response = Excon::Response.new response.status = 200 load_balancer['Instances'] = load_balancer['Instances'] | instances.dup response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'RegisterInstancesWithLoadBalancerResult' => { 'Instances' => instances } } response end alias :register_instances :register_instances_with_load_balancer end end end end fog-1.19.0/lib/fog/aws/requests/elb/create_app_cookie_stickiness_policy.rb0000644000004100000410000000331412261242551026735 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/empty' # Create an app cookie stickiness policy # # ==== Parameters # * lb_name<~String> - Name of the ELB # * policy_name<~String> - The name of the policy being created. # The name must be unique within the set of policies for this Load Balancer. # * cookie_name<~String> - Name of the application cookie used for stickiness. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def create_app_cookie_stickiness_policy(lb_name, policy_name, cookie_name) params = {'CookieName' => cookie_name, 'PolicyName' => policy_name} request({ 'Action' => 'CreateAppCookieStickinessPolicy', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::Empty.new }.merge!(params)) end end class Mock def create_app_cookie_stickiness_policy(lb_name, policy_name, cookie_name) if load_balancer = self.data[:load_balancers][lb_name] response = Excon::Response.new response.status = 200 create_load_balancer_policy(lb_name, policy_name, 'AppCookieStickinessPolicyType', {'CookieName' => cookie_name}) response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response else raise Fog::AWS::ELB::NotFound end end end end end end fog-1.19.0/lib/fog/aws/requests/elb/deregister_instances_from_load_balancer.rb0000644000004100000410000000441412261242551027542 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/deregister_instances_from_load_balancer' # Deregister an instance from an existing ELB # # ==== Parameters # * instance_ids<~Array> - List of instance IDs to remove from ELB # * lb_name<~String> - Load balancer to remove instances from # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DeregisterInstancesFromLoadBalancerResult'<~Hash>: # * 'Instances'<~Array> - array of hashes describing instances currently enabled # * 'InstanceId'<~String> def deregister_instances_from_load_balancer(instance_ids, lb_name) params = Fog::AWS.indexed_param('Instances.member.%d.InstanceId', [*instance_ids]) request({ 'Action' => 'DeregisterInstancesFromLoadBalancer', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::DeregisterInstancesFromLoadBalancer.new }.merge!(params)) end alias :deregister_instances :deregister_instances_from_load_balancer end class Mock def deregister_instances_from_load_balancer(instance_ids, lb_name) raise Fog::AWS::ELB::NotFound unless load_balancer = self.data[:load_balancers][lb_name] instance_ids = [*instance_ids] instance_ids.each do |instance| raise Fog::AWS::ELB::InvalidInstance unless Fog::Compute::AWS::Mock.data[@region][@aws_access_key_id][:instances][instance] end response = Excon::Response.new response.status = 200 load_balancer['Instances'].delete_if { |i| instance_ids.include? i['InstanceId'] } response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'DeregisterInstancesFromLoadBalancerResult' => { 'Instances' => load_balancer['Instances'].dup } } response end alias :deregister_instances :deregister_instances_from_load_balancer end end end end fog-1.19.0/lib/fog/aws/requests/elb/detach_load_balancer_from_subnets.rb0000644000004100000410000000364212261242551026333 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/detach_load_balancer_from_subnets' # Disable a subnet for an existing ELB # # ==== Parameters # * subnet_ids<~Array> - List of subnet ids to enable on ELB # * lb_name<~String> - Load balancer to disable availability zones on # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DetachLoadBalancerFromSubnetsResult'<~Hash>: # * 'Subnets'<~Array> - array of strings describing the subnet ids currently enabled def detach_load_balancer_from_subnets(subnet_ids, lb_name) params = Fog::AWS.indexed_param('Subnets.member', [*subnet_ids]) request({ 'Action' => 'DetachLoadBalancerFromSubnets', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::DetachLoadBalancerFromSubnets.new }.merge!(params)) end alias :disable_subnets :detach_load_balancer_from_subnets end class Mock def detach_load_balancer_from_subnets(subnet_ids, lb_name) raise Fog::AWS::ELB::NotFound unless load_balancer = self.data[:load_balancers][lb_name] response = Excon::Response.new response.status = 200 load_balancer['Subnets'] << subnet_ids load_balancer['Subnets'].flatten!.uniq! response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'DetachLoadBalancerFromSubnetsResult' => { 'Subnets' => load_balancer['Subnets'] } } response end alias :disable_subnets :detach_load_balancer_from_subnets end end end end fog-1.19.0/lib/fog/aws/requests/elb/describe_load_balancer_attributes.rb0000644000004100000410000000342212261242551026337 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/describe_load_balancer_attributes' # Describe the load balancer attributes # http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_DescribeLoadBalancerAttributes.html # ==== Parameters # * lb_name<~String> - The mnemonic name associated with the LoadBalancer. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeLoadBalancerAttributesResult'<~Hash>: # * 'LoadBalancerAttributes'<~Hash> # * 'CrossZoneLoadBalancing'<~Hash> # * 'Enabled'<~Boolean> - whether crosszone load balancing is enabled def describe_load_balancer_attributes(lb_name) request({ 'Action' => 'DescribeLoadBalancerAttributes', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::DescribeLoadBalancerAttributes.new }) end end class Mock def describe_load_balancer_attributes(lb_name = nil, names = []) raise Fog::AWS::ELB::NotFound unless load_balancer = self.data[:load_balancers][lb_name] attributes = load_balancer['LoadBalancerAttributes'] response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'DescribeLoadBalancerAttributesResult' => { 'LoadBalancerAttributes' => attributes } } response end end end end end fog-1.19.0/lib/fog/aws/requests/elb/disable_availability_zones_for_load_balancer.rb0000644000004100000410000000412312261242551030531 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/disable_availability_zones_for_load_balancer' # Disable an availability zone for an existing ELB # # ==== Parameters # * availability_zones<~Array> - List of availability zones to disable on ELB # * lb_name<~String> - Load balancer to disable availability zones on # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DisableAvailabilityZonesForLoadBalancerResult'<~Hash>: # * 'AvailabilityZones'<~Array> - A list of updated Availability Zones for the LoadBalancer. def disable_availability_zones_for_load_balancer(availability_zones, lb_name) params = Fog::AWS.indexed_param('AvailabilityZones.member', [*availability_zones]) request({ 'Action' => 'DisableAvailabilityZonesForLoadBalancer', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::DisableAvailabilityZonesForLoadBalancer.new }.merge!(params)) end alias :disable_zones :disable_availability_zones_for_load_balancer end class Mock def disable_availability_zones_for_load_balancer(availability_zones, lb_name) raise Fog::AWS::ELB::NotFound unless load_balancer = self.data[:load_balancers][lb_name] response = Excon::Response.new response.status = 200 load_balancer['AvailabilityZones'].delete_if { |az| availability_zones.include? az } response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'DisableAvailabilityZonesForLoadBalancerResult' => { 'AvailabilityZones' => load_balancer['AvailabilityZones'] } } response end alias :disable_zones :disable_availability_zones_for_load_balancer end end end end fog-1.19.0/lib/fog/aws/requests/elb/modify_load_balancer_attributes.rb0000644000004100000410000000343312261242551026050 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/empty' # Sets attributes of the load balancer # # Currently the only attribute that can be set is whether CrossZoneLoadBalancing # is enabled # # http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/API_ModifyLoadBalancerAttributes.html # ==== Parameters # * lb_name<~String> - Name of the ELB # * options<~Hash> # * 'CrossZoneLoadBalancing'<~Hash>: # * 'Enabled'<~Boolean> whether to enable cross zone load balancing # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def modify_load_balancer_attributes(lb_name, options) attributes = Fog::AWS.serialize_keys 'LoadBalancerAttributes', options request(attributes.merge( 'Action' => 'ModifyLoadBalancerAttributes', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::Empty.new )) end end class Mock def modify_load_balancer_attributes(lb_name, attributes) raise Fog::AWS::ELB::NotFound unless load_balancer = self.data[:load_balancers][lb_name] if attributes['CrossZoneLoadBalancing'] load_balancer['LoadBalancerAttributes'].merge! attributes end response = Excon::Response.new response.status = 200 response.body = { "ResponseMetadata" => { "RequestId" => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/elb/create_lb_cookie_stickiness_policy.rb0000644000004100000410000000373012261242551026554 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/empty' # Create a Load Balancer Cookie Stickiness Policy # # ==== Parameters # * lb_name<~String> - Name of the ELB # * policy_name<~String> - The name of the policy being created. The name # must be unique within the set of policies for this Load Balancer. # * cookie_expiration_period<~Integer> - The time period in seconds after # which the cookie should be considered stale. Not specifying this # parameter indicates that the sticky session will last for the duration of the browser session. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def create_lb_cookie_stickiness_policy(lb_name, policy_name, cookie_expiration_period=nil) params = {'PolicyName' => policy_name, 'CookieExpirationPeriod' => cookie_expiration_period} request({ 'Action' => 'CreateLBCookieStickinessPolicy', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::Empty.new }.merge!(params)) end end class Mock def create_lb_cookie_stickiness_policy(lb_name, policy_name, cookie_expiration_period=nil) if load_balancer = self.data[:load_balancers][lb_name] response = Excon::Response.new response.status = 200 create_load_balancer_policy(lb_name, policy_name, 'LBCookieStickinessPolicyType', {'CookieExpirationPeriod' => cookie_expiration_period}) response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response else raise Fog::AWS::ELB::NotFound end end end end end end fog-1.19.0/lib/fog/aws/requests/elb/attach_load_balancer_to_subnets.rb0000644000004100000410000000361412261242551026025 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/attach_load_balancer_to_subnets' # Enable a subnet for an existing ELB # # ==== Parameters # * subnet_ids<~Array> - List of subnet ids to enable on ELB # * lb_name<~String> - Load balancer to enable availability zones on # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'AttachLoadBalancerToSubnetsResult'<~Hash>: # * 'Subnets'<~Array> - array of strings describing the subnet ids currently enabled def attach_load_balancer_to_subnets(subnet_ids, lb_name) params = Fog::AWS.indexed_param('Subnets.member', [*subnet_ids]) request({ 'Action' => 'AttachLoadBalancerToSubnets', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::AttachLoadBalancerToSubnets.new }.merge!(params)) end alias :enable_subnets :attach_load_balancer_to_subnets end class Mock def attach_load_balancer_to_subnets(subnet_ids, lb_name) raise Fog::AWS::ELB::NotFound unless load_balancer = self.data[:load_balancers][lb_name] response = Excon::Response.new response.status = 200 load_balancer['Subnets'] << subnet_ids load_balancer['Subnets'].flatten!.uniq! response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'AttachLoadBalancerToSubnetsResult' => { 'Subnets' => load_balancer['Subnets'] } } response end alias :enable_subnets :attach_load_balancer_to_subnets end end end end fog-1.19.0/lib/fog/aws/requests/elb/create_load_balancer_listeners.rb0000644000004100000410000000740412261242551025650 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/empty' # Create Elastic Load Balancer Listeners # # ==== Parameters # * lb_name<~String> - Name for the new ELB -- must be unique # * listeners<~Array> - Array of Hashes describing ELB listeners to add to the ELB # * 'Protocol'<~String> - Protocol to use. Either HTTP, HTTPS, TCP or SSL. # * 'LoadBalancerPort'<~Integer> - The port that the ELB will listen to for outside traffic # * 'InstancePort'<~Integer> - The port on the instance that the ELB will forward traffic to # * 'InstanceProtocol'<~String> - Protocol for sending traffic to an instance. Either HTTP, HTTPS, TCP or SSL. # * 'SSLCertificateId'<~String> - ARN of the server certificate # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def create_load_balancer_listeners(lb_name, listeners) params = {} listener_protocol = [] listener_lb_port = [] listener_instance_port = [] listener_instance_protocol = [] listener_ssl_certificate_id = [] listeners.each do |listener| listener_protocol.push(listener['Protocol']) listener_lb_port.push(listener['LoadBalancerPort']) listener_instance_port.push(listener['InstancePort']) listener_instance_protocol.push(listener['InstanceProtocol']) listener_ssl_certificate_id.push(listener['SSLCertificateId']) end params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.Protocol', listener_protocol)) params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.LoadBalancerPort', listener_lb_port)) params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.InstancePort', listener_instance_port)) params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.InstanceProtocol', listener_instance_protocol)) params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.SSLCertificateId', listener_ssl_certificate_id)) request({ 'Action' => 'CreateLoadBalancerListeners', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::Empty.new }.merge!(params)) end end class Mock def create_load_balancer_listeners(lb_name, listeners) if load_balancer = self.data[:load_balancers][lb_name] response = Excon::Response.new certificate_ids = Fog::AWS::IAM::Mock.data[@aws_access_key_id][:server_certificates].map {|n, c| c['Arn'] } listeners.each do |listener| if listener['SSLCertificateId'] and !certificate_ids.include? listener['SSLCertificateId'] raise Fog::AWS::IAM::NotFound.new('CertificateNotFound') end if (%w( HTTP HTTPS).include?(listener['Protocol']) && !%w( HTTP HTTPS ).include?(listener['InstanceProtocol'])) || (%w( TCP SSL).include?(listener['Protocol']) && !%w( TCP SSL ).include?(listener['InstanceProtocol'])) raise Fog::AWS::ELB::ValidationError end if listener['Protocol'] && listener['InstanceProtocol'] load_balancer['ListenerDescriptions'] << {'Listener' => listener, 'PolicyNames' => []} end response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response else raise Fog::AWS::ELB::NotFound end end end end end end fog-1.19.0/lib/fog/aws/requests/elb/create_load_balancer.rb0000644000004100000410000001631312261242551023557 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/create_load_balancer' # Create a new Elastic Load Balancer # # ==== Parameters # * availability_zones<~Array> - List of availability zones for the ELB # * lb_name<~String> - Name for the new ELB -- must be unique # * listeners<~Array> - Array of Hashes describing ELB listeners to assign to the ELB # * 'Protocol'<~String> - Protocol to use. Either HTTP, HTTPS, TCP or SSL. # * 'LoadBalancerPort'<~Integer> - The port that the ELB will listen to for outside traffic # * 'InstancePort'<~Integer> - The port on the instance that the ELB will forward traffic to # * 'InstanceProtocol'<~String> - Protocol for sending traffic to an instance. Either HTTP, HTTPS, TCP or SSL. # * 'SSLCertificateId'<~String> - ARN of the server certificate # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'CreateLoadBalancerResult'<~Hash>: # * 'DNSName'<~String> - DNS name for the newly created ELB def create_load_balancer(availability_zones, lb_name, listeners, options = {}) params = Fog::AWS.indexed_param('AvailabilityZones.member', [*availability_zones]) params.merge!(Fog::AWS.indexed_param('Subnets.member.%d', options[:subnet_ids])) params.merge!(Fog::AWS.serialize_keys('Scheme', options[:scheme])) params.merge!(Fog::AWS.indexed_param('SecurityGroups.member.%d', options[:security_groups])) listener_protocol = [] listener_lb_port = [] listener_instance_port = [] listener_instance_protocol = [] listener_ssl_certificate_id = [] listeners.each do |listener| listener_protocol.push(listener['Protocol']) listener_lb_port.push(listener['LoadBalancerPort']) listener_instance_port.push(listener['InstancePort']) listener_instance_protocol.push(listener['InstanceProtocol']) listener_ssl_certificate_id.push(listener['SSLCertificateId']) end params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.Protocol', listener_protocol)) params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.LoadBalancerPort', listener_lb_port)) params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.InstancePort', listener_instance_port)) params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.InstanceProtocol', listener_instance_protocol)) params.merge!(Fog::AWS.indexed_param('Listeners.member.%d.SSLCertificateId', listener_ssl_certificate_id)) request({ 'Action' => 'CreateLoadBalancer', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::CreateLoadBalancer.new }.merge!(params)) end end class Mock def create_load_balancer(availability_zones, lb_name, listeners = [], options = {}) response = Excon::Response.new response.status = 200 raise Fog::AWS::ELB::IdentifierTaken if self.data[:load_balancers].has_key? lb_name certificate_ids = Fog::AWS::IAM::Mock.data[@aws_access_key_id][:server_certificates].map {|n, c| c['Arn'] } listeners = [*listeners].map do |listener| if listener['SSLCertificateId'] and !certificate_ids.include? listener['SSLCertificateId'] raise Fog::AWS::IAM::NotFound.new('CertificateNotFound') end {'Listener' => listener, 'PolicyNames' => []} end dns_name = Fog::AWS::ELB::Mock.dns_name(lb_name, @region) region = availability_zones ? availability_zones.first.gsub(/[a-z]$/, '') : "us-east-1" supported_platforms = Fog::Compute::AWS::Mock.data[region][@aws_access_key_id][:account_attributes].detect { |h| h["attributeName"] == "supported-platforms" }["values"] security_group = if supported_platforms.include?("EC2") Fog::Compute::AWS::Mock.data[region][@aws_access_key_id][:security_groups]['amazon-elb-sg'] else if default_sg = Fog::Compute::AWS::Mock.data[region][@aws_access_key_id][:security_groups].values.detect { |sg| sg['groupName'] =~ /default_elb/ } default_sg else default_sg_name = "default_elb_#{Fog::Mock.random_hex(6)}" default_sg = { 'groupDescription' => 'default elb security group', 'groupName' => default_sg_name, 'groupId' => Fog::AWS::Mock.security_group_id, 'ipPermissionsEgress' => [], 'ipPermissions' => [], 'ownerId' => self.data[:owner_id] } Fog::Compute::AWS::Mock.data[region][@aws_access_key_id][:security_groups][default_sg_name] = default_sg end default_sg end self.data[:load_balancers][lb_name] = { 'AvailabilityZones' => availability_zones, 'BackendServerDescriptions' => [], # Hack to facilitate not updating the local data structure # (BackendServerDescriptions) until we do a subsequent # describe as that is how AWS behaves. 'BackendServerDescriptionsRemote' => [], 'Subnets' => options[:subnet_ids] || [], 'Scheme' => options[:scheme].nil? ? 'internet-facing' : options[:scheme], 'SecurityGroups' => options[:security_groups].nil? ? [] : options[:security_groups], 'CanonicalHostedZoneName' => '', 'CanonicalHostedZoneNameID' => '', 'CreatedTime' => Time.now, 'DNSName' => dns_name, 'HealthCheck' => { 'HealthyThreshold' => 10, 'Timeout' => 5, 'UnhealthyThreshold' => 2, 'Interval' => 30, 'Target' => 'TCP:80' }, 'Instances' => [], 'ListenerDescriptions' => listeners, 'LoadBalancerAttributes' => {'CrossZoneLoadBalancing' => {'Enabled' => false}}, 'LoadBalancerName' => lb_name, 'Policies' => { 'AppCookieStickinessPolicies' => [], 'LBCookieStickinessPolicies' => [], 'OtherPolicies' => [], 'Proper' => [] }, 'SourceSecurityGroup' => { 'GroupName' => security_group['groupName'], 'OwnerAlias' => '' } } response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'CreateLoadBalancerResult' => { 'DNSName' => dns_name } } response end end end end end fog-1.19.0/lib/fog/aws/requests/elb/set_load_balancer_policies_for_backend_server.rb0000644000004100000410000000533512261242551030703 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/empty' # Replaces the current set of policies associated with a port on which the back-end server is listening with a new set of policies. # After the policies have been created using CreateLoadBalancerPolicy, they can be applied here as a list. # # ==== Parameters # * lb_name<~String> - Name of the ELB # * instance_port<~Integer> - The port on the instance that the ELB will forward traffic to # * policy_names<~Array> - Array of Strings listing the policies to set for the backend port # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def set_load_balancer_policies_for_backend_server(lb_name, instance_port, policy_names) params = {'InstancePort' => instance_port} if policy_names.any? params.merge!(Fog::AWS.indexed_param('PolicyNames.member', policy_names)) else params['PolicyNames'] = '' end request({ 'Action' => 'SetLoadBalancerPoliciesForBackendServer', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::Empty.new }.merge!(params)) end end class Mock def set_load_balancer_policies_for_backend_server(lb_name, instance_port, policy_names) if load_balancer = self.data[:load_balancers][lb_name] # Ensure policies exist policy_names.each do |policy_name| unless load_balancer['Policies']['Proper'].find { |p| p['PolicyName'] == policy_name } raise Fog::AWS::ELB::PolicyNotFound, "There is no policy with name #{policy_name} for load balancer #{lb_name}" end end # Update backend policies: description = load_balancer['BackendServerDescriptionsRemote'].find{|d| d["InstancePort"] == instance_port } || {} description["InstancePort"] = instance_port description["PolicyNames"] = policy_names load_balancer['BackendServerDescriptionsRemote'].delete_if{|d| d["InstancePort"] == instance_port } load_balancer['BackendServerDescriptionsRemote'] << description Excon::Response.new.tap do |response| response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } end else raise Fog::AWS::ELB::NotFound end end end end end end fog-1.19.0/lib/fog/aws/requests/elb/delete_load_balancer_policy.rb0000644000004100000410000000276012261242551025136 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/empty' # Delete a Load Balancer Stickiness Policy # # ==== Parameters # * lb_name<~String> - Name of the ELB # * policy_name<~String> - The name of the policy to delete # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def delete_load_balancer_policy(lb_name, policy_name) params = {'PolicyName' => policy_name} request({ 'Action' => 'DeleteLoadBalancerPolicy', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::Empty.new }.merge!(params)) end end class Mock def delete_load_balancer_policy(lb_name, policy_name) if load_balancer = self.data[:load_balancers][lb_name] response = Excon::Response.new response.status = 200 load_balancer['Policies'].each do |name, policies| policies.delete_if { |policy| policy['PolicyName'] == policy_name } end response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response else raise Fog::AWS::ELB::NotFound end end end end end end fog-1.19.0/lib/fog/aws/requests/elb/set_load_balancer_policies_of_listener.rb0000644000004100000410000000677112261242551027376 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/empty' # Associates, updates, or disables a policy with a listener on the # load balancer. Currently only zero (0) or one (1) policy can be # associated with a listener. # # ==== Parameters # * lb_name<~String> - Name of the ELB # * load_balancer_port<~Integer> - The external port of the LoadBalancer # with which this policy has to be associated. # * policy_names<~Array> - List of policies to be associated with the # listener. Currently this list can have at most one policy. If the # list is empty, the current policy is removed from the listener. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request def set_load_balancer_policies_of_listener(lb_name, load_balancer_port, policy_names) params = {'LoadBalancerPort' => load_balancer_port} if policy_names.any? params.merge!(Fog::AWS.indexed_param('PolicyNames.member', policy_names)) else params['PolicyNames'] = '' end request({ 'Action' => 'SetLoadBalancerPoliciesOfListener', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::Empty.new }.merge!(params)) end end class Mock def set_load_balancer_policies_of_listener(lb_name, load_balancer_port, policy_names) raise Fog::AWS::ELB::NotFound unless load_balancer = self.data[:load_balancers][lb_name] policy_names = [*policy_names] response = Excon::Response.new if policy_names.size > 1 response.status = 409 response.body = "InvalidConfigurationRequestRequested configuration change is invalid.#{Fog::AWS::Mock.request_id}" raise Excon::Errors.status_error({:expects => 200}, response) end unless listener = load_balancer['ListenerDescriptions'].find { |listener| listener['Listener']['LoadBalancerPort'] == load_balancer_port } response.status = 400 response.body = "ListenerNotFoundLoadBalancer does not have a listnener configured at the given port.#{Fog::AWS::Mock.request_id}" raise Excon::Errors.status_error({:expects => 200}, response) end unless load_balancer['Policies']['Proper'].find { |policy| policy['PolicyName'] == policy_names.first } response.status = 400 response.body = "PolicyNotFoundOne or more specified policies were not found.#{Fog::AWS::Mock.request_id}" raise Excon::Errors.status_error({:expects => 200}, response) end if policy_names.any? listener['PolicyNames'] = policy_names response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/elb/describe_load_balancer_policy_types.rb0000644000004100000410000000532112261242551026674 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/describe_load_balancer_policy_types' # Describe all or specified load balancer policy types # # ==== Parameters # * type_name<~Array> - Specifies the name of the policy types. If no names are specified, returns the description of all the policy types defined by Elastic Load Balancing service. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'DescribeLoadBalancerPolicyTypesResult'<~Hash>: # * 'PolicyTypeDescriptions'<~Array> # * 'Description'<~String> - A human-readable description of the policy type. # * 'PolicyAttributeTypeDescriptions'<~Array> # * 'AttributeName'<~String> - The name of the attribute associated with the policy type. # * 'AttributeValue'<~String> - The type of attribute. For example, Boolean, Integer, etc. # * 'Cardinality'<~String> - The cardinality of the attribute. # * 'DefaultValue'<~String> - The default value of the attribute, if applicable. # * 'Description'<~String> - A human-readable description of the attribute. # * 'PolicyTypeName'<~String> - The name of the policy type. def describe_load_balancer_policy_types(type_names = []) params = Fog::AWS.indexed_param('PolicyTypeNames.member', [*type_names]) request({ 'Action' => 'DescribeLoadBalancerPolicyTypes', :parser => Fog::Parsers::AWS::ELB::DescribeLoadBalancerPolicyTypes.new }.merge!(params)) end end class Mock def describe_load_balancer_policy_types(type_names = []) type_names = [*type_names] policy_types = if type_names.any? type_names.map do |type_name| policy_type = self.data[:policy_types].find { |pt| pt['PolicyTypeName'] == type_name } raise Fog::AWS::ELB::PolicyTypeNotFound unless policy_type policy_type[1].dup end.compact else self.data[:policy_types].map { |policy_type| policy_type.dup } end response = Excon::Response.new response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'DescribeLoadBalancerPolicyTypesResult' => { 'PolicyTypeDescriptions' => policy_types } } response end end end end end fog-1.19.0/lib/fog/aws/requests/elb/apply_security_groups_to_load_balancer.rb0000644000004100000410000000406312261242551027470 0ustar www-datawww-datamodule Fog module AWS class ELB class Real require 'fog/aws/parsers/elb/apply_security_groups_to_load_balancer' # Sets the security groups for an ELB in VPC # # ==== Parameters # * security_group_ids<~Array> - List of security group ids to enable on ELB # * lb_name<~String> - Load balancer to disable availability zones on # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ResponseMetadata'<~Hash>: # * 'RequestId'<~String> - Id of request # * 'ApplySecurityGroupsToLoadBalancer'<~Hash>: # * 'SecurityGroups'<~Array> - array of strings describing the security group ids currently enabled def apply_security_groups_to_load_balancer(security_group_ids, lb_name) params = Fog::AWS.indexed_param('SecurityGroups.member', [*security_group_ids]) request({ 'Action' => 'ApplySecurityGroupsToLoadBalancer', 'LoadBalancerName' => lb_name, :parser => Fog::Parsers::AWS::ELB::ApplySecurityGroupsToLoadBalancer.new }.merge!(params)) end alias :apply_security_groups :apply_security_groups_to_load_balancer end class Mock def apply_security_groups_to_load_balancer(security_group_ids, lb_name) raise Fog::AWS::ELB::NotFound unless load_balancer = self.data[:load_balancers][lb_name] response = Excon::Response.new response.status = 200 load_balancer['SecurityGroups'] << security_group_ids load_balancer['SecurityGroups'].flatten!.uniq! response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'DetachLoadBalancerFromSubnetsResult' => { 'SecurityGroups' => load_balancer['SecurityGroups'] } } response end alias :apply_security_groups :apply_security_groups_to_load_balancer end end end end fog-1.19.0/lib/fog/aws/requests/data_pipeline/0000755000004100000410000000000012261242551021171 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/data_pipeline/get_pipeline_definition.rb0000644000004100000410000000154712261242551026401 0ustar www-datawww-datamodule Fog module AWS class DataPipeline class Real # Get pipeline definition JSON # http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_GetPipelineDefinition.html # ==== Parameters # * PipelineId <~String> - The ID of the pipeline # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def get_pipeline_definition(id) params = { 'pipelineId' => id, } response = request({ :body => Fog::JSON.encode(params), :headers => { 'X-Amz-Target' => 'DataPipeline.GetPipelineDefinition' }, }) Fog::JSON.decode(response.body) end end class Mock def get_pipeline_definition(id, objects) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/data_pipeline/list_pipelines.rb0000644000004100000410000000156212261242551024545 0ustar www-datawww-datamodule Fog module AWS class DataPipeline class Real # List all pipelines # http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_ListPipelines.html # ==== Parameters # * Marker <~String> - The starting point for the results to be returned. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def list_pipelines(options={}) params = {} params['Marker'] = options[:marker] if options[:marker] response = request({ :body => Fog::JSON.encode(params), :headers => { 'X-Amz-Target' => 'DataPipeline.ListPipelines' }, }) Fog::JSON.decode(response.body) end end class Mock def list_pipelines(options={}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/data_pipeline/create_pipeline.rb0000644000004100000410000000211412261242551024644 0ustar www-datawww-datamodule Fog module AWS class DataPipeline class Real # Create a pipeline # http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_CreatePipeline.html # ==== Parameters # * UniqueId <~String> - A unique ID for of the pipeline # * Name <~String> - The name of the pipeline # * Description <~String> - Description of the pipeline # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def create_pipeline(unique_id, name, description=nil) params = { 'uniqueId' => unique_id, 'name' => name, } params['Description'] = description if description response = request({ :body => Fog::JSON.encode(params), :headers => { 'X-Amz-Target' => 'DataPipeline.CreatePipeline' }, }) Fog::JSON.decode(response.body) end end class Mock def create_pipeline(unique_id, name, description=nil) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/data_pipeline/put_pipeline_definition.rb0000644000004100000410000000374412261242551026433 0ustar www-datawww-datamodule Fog module AWS class DataPipeline class Real # Put raw pipeline definition JSON # http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_PutPipelineDefinition.html # ==== Parameters # * PipelineId <~String> - The ID of the pipeline # * PipelineObjects <~String> - Objects in the pipeline # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def put_pipeline_definition(id, objects) params = { 'pipelineId' => id, 'pipelineObjects' => transform_objects(objects), } response = request({ :body => Fog::JSON.encode(params), :headers => { 'X-Amz-Target' => 'DataPipeline.PutPipelineDefinition' }, }) Fog::JSON.decode(response.body) end # Take a list of pipeline object hashes as specified in the Data Pipeline JSON format # and transform it into the format expected by the API private def transform_objects(objects) output = [] objects.each do |object| new_object = {} new_object['id'] = object.delete('id') new_object['name'] = object.delete('name') || new_object['id'] new_object['fields'] = [] object.each do |key, value| if value.is_a?(Hash) new_object['fields'] << { 'key' => key, 'refValue' => value['ref'] } elsif value.is_a?(Array) value.each do |v| new_object['fields'] << { 'key' => key, 'stringValue' => v } end else new_object['fields'] << { 'key' => key, 'stringValue' => value } end end output << new_object end output end end class Mock def put_pipeline_definition(id, objects) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/data_pipeline/query_objects.rb0000644000004100000410000000212112261242551024370 0ustar www-datawww-datamodule Fog module AWS class DataPipeline class Real # Queries a pipeline for the names of objects that match a specified set of conditions. # http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_QueryObjects.html # ==== Parameters # * PipelineId <~String> - The ID of the pipeline # * Sphere <~String> - Specifies whether the query applies to components or instances. # Allowable values: COMPONENT, INSTANCE, ATTEMPT. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def query_objects(id, sphere) params = { 'pipelineId' => id, 'sphere' => sphere, } response = request({ :body => Fog::JSON.encode(params), :headers => { 'X-Amz-Target' => 'DataPipeline.QueryObjects' }, }) Fog::JSON.decode(response.body) end end class Mock def query_objects(id, objects) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/data_pipeline/activate_pipeline.rb0000644000004100000410000000146412261242551025210 0ustar www-datawww-datamodule Fog module AWS class DataPipeline class Real # Activate a pipeline # http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_ActivatePipeline.html # ==== Parameters # * PipelineId <~String> - The ID of the pipeline to activate # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def activate_pipeline(id) params = { 'pipelineId' => id } response = request({ :body => Fog::JSON.encode(params), :headers => { 'X-Amz-Target' => 'DataPipeline.ActivatePipeline' }, }) Fog::JSON.decode(response.body) end end class Mock def activate_pipeline(id) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/data_pipeline/describe_pipelines.rb0000644000004100000410000000152412261242551025350 0ustar www-datawww-datamodule Fog module AWS class DataPipeline class Real # Describe pipelines # http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_DescribePipelines.html # ==== Parameters # * PipelineIds <~String> - ID of pipeline to retrieve information for # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def describe_pipelines(ids) params = {} params['pipelineIds'] = ids response = request({ :body => Fog::JSON.encode(params), :headers => { 'X-Amz-Target' => 'DataPipeline.DescribePipelines' }, }) Fog::JSON.decode(response.body) end end class Mock def describe_pipelines(ids) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/data_pipeline/describe_objects.rb0000644000004100000410000000227012261242551025010 0ustar www-datawww-datamodule Fog module AWS class DataPipeline class Real # Queries a pipeline for the names of objects that match a specified set of conditions. # http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_DescribeObjects.html # ==== Parameters # * PipelineId <~String> - The ID of the pipeline # * ObjectIds <~Array> - Identifiers of the pipeline objects that contain the definitions # to be described. You can pass as many as 25 identifiers in a # single call to DescribeObjects. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def describe_objects(id, objectIds) params = { 'pipelineId' => id, 'objectIds' => objectIds, } response = request({ :body => Fog::JSON.encode(params), :headers => { 'X-Amz-Target' => 'DataPipeline.DescribeObjects' }, }) Fog::JSON.decode(response.body) end end class Mock def describe_objects(id, objects) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/data_pipeline/delete_pipeline.rb0000644000004100000410000000143612261242551024651 0ustar www-datawww-datamodule Fog module AWS class DataPipeline class Real # Delete a pipeline # http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_DeletePipeline.html # ==== Parameters # * PipelineId <~String> - The id of the pipeline to delete # ==== Returns # * success<~Boolean> - Whether the delete was successful def delete_pipeline(id) params = { 'pipelineId' => id } response = request({ :body => Fog::JSON.encode(params), :headers => { 'X-Amz-Target' => 'DataPipeline.DeletePipeline' }, }) 200 == response.status end end class Mock def delete_pipeline(id) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/cdn/0000755000004100000410000000000012261242551017137 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/cdn/get_invalidation_list.rb0000644000004100000410000000516612261242551024047 0ustar www-datawww-datamodule Fog module CDN class AWS class Real require 'fog/aws/parsers/cdn/get_invalidation_list' # Get invalidation list. # # @param options [Hash] Config arguments for list. # @option options Marker [String] Limits object keys to only those that appear lexicographically after its value. # @option options MaxItems [Integer] Limits number of object keys returned. # # @return [Excon::Response] # * body [Hash]: # * IsTruncated [Boolean] - Whether or not the listing is truncated. # * Marker [String] - Marker specified for query. # * MaxItems [Integer] - Maximum number of keys specified for query. # * NextMarker [String] - Marker to specify for next page (id of last result of current page). # * InvalidationSummary [Array]: # * Id [String] # * Status [String] # # @see http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListInvalidation.html def get_invalidation_list(distribution_id, options = {}) request({ :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::CDN::AWS::GetInvalidationList.new, :path => "/distribution/#{distribution_id}/invalidation", :query => options }) end end class Mock def get_invalidation_list(distribution_id, options = {}) distribution = self.data[:distributions][distribution_id] unless distribution Fog::CDN::AWS::Mock.error(:no_such_distribution) end invalidations = (self.data[:invalidations][distribution_id] || {}).values invalidations.each do |invalidation| if invalidation['Status'] == 'InProgress' && (Time.now - Time.parse(invalidation['CreateTime']) >= Fog::Mock.delay * 2) invalidation['Status'] = 'Completed' distribution['InProgressInvalidationBatches'] -= 1 end end response = Excon::Response.new response.status = 200 response.body = { 'Marker' => Fog::Mock.random_hex(16), 'IsTruncated' => false, 'MaxItems' => 100, 'InvalidationSummary' => invalidations.map { |i| to_invalidation_summary(i) } } response end private def to_invalidation_summary(d) { 'Id' => d['Id'], 'Status' => d['Status'] } end end end end end fog-1.19.0/lib/fog/aws/requests/cdn/post_invalidation.rb0000644000004100000410000000555212261242551023221 0ustar www-datawww-datamodule Fog module CDN class AWS class Real require 'fog/aws/parsers/cdn/post_invalidation' # List information about distributions in CloudFront. # # @param distribution_id [String] Id of distribution for invalidations. # @param paths [Array] Array of string paths to objects to invalidate. # @param caller_reference [String] Used to prevent replay, defaults to Time.now.to_i.to_s. # # @return [Excon::Response] # * body [Hash]: # * Id [String] - Id of invalidation. # * Status [String] - Status of invalidation. # * CreateTime [Integer] - Time of invalidation creation. # * InvalidationBatch [Array]: # * Path [Array] - Array of strings of objects to invalidate. # * CallerReference [String] - Used to prevent replay, defaults to Time.now.to_i.to_s. # # @see http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateInvalidation.html def post_invalidation(distribution_id, paths, caller_reference = Time.now.to_i.to_s) body = '' body << "" for path in [*paths] body << "" << path << "" end body << "" << caller_reference << "" body << "" request({ :body => body, :expects => 201, :headers => {'Content-Type' => 'text/xml'}, :idempotent => true, :method => 'POST', :parser => Fog::Parsers::CDN::AWS::PostInvalidation.new, :path => "/distribution/#{distribution_id}/invalidation" }) end end class Mock def post_invalidation(distribution_id, paths, caller_reference = Time.now.to_i.to_s) distribution = self.data[:distributions][distribution_id] if distribution invalidation_id = Fog::CDN::AWS::Mock.distribution_id invalidation = { 'Id' => invalidation_id, 'Status' => 'InProgress', 'CreateTime' => Time.now.utc.iso8601, 'InvalidationBatch' => { 'CallerReference' => caller_reference, 'Path' => paths } } distribution['InProgressInvalidationBatches'] += 1 self.data[:invalidations][distribution_id] ||= {} self.data[:invalidations][distribution_id][invalidation_id] = invalidation response = Excon::Response.new response.status = 201 response.body = invalidation response else Fog::CDN::AWS::Mock.error(:no_such_distribution) end end end end end end fog-1.19.0/lib/fog/aws/requests/cdn/delete_streaming_distribution.rb0000644000004100000410000000336212261242551025602 0ustar www-datawww-datamodule Fog module CDN class AWS class Real # Delete a streaming distribution from CloudFront. # # @param [String] distribution_id Id of distribution to delete. # @param [String] etag Etag of that distribution from earlier get or put # # @see http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/DeleteStreamingDistribution.html def delete_streaming_distribution(distribution_id, etag) request({ :expects => 204, :headers => { 'If-Match' => etag }, :idempotent => true, :method => 'DELETE', :path => "/streaming-distribution/#{distribution_id}" }) end end class Mock def delete_streaming_distribution(distribution_id, etag) distribution = self.data[:streaming_distributions][distribution_id] if distribution if distribution['ETag'] != etag Fog::CDN::AWS::Mock.error(:invalid_if_match_version) end unless distribution['StreamingDistributionConfig']['CallerReference'] Fog::CDN::AWS::Mock.error(:illegal_update) end if distribution['StreamingDistributionConfig']['Enabled'] Fog::CDN::AWS::Mock.error(:distribution_not_disabled) end self.data[:streaming_distributions].delete(distribution_id) response = Excon::Response.new response.status = 204 response.body = "x-amz-request-id: #{Fog::AWS::Mock.request_id}" response else Fog::CDN::AWS::Mock.error(:no_such_streaming_distribution) end end end end end end fog-1.19.0/lib/fog/aws/requests/cdn/get_invalidation.rb0000644000004100000410000000360212261242551023005 0ustar www-datawww-datamodule Fog module CDN class AWS class Real require 'fog/aws/parsers/cdn/get_invalidation' # Get invalidation. # # @param distribution_id [String] Distribution id. # @param invalidation_id [String] Invalidation id. # # @return [Excon::Response] # * body [Hash]: # * Id [String] - Invalidation id. # * Status [String] # * CreateTime [String] # * InvalidationBatch [Array]: # * Path [String] # # @see http://docs.amazonwebservices.com/AmazonCloudFront/2010-11-01/APIReference/GetInvalidation.html def get_invalidation(distribution_id, invalidation_id) request({ :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::CDN::AWS::GetInvalidation.new, :path => "/distribution/#{distribution_id}/invalidation/#{invalidation_id}" }) end end class Mock def get_invalidation(distribution_id, invalidation_id) distribution = self.data[:distributions][distribution_id] unless distribution Fog::CDN::AWS::Mock.error(:no_such_distribution) end invalidation = self.data[:invalidations][distribution_id][invalidation_id] unless invalidation Fog::CDN::AWS::Mock.error(:no_such_invalidation) end if invalidation['Status'] == 'InProgress' && (Time.now - Time.parse(invalidation['CreateTime']) >= Fog::Mock.delay * 2) invalidation['Status'] = 'Completed' distribution['InProgressInvalidationBatches'] -= 1 end response = Excon::Response.new response.status = 200 response.body = invalidation response end end end end end fog-1.19.0/lib/fog/aws/requests/cdn/get_distribution_list.rb0000644000004100000410000000647412261242551024110 0ustar www-datawww-datamodule Fog module CDN class AWS class Real require 'fog/aws/parsers/cdn/get_distribution_list' # List information about distributions in CloudFront. # # @param options [Hash] Config arguments for list. # @option options Marker [String] Limits object keys to only those that appear lexicographically after its value. # @option options MaxItems [Integer] Limits number of object keys returned. # # @return [Excon::Response] # * body [Hash]: # * IsTruncated [Boolean] - Whether or not the listing is truncated. # * Marker [String] Marker specified for query. # * MaxItems [Integer] - Maximum number of keys specified for query. # * NextMarker [String] - Marker to specify for next page (id of last result of current page). # * DistributionSummary [Array]: # * S3Origin [Hash]: # * DNSName [String] - Origin to associate with distribution, ie 'mybucket.s3.amazonaws.com'. # * OriginAccessIdentity [String] - Optional: Used when serving private content. # or # * CustomOrigin [Hash]: # * DNSName [String] - Origin to associate with distribution, ie 'www.example.com'. # * HTTPPort [Integer] - HTTP port of origin, in [80, 443] or (1024...65535). # * HTTPSPort [Integer] - HTTPS port of origin, in [80, 443] or (1024...65535). # * OriginProtocolPolicy [String] - Policy on using http vs https, in ['http-only', 'match-viewer']. # * Comment [String] - Comment associated with distribution. # * CNAME [Array] - Array of associated cnames. # * Enabled [Boolean] - Whether or not distribution is enabled. # * Id [String] - Id of distribution. # * LastModifiedTime [String] - Timestamp of last modification of distribution. # * Origin [String] - S3 origin bucket. # * Status [String] - Status of distribution. # * TrustedSigners [Array] - Trusted signers. # # @see http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListDistributions.html # def get_distribution_list(options = {}) request({ :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::CDN::AWS::GetDistributionList.new, :path => "/distribution", :query => options }) end end class Mock def get_distribution_list(options = {}) response = Excon::Response.new response.status = 200 distributions = self.data[:distributions].values response.body = { 'Marker' => Fog::Mock.random_hex(16), 'IsTruncated' => false, 'MaxItems' => 100, 'DistributionSummary' => distributions.map { |d| to_distribution_summary(d) } } response end private def to_distribution_summary(d) { 'DomainName' => d['DomainName'], 'Id' => d['Id'], 'LastModifiedTime' => d['LastModifiedTime'] }.merge(d['DistributionConfig']) end end end end end fog-1.19.0/lib/fog/aws/requests/cdn/post_distribution.rb0000644000004100000410000001330112261242551023246 0ustar www-datawww-datamodule Fog module CDN class AWS class Real require 'fog/aws/parsers/cdn/distribution' # Create a new distribution in CloudFront. # # @param options [Hash] Config for distribution. # # REQUIRED: # * S3Origin [Hash]: # * DNSName [String] Origin to associate with distribution, ie 'mybucket.s3.amazonaws.com'. # * OriginAccessIdentity [String] Optional: used when serving private content. # or # * CustomOrigin [Hash]: # * DNSName [String] Origin to associate with distribution, ie 'www.example.com'. # * HTTPPort [Integer] Optional HTTP port of origin, in [80, 443] or (1024...65535), defaults to 80. # * HTTPSPort [Integer] Optional HTTPS port of origin, in [80, 443] or (1024...65535), defaults to 443. # * OriginProtocolPolicy [String] Policy on using http vs https, in ['http-only', 'match-viewer']. # OPTIONAL: # * CallerReference [String] Used to prevent replay, defaults to Time.now.to_i.to_s. # * Comment [String] Optional comment about distribution. # * CNAME [Array] Optional array of strings to set as CNAMEs. # * DefaultRootObject [String] Optional default object to return for '/'. # * Enabled [Boolean] Whether or not distribution should accept requests, defaults to true. # * Logging [Hash]: Optional logging config. # * Bucket [String] Bucket to store logs in, ie 'mylogs.s3.amazonaws.com'. # * Prefix [String] Optional prefix for log filenames, ie 'myprefix/'. # * OriginAccessIdentity [String] Used for serving private content, in format 'origin-access-identity/cloudfront/ID'. # * RequiredProtocols [String] Optional, set to 'https' to force https connections. # * TrustedSigners [Array] Optional grant of rights to up to 5 aws accounts to generate signed URLs for private content, elements are either 'Self' for your own account or an AWS Account Number. # # @return [Excon::Response] # * body [Hash]: # * DomainName [String] - Domain name of distribution. # * Id [String] - Id of distribution. # * LastModifiedTime [String] - Timestamp of last modification of distribution. # * Status [String] - Status of distribution. # * DistributionConfig [Array]: # * CallerReference [String] - Used to prevent replay, defaults to Time.now.to_i.to_s. # * CNAME [Array] - Array of associated cnames. # * Comment [String] - Comment associated with distribution. # * Enabled [Boolean] - Whether or not distribution is enabled. # * Logging [Hash]: # * Bucket [String] - Bucket logs are stored in. # * Prefix [String] - Prefix logs are stored with. # * Origin [String] - S3 origin bucket. # * TrustedSigners [Array] - Trusted signers. # # @see http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateDistribution.html def post_distribution(options = {}) options['CallerReference'] = Time.now.to_i.to_s data = '' data << "" for key, value in options case value when Array for item in value data << "<#{key}>#{item}" end when Hash data << "<#{key}>" for inner_key, inner_value in value data << "<#{inner_key}>#{inner_value}" end data << "" else data << "<#{key}>#{value}" end end data << "" request({ :body => data, :expects => 201, :headers => { 'Content-Type' => 'text/xml' }, :idempotent => true, :method => 'POST', :parser => Fog::Parsers::CDN::AWS::Distribution.new, :path => "/distribution" }) end end class Mock require 'time' def post_distribution(options = {}) if self.data[:distributions].values.any? { |d| (d['CNAME'] & (options['CNAME']||[])).empty? } Fog::CDN::AWS::Mock.error(:invalid_argument, 'CNAME is already in use') end response = Excon::Response.new response.status = 201 options['CallerReference'] = Time.now.to_i.to_s dist_id = Fog::CDN::AWS::Mock.distribution_id distribution = { 'DomainName' => Fog::CDN::AWS::Mock.domain_name, 'Id' => dist_id, 'Status' => 'InProgress', 'LastModifiedTime' => Time.now.utc.iso8601, 'InProgressInvalidationBatches' => 0, 'DistributionConfig' => { 'CallerReference' => options['CallerReference'], 'CNAME' => options['CNAME'] || [], 'Comment' => options['Comment'], 'Enabled' => options['Enabled'], 'Logging' => { 'Bucket' => options['Bucket'], 'Prefix' => options['Prefix'] }, 'S3Origin' => options['S3Origin'], 'CustomOrigin' => options['CustomOrigin'], 'TrustedSigners' => options['TrustedSigners'] || [] } } self.data[:distributions][dist_id] = distribution response.body = distribution response end end end end endfog-1.19.0/lib/fog/aws/requests/cdn/delete_distribution.rb0000644000004100000410000000331712261242551023531 0ustar www-datawww-datamodule Fog module CDN class AWS class Real # Delete a distribution from CloudFront. # # @param distribution_id [String] Id of distribution to delete. # @param etag [String] etag of that distribution from earlier get or put # # @see http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/DeleteDistribution.html def delete_distribution(distribution_id, etag) request({ :expects => 204, :headers => { 'If-Match' => etag }, :idempotent => true, :method => 'DELETE', :path => "/distribution/#{distribution_id}" }) end end class Mock def delete_distribution(distribution_id, etag) distribution = self.data[:distributions][distribution_id] if distribution if distribution['ETag'] != etag Fog::CDN::AWS::Mock.error(:invalid_if_match_version) end unless distribution['DistributionConfig']['CallerReference'] Fog::CDN::AWS::Mock.error(:illegal_update) end if distribution['DistributionConfig']['Enabled'] Fog::CDN::AWS::Mock.error(:distribution_not_disabled) end self.data[:distributions].delete(distribution_id) self.data[:invalidations].delete(distribution_id) response = Excon::Response.new response.status = 204 response.body = "x-amz-request-id: #{Fog::AWS::Mock.request_id}" response else Fog::CDN::AWS::Mock.error(:no_such_distribution) end end end end end end fog-1.19.0/lib/fog/aws/requests/cdn/put_distribution_config.rb0000644000004100000410000001250112261242551024417 0ustar www-datawww-datamodule Fog module CDN class AWS class Real require 'fog/aws/parsers/cdn/distribution' # Update a distribution in CloudFront. # # @param distribution_id [String] Id of distribution to update config for. # @param options [Hash] Config for distribution. # # REQUIRED: # * S3Origin [Hash]: # * DNSName [String] - origin to associate with distribution, ie 'mybucket.s3.amazonaws.com'. # * OriginAccessIdentity [String] - Optional: Used when serving private content. # or # * CustomOrigin [Hash]: # * DNSName [String] - Origin to associate with distribution, ie 'www.example.com'. # * HTTPPort [Integer] - HTTP port of origin, in [80, 443] or (1024...65535). # * HTTPSPort [Integer] - HTTPS port of origin, in [80, 443] or (1024...65535). # * OriginProtocolPolicy [String] - Policy on using http vs https, in ['http-only', 'match-viewer']. # OPTIONAL: # * CallerReference [String] Used to prevent replay, defaults to Time.now.to_i.to_s. # * Comment [String] Optional comment about distribution. # * CNAME [Array] Optional array of strings to set as CNAMEs. # * DefaultRootObject [String] Optional default object to return for '/'. # * Enabled [Boolean] Whether or not distribution should accept requests, defaults to true. # * Logging [Hash]: Optional logging config. # * Bucket [String] Bucket to store logs in, ie 'mylogs.s3.amazonaws.com'. # * Prefix [String] Optional prefix for log filenames, ie 'myprefix/'. # * OriginAccessIdentity [String] Used for serving private content, in format 'origin-access-identity/cloudfront/ID'. # * RequiredProtocols [String] Optional, set to 'https' to force https connections. # * TrustedSigners [Array] Optional grant of rights to up to 5 aws accounts to generate signed URLs for private content, elements are either 'Self' for your own account or an AWS Account Number. # # @return [Excon::Response] # * body [Hash]: # * DomainName [String]: Domain name of distribution. # * Id [String] - Id of distribution. # * LastModifiedTime [String] - Timestamp of last modification of distribution. # * Status [String] - Status of distribution. # * DistributionConfig [Array]: # * CallerReference [String] - Used to prevent replay, defaults to Time.now.to_i.to_s. # * CNAME [Array] - Array of associated cnames. # * Comment [String] - Comment associated with distribution. # * Enabled [Boolean] - Whether or not distribution is enabled. # * Logging [Hash]: # * Bucket [String] - Bucket logs are stored in. # * Prefix [String] - Prefix logs are stored with. # * Origin [String] - S3 origin bucket. # * TrustedSigners [Array] - Trusted signers. # # @see http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateDistribution.html def put_distribution_config(distribution_id, etag, options = {}) data = '' data << "" for key, value in options case value when Array for item in value data << "<#{key}>#{item}" end when Hash data << "<#{key}>" for inner_key, inner_value in value data << "<#{inner_key}>#{inner_value}" end data << "" else data << "<#{key}>#{value}" end end data << "" request({ :body => data, :expects => 200, :headers => { 'Content-Type' => 'text/xml', 'If-Match' => etag }, :idempotent => true, :method => 'PUT', :parser => Fog::Parsers::CDN::AWS::Distribution.new, :path => "/distribution/#{distribution_id}/config" }) end end class Mock def put_distribution_config(distribution_id, etag, options = {}) distribution = self.data[:distributions][distribution_id] if distribution if distribution['ETag'] != etag Fog::CDN::AWS::Mock.error(:invalid_if_match_version) end unless distribution['DistributionConfig']['CallerReference'] Fog::CDN::AWS::Mock.error(:illegal_update) end distribution['DistributionConfig'].merge!(options) distribution['Status'] = 'InProgress' response = Excon::Response.new response.status = 200 response.headers['ETag'] = Fog::CDN::AWS::Mock.generic_id response.body = distribution.merge({ 'LastModifiedTime' => Time.now.utc.iso8601 }).reject{ |k,v| k == 'ETag' } response else Fog::CDN::AWS::Mock.error(:no_such_distribution) end end end end end end fog-1.19.0/lib/fog/aws/requests/cdn/put_streaming_distribution_config.rb0000644000004100000410000001074212261242551026475 0ustar www-datawww-datamodule Fog module CDN class AWS class Real require 'fog/aws/parsers/cdn/streaming_distribution' # Update a streaming distribution in CloudFront. # # @param distribution_id [String] - Id of distribution to update config for. # @param options [Hash] - Config for distribution. # # REQUIRED: # * S3Origin [Hash]: # * DNSName [String] Origin to associate with distribution, ie 'mybucket.s3.amazonaws.com'. # OPTIONAL: # @option options CallerReference [String] Used to prevent replay, defaults to Time.now.to_i.to_s # @option options Comment [String] Optional comment about distribution # @option options CNAME [Array] Optional array of strings to set as CNAMEs # @option options Enabled [Boolean] Whether or not distribution should accept requests, defaults to true # @option options Logging [Hash]: Optional logging config # * Bucket [String] Bucket to store logs in, ie 'mylogs.s3.amazonaws.com' # * Prefix String] Optional prefix for log filenames, ie 'myprefix/' # # @return [Excon::Response] # * body [Hash]: # * DomainName [String] - Domain name of distribution. # * Id [String] - Id of distribution. # * LastModifiedTime [String] - Timestamp of last modification of distribution. # * Status [String] - Status of distribution. # * StreamingDistributionConfig [Array]: # * CallerReference [String] - Used to prevent replay, defaults to Time.now.to_i.to_s. # * CNAME [Array] - Array of associated cnames. # * Comment [String] - Comment associated with distribution. # * Enabled [Boolean] - Whether or not distribution is enabled. # * Logging [Hash]: # * Bucket [String] - Bucket logs are stored in. # * Prefix [String] - Prefix logs are stored with. # * Origin [String] - S3 origin bucket. # * TrustedSigners [Array] - Trusted signers. # # @see http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/PutStreamingDistribution.html def put_streaming_distribution_config(distribution_id, etag, options = {}) data = '' data << "" for key, value in options case value when Array for item in value data << "<#{key}>#{item}" end when Hash data << "<#{key}>" for inner_key, inner_value in value data << "<#{inner_key}>#{inner_value}" end data << "" else data << "<#{key}>#{value}" end end data << "" request({ :body => data, :expects => 200, :headers => { 'Content-Type' => 'text/xml', 'If-Match' => etag }, :idempotent => true, :method => 'PUT', :parser => Fog::Parsers::CDN::AWS::StreamingDistribution.new, :path => "/streaming-distribution/#{distribution_id}/config" }) end end class Mock def put_streaming_distribution_config(distribution_id, etag, options = {}) distribution = self.data[:streaming_distributions][distribution_id] if distribution if distribution['ETag'] != etag Fog::CDN::AWS::Mock.error(:invalid_if_match_version) end unless distribution['StreamingDistributionConfig']['CallerReference'] Fog::CDN::AWS::Mock.error(:illegal_update) end distribution['StreamingDistributionConfig'].merge!(options) distribution['Status'] = 'InProgress' response = Excon::Response.new response.status = 200 response.headers['ETag'] = Fog::CDN::AWS::Mock.generic_id response.body = distribution.merge({ 'LastModifiedTime' => Time.now.utc.iso8601 }).reject{ |k,v| k == 'ETag' } response else Fog::CDN::AWS::Mock.error(:no_such_streaming_distribution) end end end end end end fog-1.19.0/lib/fog/aws/requests/cdn/get_streaming_distribution.rb0000644000004100000410000000540612261242551025120 0ustar www-datawww-datamodule Fog module CDN class AWS class Real require 'fog/aws/parsers/cdn/streaming_distribution' # Get information about a streaming distribution from CloudFront. # # @param distribution_id [String] Id of distribution. # # @return [Excon::Response] # * body [Hash]: # * S3Origin [Hash]: # * DNSName [String] - Origin to associate with distribution, ie 'mybucket.s3.amazonaws.com'. # * OriginAccessIdentity [String] - Optional: Used when serving private content. # * Id [String] - Id of distribution. # * LastModifiedTime [String] - Timestamp of last modification of distribution. # * Status [String] - Status of distribution. # * StreamingDistributionConfig [Array]: # * CallerReference [String] - Used to prevent replay, defaults to Time.now.to_i.to_s. # * CNAME [Array] - Array of associated cnames. # * Comment [String] - Comment associated with distribution. # * Enabled [Boolean] - Whether or not distribution is enabled. # * InProgressInvalidationBatches [Integer] - Number of invalidation batches in progress. # * Logging [Hash]: # * Bucket [String] - Bucket logs are stored in. # * Prefix [String] - Prefix logs are stored with. # * Origin [String] - S3 origin bucket. # * TrustedSigners [Array] - Trusted signers. # # @see http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetStreamingDistribution.html def get_streaming_distribution(distribution_id) request({ :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::CDN::AWS::StreamingDistribution.new, :path => "/streaming-distribution/#{distribution_id}" }) end end class Mock def get_streaming_distribution(distribution_id) response = Excon::Response.new distribution = self.data[:streaming_distributions][distribution_id] unless distribution Fog::CDN::AWS::Mock.error(:no_such_streaming_distribution) end if distribution['Status'] == 'InProgress' && (Time.now - Time.parse(distribution['LastModifiedTime']) >= Fog::Mock.delay * 2) distribution['Status'] = 'Deployed' end etag = Fog::CDN::AWS::Mock.generic_id response.status = 200 response.body = distribution.reject { |k,v| k == 'ETag' } response.headers['ETag'] = etag distribution['ETag'] = etag response end end end end end fog-1.19.0/lib/fog/aws/requests/cdn/get_streaming_distribution_list.rb0000644000004100000410000000666012261242551026156 0ustar www-datawww-datamodule Fog module CDN class AWS class Real require 'fog/aws/parsers/cdn/get_streaming_distribution_list' # List information about distributions in CloudFront. # # @param options [Hash] Config arguments for list. # @option options Marker [String] Limits object keys to only those that appear lexicographically after its value. # @option options MaxItems [Integer] Limits number of object keys returned. # # @return [Excon::Response] # * body [Hash]: # * IsTruncated [Boolean] - Whether or not the listing is truncated. # * Marker [String] - Marker specified for query. # * MaxItems [Integer] - Maximum number of keys specified for query. # * NextMarker [String] - Marker to specify for next page (id of last result of current page). # * StreamingDistributionSummary [Array]: # * S3Origin [Hash]: # * DNSName [String] - Origin to associate with distribution, ie 'mybucket.s3.amazonaws.com'. # * OriginAccessIdentity [String] - Optional: Used when serving private content. # or # * CustomOrigin [Hash]: # * DNSName [String] - Origin to associate with distribution, ie 'www.example.com'. # * HTTPPort [Integer] - HTTP port of origin, in [80, 443] or (1024...65535). # * HTTPSPort [Integer] - HTTPS port of origin, in [80, 443] or (1024...65535). # * OriginProtocolPolicy [String] - Policy on using http vs https, in ['http-only', 'match-viewer']. # * Comment [String] - Comment associated with distribution. # * CNAME [Array] - Array of associated cnames. # * Enabled [Boolean] - Whether or not distribution is enabled. # * Id [String] - Id of distribution. # * LastModifiedTime [String] - Timestamp of last modification of distribution. # * Origin [String] - S3 origin bucket. # * Status [String] - Status of distribution. # * TrustedSigners [Array] - Trusted signers. # # @see http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListStreamingDistributions.html def get_streaming_distribution_list(options = {}) request({ :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::CDN::AWS::GetStreamingDistributionList.new, :path => "/streaming-distribution", :query => options }) end end class Mock def get_streaming_distribution_list(options = {}) response = Excon::Response.new response.status = 200 distributions = self.data[:streaming_distributions].values response.body = { 'Marker' => Fog::Mock.random_hex(16), 'IsTruncated' => false, 'MaxItems' => 100, 'StreamingDistributionSummary' => distributions.map { |d| to_streaming_distribution_summary(d) } } response end private def to_streaming_distribution_summary(d) { 'DomainName' => d['DomainName'], 'Id' => d['Id'], 'LastModifiedTime' => d['LastModifiedTime'] }.merge(d['StreamingDistributionConfig']) end end end end end fog-1.19.0/lib/fog/aws/requests/cdn/get_distribution.rb0000644000004100000410000000627112261242551023050 0ustar www-datawww-datamodule Fog module CDN class AWS class Real require 'fog/aws/parsers/cdn/distribution' # Get information about a distribution from CloudFront. # # @param distribution_id [String] Id of distribution. # # @return [Excon::Response] # * body [Hash]: # * S3Origin [Hash]: # * DNSName [String] - Origin to associate with distribution, ie 'mybucket.s3.amazonaws.com'. # * OriginAccessIdentity [String] - Optional: Used when serving private content. # or # * CustomOrigin [Hash]: # * DNSName [String] - Origin to associate with distribution, ie 'www.example.com'. # * HTTPPort [Integer] - HTTP port of origin, in [80, 443] or (1024...65535). # * HTTPSPort [Integer] - HTTPS port of origin, in [80, 443] or (1024...65535). # * OriginProtocolPolicy [String] - Policy on using http vs https, in ['http-only', 'match-viewer']. # # * Id [String] Id of distribution. # * LastModifiedTime [String] - Timestamp of last modification of distribution. # * Status [String] - Status of distribution. # * DistributionConfig [Array]: # * CallerReference [String] - Used to prevent replay, defaults to Time.now.to_i.to_s. # * CNAME [Array] - Array of associated cnames. # * Comment [String] - Comment associated with distribution. # * Enabled [Boolean] - Whether or not distribution is enabled. # * InProgressInvalidationBatches [Integer] - Number of invalidation batches in progress. # * Logging [Hash]: # * Bucket [String] - Bucket logs are stored in. # * Prefix [String] - Prefix logs are stored with. # * Origin [String] - S3 origin bucket. # * TrustedSigners [Array] - Trusted signers. # # @see http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/GetDistribution.html def get_distribution(distribution_id) request({ :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::CDN::AWS::Distribution.new, :path => "/distribution/#{distribution_id}" }) end end class Mock def get_distribution(distribution_id) response = Excon::Response.new distribution = self.data[:distributions][distribution_id] unless distribution Fog::CDN::AWS::Mock.error(:no_such_distribution) end if distribution['Status'] == 'InProgress' && (Time.now - Time.parse(distribution['LastModifiedTime']) >= Fog::Mock.delay * 2) distribution['Status'] = 'Deployed' end etag = Fog::CDN::AWS::Mock.generic_id response.status = 200 response.body = { 'InProgressInvalidationBatches' => 0, }.merge(distribution.reject { |k,v| k == 'ETag' }) response.headers['ETag'] = etag distribution['ETag'] = etag response end end end end end fog-1.19.0/lib/fog/aws/requests/cdn/post_streaming_distribution.rb0000644000004100000410000001104412261242551025321 0ustar www-datawww-datamodule Fog module CDN class AWS class Real require 'fog/aws/parsers/cdn/streaming_distribution' # Create a new streaming distribution in CloudFront. # # @param options [Hash] Config for distribution. # # REQUIRED: # * S3Origin [Hash]: # * DNSName [String] Origin to associate with distribution, ie 'mybucket.s3.amazonaws.com'. # OPTIONAL: # * CallerReference [String] Used to prevent replay, defaults to Time.now.to_i.to_s. # * Comment [String] Optional comment about distribution. # * CNAME [Array] Optional array of strings to set as CNAMEs. # * Enabled [Boolean] Whether or not distribution should accept requests, defaults to true. # * Logging [Hash]: Optional logging config. # * Bucket [String] Bucket to store logs in, ie 'mylogs.s3.amazonaws.com'. # * Prefix [String] Optional prefix for log filenames, ie 'myprefix/'. # # @return [Excon::Response] # * body[Hash]: # * Id [String] - Id of distribution. # * Status'[String] - Status of distribution. # * LastModifiedTime [String] - Timestamp of last modification of distribution. # * DomainName [String] - Domain name of distribution. # * StreamingDistributionConfig [Array]: # * CallerReference [String] - Used to prevent replay, defaults to Time.now.to_i.to_s. # * CNAME [Array] - Array of associated cnames. # * Comment [String] - Comment associated with distribution. # * Enabled [Boolean] - Whether or not distribution is enabled. # * Logging [Hash]: # * Bucket [String] - Bucket logs are stored in. # * Prefix [String] - Prefix logs are stored with. # # @see http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/CreateStreamingDistribution.html def post_streaming_distribution(options = {}) options['CallerReference'] = Time.now.to_i.to_s data = '' data << "" for key, value in options case value when Array for item in value data << "<#{key}>#{item}" end when Hash data << "<#{key}>" for inner_key, inner_value in value data << "<#{inner_key}>#{inner_value}" end data << "" else data << "<#{key}>#{value}" end end data << "" request({ :body => data, :expects => 201, :headers => { 'Content-Type' => 'text/xml' }, :idempotent => true, :method => 'POST', :parser => Fog::Parsers::CDN::AWS::StreamingDistribution.new, :path => "/streaming-distribution" }) end end class Mock require 'time' def post_streaming_distribution(options = {}) if self.data[:streaming_distributions].values.any? { |d| (d['CNAME'] & (options['CNAME']||[])).empty? } Fog::CDN::AWS::Mock.error(:invalid_argument, 'CNAME is already in use') end response = Excon::Response.new response.status = 201 options['CallerReference'] = Time.now.to_i.to_s dist_id = Fog::CDN::AWS::Mock.distribution_id distribution = { 'DomainName' => Fog::CDN::AWS::Mock.domain_name, 'Id' => dist_id, 'Status' => 'InProgress', 'LastModifiedTime' => Time.now.utc.iso8601, 'StreamingDistributionConfig' => { 'CallerReference' => options['CallerReference'], 'CNAME' => options['CNAME'] || [], 'Comment' => options['Comment'], 'Enabled' => options['Enabled'], 'Logging' => { 'Bucket' => options['Bucket'], 'Prefix' => options['Prefix'] }, 'S3Origin' => options['S3Origin'], 'TrustedSigners' => options['TrustedSigners'] || [] } } self.data[:streaming_distributions][dist_id] = distribution response.body = distribution response end end end end end fog-1.19.0/lib/fog/aws/requests/dynamodb/0000755000004100000410000000000012261242551020170 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/dynamodb/update_table.rb0000644000004100000410000000357612261242551023161 0ustar www-datawww-datamodule Fog module AWS class DynamoDB class Real # Update DynamoDB table throughput # # ==== Parameters # * 'table_name'<~String> - name of table to describe # * 'provisioned_throughput'<~Hash>: # * 'ReadCapacityUnits'<~Integer> - read capacity for table, in 5..10000 # * 'WriteCapacityUnits'<~Integer> - write capacity for table, in 5..10000 # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Table'<~Hash> # * 'KeySchema'<~Hash> - schema for table # * 'HashKeyElement'<~Hash>: info for primary key # * 'AttributeName'<~String> - name of attribute # * 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set # * 'RangeKeyElement'<~Hash>: optional, info for range key # * 'AttributeName'<~String> - name of attribute # * 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set # * 'ProvisionedThroughput'<~Hash>: # * 'ReadCapacityUnits'<~Integer> - read capacity for table, in 5..10000 # * 'WriteCapacityUnits'<~Integer> - write capacity for table, in 5..10000 # * 'TableName'<~String> - name of table # * 'TableStatus'<~String> - status of table def update_table(table_name, provisioned_throughput) body = { 'ProvisionedThroughput' => provisioned_throughput, 'TableName' => table_name } request( :body => Fog::JSON.encode(body), :headers => {'x-amz-target' => 'DynamoDB_20111205.UpdateTable'}, :idempotent => true ) end end end end end fog-1.19.0/lib/fog/aws/requests/dynamodb/batch_write_item.rb0000644000004100000410000000172212261242551024030 0ustar www-datawww-datamodule Fog module AWS class DynamoDB class Real def batch_put_item(request_items) Fog::Logger.deprecation("batch_put_item is deprecated, use batch_write_item instead") batch_write_item(request_items) end #request_items has form: #{"table_name"=> # [{"PutRequest"=> # {"Item"=> # {"hash_key"=>{"N"=>"99"}, # "range_key"=>{"N"=>"99"}, # "attribute"=>{"S"=>"hi"} # }}}, ... ]} # For more information: # http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/API_BatchWriteItems.html def batch_write_item(request_items) body = { 'RequestItems' => request_items } request( :body => Fog::JSON.encode(body), :headers => {'x-amz-target' => 'DynamoDB_20111205.BatchWriteItem'} ) end end end end end fog-1.19.0/lib/fog/aws/requests/dynamodb/batch_get_item.rb0000644000004100000410000000300712261242551023453 0ustar www-datawww-datamodule Fog module AWS class DynamoDB class Real # Get DynamoDB items # # ==== Parameters # * 'request_items'<~Hash>: # * 'table_name'<~Hash>: # * 'Keys'<~Array>: array of keys # * 'HashKeyElement'<~Hash>: info for primary key # * 'AttributeType'<~String> - type of attribute # * 'AttributeName'<~String> - name of attribute # * 'RangeKeyElement'<~Hash>: optional, info for range key # * 'AttributeType'<~String> - type of attribute # * 'AttributeName'<~String> - name of attribute # * 'AttributesToGet'<~Array> - optional attributes to return, defaults to all # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Responses'<~Hash>: # * 'table_name'<~Hash>: # * 'Items'<~Array> - Matching items # * 'ConsumedCapacityUnits'<~Float> - Capacity units used in read # * 'UnprocessedKeys':<~Hash> - tables and keys in excess of per request limit, pass this to subsequent batch get for pseudo-pagination def batch_get_item(request_items) body = { 'RequestItems' => request_items } request( :body => Fog::JSON.encode(body), :headers => {'x-amz-target' => 'DynamoDB_20111205.BatchGetItem'}, :idempotent => true ) end end end end end fog-1.19.0/lib/fog/aws/requests/dynamodb/delete_table.rb0000644000004100000410000000310412261242551023124 0ustar www-datawww-datamodule Fog module AWS class DynamoDB class Real # Delete DynamoDB table # # ==== Parameters # * 'table_name'<~String> - name of table to delete # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'TableDescription'<~Hash> # * 'KeySchema'<~Hash> - schema for table # * 'HashKeyElement'<~Hash>: info for primary key # * 'AttributeName'<~String> - name of attribute # * 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set # * 'RangeKeyElement'<~Hash>: optional, info for range key # * 'AttributeName'<~String> - name of attribute # * 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set # * 'ProvisionedThroughput'<~Hash>: # * 'ReadCapacityUnits'<~Integer> - read capacity for table, in 5..10000 # * 'WriteCapacityUnits'<~Integer> - write capacity for table, in 5..10000 # * 'TableName'<~String> - name of table # * 'TableStatus'<~String> - status of table def delete_table(table_name) body = { 'TableName' => table_name } request( :body => Fog::JSON.encode(body), :headers => {'x-amz-target' => 'DynamoDB_20111205.DeleteTable'}, :idempotent => true ) end end end end end fog-1.19.0/lib/fog/aws/requests/dynamodb/list_tables.rb0000644000004100000410000000151712261242551023026 0ustar www-datawww-datamodule Fog module AWS class DynamoDB class Real # List DynamoDB tables # # ==== Parameters # * 'options'<~Hash> - options, defaults to {} # * 'ExclusiveStartTableName'<~String> - name of table to begin listing with # * 'Limit'<~Integer> - limit number of tables to return # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'LastEvaluatedTableName'<~String> - last table name, for pagination # * 'TableNames'<~Array> - table names def list_tables(options = {}) request( :body => Fog::JSON.encode(options), :headers => {'x-amz-target' => 'DynamoDB_20111205.ListTables'}, :idempotent => true ) end end end end end fog-1.19.0/lib/fog/aws/requests/dynamodb/describe_table.rb0000644000004100000410000000333012261242551023443 0ustar www-datawww-datamodule Fog module AWS class DynamoDB class Real # Describe DynamoDB table # # ==== Parameters # * 'table_name'<~String> - name of table to describe # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Table'<~Hash> # * 'CreationDateTime'<~Float> - Unix epoch time of table creation # * 'KeySchema'<~Hash> - schema for table # * 'HashKeyElement'<~Hash>: info for primary key # * 'AttributeName'<~String> - name of attribute # * 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set # * 'RangeKeyElement'<~Hash>: optional, info for range key # * 'AttributeName'<~String> - name of attribute # * 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set # * 'ProvisionedThroughput'<~Hash>: # * 'ReadCapacityUnits'<~Integer> - read capacity for table, in 5..10000 # * 'WriteCapacityUnits'<~Integer> - write capacity for table, in 5..10000 # * 'TableName'<~String> - name of table # * 'TableSizeBytes'<~Integer> - size of table in bytes # * 'TableStatus'<~String> - status of table def describe_table(table_name) body = { 'TableName' => table_name } request( :body => Fog::JSON.encode(body), :headers => {'x-amz-target' => 'DynamoDB_20111205.DescribeTable'}, :idempotent => true ) end end end end end fog-1.19.0/lib/fog/aws/requests/dynamodb/query.rb0000644000004100000410000000367112261242551021671 0ustar www-datawww-datamodule Fog module AWS class DynamoDB class Real # Query DynamoDB items # # ==== Parameters # * 'table_name'<~String> - name of table to query # * 'hash_key'<~Hash> - hash key to query # * options<~Hash>: # * 'AttributesToGet'<~Array> - Array of attributes to get for each item, defaults to all # * 'ConsistentRead'<~Boolean> - Whether to wait for consistency, defaults to false # * 'Count'<~Boolean> - If true, returns only a count of such items rather than items themselves, defaults to false # * 'Limit'<~Integer> - limit of total items to return # * 'RangeKeyCondition'<~Hash>: value to compare against range key # * 'AttributeValueList'<~Hash>: one or more values to compare against # * 'ComparisonOperator'<~String>: comparison operator to use with attribute value list, in %w{BETWEEN BEGINS_WITH EQ LE LT GE GT} # * 'ScanIndexForward'<~Boolean>: Whether to scan from start or end of index, defaults to start # * 'ExclusiveStartKey'<~Hash>: Key to start listing from, can be taken from LastEvaluatedKey in response # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ConsumedCapacityUnits'<~Integer> - number of capacity units used for query # * 'Count'<~Integer> - number of items in response # * 'Items'<~Array> - array of items returned # * 'LastEvaluatedKey'<~Hash> - last key scanned, can be passed to ExclusiveStartKey for pagination def query(table_name, hash_key, options = {}) body = { 'TableName' => table_name, 'HashKeyValue' => hash_key }.merge(options) request( :body => Fog::JSON.encode(body), :headers => {'x-amz-target' => 'DynamoDB_20111205.Query'} ) end end end end end fog-1.19.0/lib/fog/aws/requests/dynamodb/create_table.rb0000644000004100000410000000503412261242551023131 0ustar www-datawww-datamodule Fog module AWS class DynamoDB class Real # Create DynamoDB table # # ==== Parameters # * 'table_name'<~String> - name of table to create # * 'key_schema'<~Hash>: # * 'HashKeyElement'<~Hash>: info for primary key # * 'AttributeName'<~String> - name of attribute # * 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set # * 'RangeKeyElement'<~Hash>: optional, info for range key # * 'AttributeName'<~String> - name of attribute # * 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set # * 'provisioned_throughput'<~Hash>: # * 'ReadCapacityUnits'<~Integer> - read capacity for table, in 5..10000 # * 'WriteCapacityUnits'<~Integer> - write capacity for table, in 5..10000 # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'TableDescription'<~Hash> # * 'CreationDateTime'<~Float> - Unix epoch time of table creation # * 'KeySchema'<~Hash> - schema for table # * 'HashKeyElement'<~Hash>: info for primary key # * 'AttributeName'<~String> - name of attribute # * 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set # * 'RangeKeyElement'<~Hash>: optional, info for range key # * 'AttributeName'<~String> - name of attribute # * 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set # * 'ProvisionedThroughput'<~Hash>: # * 'ReadCapacityUnits'<~Integer> - read capacity for table, in 5..10000 # * 'WriteCapacityUnits'<~Integer> - write capacity for table, in 5..10000 # * 'TableName'<~String> - name of table # * 'TableStatus'<~String> - status of table def create_table(table_name, key_schema, provisioned_throughput) body = { 'KeySchema' => key_schema, 'ProvisionedThroughput' => provisioned_throughput, 'TableName' => table_name } request( :body => Fog::JSON.encode(body), :headers => {'x-amz-target' => 'DynamoDB_20111205.CreateTable'}, :idempotent => true ) end end end end end fog-1.19.0/lib/fog/aws/requests/dynamodb/delete_item.rb0000644000004100000410000000325312261242551023000 0ustar www-datawww-datamodule Fog module AWS class DynamoDB class Real # Delete DynamoDB item # # ==== Parameters # * 'table_name'<~String> - name of table for item # * 'key'<~Hash>: # * 'HashKeyElement'<~Hash>: info for primary key # * 'AttributeName'<~String> - name of attribute # * 'AttributeType'<~String> - type of attribute # * 'RangeKeyElement'<~Hash>: optional, info for range key # * 'AttributeName'<~String> - name of attribute # * 'AttributeType'<~String> - type of attribute # * 'options'<~Hash>: # * 'Expected'<~Hash>: data to check against # * 'AttributeName'<~String> - name of attribute # * 'Value'<~Hash> - a value to check for the value of # or # * 'Exists'<~Boolean> - set as false to only allow update if attribute doesn't exist # * 'ReturnValues'<~String> - data to return in %w{ALL_NEW ALL_OLD NONE UPDATED_NEW UPDATED_OLD}, defaults to NONE # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # varies based on ReturnValues param, see: http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/API_UpdateItem.html def delete_item(table_name, key, options = {}) body = { 'Key' => key, 'TableName' => table_name }.merge(options) request( :body => Fog::JSON.encode(body), :headers => {'x-amz-target' => 'DynamoDB_20111205.DeleteItem'}, :idempotent => true ) end end end end end fog-1.19.0/lib/fog/aws/requests/dynamodb/put_item.rb0000644000004100000410000000302312261242551022341 0ustar www-datawww-datamodule Fog module AWS class DynamoDB class Real # Update DynamoDB item # # ==== Parameters # * 'table_name'<~String> - name of table for item # * 'item'<~Hash>: data to update, must include primary key # * 'AttributeName'<~String> - Attribute to update # * 'Value'<~Hash> - formated as {type => value} # * 'Action'<~String> - action to take if expects matches, in %w{ADD DELETE PUT}, defaults to PUT # * 'options'<~Hash>: # * 'Expected'<~Hash>: data to check against # * 'AttributeName'<~String> - name of attribute # * 'Value'<~Hash> - a value to check for the value of # or # * 'Exists'<~Boolean> - set as false to only allow update if attribute doesn't exist # * 'ReturnValues'<~String> - data to return in %w{ALL_NEW ALL_OLD NONE UPDATED_NEW UPDATED_OLD}, defaults to NONE # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # varies based on ReturnValues param, see: http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/API_UpdateItem.html def put_item(table_name, item, options = {}) body = { 'Item' => item, 'TableName' => table_name }.merge(options) request( :body => Fog::JSON.encode(body), :headers => {'x-amz-target' => 'DynamoDB_20111205.PutItem'} ) end end end end end fog-1.19.0/lib/fog/aws/requests/dynamodb/get_item.rb0000644000004100000410000000272612261242551022321 0ustar www-datawww-datamodule Fog module AWS class DynamoDB class Real # Get DynamoDB item # # ==== Parameters # * 'table_name'<~String> - name of table for item # * 'key'<~Hash>: # * 'HashKeyElement'<~Hash>: info for primary key # * 'AttributeType'<~String> - type of attribute # * 'AttributeName'<~String> - name of attribute # * 'RangeKeyElement'<~Hash>: optional, info for range key # * 'AttributeType'<~String> - type of attribute # * 'AttributeName'<~String> - name of attribute # * 'options'<~Hash>: # * 'AttributesToGet'<~Array>: list of array names to return, defaults to returning all # * 'ConsistentRead'<~Boolean>: whether to wait for updates, defaults to false # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ConsumedCapacityUnits'<~Float> - Capacity units used in read # * 'Item':<~Hash>: # * 'AttributeName'<~Hash>: in form of {"type":value} def get_item(table_name, key, options = {}) body = { 'Key' => key, 'TableName' => table_name }.merge(options) request( :body => Fog::JSON.encode(body), :headers => {'x-amz-target' => 'DynamoDB_20111205.GetItem'}, :idempotent => true ) end end end end end fog-1.19.0/lib/fog/aws/requests/dynamodb/scan.rb0000644000004100000410000000374612261242551021453 0ustar www-datawww-datamodule Fog module AWS class DynamoDB class Real # Scan DynamoDB items # # ==== Parameters # * 'table_name'<~String> - name of table to query # * options<~Hash>: # * 'AttributesToGet'<~Array> - Array of attributes to get for each item, defaults to all # * 'ConsistentRead'<~Boolean> - Whether to wait for consistency, defaults to false # * 'Count'<~Boolean> - If true, returns only a count of such items rather than items themselves, defaults to false # * 'Limit'<~Integer> - limit of total items to return # * 'ScanFilter'<~Hash>: value to compare against # * attribute_name<~Hash>: # * 'AttributeValueList'<~Hash>: one or more values to compare against # * 'ComparisonOperator'<~String>: comparison operator to use with attribute value list, in %w{BETWEEN BEGINS_WITH EQ LE LT GE GT} # * 'ScanIndexForward'<~Boolean>: Whether to scan from start or end of index, defaults to start # * 'ExclusiveStartKey'<~Hash>: Key to start listing from, can be taken from LastEvaluatedKey in response # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ConsumedCapacityUnits'<~Integer> - number of capacity units used for scan # * 'Count'<~Integer> - number of items in response # * 'Items'<~Array> - array of items returned # * 'LastEvaluatedKey'<~Hash> - last key scanned, can be passed to ExclusiveStartKey for pagination # * 'ScannedCount'<~Integer> - number of items scanned before applying filters def scan(table_name, options = {}) body = { 'TableName' => table_name }.merge(options) request( :body => Fog::JSON.encode(body), :headers => {'x-amz-target' => 'DynamoDB_20111205.Scan'}, :idempotent => true ) end end end end end fog-1.19.0/lib/fog/aws/requests/dynamodb/update_item.rb0000644000004100000410000000373712261242551023027 0ustar www-datawww-datamodule Fog module AWS class DynamoDB class Real # Update DynamoDB item # # ==== Parameters # * 'table_name'<~String> - name of table for item # * 'key'<~Hash>: # * 'HashKeyElement'<~Hash>: info for primary key # * 'AttributeName'<~String> - name of attribute # * 'AttributeType'<~String> - type of attribute # * 'RangeKeyElement'<~Hash>: optional, info for range key # * 'AttributeName'<~String> - name of attribute # * 'AttributeType'<~String> - type of attribute # * 'attribute_updates'<~Hash>: # * 'AttributeName'<~String> - Attribute to update # * 'Value'<~Hash> - formated as {type => value} # * 'Action'<~String> - action to take if expects matches, in %w{ADD DELETE PUT}, defaults to PUT # * 'options'<~Hash>: # * 'Expected'<~Hash>: data to check against # * 'AttributeName'<~String> - name of attribute # * 'Value'<~Hash> - a value to check for the value of # or # * 'Exists'<~Boolean> - set as false to only allow update if attribute doesn't exist # * 'ReturnValues'<~String> - data to return in %w{ALL_NEW ALL_OLD NONE UPDATED_NEW UPDATED_OLD}, defaults to NONE # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # varies based on ReturnValues param, see: http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/API_UpdateItem.html def update_item(table_name, key, attribute_updates, options = {}) body = { 'AttributeUpdates' => attribute_updates, 'Key' => key, 'TableName' => table_name }.merge(options) request( :body => Fog::JSON.encode(body), :headers => {'x-amz-target' => 'DynamoDB_20111205.UpdateItem'} ) end end end end end fog-1.19.0/lib/fog/aws/requests/rds/0000755000004100000410000000000012261242551017163 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/rds/delete_db_security_group.rb0000644000004100000410000000237612261242551024572 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/delete_db_security_group' # deletes a db security group # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/index.html?API_DeleteDBSecurityGroup.html # ==== Parameters # * DBSecurityGroupName <~String> - The name for the DB Security Group to delete # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def delete_db_security_group(name) request({ 'Action' => 'DeleteDBSecurityGroup', 'DBSecurityGroupName' => name, :parser => Fog::Parsers::AWS::RDS::DeleteDBSecurityGroup.new }) end end class Mock def delete_db_security_group(name, description = name) response = Excon::Response.new if self.data[:security_groups].delete(name) response.status = 200 response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, } response else raise Fog::AWS::RDS::NotFound.new("DBSecurityGroupNotFound => #{name} not found") end end end end end end fog-1.19.0/lib/fog/aws/requests/rds/delete_db_instance.rb0000644000004100000410000000372112261242551023306 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/delete_db_instance' # delete a database instance # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_DeleteDBInstance.html # ==== Parameters # * DBInstanceIdentifier <~String> - The DB Instance identifier for the DB Instance to be deleted. # * FinalDBSnapshotIdentifier <~String> - The DBSnapshotIdentifier of the new DBSnapshot created when SkipFinalSnapshot is set to false # * SkipFinalSnapshot <~Boolean> - Determines whether a final DB Snapshot is created before the DB Instance is deleted # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def delete_db_instance(identifier, snapshot_identifier, skip_snapshot = false) params = {} params['FinalDBSnapshotIdentifier'] = snapshot_identifier if snapshot_identifier request({ 'Action' => 'DeleteDBInstance', 'DBInstanceIdentifier' => identifier, 'SkipFinalSnapshot' => skip_snapshot, :parser => Fog::Parsers::AWS::RDS::DeleteDBInstance.new }.merge(params)) end end class Mock def delete_db_instance(identifier, snapshot_identifier, skip_snapshot = false) response = Excon::Response.new unless skip_snapshot create_db_snapshot(identifier, snapshot_identifier) end if server_set = self.data[:servers].delete(identifier) response.status = 200 response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, "DeleteDBInstanceResult" => { "DBInstance" => server_set } } response else raise Fog::AWS::RDS::NotFound.new("DBInstance #{identifier} not found") end end end end end end fog-1.19.0/lib/fog/aws/requests/rds/list_tags_for_resource.rb0000644000004100000410000000240412261242551024256 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/tag_list_parser' # returns a Hash of tags for a database instance # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_ListTagsForResource.html # ==== Parameters # * rds_id <~String> - name of the RDS instance whose tags are to be retrieved # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def list_tags_for_resource(rds_id) request( 'Action' => 'ListTagsForResource', 'ResourceName' => "arn:aws:rds:#{@region}:#{owner_id}:db:#{rds_id}", :parser => Fog::Parsers::AWS::RDS::TagListParser.new ) end end class Mock def list_tags_for_resource(rds_id) response = Excon::Response.new if server = self.data[:servers][rds_id] response.status = 200 response.body = { "ListTagsForResourceResult" => {"TagList" => self.data[:tags][rds_id]} } response else raise Fog::AWS::RDS::NotFound.new("DBInstance #{rds_id} not found") end end end end end end fog-1.19.0/lib/fog/aws/requests/rds/modify_db_parameter_group.rb0000644000004100000410000000401712261242551024722 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/modify_db_parameter_group' # modifies a database parameter group # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_ModifyDBParameterGroup.html # ==== Parameters # * DBParameterGroupName <~String> - name of the parameter group # * Parameters<~Array> - Array of up to 20 Hashes describing parameters to set # * 'ParameterName'<~String> - parameter name. # * 'ParameterValue'<~String> - new paremeter value # * 'ApplyMethod'<~String> - immediate | pending-reboot whether to set the parameter immediately or not (may require an instance restart) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def modify_db_parameter_group(group_name, parameters) parameter_names = [] parameter_values = [] parameter_apply_methods = [] parameters.each do |parameter| parameter_names.push(parameter['ParameterName']) parameter_values.push(parameter['ParameterValue']) parameter_apply_methods.push(parameter['ApplyMethod']) end params = {} params.merge!(Fog::AWS.indexed_param('Parameters.member.%d.ParameterName', parameter_names)) params.merge!(Fog::AWS.indexed_param('Parameters.member.%d.ParameterValue', parameter_values)) params.merge!(Fog::AWS.indexed_param('Parameters.member.%d.ApplyMethod', parameter_apply_methods)) request({ 'Action' => 'ModifyDBParameterGroup', 'DBParameterGroupName' => group_name, :parser => Fog::Parsers::AWS::RDS::ModifyDbParameterGroup.new }.merge(params)) end end class Mock def modify_db_parameter_group(group_name, parameters) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/rds/describe_db_log_files.rb0000644000004100000410000000651112261242551023763 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/describe_db_log_files' # Describe log files for a DB instance # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_DescribeDBLogFiles.html # ==== Parameters # * DBInstanceIdentifier <~String> - ID of instance to retrieve information for. Required. # * Options <~Hash> - Hash of options. Optional. The following keys are used: # * :file_last_written <~Long> - Filter available log files for those written after this time. Optional. # * :file_size <~Long> - Filters the available log files for files larger than the specified size. Optional. # * :filename_contains <~String> - Filters the available log files for log file names that contain the specified string. Optional. # * :marker <~String> - The pagination token provided in the previous request. If this parameter is specified the response includes only records beyond the marker, up to MaxRecords. Optional. # * :max_records <~Integer> - The maximum number of records to include in the response. If more records exist, a pagination token is included in the response. Optional. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def describe_db_log_files(rds_id=nil, opts={}) params = {} params['DBInstanceIdentifier'] = rds_id if rds_id params['Marker'] = opts[:marker] if opts[:marker] params['MaxRecords'] = opts[:max_records] if opts[:max_records] params['FilenameContains'] = opts[:filename_contains] if opts[:filename_contains] params['FileSize'] = opts[:file_size] if opts[:file_size] params['FileLastWritten'] = opts[:file_last_written] if opts[:file_last_written] request({ 'Action' => 'DescribeDBLogFiles', :parser => Fog::Parsers::AWS::RDS::DescribeDBLogFiles.new(rds_id) }.merge(params)) end end class Mock def describe_db_log_files(rds_id=nil, opts={}) response = Excon::Response.new log_file_set = [] if rds_id if server = self.data[:servers][rds_id] log_file_set << {"LastWritten" => Time.parse('2013-07-05 17:00:00 -0700'), "LogFileName" => "error/mysql-error.log", "Size" => 0} log_file_set << {"LastWritten" => Time.parse('2013-07-05 17:10:00 -0700'), "LogFileName" => "error/mysql-error-running.log", "Size" => 0} log_file_set << {"LastWritten" => Time.parse('2013-07-05 17:20:00 -0700'), "LogFileName" => "error/mysql-error-running.log.0", "Size" => 8220} log_file_set << {"LastWritten" => Time.parse('2013-07-05 17:30:00 -0700'), "LogFileName" => "error/mysql-error-running.log.1", "Size" => 0} else raise Fog::AWS::RDS::NotFound.new("DBInstance #{rds_id} not found") end else raise Fog::AWS::RDS::NotFound.new('An identifier for an RDS instance must be provided') end response.status = 200 response.body = { "ResponseMetadata" => { "RequestId" => Fog::AWS::Mock.request_id }, "DescribeDBLogFilesResult" => { "DBLogFiles" => log_file_set } } response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/revoke_db_security_group_ingress.rb0000644000004100000410000000525312261242551026352 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/revoke_db_security_group_ingress' # revokes a db security group ingress # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/index.html?API_RevokeDBSecurityGroupIngress.html # ==== Parameters # * CIDRIP <~String> - The IP range to revoke # * DBSecurityGroupName <~String> - The name for the DB Security Group. # * EC2SecurityGroupName <~String> - Name of the EC2 Security Group to revoke. # * EC2SecurityGroupOwnerId <~String> - AWS Account Number of the owner of the security group specified in the EC2SecurityGroupName parameter. The AWS Access Key ID is not an acceptable value. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def revoke_db_security_group_ingress(name, opts={}) unless opts.key?('CIDRIP') || (opts.key?('EC2SecurityGroupName') && opts.key?('EC2SecurityGroupOwnerId')) raise ArgumentError, 'Must specify CIDRIP, or both EC2SecurityGroupName and EC2SecurityGroupOwnerId' end request({ 'Action' => 'RevokeDBSecurityGroupIngress', :parser => Fog::Parsers::AWS::RDS::RevokeDBSecurityGroupIngress.new, 'DBSecurityGroupName' => name }.merge(opts)) end end class Mock def revoke_db_security_group_ingress(name, opts = {}) unless opts.key?('CIDRIP') || (opts.key?('EC2SecurityGroupName') && opts.key?('EC2SecurityGroupOwnerId')) raise ArgumentError, 'Must specify CIDRIP, or both EC2SecurityGroupName and EC2SecurityGroupOwnerId' end response = Excon::Response.new if sec_group = self.data[:security_groups][name] if opts.key?('CIDRIP') sec_group['IPRanges'].each do |iprange| iprange['Status']= 'revoking' if iprange['CIDRIP'] == opts['CIDRIP'] end else sec_group['EC2SecurityGroups'].each do |ec2_secg| ec2_secg['Status']= 'revoking' if ec2_secg['EC2SecurityGroupName'] == opts['EC2SecurityGroupName'] end end response.status = 200 response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, 'RevokeDBSecurityGroupIngressResult' => { 'DBSecurityGroup' => sec_group } } response else raise Fog::AWS::RDS::NotFound.new("DBSecurityGroupNotFound => #{name} not found") end end end end end end fog-1.19.0/lib/fog/aws/requests/rds/describe_events.rb0000644000004100000410000000351212261242551022655 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/event_list' # Returns a list of service events # # For more information see: # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_DescribeEvents.html # # === Parameters (optional) # * options <~Hash> (optional): # * :start_time <~DateTime> - starting time for event records # * :end_time <~DateTime> - ending time for event records # * :duration <~Integer> - The number of minutes to retrieve events for # Default = 60 Mins # * :marker <~String> - marker provided in the previous request # * :max_records <~Integer> - the maximum number of records to include # Default = 100 # Constraints: min = 20, maximum 100 # * :source_identifier <~String> - identifier of the event source # * :source_type <~DateTime> - event type, one of: # (db-instance | db-parameter-group | db-security-group | db-snapshot) # === Returns # * response <~Excon::Response>: # * body <~Hash> def describe_events(options = {}) request( 'Action' => 'DescribeEvents', 'StartTime' => options[:start_time], 'EndTime' => options[:end_time], 'Duration' => options[:duration], 'Marker' => options[:marker], 'MaxRecords' => options[:max_records], 'SourceIdentifier' => options[:source_identifier], 'SourceType' => options[:source_type], :parser => Fog::Parsers::AWS::RDS::EventListParser.new ) end end class Mock def describe_events Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/rds/add_tags_to_resource.rb0000644000004100000410000000276312261242551023677 0ustar www-datawww-datamodule Fog module AWS class RDS class Real # adds tags to a database instance # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_AddTagsToResource.html # ==== Parameters # * rds_id <~String> - name of the RDS instance whose tags are to be retrieved # * tags <~Hash> A Hash of (String) key-value pairs # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def add_tags_to_resource(rds_id, tags) keys = tags.keys.sort values = keys.map {|key| tags[key]} request({ 'Action' => 'AddTagsToResource', 'ResourceName' => "arn:aws:rds:#{@region}:#{owner_id}:db:#{rds_id}", :parser => Fog::Parsers::AWS::RDS::Base.new, }.merge(Fog::AWS.indexed_param('Tags.member.%d.Key', keys)). merge(Fog::AWS.indexed_param('Tags.member.%d.Value', values))) end end class Mock def add_tags_to_resource(rds_id, tags) response = Excon::Response.new if server = self.data[:servers][rds_id] self.data[:tags][rds_id].merge! tags response.status = 200 response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id } } response else raise Fog::AWS::RDS::NotFound.new("DBInstance #{rds_id} not found") end end end end end end fog-1.19.0/lib/fog/aws/requests/rds/restore_db_instance_from_db_snapshot.rb0000644000004100000410000000171212261242551027134 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/restore_db_instance_from_db_snapshot' # Restores a DB Instance from a DB Snapshot # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/index.html?API_RestoreDBInstanceFromDBSnapshot.html # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def restore_db_instance_from_db_snapshot(snapshot_id, db_name, opts={}) request({ 'Action' => 'RestoreDBInstanceFromDBSnapshot', 'DBSnapshotIdentifier' => snapshot_id, 'DBInstanceIdentifier' => db_name, :parser => Fog::Parsers::AWS::RDS::RestoreDBInstanceFromDBSnapshot.new, }.merge(opts)) end end class Mock def restore_db_instance_from_db_snapshot(snapshot_id, db_id, options={}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/rds/create_db_instance_read_replica.rb0000644000004100000410000000720412261242551026001 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/create_db_instance_read_replica' # create a read replica db instance # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_CreateDBInstanceReadReplica.html # ==== Parameters # * DBInstanceIdentifier <~String> - name of the db instance to create # * SourceDBInstanceIdentifier <~String> - name of the db instance that will be the source. Must have backup retention on # * AutoMinorVersionUpgrade <~Boolean> Indicates that minor version upgrades will be applied automatically to the DB Instance during the maintenance window # * AvailabilityZone <~String> The availability zone to create the instance in # * DBInstanceClass <~String> The new compute and memory capacity of the DB Instance # * Port <~Integer> The port number on which the database accepts connections. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def create_db_instance_read_replica(instance_identifier, source_identifier, options={}) request({ 'Action' => 'CreateDBInstanceReadReplica', 'DBInstanceIdentifier' => instance_identifier, 'SourceDBInstanceIdentifier' => source_identifier, :parser => Fog::Parsers::AWS::RDS::CreateDBInstanceReadReplica.new, }.merge(options)) end end class Mock def create_db_instance_read_replica(instance_identifier, source_identifier, options={}) # TODO: throw error when instance_identifier already exists, # or source_identifier doesn't exist source = self.data[:servers][source_identifier] data = { 'AllocatedStorage' => source['AllocatedStorage'], 'AutoMinorVersionUpgrade' => options.key?('AutoMinorVersionUpgrade') ? options['AutoMinorVersionUpgrade'] : true, 'AvailabilityZone' => options['AvailabilityZone'], 'DBInstanceClass' => options['DBInstanceClass'] || 'db.m1.small', 'DBInstanceIdentifier' => instance_identifier, 'DBInstanceStatus' => 'creating', 'DBName' => source['DBName'], 'DBParameterGroups' => source['DBParameterGroups'], 'DBSecurityGroups' => source['DBSecurityGroups'], 'Endpoint' => {}, 'Engine' => source['Engine'], 'EngineVersion' => options['EngineVersion'] || '5.5.12', 'InstanceCreateTime' => nil, 'LatestRestorableTime' => nil, 'LicenseModel' => 'general-public-license', 'MasterUsername' => source['MasterUsername'], 'MultiAZ' => false, 'PendingModifiedValues' => {}, 'PreferredBackupWindow'=> '08:00-08:30', 'PreferredMaintenanceWindow'=> "mon:04:30-mon:05:00", 'ReadReplicaDBInstanceIdentifiers'=> [], 'ReadReplicaSourceDBInstanceIdentifier'=> source_identifier } self.data[:servers][instance_identifier] = data self.data[:servers][source_identifier]['ReadReplicaDBInstanceIdentifiers'] << instance_identifier response = Excon::Response.new response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, "CreateDBInstanceReadReplicaResult"=> {"DBInstance"=> data} } response.status = 200 # This values aren't showed at creating time but at available time self.data[:servers][instance_identifier]["InstanceCreateTime"] = Time.now response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/create_db_parameter_group.rb0000644000004100000410000000376512261242551024707 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/create_db_parameter_group' # create a database parameter group # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_CreateDBParameterGroup.html # ==== Parameters # * DBParameterGroupName <~String> - name of the parameter group # * DBParameterGroupFamily <~String> - The DB parameter group family name. Current valid values: MySQL5.1 | MySQL5.5 # * Description <~String> - The description for the DB Parameter Grou # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def create_db_parameter_group(group_name, group_family, description) request({ 'Action' => 'CreateDBParameterGroup', 'DBParameterGroupName' => group_name, 'DBParameterGroupFamily' => group_family, 'Description' => description, :parser => Fog::Parsers::AWS::RDS::CreateDbParameterGroup.new }) end end class Mock def create_db_parameter_group(group_name, group_family, description) response = Excon::Response.new if self.data[:parameter_groups] and self.data[:parameter_groups][group_name] raise Fog::AWS::RDS::IdentifierTaken.new("Parameter group #{group_name} already exists") end data = { 'DBParameterGroupName' => group_name, 'DBParameterGroupFamily' => group_family.downcase, 'Description' => description } self.data[:parameter_groups][group_name] = data response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, "CreateDBParameterGroupResult"=> {"DBParameterGroup"=> data} } response.status = 200 response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/describe_db_security_groups.rb0000644000004100000410000000645212261242551025272 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/describe_db_security_groups' # Describe all or specified db security groups # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/index.html?API_DescribeDBSecurityGroups.html # ==== Parameters # * DBSecurityGroupName <~String> - The name of the DB Security Group to return details for. # * Marker <~String> - An optional marker provided in the previous DescribeDBInstances request # * MaxRecords <~Integer> - Max number of records to return (between 20 and 100) # Only one of DBInstanceIdentifier or DBSnapshotIdentifier can be specified # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def describe_db_security_groups(opts={}) opts = {'DBSecurityGroupName' => opts} if opts.is_a?(String) request({ 'Action' => 'DescribeDBSecurityGroups', :parser => Fog::Parsers::AWS::RDS::DescribeDBSecurityGroups.new }.merge(opts)) end end class Mock def describe_db_security_groups(opts={}) response = Excon::Response.new sec_group_set = [] if opts.is_a?(String) sec_group_name = opts if sec_group = self.data[:security_groups][sec_group_name] sec_group_set << sec_group else raise Fog::AWS::RDS::NotFound.new("Security Group #{sec_group_name} not found") end else sec_group_set = self.data[:security_groups].values end # TODO: refactor to not delete items that we're iterating over. Causes # model tests to fail (currently pending) sec_group_set.each do |sec_group| sec_group["IPRanges"].each do |iprange| if iprange["Status"] == "authorizing" || iprange["Status"] == "revoking" iprange[:tmp] ||= Time.now + Fog::Mock.delay * 2 if iprange[:tmp] <= Time.now iprange["Status"] = "authorized" if iprange["Status"] == "authorizing" iprange.delete(:tmp) sec_group["IPRanges"].delete(iprange) if iprange["Status"] == "revoking" end end end # TODO: refactor to not delete items that we're iterating over. Causes # model tests to fail (currently pending) sec_group["EC2SecurityGroups"].each do |ec2_secg| if ec2_secg["Status"] == "authorizing" || ec2_secg["Status"] == "revoking" ec2_secg[:tmp] ||= Time.now + Fog::Mock.delay * 2 if ec2_secg[:tmp] <= Time.now ec2_secg["Status"] = "authorized" if ec2_secg["Status"] == "authorizing" ec2_secg.delete(:tmp) sec_group["EC2SecurityGroups"].delete(ec2_secg) if ec2_secg["Status"] == "revoking" end end end end response.status = 200 response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, "DescribeDBSecurityGroupsResult" => { "DBSecurityGroups" => sec_group_set } } response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/restore_db_instance_to_point_in_time.rb0000644000004100000410000000176112261242551027150 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/restore_db_instance_to_point_in_time' # Restores a DB Instance to a point in time # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/index.html?API_RestoreDBInstanceToPointInTime.html # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def restore_db_instance_to_point_in_time(source_db_name, target_db_name, opts={}) request({ 'Action' => 'RestoreDBInstanceToPointInTime', 'SourceDBInstanceIdentifier' => source_db_name, 'TargetDBInstanceIdentifier' => target_db_name, :parser => Fog::Parsers::AWS::RDS::RestoreDBInstanceToPointInTime.new, }.merge(opts)) end end class Mock def restore_db_instance_to_point_in_time(source_db_name, target_db_name, opts={}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/rds/describe_db_parameter_groups.rb0000644000004100000410000000404712261242551025401 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/describe_db_parameter_groups' # This API returns a list of DBParameterGroup descriptions. If a DBParameterGroupName is specified, the list will contain only the descriptions of the specified DBParameterGroup # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_DescribeDBParameterGroups.html # ==== Parameters # * DBParameterGroupName <~String> - The name of a specific database parameter group to return details for. # * Source <~String> - The parameter types to return. user | system | engine-default # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def describe_db_parameter_groups(name=nil, opts={}) params={} if opts[:marker] params['Marker'] = opts[:marker] end if name params['DBParameterGroupName'] = name end if opts[:max_records] params['MaxRecords'] = opts[:max_records] end request({ 'Action' => 'DescribeDBParameterGroups', :parser => Fog::Parsers::AWS::RDS::DescribeDBParameterGroups.new }.merge(params)) end end class Mock def describe_db_parameter_groups(name=nil, opts={}) response = Excon::Response.new parameter_set = [] if name if server = self.data[:parameter_groups][name] parameter_set << server else raise Fog::AWS::RDS::NotFound.new("DBInstance #{name} not found") end else parameter_set = self.data[:parameter_groups].values end response.status = 200 response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, "DescribeDBParameterGroupsResult" => { "DBParameterGroups" => parameter_set } } response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/describe_db_instances.rb0000644000004100000410000000653712261242551024017 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/describe_db_instances' # Describe all or specified load db instances # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_DescribeDBInstances.html # ==== Parameters # * DBInstanceIdentifier <~String> - ID of instance to retrieve information for. if absent information for all instances is returned # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def describe_db_instances(identifier=nil, opts={}) params = {} params['DBInstanceIdentifier'] = identifier if identifier if opts[:marker] params['Marker'] = opts[:marker] end if opts[:max_records] params['MaxRecords'] = opts[:max_records] end request({ 'Action' => 'DescribeDBInstances', :parser => Fog::Parsers::AWS::RDS::DescribeDBInstances.new }.merge(params)) end end class Mock def describe_db_instances(identifier=nil, opts={}) response = Excon::Response.new server_set = [] if identifier if server = self.data[:servers][identifier] server_set << server else raise Fog::AWS::RDS::NotFound.new("DBInstance #{identifier} not found") end else server_set = self.data[:servers].values end server_set.each do |server| case server["DBInstanceStatus"] when "creating" if Time.now - server['InstanceCreateTime'] >= Fog::Mock.delay * 2 region = "us-east-1" server["DBInstanceStatus"] = "available" server["AvailabilityZone"] ||= region + 'a' server["Endpoint"] = {"Port"=>3306, "Address"=> Fog::AWS::Mock.rds_address(server["DBInstanceIdentifier"],region) } server["PendingModifiedValues"] = {} end when "rebooting" if Time.now - self.data[:reboot_time] >= Fog::Mock.delay # apply pending modified values server.merge!(server["PendingModifiedValues"]) server["PendingModifiedValues"] = {} server["DBInstanceStatus"] = 'available' self.data.delete(:reboot_time) end when "modifying" # TODO there are some fields that only applied after rebooting if Time.now - self.data[:modify_time] >= Fog::Mock.delay server.merge!(server["PendingModifiedValues"]) server["PendingModifiedValues"] = {} server["DBInstanceStatus"] = 'available' end when "available" # I'm not sure if amazon does this unless server["PendingModifiedValues"].empty? server["DBInstanceStatus"] = 'modifying' end end end response.status = 200 response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, "DescribeDBInstancesResult" => { "DBInstances" => server_set } } response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/reboot_db_instance.rb0000644000004100000410000000314312261242551023334 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/reboot_db_instance' # reboots a database instance # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_RebootDBInstance.html # ==== Parameters # * DBInstanceIdentifier <~String> - name of the db instance to reboot # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def reboot_db_instance(instance_identifier) request({ 'Action' => 'RebootDBInstance', 'DBInstanceIdentifier' => instance_identifier, :parser => Fog::Parsers::AWS::RDS::RebootDBInstance.new, }) end end class Mock def reboot_db_instance(instance_identifier) response = Excon::Response.new if server = self.data[:servers][instance_identifier] if server["DBInstanceStatus"] != "available" raise Fog::AWS::RDS::NotFound.new("DBInstance #{instance_identifier} not available for rebooting") else server["DBInstanceStatus"] = 'rebooting' self.data[:reboot_time] = Time.now response.status = 200 response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, "RebootDBInstanceResult" => { "DBInstance" => server } } response end else raise Fog::AWS::RDS::NotFound.new("DBInstance #{instance_identifier} not found") end end end end end end fog-1.19.0/lib/fog/aws/requests/rds/create_db_snapshot.rb0000644000004100000410000000464212261242551023345 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/create_db_snapshot' # creates a db snapshot # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_CreateDBSnapshot.html # ==== Parameters # * DBInstanceIdentifier <~String> - ID of instance to create snapshot for # * DBSnapshotIdentifier <~String> - The identifier for the DB Snapshot. 1-255 alphanumeric or hyphen characters. Must start with a letter # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def create_db_snapshot(identifier, name) request({ 'Action' => 'CreateDBSnapshot', 'DBInstanceIdentifier' => identifier, 'DBSnapshotIdentifier' => name, :parser => Fog::Parsers::AWS::RDS::CreateDBSnapshot.new }) end end class Mock def create_db_snapshot(identifier, name) response = Excon::Response.new if data[:snapshots][name] raise Fog::AWS::RDS::IndentifierTaken.new end server_data = data[:servers][identifier] unless server_data raise Fog::AWS::RDS::NotFound.new("DBInstance #{identifier} not found") end # TODO: raise an error if the server isn't in 'available' state snapshot_data = { 'Status' => 'creating', 'SnapshotType' => 'manual', 'DBInstanceIdentifier' => identifier, 'DBSnapshotIdentifier' => name, 'InstanceCreateTime' => Time.now } # Copy attributes from server %w(Engine EngineVersion AvailabilityZone AllocatedStorage MasterUsername InstanceCreateTime).each do |key| snapshot_data[key] = server_data[key] end snapshot_data['Port'] = server_data['Endpoint']['Port'] self.data[:snapshots][name] = snapshot_data # TODO: put the server in 'modifying' state response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, "CreateDBSnapshotResult"=> {"DBSnapshot"=> snapshot_data.dup} } response.status = 200 # SnapshotCreateTime is not part of the response. self.data[:snapshots][name]['SnapshotCreateTime'] = Time.now response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/describe_db_engine_versions.rb0000644000004100000410000000200212261242551025204 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/describe_db_engine_versions' def describe_db_engine_versions(opts={}) params = {} params['DBParameterGroupFamily'] = opts[:db_parameter_group_family] if opts[:db_parameter_group_family] params['DefaultOnly'] = opts[:default_only] if opts[:default_only] params['Engine'] = opts[:engine] if opts[:engine] params['EngineVersion'] = opts[:engine_version] if opts[:engine_version] params['Marker'] = opts[:marker] if opts[:marker] params['MaxRecords'] = opts[:max_records] if opts[:max_records] request({ 'Action' => 'DescribeDBEngineVersions', :parser => Fog::Parsers::AWS::RDS::DescribeDBEngineVersions.new }.merge(params)) end end class Mock def describe_db_engine_versions(opts={}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/rds/describe_db_parameters.rb0000644000004100000410000000244412261242551024164 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/describe_db_parameters' # Describe parameters from a parameter group # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_DescribeDBParameters.html # ==== Parameters # * DBParameterGroupName <~String> - name of parameter group to retrieve parameters for # * Source <~String> - The parameter types to return. user | system | engine-default # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def describe_db_parameters(name, opts={}) params={} if opts[:marker] params['Marker'] = opts[:marker] end if opts[:source] params['Source'] = opts[:source] end if opts[:max_records] params['MaxRecords'] = opts[:max_records] end request({ 'Action' => 'DescribeDBParameters', 'DBParameterGroupName' => name, :parser => Fog::Parsers::AWS::RDS::DescribeDBParameters.new }.merge(params)) end end class Mock def describe_db_parameters(name, opts={}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/rds/delete_db_subnet_group.rb0000644000004100000410000000251712261242551024220 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/delete_db_subnet_group' # Deletes a db subnet group # http://docs.aws.amazon.com/AmazonRDS/2013-09-09/APIReference/API_DeleteDBSubnetGroup.html # ==== Parameters # * DBSubnetGroupName <~String> - The name for the DB Subnet Group. This value is stored as a lowercase string. Must contain no more than 255 alphanumeric characters or hyphens. Must not be "Default". # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def delete_db_subnet_group(name) params = { 'Action' => 'DeleteDBSubnetGroup', 'DBSubnetGroupName' => name, :parser => Fog::Parsers::AWS::RDS::DeleteDBSubnetGroup.new } request(params) end end class Mock def delete_db_subnet_group(name) response = Excon::Response.new unless self.data[:subnet_groups] && self.data[:subnet_groups][name] raise Fog::AWS::RDS::NotFound.new("DBSubnetGroupNotFound => The subnet group '#{name}' doesn't exists") end response.body = { 'ResponseMetadata'=>{ 'RequestId'=> Fog::AWS::Mock.request_id }, 'return' => true, } response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/download_db_logfile_portion.rb0000644000004100000410000000500612261242551025240 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/download_db_logfile_portion' # Retrieve a portion of a log file of a db instance # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_DownloadDBLogFilePortion.html # ==== Parameters # * DBInstanceIdentifier <~String> - ID of instance to retrieve information for. Required. # * LogFileName <~String> - The name of the log file to be downloaded. Required. # * Options <~Hash> - Hash of options. Optional. The following keys are used: # * :marker <~String> - The pagination token provided in the previous request. If this parameter is specified the response includes only records beyond the marker, up to MaxRecords. Optional. # * :max_records <~Integer> - The maximum number of records to include in the response. If more records exist, a pagination token is included in the response. Optional. # * :number_of_lines <~Integer> - The number of lines to download. Optional. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def download_db_logfile_portion(identifier=nil, filename=nil, opts={}) params = {} params['DBInstanceIdentifier'] = identifier if identifier params['LogFileName'] = filename if filename params['Marker'] = opts[:marker] if opts[:marker] params['MaxRecords'] = opts[:max_records] if opts[:max_records] params['NumberOfLines'] = opts[:number_of_lines] if opts[:number_of_lines] request({ 'Action' => 'DownloadDBLogFilePortion', :parser => Fog::Parsers::AWS::RDS::DownloadDBLogFilePortion.new }.merge(params)) end end class Mock def download_db_logfile_portion(identifier=nil, filename=nil, opts={}) response = Excon::Response.new server_set = [] if identifier if server = self.data[:servers][identifier] server_set << server else raise Fog::AWS::RDS::NotFound.new("DBInstance #{identifier} not found") end else server_set = self.data[:servers].values end response.status = 200 response.body = { "ResponseMetadata" => { "RequestId"=> Fog::AWS::Mock.request_id }, "DescribeDBInstancesResult" => { "DBInstances" => server_set } } response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/describe_db_reserved_instances.rb0000644000004100000410000000236212261242551025706 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/describe_db_reserved_instances' # Describe all or specified load db instances # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_DescribeDBInstances.html # ==== Parameters # * DBInstanceIdentifier <~String> - ID of instance to retrieve information for. if absent information for all instances is returned # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def describe_db_reserved_instances(identifier=nil, opts={}) params = {} params['ReservedDBInstanceId'] = identifier if identifier if opts[:marker] params['Marker'] = opts[:marker] end if opts[:max_records] params['MaxRecords'] = opts[:max_records] end request({ 'Action' => 'DescribeReservedDBInstances', :parser => Fog::Parsers::AWS::RDS::DescribeDBReservedInstances.new }.merge(params)) end end class Mock def describe_db_reserved_instances(identifier=nil, opts={}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/rds/describe_orderable_db_instance_options.rb0000644000004100000410000000760012261242551027416 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/describe_orderable_db_instance_options' # Describe all or specified load db instances # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_DescribeDBInstances.html # ==== Parameters # * Engine <~String> - The name of the engine to retrieve DB Instance options for. Required. # * Options <~Hash> - Hash of options. Optional. The following keys are used: # * :db_instance_class <~String> - Filter available offerings matching the specified DB Instance class. Optional. # * :engine_version <~String> - Filters available offerings matching the specified engine version. Optional. # * :license_model <~String> - Filters available offerings matching the specified license model. Optional. # * :marker <~String> - The pagination token provided in the previous request. If this parameter is specified the response includes only records beyond the marker, up to MaxRecords. Optional. # * :max_records <~Integer> - The maximum number of records to include in the response. If more records exist, a pagination token is included in the response. Optional. # * :vpc <~Boolean> - Filter to show only the available VPC or non-VPC offerings. Optional. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def describe_orderable_db_instance_options(engine=nil, opts={}) params = {} params['Engine'] = engine if engine params['DBInstanceClass'] = opts[:db_instance_class] if opts[:db_instance_class] params['EngineVersion'] = opts[:engine_version] if opts[:engine_version] params['LicenseModel'] = opts[:license_model] if opts[:license_model] params['Marker'] = opts[:marker] if opts[:marker] params['MaxRecords'] = opts[:max_records] if opts[:max_records] params['Vpc'] = opts[:vpc] if opts[:vpc] request({ 'Action' => 'DescribeOrderableDBInstanceOptions', :parser => Fog::Parsers::AWS::RDS::DescribeOrderableDBInstanceOptions.new }.merge(params)) end end class Mock def describe_orderable_db_instance_options(engine=nil, opts={}) instance_options = [] response = Excon::Response.new if engine (opts[:db_instance_class] || %w(db.m2.xlarge db.m1.large)).each do |size| instance_options << {'MultiAZCapable' => true, 'Engine' => engine, 'LicenseModel' => opts[:license_model] || 'general-public-license', 'ReadReplicaCapable' => true, 'EngineVersion' => opts[:engine_version] || '5.6.12', 'AvailabilityZones' => [ {'Name' => 'us-east-1b', 'ProvisionedIopsCapable' => true}, {'Name' => 'us-east-1c', 'ProvisionedIopsCapable' => true}, {'Name' => 'us-east-1d', 'ProvisionedIopsCapable' => false}, {'Name' => 'us-east-1e', 'ProvisionedIopsCapable' => true}], 'DBInstanceClass' => size, 'Vpc' => opts[:vpc].nil? ? true : opts[:vpc]} end else raise Fog::AWS::RDS::NotFound.new('An engine must be specified to retrieve orderable instance options') end response.status = 200 response.body = { 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id }, 'DescribeOrderableDBInstanceOptionsResult' => { 'OrderableDBInstanceOptions' => instance_options } } response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/create_db_subnet_group.rb0000644000004100000410000000473712261242551024227 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/create_db_subnet_group' # Creates a db subnet group # http://docs.amazonwebservices.com/AmazonRDS/2012-01-15/APIReference/API_CreateDBSubnetGroup.html # ==== Parameters # * DBSubnetGroupName <~String> - The name for the DB Subnet Group. This value is stored as a lowercase string. Must contain no more than 255 alphanumeric characters or hyphens. Must not be "Default". # * SubnetIds <~Array> - The EC2 Subnet IDs for the DB Subnet Group. # * DBSubnetGroupDescription <~String> - The description for the DB Subnet Group # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def create_db_subnet_group(name, subnet_ids, description = name) params = { 'Action' => 'CreateDBSubnetGroup', 'DBSubnetGroupName' => name, 'DBSubnetGroupDescription' => description, :parser => Fog::Parsers::AWS::RDS::CreateDBSubnetGroup.new } params.merge!(Fog::AWS.indexed_param("SubnetIds.member", Array(subnet_ids))) request(params) end end class Mock def create_db_subnet_group(name, subnet_ids, description = name) response = Excon::Response.new if self.data[:subnet_groups] && self.data[:subnet_groups][name] raise Fog::AWS::RDS::IdentifierTaken.new("DBSubnetGroupAlreadyExists => The subnet group '#{name}' already exists") end # collection = Fog::Compute::AWS.new(:aws_access_key_id => 'mock key', :aws_secret_access_key => 'mock secret') collection = Fog::Compute[:aws] subnets = subnet_ids.map do |snid| subnet = collection.subnets.get(snid) raise Fog::AWS::RDS::NotFound.new("InvalidSubnet => The subnet '#{snid}' was not found") if subnet.nil? subnet end vpc_id = subnets.first.vpc_id data = { 'DBSubnetGroupName' => name, 'DBSubnetGroupDescription' => description, 'SubnetGroupStatus' => 'Complete', 'Subnets' => subnet_ids, 'VpcId' => vpc_id } self.data[:subnet_groups][name] = data response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, 'CreateDBSubnetGroupResult' => { 'DBSubnetGroup' => data } } response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/delete_db_parameter_group.rb0000644000004100000410000000246312261242551024700 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/delete_db_parameter_group' # delete a database parameter group # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_DeleteDBParameterGroup.html # ==== Parameters # * DBParameterGroupName <~String> - name of the parameter group. Must not be associated with any instances # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def delete_db_parameter_group(group_name) request({ 'Action' => 'DeleteDBParameterGroup', 'DBParameterGroupName' => group_name, :parser => Fog::Parsers::AWS::RDS::DeleteDbParameterGroup.new }) end end class Mock def delete_db_parameter_group(group_name) response = Excon::Response.new if self.data[:parameter_groups].delete(group_name) response.status = 200 response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, } response else raise Fog::AWS::RDS::NotFound.new("DBParameterGroup not found: #{group_name}") end end end end end end fog-1.19.0/lib/fog/aws/requests/rds/create_db_security_group.rb0000644000004100000410000000363312261242551024570 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/create_db_security_group' # creates a db security group # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/index.html?API_CreateDBSecurityGroup.html # ==== Parameters # * DBSecurityGroupDescription <~String> - The description for the DB Security Group # * DBSecurityGroupName <~String> - The name for the DB Security Group. This value is stored as a lowercase string. Must contain no more than 255 alphanumeric characters or hyphens. Must not be "Default". # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def create_db_security_group(name, description = name) request({ 'Action' => 'CreateDBSecurityGroup', 'DBSecurityGroupName' => name, 'DBSecurityGroupDescription' => description, :parser => Fog::Parsers::AWS::RDS::CreateDBSecurityGroup.new }) end end class Mock def create_db_security_group(name, description = name) response = Excon::Response.new if self.data[:security_groups] and self.data[:security_groups][name] raise Fog::AWS::RDS::IdentifierTaken.new("DBInstanceAlreadyExists => The security group '#{name}' already exists") end data = { 'DBSecurityGroupName' => name, 'DBSecurityGroupDescription' => description, 'EC2SecurityGroups' => [], 'IPRanges' => [], 'OwnerId' => '0123456789' } self.data[:security_groups][name] = data response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, 'CreateDBSecurityGroupResult' => { 'DBSecurityGroup' => data } } response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/describe_db_snapshots.rb0000644000004100000410000000542712261242551024047 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/describe_db_snapshots' # Describe all or specified db snapshots # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_DescribeDBSnapshots.html # ==== Parameters # * DBInstanceIdentifier <~String> - ID of instance to retrieve information for. if absent information for all instances is returned # * DBSnapshotIdentifier <~String> - ID of snapshot to retrieve information for. if absent information for all snapshots is returned # * SnapshotType <~String> - type of snapshot to retrive (automated|manual) # * Marker <~String> - An optional marker provided in the previous DescribeDBInstances request # * MaxRecords <~Integer> - Max number of records to return (between 20 and 100) # Only one of DBInstanceIdentifier or DBSnapshotIdentifier can be specified # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def describe_db_snapshots(opts={}) params = {} params['SnapshotType'] = opts[:type] if opts[:type] params['DBInstanceIdentifier'] = opts[:identifier] if opts[:identifier] params['DBSnapshotIdentifier'] = opts[:snapshot_id] if opts[:snapshot_id] params['Marker'] = opts[:marker] if opts[:marker] params['MaxRecords'] = opts[:max_records] if opts[:max_records] request({ 'Action' => 'DescribeDBSnapshots', :parser => Fog::Parsers::AWS::RDS::DescribeDBSnapshots.new }.merge(params)) end end class Mock def describe_db_snapshots(opts={}) response = Excon::Response.new snapshots = self.data[:snapshots].values if opts[:identifier] snapshots = snapshots.select{|snapshot| snapshot['DBInstanceIdentifier'] == opts[:identifier]} end if opts[:snapshot_id] snapshots = snapshots.select{|snapshot| snapshot['DBSnapshotIdentifier'] == opts[:snapshot_id]} raise Fog::AWS::RDS::NotFound.new("DBSnapshot #{opts[:snapshot_id]} not found") if snapshots.empty? end snapshots.each do |snapshot| case snapshot['Status'] when 'creating' if Time.now - snapshot['SnapshotCreateTime'] > Fog::Mock.delay snapshot['Status'] = 'available' end end end # Build response response.status = 200 response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, "DescribeDBSnapshotsResult" => { "DBSnapshots" => snapshots } } response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/describe_db_subnet_groups.rb0000644000004100000410000000367012261242551024722 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/describe_db_subnet_groups' # This API returns a list of DBSubnetGroup descriptions. If a DBSubnetGroupName is specified, the list will contain only # the descriptions of the specified DBSubnetGroup # http://docs.amazonwebservices.com/AmazonRDS/2012-01-15/APIReference/API_DescribeDBSubnetGroups.html # ==== Parameters # * DBSubnetGroupName <~String> - The name of a specific database subnet group to return details for. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def describe_db_subnet_groups(name = nil, opts = {}) params = {} if opts[:marker] params['Marker'] = opts[:marker] end if name params['DBSubnetGroupName'] = name end if opts[:max_records] params['MaxRecords'] = opts[:max_records] end request({ 'Action' => 'DescribeDBSubnetGroups', :parser => Fog::Parsers::AWS::RDS::DescribeDBSubnetGroups.new }.merge(params)) end end class Mock def describe_db_subnet_groups(name = nil, opts = {}) response = Excon::Response.new subnet_group_set = [] if name if subnet_group = self.data[:subnet_groups][name] subnet_group_set << subnet_group else raise Fog::AWS::RDS::NotFound.new("Subnet Group #{name} not found") end else subnet_group_set = self.data[:subnet_groups].values end response.status = 200 response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, "DescribeDBSubnetGroupsResult" => { "DBSubnetGroups" => subnet_group_set } } response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/delete_db_snapshot.rb0000644000004100000410000000244512261242551023343 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/delete_db_snapshot' # delete a database snapshot # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_DeleteDBSnapshot.html # ==== Parameters # * DBSnapshotIdentifier <~String> - name of the snapshot # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def delete_db_snapshot(name) request({ 'Action' => 'DeleteDBSnapshot', 'DBSnapshotIdentifier' => name, :parser => Fog::Parsers::AWS::RDS::DeleteDBSnapshot.new }) end end class Mock def delete_db_snapshot(name) # TODO: raise error if snapshot isn't 'available' response = Excon::Response.new snapshot_data = self.data[:snapshots].delete(name) raise Fog::AWS::RDS::NotFound.new("DBSnapshtoNotFound => #{name} not found") unless snapshot_data response.status = 200 response.body = { "ResponseMetadata"=> { "RequestId"=> Fog::AWS::Mock.request_id }, "DeleteDBSnapshotResult"=> {"DBSnapshot"=> snapshot_data} } response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/authorize_db_security_group_ingress.rb0000644000004100000410000000604312261242551027067 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/authorize_db_security_group_ingress' # authorizes a db security group ingress # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/index.html?API_AuthorizeDBSecurityGroupIngress.html # ==== Parameters # * CIDRIP <~String> - The IP range to authorize # * DBSecurityGroupName <~String> - The name for the DB Security Group. # * EC2SecurityGroupName <~String> - Name of the EC2 Security Group to authorize. # * EC2SecurityGroupOwnerId <~String> - AWS Account Number of the owner of the security group specified in the EC2SecurityGroupName parameter. The AWS Access Key ID is not an acceptable value. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def authorize_db_security_group_ingress(name, opts={}) unless opts.key?('CIDRIP') || (opts.key?('EC2SecurityGroupName') && opts.key?('EC2SecurityGroupOwnerId')) raise ArgumentError, 'Must specify CIDRIP, or both EC2SecurityGroupName and EC2SecurityGroupOwnerId' end request({ 'Action' => 'AuthorizeDBSecurityGroupIngress', :parser => Fog::Parsers::AWS::RDS::AuthorizeDBSecurityGroupIngress.new, 'DBSecurityGroupName' => name }.merge(opts)) end end class Mock def authorize_db_security_group_ingress(name, opts = {}) unless opts.key?('CIDRIP') || (opts.key?('EC2SecurityGroupName') && opts.key?('EC2SecurityGroupOwnerId')) raise ArgumentError, 'Must specify CIDRIP, or both EC2SecurityGroupName and EC2SecurityGroupOwnerId' end response = Excon::Response.new if sec_group = self.data[:security_groups][name] if opts.key?('CIDRIP') if sec_group['IPRanges'].detect{|h| h['CIDRIP'] == opts['CIDRIP']} raise Fog::AWS::RDS::AuthorizationAlreadyExists.new("AuthorizationAlreadyExists => #{opts['CIDRIP']} is alreay defined") end sec_group['IPRanges'] << opts.merge({"Status" => 'authorizing'}) else if sec_group['EC2SecurityGroups'].detect{|h| h['EC2SecurityGroupName'] == opts['EC2SecurityGroupName']} raise Fog::AWS::RDS::AuthorizationAlreadyExists.new("AuthorizationAlreadyExists => #{opts['EC2SecurityGroupName']} is alreay defined") end sec_group['EC2SecurityGroups'] << opts.merge({"Status" => 'authorizing'}) end response.status = 200 response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, 'AuthorizeDBSecurityGroupIngressResult' => { 'DBSecurityGroup' => sec_group } } response else raise Fog::AWS::RDS::NotFound.new("DBSecurityGroupNotFound => #{name} not found") end end end end end end fog-1.19.0/lib/fog/aws/requests/rds/create_db_instance.rb0000644000004100000410000001521312261242551023306 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/create_db_instance' # Create a db instance # # @param DBInstanceIdentifier [String] name of the db instance to modify # @param AllocatedStorage [Integer] Storage space, in GB # @param AutoMinorVersionUpgrade [Boolean] Indicates that minor version upgrades will be applied automatically to the DB Instance during the maintenance window # @param AvailabilityZone [String] The availability zone to create the instance in # @param BackupRetentionPeriod [Integer] 0-8 The number of days to retain automated backups. # @param DBInstanceClass [String] The new compute and memory capacity of the DB Instance # @param DBName [String] The name of the database to create when the DB Instance is created # @param DBParameterGroupName [String] The name of the DB Parameter Group to apply to this DB Instance # @param DBSecurityGroups [Array] A list of DB Security Groups to authorize on this DB Instance # @param Engine [String] The name of the database engine to be used for this instance. # @param EngineVersion [String] The version number of the database engine to use. # @param MasterUsername [String] The db master user # @param MasterUserPassword [String] The new password for the DB Instance master user # @param MultiAZ [Boolean] Specifies if the DB Instance is a Multi-AZ deployment # @param Port [Integer] The port number on which the database accepts connections. # @param PreferredBackupWindow [String] The daily time range during which automated backups are created if automated backups are enabled # @param PreferredMaintenanceWindow [String] The weekly time range (in UTC) during which system maintenance can occur, which may result in an outage # @param DBSubnetGroupName [String] The name, if any, of the VPC subnet for this RDS instance # @param PubliclyAcccesible [Boolean] Whether an RDS instance inside of the VPC subnet should have a public-facing endpoint # @param VpcSecurityGroups [Array] A list of VPC Security Groups to authorize on this DB instance # # @return [Excon::Response]: # * body [Hash]: # # @see http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_CreateDBInstance.html def create_db_instance(db_name, options={}) if security_groups = options.delete('DBSecurityGroups') options.merge!(Fog::AWS.indexed_param('DBSecurityGroups.member.%d', [*security_groups])) end if vpc_security_groups = options.delete('VpcSecurityGroups') options.merge!(Fog::AWS.indexed_param('VpcSecurityGroupIds.member.%d', [*vpc_security_groups])) end request({ 'Action' => 'CreateDBInstance', 'DBInstanceIdentifier' => db_name, :parser => Fog::Parsers::AWS::RDS::CreateDBInstance.new, }.merge(options)) end end class Mock def create_db_instance(db_name, options={}) response = Excon::Response.new if self.data[:servers] and self.data[:servers][db_name] # I don't know how to raise an exception that contains the excon data #response.status = 400 #response.body = { # 'Code' => 'DBInstanceAlreadyExists', # 'Message' => "DB Instance already exists" #} #return response raise Fog::AWS::RDS::IdentifierTaken.new("DBInstanceAlreadyExists #{response.body.to_s}") end # These are the required parameters according to the API required_params = %w{AllocatedStorage DBInstanceClass Engine MasterUserPassword MasterUsername } required_params.each do |key| unless options.has_key?(key) and options[key] and !options[key].to_s.empty? #response.status = 400 #response.body = { # 'Code' => 'MissingParameter', # 'Message' => "The request must contain the parameter #{key}" #} #return response raise Fog::AWS::RDS::NotFound.new("The request must contain the parameter #{key}") end end data = { "DBInstanceIdentifier"=> db_name, "DBName" => options["DBName"], "InstanceCreateTime" => nil, "AutoMinorVersionUpgrade"=>true, "Endpoint"=>{}, "ReadReplicaDBInstanceIdentifiers"=>[], "PreferredMaintenanceWindow"=>"mon:04:30-mon:05:00", "Engine"=> options["Engine"], "EngineVersion"=> options["EngineVersion"] || "5.5.12", "PendingModifiedValues"=>{"MasterUserPassword"=>"****"}, # This clears when is available "MultiAZ"=> !!options['MultiAZ'], "MasterUsername"=> options["MasterUsername"], "DBInstanceClass"=> options["DBInstanceClass"], "DBInstanceStatus"=>"creating", "BackupRetentionPeriod"=> options["BackupRetentionPeriod"] || 1, "AllocatedStorage"=> options["AllocatedStorage"], "DBParameterGroups"=> # I think groups should be in the self.data method [{"DBParameterGroupName"=>"default.mysql5.5", "ParameterApplyStatus"=>"in-sync"}], "DBSecurityGroups"=> [{"Status"=>"active", "DBSecurityGroupName"=>"default"}], "LicenseModel"=>"general-public-license", "PreferredBackupWindow"=>"08:00-08:30", # "ReadReplicaSourceDBInstanceIdentifier" => nil, # "LatestRestorableTime" => nil, "AvailabilityZone" => options["AvailabilityZone"], "DBSubnetGroupName" => options["DBSubnetGroupName"], "PubliclyAccessible" => options["PubliclyAccessible"], "VpcSecurityGroups" => options["VpcSecurityGroups"], } self.data[:servers][db_name] = data response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, "CreateDBInstanceResult"=> {"DBInstance"=> data} } response.status = 200 # This values aren't showed at creating time but at available time self.data[:servers][db_name]["InstanceCreateTime"] = Time.now self.data[:tags] ||= {} self.data[:tags][db_name] = {} response end end end end end fog-1.19.0/lib/fog/aws/requests/rds/modify_db_instance.rb0000644000004100000410000000754312261242551023341 0ustar www-datawww-datamodule Fog module AWS class RDS class Real require 'fog/aws/parsers/rds/modify_db_instance' # modifies a database instance # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_ModifyDBInstance.html # ==== Parameters # * DBInstanceIdentifier <~String> - name of the db instance to modify # * ApplyImmediately <~Boolean> - whether to apply the changes immediately or wait for the next maintenance window # # * AllocatedStorage <~Integer> Storage space, in GB # * AllowMajorVersionUpgrade <~Boolean> Must be set to true if EngineVersion specifies a different major version # * AutoMinorVersionUpgrade <~Boolean> Indicates that minor version upgrades will be applied automatically to the DB Instance during the maintenance window # * BackupRetentionPeriod <~Integer> 0-8 The number of days to retain automated backups. # * DBInstanceClass <~String> The new compute and memory capacity of the DB Instanc # * DBParameterGroupName <~String> The name of the DB Parameter Group to apply to this DB Instance # * DBSecurityGroups <~Array> A list of DB Security Groups to authorize on this DB Instance # * EngineVersion <~String> The version number of the database engine to upgrade to. # * MasterUserPassword <~String> The new password for the DB Instance master user # * MultiAZ <~Boolean> Specifies if the DB Instance is a Multi-AZ deployment # * PreferredBackupWindow <~String> The daily time range during which automated backups are created if automated backups are enabled # * PreferredMaintenanceWindow <~String> The weekly time range (in UTC) during which system maintenance can occur, which may result in an outage # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def modify_db_instance(db_name, apply_immediately, options={}) if security_groups = options.delete('DBSecurityGroups') options.merge!(Fog::AWS.indexed_param('DBSecurityGroups.member.%d', [*security_groups])) end request({ 'Action' => 'ModifyDBInstance', 'DBInstanceIdentifier' => db_name, 'ApplyImmediately' => apply_immediately, :parser => Fog::Parsers::AWS::RDS::ModifyDBInstance.new, }.merge(options)) end end class Mock def modify_db_instance(db_name, apply_immediately, options={}) response = Excon::Response.new if self.data[:servers][db_name] if self.data[:servers][db_name]["DBInstanceStatus"] != "available" raise Fog::AWS::RDS::NotFound.new("DBInstance #{db_name} not available for modification") else self.data[:modify_time] = Time.now # TODO verify the params options # if apply_immediately is false, all the options go to pending_modified_values and then apply and clear after either # a reboot or the maintainance window #if apply_immediately # modified_server = server.merge(options) #else # modified_server = server["PendingModifiedValues"].merge!(options) # it appends #end self.data[:servers][db_name]["PendingModifiedValues"].merge!(options) # it appends self.data[:servers][db_name]["DBInstanceStatus"] = "modifying" response.status = 200 response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, "ModifyDBInstanceResult" => { "DBInstance" => self.data[:servers][db_name] } } response end else raise Fog::AWS::RDS::NotFound.new("DBInstance #{db_name} not found") end end end end end end fog-1.19.0/lib/fog/aws/requests/rds/remove_tags_from_resource.rb0000644000004100000410000000263412261242551024762 0ustar www-datawww-datamodule Fog module AWS class RDS class Real # removes tags from a database instance # http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_RemoveTagsFromResource.html # ==== Parameters # * rds_id <~String> - name of the RDS instance whose tags are to be retrieved # * keys <~Array> A list of String keys for the tags to remove # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def remove_tags_from_resource(rds_id, keys) request( { 'Action' => 'RemoveTagsFromResource', 'ResourceName' => "arn:aws:rds:#{@region}:#{owner_id}:db:#{rds_id}", :parser => Fog::Parsers::AWS::RDS::Base.new, }.merge(Fog::AWS.indexed_param('TagKeys.member.%d', keys)) ) end end class Mock def remove_tags_from_resource(rds_id, keys) response = Excon::Response.new if server = self.data[:servers][rds_id] keys.each {|key| self.data[:tags][rds_id].delete key} response.status = 200 response.body = { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id } } response else raise Fog::AWS::RDS::NotFound.new("DBInstance #{rds_id} not found") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/0000755000004100000410000000000012261242551020047 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/compute/modify_image_attribute.rb0000644000004100000410000000571512261242551025120 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Modify image attributes # # ==== Parameters # * image_id<~String> - Id of machine image to modify # * attributes<~Hash>: # * 'Add.Group'<~Array> - One or more groups to grant launch permission to # * 'Add.UserId'<~Array> - One or more account ids to grant launch permission to # * 'Description.Value' - New description for image # * 'ProductCode'<~Array> - One or more product codes to add to image (these can not be removed) # * 'Remove.Group'<~Array> - One or more groups to revoke launch permission from # * 'Remove.UserId'<~Array> - One or more account ids to revoke launch permission from # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyImageAttribute.html] # def modify_image_attribute(image_id, attributes) raise ArgumentError.new("image_id is required") unless image_id params = {} params.merge!(Fog::AWS.indexed_param('LaunchPermission.Add.%d.Group', attributes['Add.Group'] || [])) params.merge!(Fog::AWS.indexed_param('LaunchPermission.Add.%d.UserId', attributes['Add.UserId'] || [])) params.merge!(Fog::AWS.indexed_param('LaunchPermission.Remove.%d.Group', attributes['Remove.Group'] || [])) params.merge!(Fog::AWS.indexed_param('LaunchPermission.Remove.%d.UserId', attributes['Remove.UserId'] || [])) params.merge!(Fog::AWS.indexed_param('ProductCode', attributes['ProductCode'] || [])) request({ 'Action' => 'ModifyImageAttribute', 'ImageId' => image_id, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new }.merge!(params)) end end class Mock def modify_image_attribute(image_id, attributes) raise ArgumentError.new("image_id is required") unless image_id unless self.data[:images][image_id] raise Fog::Compute::AWS::NotFound.new("The AMI ID '#{image_id}' does not exist") end (attributes['Add.UserId'] || []).each do |user_id| if image_launch_permissions = self.data[:image_launch_permissions][image_id] image_launch_permissions[:users].push(user_id) end end (attributes['Remove.UserId'] || []).each do |user_id| if image_launch_permissions = self.data[:image_launch_permissions][image_id] image_launch_permissions[:users].delete(user_id) end end response = Excon::Response.new response.status = 200 response.body = { 'return' => true, 'requestId' => Fog::AWS::Mock.request_id } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_tags.rb0000644000004100000410000000524112261242551022657 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Adds tags to resources # # ==== Parameters # * resources<~String> - One or more resources to tag # * tags<~String> - hash of key value tag pairs to assign # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateTags.html] def create_tags(resources, tags) resources = [*resources] for key, value in tags if value.nil? tags[key] = '' end end params = {} params.merge!(Fog::AWS.indexed_param('ResourceId', resources)) params.merge!(Fog::AWS.indexed_param('Tag.%d.Key', tags.keys)) params.merge!(Fog::AWS.indexed_param('Tag.%d.Value', tags.values)) request({ 'Action' => 'CreateTags', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new }.merge!(params)) end end class Mock def create_tags(resources, tags) resources = [*resources] tagged = resources.map do |resource_id| type = case resource_id when /^ami\-[a-z0-9]{8}$/i 'image' when /^i\-[a-z0-9]{8}$/i 'instance' when /^snap\-[a-z0-9]{8}$/i 'snapshot' when /^vol\-[a-z0-9]{8}$/i 'volume' when /^igw\-[a-z0-9]{8}$/i 'internet_gateway' end if type && ((type == 'image' && visible_images[resource_id]) || self.data[:"#{type}s"][resource_id]) { 'resourceId' => resource_id, 'resourceType' => type } else raise(Fog::Service::NotFound.new("The #{type} ID '#{resource_id}' does not exist")) end end tags.each do |key, value| self.data[:tags][key] ||= {} self.data[:tags][key][value] ||= [] self.data[:tags][key][value] |= tagged tagged.each do |resource| self.data[:tag_sets][resource['resourceId']][key] = value end end response = Excon::Response.new response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_reserved_instances.rb0000644000004100000410000000506612261242551026131 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_reserved_instances' # Describe all or specified reserved instances # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'reservedInstancesSet'<~Array>: # * 'availabilityZone'<~String> - availability zone of the instance # * 'duration'<~Integer> - duration of reservation, in seconds # * 'fixedPrice'<~Float> - purchase price of reserved instance # * 'instanceType'<~String> - type of instance # * 'instanceCount'<~Integer> - number of reserved instances # * 'productDescription'<~String> - reserved instance description # * 'reservedInstancesId'<~String> - id of the instance # * 'start'<~Time> - start time for reservation # * 'state'<~String> - state of reserved instance purchase, in .[pending-payment, active, payment-failed, retired] # * 'usagePrice"<~Float> - usage price of reserved instances, per hour # * 'end' - time reservation stopped being applied (i.e sold or canceled - as of version 2013/10/01) # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeReservedInstances.html] def describe_reserved_instances(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_reserved_instances with #{filters.class} param is deprecated, use describe_reserved_instances('reserved-instances-id' => []) instead [light_black](#{caller.first})[/]") filters = {'reserved-instances-id' => [*filters]} end params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeReservedInstances', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeReservedInstances.new }.merge!(params)) end end class Mock def describe_reserved_instances(filters = {}) response = Excon::Response.new response.status = 200 response.body = { 'reservedInstancesSet' => self.data[:reserved_instances].values, 'requestId' => Fog::AWS::Mock.request_id } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_key_pair.rb0000644000004100000410000000333412261242551023525 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/create_key_pair' # Create a new key pair # # ==== Parameters # * key_name<~String> - Unique name for key pair. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'keyFingerprint'<~String> - SHA-1 digest of DER encoded private key # * 'keyMaterial'<~String> - Unencrypted encoded PEM private key # * 'keyName'<~String> - Name of key # * 'requestId'<~String> - Id of request # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateKeyPair.html] def create_key_pair(key_name) request( 'Action' => 'CreateKeyPair', 'KeyName' => key_name, :parser => Fog::Parsers::Compute::AWS::CreateKeyPair.new ) end end class Mock def create_key_pair(key_name) response = Excon::Response.new unless self.data[:key_pairs][key_name] response.status = 200 data = { 'keyFingerprint' => Fog::AWS::Mock.key_fingerprint, 'keyMaterial' => Fog::AWS::Mock.key_material, 'keyName' => key_name } self.data[:key_pairs][key_name] = data response.body = { 'requestId' => Fog::AWS::Mock.request_id }.merge!(data) response else raise Fog::Compute::AWS::Error.new("InvalidKeyPair.Duplicate => The keypair '#{key_name}' already exists.") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_security_groups.rb0000644000004100000410000001106012261242551025500 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_security_groups' # Describe all or specified security groups # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'securityGroupInfo'<~Array>: # * 'groupDescription'<~String> - Description of security group # * 'groupId'<~String> - ID of the security group. # * 'groupName'<~String> - Name of security group # * 'ipPermissions'<~Array>: # * 'fromPort'<~Integer> - Start of port range (or -1 for ICMP wildcard) # * 'groups'<~Array>: # * 'groupName'<~String> - Name of security group # * 'userId'<~String> - AWS User Id of account # * 'ipProtocol'<~String> - Ip protocol, must be in ['tcp', 'udp', 'icmp'] # * 'ipRanges'<~Array>: # * 'cidrIp'<~String> - CIDR range # * 'toPort'<~Integer> - End of port range (or -1 for ICMP wildcard) # * 'ownerId'<~String> - AWS Access Key Id of the owner of the security group # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSecurityGroups.html] def describe_security_groups(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_security_groups with #{filters.class} param is deprecated, use describe_security_groups('group-name' => []) instead [light_black](#{caller.first})[/]") filters = {'group-name' => [*filters]} end params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeSecurityGroups', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeSecurityGroups.new }.merge!(params)) end end class Mock def describe_security_groups(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_security_groups with #{filters.class} param is deprecated, use describe_security_groups('group-name' => []) instead [light_black](#{caller.first})[/]") filters = {'group-name' => [*filters]} end response = Excon::Response.new security_group_info = self.data[:security_groups].reject { |k,v| k['amazon-elb-sg'] }.values aliases = { 'description' => 'groupDescription', 'group-name' => 'groupName', 'group-id' => 'groupId', 'owner-id' => 'ownerId' } permission_aliases = { 'cidr' => 'cidrIp', 'from-port' => 'fromPort', 'protocol' => 'ipProtocol', 'to-port' => 'toPort' } for filter_key, filter_value in filters if permission_key = filter_key.split('ip-permission.')[1] if permission_key == 'group-name' security_group_info = security_group_info.reject{|security_group| !security_group['ipPermissions']['groups'].detect {|group| [*filter_value].include?(group['groupName'])}} elsif permission_key == 'group-id' security_group_info = security_group_info.reject{|security_group| !security_group['ipPermissions']['groups'].detect {|group| [*filter_value].include?(group['groupId'])}} elsif permission_key == 'user-id' security_group_info = security_group_info.reject{|security_group| !security_group['ipPermissions']['groups'].detect {|group| [*filter_value].include?(group['userId'])}} else aliased_key = permission_aliases[filter_key] security_group_info = security_group_info.reject{|security_group| !security_group['ipPermissions'].detect {|permission| [*filter_value].include?(permission[aliased_key])}} end else aliased_key = aliases[filter_key] security_group_info = security_group_info.reject{|security_group| ![*filter_value].include?(security_group[aliased_key])} end end response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'securityGroupInfo' => security_group_info } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_regions.rb0000644000004100000410000000464712261242551023715 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_regions' # Describe all or specified regions # # ==== Params # * filters<~Hash> - List of filters to limit results with # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'regionInfo'<~Array>: # * 'regionName'<~String> - Name of region # * 'regionEndpoint'<~String> - Service endpoint for region # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeRegions.html] def describe_regions(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_regions with #{filters.class} param is deprecated, use describe_regions('region-name' => []) instead [light_black](#{caller.first})[/]") filters = {'region-name' => [*filters]} end params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeRegions', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeRegions.new }.merge!(params)) end end class Mock def describe_regions(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_regions with #{filters.class} param is deprecated, use describe_regions('region-name' => []) instead [light_black](#{caller.first})[/]") filters = {'region-name' => [*filters]} end response = Excon::Response.new region_info = [ {"regionName"=>"eu-west-1", "regionEndpoint"=>"eu-west-1.ec2.amazonaws.com"}, {"regionName"=>"us-east-1", "regionEndpoint"=>"us-east-1.ec2.amazonaws.com"} ] aliases = {'region-name' => 'regionName', 'endpoint' => 'regionEndpoint'} for filter_key, filter_value in filters aliased_key = aliases[filter_key] region_info = region_info.reject{|region| ![*filter_value].include?(region[aliased_key])} end response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'regionInfo' => region_info } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/reboot_instances.rb0000644000004100000410000000316112261242551023736 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Reboot specified instances # # ==== Parameters # * instance_id<~Array> - Ids of instances to reboot # # ==== Returns # # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RebootInstances.html] def reboot_instances(instance_id = []) params = Fog::AWS.indexed_param('InstanceId', instance_id) request({ 'Action' => 'RebootInstances', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new }.merge!(params)) end end class Mock def reboot_instances(instance_id = []) response = Excon::Response.new instance_id = [*instance_id] if (self.data[:instances].keys & instance_id).length == instance_id.length for instance_id in instance_id self.data[:instances][instance_id]['status'] = 'rebooting' end response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else raise Fog::Compute::AWS::NotFound.new("The instance ID #{instance_id.inspect} does not exist") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/get_console_output.rb0000644000004100000410000000336612261242551024325 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/get_console_output' # Retrieve console output for specified instance # # ==== Parameters # * instance_id<~String> - Id of instance to get console output from # # ==== Returns # # * response<~Excon::Response>: # * body<~Hash>: # * 'instanceId'<~String> - Id of instance # * 'output'<~String> - Console output # * 'requestId'<~String> - Id of request # * 'timestamp'<~Time> - Timestamp of last update to output # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-GetConsoleOutput.html] def get_console_output(instance_id) request( 'Action' => 'GetConsoleOutput', 'InstanceId' => instance_id, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::GetConsoleOutput.new ) end end class Mock def get_console_output(instance_id) response = Excon::Response.new if instance = self.data[:instances][instance_id] response.status = 200 response.body = { 'instanceId' => instance_id, 'output' => (Time.now - instance['launchTime'] >= Fog::Mock.delay) ? nil : Fog::AWS::Mock.console_output, 'requestId' => Fog::AWS::Mock.request_id, 'timestamp' => Time.now } response else; raise Fog::Compute::AWS::NotFound.new("The instance ID '#{instance_id}' does not exist") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_reserved_instances_offerings.rb0000644000004100000410000000753312261242551030174 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_reserved_instances_offerings' # Describe all or specified reserved instances offerings # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # * filters and/or the following # * 'AvailabilityZone'<~String> - availability zone of offering # * 'InstanceType'<~String> - instance type of offering # * 'InstanceTenancy'<~String> - tenancy of offering in ['default', 'dedicated'] # * 'OfferingType'<~String> - type of offering, in ['Heavy Utilization', 'Medium Utilization', 'Light Utilization'] # * 'ProductDescription'<~String> - description of offering, in ['Linux/UNIX', 'Linux/UNIX (Amazon VPC)', 'Windows', 'Windows (Amazon VPC)'] # * 'MaxDuration'<~Integer> - maximum duration (in seconds) of offering # * 'MinDuration'<~Integer> - minimum duration (in seconds) of offering # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'reservedInstancesOfferingsSet'<~Array>: # * 'availabilityZone'<~String> - availability zone of offering # * 'duration'<~Integer> - duration, in seconds, of offering # * 'fixedPrice'<~Float> - purchase price of offering # * 'includeMarketplace'<~Boolean> - whether or not to include marketplace offerings # * 'instanceType'<~String> - instance type of offering # * 'offeringType'<~String> - type of offering, in ['Heavy Utilization', 'Medium Utilization', 'Light Utilization'] # * 'productDescription'<~String> - description of offering # * 'reservedInstancesOfferingId'<~String> - id of offering # * 'usagePrice'<~Float> - usage price of offering, per hour # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeReservedInstancesOfferings.html] def describe_reserved_instances_offerings(filters = {}) options = {} for key in ['AvailabilityZone', 'InstanceType', 'InstanceTenancy', 'OfferingType', 'ProductDescription', 'MaxDuration', 'MinDuration'] if filters.is_a?(Hash) && filters.key?(key) options[key] = filters.delete(key) end end params = Fog::AWS.indexed_filters(filters).merge!(options) request({ 'Action' => 'DescribeReservedInstancesOfferings', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeReservedInstancesOfferings.new }.merge!(params)) end end class Mock def describe_reserved_instances_offerings(filters = {}) response = Excon::Response.new response.status = 200 self.data[:reserved_instances_offerings] ||= [{ 'reservedInstancesOfferingId' => Fog::AWS::Mock.reserved_instances_offering_id, 'instanceType' => 'm1.small', 'availabilityZone' => 'us-east-1d', 'duration' => 31536000, 'fixedPrice' => 350.0, 'offeringType' => 'Medium Utilization', 'usagePrice' => 0.03, 'productDescription' => 'Linux/UNIX', 'instanceTenancy' => 'default', 'currencyCode' => 'USD' }] response.body = { 'reservedInstancesOfferingsSet' => self.data[:reserved_instances_offerings], 'requestId' => Fog::AWS::Mock.request_id } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_network_interface.rb0000644000004100000410000001252712261242551025437 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/create_network_interface' # Creates a network interface # # ==== Parameters # * subnetId<~String> - The ID of the subnet to associate with the network interface # * options<~Hash>: # * PrivateIpAddress<~String> - The private IP address of the network interface # * Description<~String> - The description of the network interface # * groupSet<~Array> - The security group IDs for use by the network interface # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'networkInterface'<~Hash> - The created network interface # * 'networkInterfaceId'<~String> - The ID of the network interface # * 'subnetId'<~String> - The ID of the subnet # * 'vpcId'<~String> - The ID of the VPC # * 'availabilityZone'<~String> - The availability zone # * 'description'<~String> - The description # * 'ownerId'<~String> - The ID of the person who created the interface # * 'requesterId'<~String> - The ID ot teh entity requesting this interface # * 'requesterManaged'<~String> - # * 'status'<~String> - "available" or "in-use" # * 'macAddress'<~String> - # * 'privateIpAddress'<~String> - IP address of the interface within the subnet # * 'privateDnsName'<~String> - The private DNS name # * 'sourceDestCheck'<~Boolean> - Flag indicating whether traffic to or from the instance is validated # * 'groupSet'<~Hash> - Associated security groups # * 'key'<~String> - ID of associated group # * 'value'<~String> - Name of associated group # * 'attachment'<~Hash>: - Describes the way this nic is attached # * 'attachmentID'<~String> # * 'instanceID'<~String> # * 'association'<~Hash>: - Describes an eventual instance association # * 'attachmentID'<~String> - ID of the network interface attachment # * 'instanceID'<~String> - ID of the instance attached to the network interface # * 'publicIp'<~String> - Address of the Elastic IP address bound to the network interface # * 'ipOwnerId'<~String> - ID of the Elastic IP address owner # * 'tagSet'<~Array>: - Tags assigned to the resource. # * 'key'<~String> - Tag's key # * 'value'<~String> - Tag's value # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/2012-03-01/APIReference/ApiReference-query-CreateNetworkInterface.html] def create_network_interface(subnetId, options = {}) if security_groups = options.delete('GroupSet') options.merge!(Fog::AWS.indexed_param('SecurityGroupId', [*security_groups])) end request({ 'Action' => 'CreateNetworkInterface', 'SubnetId' => subnetId, :parser => Fog::Parsers::Compute::AWS::CreateNetworkInterface.new }.merge!(options)) end end class Mock def create_network_interface(subnetId, options = {}) response = Excon::Response.new if subnetId id = Fog::AWS::Mock.network_interface_id groups = {} if options['GroupSet'] options['GroupSet'].each do |group_id| name = self.data[:security_groups].select { |k,v| v['groupId'] == group_id } .first.first if name.nil? raise Fog::Compute::AWS::Error.new("Unknown security group '#{group_id}' specified") end groups[group_id] = name end end if options['PrivateIpAddress'].nil? options['PrivateIpAddress'] = "10.0.0.2" end data = { 'networkInterfaceId' => id, 'subnetId' => subnetId, 'vpcId' => 'mock-vpc-id', 'availabilityZone' => 'mock-zone', 'description' => options['Description'], 'ownerId' => '', 'requesterManaged' => 'false', 'status' => 'available', 'macAddress' => '00:11:22:33:44:55', 'privateIpAddress' => options['PrivateIpAddress'], 'sourceDestCheck' => true, 'groupSet' => groups, 'attachment' => {}, 'association' => {}, 'tagSet' => {} } self.data[:network_interfaces][id] = data response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'networkInterface' => data } response else response.status = 400 response.body = { 'Code' => 'InvalidParameterValue', 'Message' => "Invalid value '' for subnetId" } end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/delete_security_group.rb0000644000004100000410000000625312261242551025007 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Delete a security group that you own # # ==== Parameters # * group_name<~String> - Name of the security group, must be nil if id is specified # * group_id<~String> - Id of the security group, must be nil if name is specified # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteSecurityGroup.html] def delete_security_group(name, id = nil) if name && id raise Fog::Compute::AWS::Error.new("May not specify both group_name and group_id") end if name type_id = 'GroupName' identifier = name else type_id = 'GroupId' identifier = id end request( 'Action' => 'DeleteSecurityGroup', type_id => identifier, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def delete_security_group(name, id = nil) if name == 'default' raise Fog::Compute::AWS::Error.new("InvalidGroup.Reserved => The security group 'default' is reserved") end if name && id raise Fog::Compute::AWS::Error.new("May not specify both group_name and group_id") end if id name = self.data[:security_groups].reject { |k,v| v['groupId'] != id } .keys.first end response = Excon::Response.new if self.data[:security_groups][name] used_by_groups = [] self.region_data.each do |access_key, key_data| key_data[:security_groups].each do |group_name, group| next if group == self.data[:security_groups][name] group['ipPermissions'].each do |group_ip_permission| group_ip_permission['groups'].each do |group_group_permission| if group_group_permission['groupName'] == name && group_group_permission['userId'] == self.data[:owner_id] used_by_groups << "#{key_data[:owner_id]}:#{group_name}" end end end end end unless used_by_groups.empty? raise Fog::Compute::AWS::Error.new("InvalidGroup.InUse => Group #{self.data[:owner_id]}:#{name} is used by groups: #{used_by_groups.uniq.join(" ")}") end self.data[:security_groups].delete(name) response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else raise Fog::Compute::AWS::NotFound.new("The security group '#{name}' does not exist") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/delete_vpc.rb0000644000004100000410000000331612261242551022511 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Deletes a VPC. You must detach or delete all gateways or other objects # that are dependent on the VPC first. For example, you must terminate # all running instances, delete all VPC security groups (except the # default), delete all the route tables (except the default), etc. # # ==== Parameters # * vpc_id<~String> - The ID of the VPC you want to delete. # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - Returns true if the request succeeds. # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/2011-07-15/APIReference/index.html?ApiReference-query-DeleteVpc.html] def delete_vpc(vpc_id) request( 'Action' => 'DeleteVpc', 'VpcId' => vpc_id, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def delete_vpc(vpc_id) Excon::Response.new.tap do |response| if vpc_id response.status = 200 self.data[:vpcs].reject! { |v| v['vpcId'] == vpc_id } response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } else message = 'MissingParameter => ' message << 'The request must contain the parameter vpc_id' raise Fog::Compute::AWS::Error.new(message) end end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_image.rb0000644000004100000410000001120312261242551022776 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/create_image' # Create a bootable EBS volume AMI # # ==== Parameters # * instance_id<~String> - Instance used to create image. # * name<~Name> - Name to give image. # * description<~Name> - Description of image. # * no_reboot<~Boolean> - Optional, whether or not to reboot the image when making the snapshot # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'imageId'<~String> - The ID of the created AMI. # * 'requestId'<~String> - Id of request. # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateImage.html] def create_image(instance_id, name, description, no_reboot = false, options={}) params = {} block_device_mappings = options[:block_device_mappings] || [] params.merge!Fog::AWS.indexed_param('BlockDeviceMapping.%d.DeviceName', block_device_mappings.map{|mapping| mapping['DeviceName']}) params.merge!Fog::AWS.indexed_param('BlockDeviceMapping.%d.NoDevice', block_device_mappings.map{|mapping| mapping['NoDevice']}) params.merge!Fog::AWS.indexed_param('BlockDeviceMapping.%d.VirtualName', block_device_mappings.map{|mapping| mapping['VirtualName']}) params.merge!Fog::AWS.indexed_param('BlockDeviceMapping.%d.Ebs.SnapshotId', block_device_mappings.map{|mapping| mapping['Ebs.SnapshotId']}) params.merge!Fog::AWS.indexed_param('BlockDeviceMapping.%d.Ebs.DeleteOnTermination', block_device_mappings.map{|mapping| mapping['Ebs.DeleteOnTermination']}) params.merge!Fog::AWS.indexed_param('BlockDeviceMapping.%d.Ebs.VolumeType', block_device_mappings.map{|mapping| mapping['Ebs.VolumeType']}) params.merge!Fog::AWS.indexed_param('BlockDeviceMapping.%d.Ebs.Iops', block_device_mappings.map{|mapping| mapping['Ebs.Iops']}) params.reject!{|k,v| v.nil?} request({ 'Action' => 'CreateImage', 'InstanceId' => instance_id, 'Name' => name, 'Description' => description, 'NoReboot' => no_reboot.to_s, :parser => Fog::Parsers::Compute::AWS::CreateImage.new }.merge!(params)) end end class Mock # Usage # # AWS[:compute].create_image("i-ac65ee8c", "test", "something") # def create_image(instance_id, name, description, no_reboot = false, options = {}) params = {} block_device_mappings = options[:block_device_mappings] || [] params.merge!Fog::AWS.indexed_param('BlockDeviceMapping.%d.DeviceName', block_device_mappings.map{|mapping| mapping['DeviceName']}) params.merge!Fog::AWS.indexed_param('BlockDeviceMapping.%d.NoDevice', block_device_mappings.map{|mapping| mapping['NoDevice']}) params.merge!Fog::AWS.indexed_param('BlockDeviceMapping.%d.VirtualName', block_device_mappings.map{|mapping| mapping['VirtualName']}) params.merge!Fog::AWS.indexed_param('BlockDeviceMapping.%d.Ebs.SnapshotId', block_device_mappings.map{|mapping| mapping['Ebs.SnapshotId']}) params.merge!Fog::AWS.indexed_param('BlockDeviceMapping.%d.Ebs.DeleteOnTermination', block_device_mappings.map{|mapping| mapping['Ebs.DeleteOnTermination']}) params.merge!Fog::AWS.indexed_param('BlockDeviceMapping.%d.Ebs.VolumeType', block_device_mappings.map{|mapping| mapping['Ebs.VolumeType']}) params.merge!Fog::AWS.indexed_param('BlockDeviceMapping.%d.Ebs.Iops', block_device_mappings.map{|mapping| mapping['Ebs.Iops']}) params.reject!{|k,v| v.nil?} reserved_ebs_root_device = '/dev/sda1' block_devices = options.delete(:block_device_mappings) || [] register_image_response = register_image(name, description, reserved_ebs_root_device, block_devices, options) response = Excon::Response.new if instance_id && !name.empty? response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'imageId' => register_image_response.body['imageId'] } else response.status = 400 response.body = { 'Code' => 'InvalidParameterValue' } if name.empty? response.body['Message'] = "Invalid value '' for name. Must be specified." end end response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_volumes.rb0000644000004100000410000001154512261242551023734 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_volumes' # Describe all or specified volumes. # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'volumeSet'<~Array>: # * 'availabilityZone'<~String> - Availability zone for volume # * 'createTime'<~Time> - Timestamp for creation # * 'iops'<~Integer> - Number of IOPS volume supports # * 'size'<~Integer> - Size in GiBs for volume # * 'snapshotId'<~String> - Snapshot volume was created from, if any # * 'status'<~String> - State of volume # * 'volumeId'<~String> - Reference to volume # * 'volumeType'<~String> - Type of volume # * 'attachmentSet'<~Array>: # * 'attachmentTime'<~Time> - Timestamp for attachment # * 'deleteOnTermination'<~Boolean> - Whether or not to delete volume on instance termination # * 'device'<~String> - How value is exposed to instance # * 'instanceId'<~String> - Reference to attached instance # * 'status'<~String> - Attachment state # * 'volumeId'<~String> - Reference to volume # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumes.html] def describe_volumes(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_volumes with #{filters.class} param is deprecated, use describe_volumes('volume-id' => []) instead [light_black](#{caller.first})[/]") filters = {'volume-id' => [*filters]} end params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeVolumes', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeVolumes.new }.merge!(params)) end end class Mock def describe_volumes(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_volumes with #{filters.class} param is deprecated, use describe_volumes('volume-id' => []) instead [light_black](#{caller.first})[/]") filters = {'volume-id' => [*filters]} end response = Excon::Response.new volume_set = self.data[:volumes].values volume_set = apply_tag_filters(volume_set, filters, 'volumeId') aliases = { 'availability-zone' => 'availabilityZone', 'create-time' => 'createTime', 'size' => 'size', 'snapshot-id' => 'snapshotId', 'status' => 'status', 'volume-id' => 'volumeId' } attachment_aliases = { 'attach-time' => 'attachTime', 'delete-on-termination' => 'deleteOnTermination', 'device' => 'device', 'instance-id' => 'instanceId', 'status' => 'status' } for filter_key, filter_value in filters if attachment_key = filter_key.split('attachment.')[1] aliased_key = attachment_aliases[filter_key] volume_set = volume_set.reject{|volume| !volume['attachmentSet'].detect {|attachment| [*filter_value].include?(attachment[aliased_key])}} else aliased_key = aliases[filter_key] volume_set = volume_set.reject{|volume| ![*filter_value].include?(volume[aliased_key])} end end volume_set.each do |volume| case volume['status'] when 'attaching' if Time.now - volume['attachmentSet'].first['attachTime'] >= Fog::Mock.delay volume['attachmentSet'].first['status'] = 'in-use' volume['status'] = 'in-use' end when 'creating' if Time.now - volume['createTime'] >= Fog::Mock.delay volume['status'] = 'available' end when 'deleting' if Time.now - self.data[:deleted_at][volume['volumeId']] >= Fog::Mock.delay self.data[:deleted_at].delete(volume['volumeId']) self.data[:volumes].delete(volume['volumeId']) end end end volume_set = volume_set.reject {|volume| !self.data[:volumes][volume['volumeId']]} volume_set = volume_set.map {|volume| volume.merge('tagSet' => self.data[:tag_sets][volume['volumeId']]) } response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'volumeSet' => volume_set } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_placement_groups.rb0000644000004100000410000000225212261242551025604 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_placement_groups' # Describe all or specified placement groups # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'placementGroupSet'<~Array>: # * 'groupName'<~String> - Name of placement group # * 'strategy'<~String> - Strategy of placement group # * 'state'<~String> - State of placement group # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribePlacementGroups.html] def describe_placement_groups(filters = {}) params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribePlacementGroups', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribePlacementGroups.new }.merge!(params)) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/stop_instances.rb0000644000004100000410000000423412261242551023433 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/start_stop_instances' # Stop specified instance # # ==== Parameters # * instance_id<~Array> - Id of instance to start # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * TODO: fill in the blanks # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-StopInstances.html] def stop_instances(instance_id, force = false) params = Fog::AWS.indexed_param('InstanceId', instance_id) params.merge!('Force' => 'true') if force request({ 'Action' => 'StopInstances', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::StartStopInstances.new }.merge!(params)) end end class Mock def stop_instances(instance_id, force = false) instance_ids = Array(instance_id) instance_set = self.data[:instances].values instance_set = apply_tag_filters(instance_set, {'instance_id' => instance_ids}, 'instanceId') instance_set = instance_set.find_all {|x| instance_ids.include?(x["instanceId"]) } if instance_set.empty? raise Fog::Compute::AWS::NotFound.new("The instance ID '#{instance_ids.first}' does not exist") else response = Excon::Response.new response.status = 200 response.body = { 'instancesSet' => instance_set.inject([]) do |ia, instance| ia << {'currentState' => { 'code' => 0, 'name' => 'stopping' }, 'previousState' => instance['instanceState'], 'instanceId' => instance['instanceId'] } instance['instanceState'] = {'code'=>0, 'name'=>'stopping'} ia end } response end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/delete_network_interface.rb0000644000004100000410000000335212261242551025432 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Deletes a network interface. # # ==== Parameters # * network_interface_id<~String> - The ID of the network interface you want to delete. # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - Returns true if the request succeeds. # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/2012-03-01/APIReference/ApiReference-query-DeleteNetworkInterface.html] def delete_network_interface(network_interface_id) request( 'Action' => 'DeleteNetworkInterface', 'NetworkInterfaceId' => network_interface_id, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def delete_network_interface(network_interface_id) response = Excon::Response.new if self.data[:network_interfaces][network_interface_id] if self.data[:network_interfaces][network_interface_id]['attachment']['attachmentId'] raise Fog::Compute::AWS::Error.new("Interface is in use") end self.data[:network_interfaces].delete(network_interface_id) response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else raise Fog::Compute::AWS::NotFound.new("The network interface '#{network_interface_id}' does not exist") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/unmonitor_instances.rb0000644000004100000410000000371512261242551024503 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/monitor_unmonitor_instances' # UnMonitor specified instance # http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-UnmonitorInstances.html # # ==== Parameters # * instance_ids<~Array> - Arrays of instances Ids to monitor # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'instancesSet': http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-MonitorInstancesResponseSetItemType.html # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-UnmonitorInstances.html] def unmonitor_instances(instance_ids) params = Fog::AWS.indexed_param('InstanceId', instance_ids) request({ 'Action' => 'UnmonitorInstances', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::MonitorUnmonitorInstances.new }.merge!(params)) end end class Mock def unmonitor_instances(instance_ids) response = Excon::Response.new response.status = 200 [*instance_ids].each do |instance_id| if instance = self.data[:instances][instance_id] instance['monitoring']['state'] = 'enabled' else raise Fog::Compute::AWS::NotFound.new("The instance ID '#{instance_ids}' does not exist") end end instances_set = [*instance_ids].inject([]) { |memo, id| memo << {'instanceId' => id, 'monitoring' => 'disabled'} } response.body = {'requestId' => 'some_request_id', 'instancesSet' => instances_set} response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/request_spot_instances.rb0000644000004100000410000001270212261242551025202 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/spot_instance_requests' # Launch specified instances # # ==== Parameters # * 'image_id'<~String> - Id of machine image to load on instances # * 'instance_type'<~String> - Type of instance # * 'spot_price'<~Float> - maximum hourly price for instances launched # * options<~Hash>: # * 'AvailabilityZoneGroup'<~String> - specify whether or not to launch all instances in the same availability group # * 'InstanceCount'<~Integer> - maximum number of instances to launch # * 'LaunchGroup'<~String> - whether or not to launch/shutdown instances as a group # * 'LaunchSpecification.BlockDeviceMapping'<~Array>: array of hashes # * 'DeviceName'<~String> - where the volume will be exposed to instance # * 'VirtualName'<~String> - volume virtual device name # * 'Ebs.SnapshotId'<~String> - id of snapshot to boot volume from # * 'Ebs.NoDevice'<~String> - specifies that no device should be mapped # * 'Ebs.VolumeSize'<~String> - size of volume in GiBs required unless snapshot is specified # * 'Ebs.DeleteOnTermination'<~String> - specifies whether or not to delete the volume on instance termination # * 'LaunchSpecification.KeyName'<~String> - Name of a keypair to add to booting instances # * 'LaunchSpecification.Monitoring.Enabled'<~Boolean> - Enables monitoring, defaults to disabled # * 'LaunchSpecification.SubnetId'<~String> - VPC subnet ID in which to launch the instance # * 'LaunchSpecification.Placement.AvailabilityZone'<~String> - Placement constraint for instances # * 'LaunchSpecification.SecurityGroup'<~Array> or <~String> - Name of security group(s) for instances, not supported in VPC # * 'LaunchSpecification.SecurityGroupId'<~Array> or <~String> - Id of security group(s) for instances, use this or LaunchSpecification.SecurityGroup # * 'LaunchSpecification.UserData'<~String> - Additional data to provide to booting instances # * 'LaunchSpecification.EbsOptimized'<~Boolean> - Whether the instance is optimized for EBS I/O # * 'Type'<~String> - spot instance request type in ['one-time', 'persistent'] # * 'ValidFrom'<~Time> - start date for request # * 'ValidUntil'<~Time> - end date for request # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'spotInstanceRequestSet'<~Array>: # * 'createTime'<~Time> - time of instance request creation # * 'instanceId'<~String> - instance id if one has been launched to fulfill request # * 'launchedAvailabilityZone'<~String> - availability zone of instance if one has been launched to fulfill request # * 'launchSpecification'<~Hash>: # * 'blockDeviceMapping'<~Hash> - list of block device mappings for instance # * 'groupSet'<~String> - security group(s) for instance # * 'keyName'<~String> - keypair name for instance # * 'imageId'<~String> - AMI for instance # * 'instanceType'<~String> - type for instance # * 'monitoring'<~Boolean> - monitoring status for instance # * 'subnetId'<~String> - VPC subnet ID for instance # * 'productDescription'<~String> - general description of AMI # * 'spotInstanceRequestId'<~String> - id of spot instance request # * 'spotPrice'<~Float> - maximum price for instances to be launched # * 'state'<~String> - spot instance request state # * 'type'<~String> - spot instance request type # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RequestSpotInstances.html] def request_spot_instances(image_id, instance_type, spot_price, options = {}) if block_device_mapping = options.delete('LaunchSpecification.BlockDeviceMapping') block_device_mapping.each_with_index do |mapping, index| for key, value in mapping options.merge!({ format("LaunchSpecification.BlockDeviceMapping.%d.#{key}", index) => value }) end end end if security_groups = options.delete('LaunchSpecification.SecurityGroup') options.merge!(Fog::AWS.indexed_param('LaunchSpecification.SecurityGroup', [*security_groups])) end if security_group_ids = options.delete('LaunchSpecification.SecurityGroupId') options.merge!(Fog::AWS.indexed_param('LaunchSpecification.SecurityGroupId', [*security_group_ids])) end if options['LaunchSpecification.UserData'] options['LaunchSpecification.UserData'] = Base64.encode64(options['LaunchSpecification.UserData']) end request({ 'Action' => 'RequestSpotInstances', 'LaunchSpecification.ImageId' => image_id, 'LaunchSpecification.InstanceType' => instance_type, 'SpotPrice' => spot_price, :parser => Fog::Parsers::Compute::AWS::SpotInstanceRequests.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/get_password_data.rb0000644000004100000410000000353312261242551024072 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/get_password_data' # Retrieves the encrypted administrator password for an instance running Windows. # # ==== Parameters # * instance_id<~String> - A Windows instance ID # # ==== Returns # # * response<~Excon::Response>: # * body<~Hash>: # * 'instanceId'<~String> - Id of instance # * 'passwordData'<~String> - The encrypted, base64-encoded password of the instance. # * 'requestId'<~String> - Id of request # * 'timestamp'<~Time> - Timestamp of last update to output # # See http://docs.amazonwebservices.com/AWSEC2/2010-08-31/APIReference/index.html?ApiReference-query-GetPasswordData.html # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-GetPasswordData.html] def get_password_data(instance_id) request( 'Action' => 'GetPasswordData', 'InstanceId' => instance_id, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::GetPasswordData.new ) end end class Mock def get_password_data(instance_id) response = Excon::Response.new if instance = self.data[:instances][instance_id] response.status = 200 response.body = { 'instanceId' => instance_id, 'passwordData' => nil, 'requestId' => Fog::AWS::Mock.request_id, 'timestamp' => Time.now } response else; raise Fog::Compute::AWS::NotFound.new("The instance ID '#{instance_id}' does not exist") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/cancel_spot_instance_requests.rb0000644000004100000410000000232412261242551026506 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/cancel_spot_instance_requests' # Terminate specified spot instance requests # # ==== Parameters # * spot_instance_request_id<~Array> - Ids of instances to terminates # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> id of request # * 'spotInstanceRequestSet'<~Array>: # * 'spotInstanceRequestId'<~String> - id of cancelled spot instance # * 'state'<~String> - state of cancelled spot instance # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CancelSpotInstanceRequests.html] def cancel_spot_instance_requests(spot_instance_request_id) params = Fog::AWS.indexed_param('SpotInstanceRequestId', spot_instance_request_id) request({ 'Action' => 'CancelSpotInstanceRequests', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::CancelSpotInstanceRequests.new }.merge!(params)) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/attach_internet_gateway.rb0000644000004100000410000000351112261242551025271 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Attaches an Internet gateway to a VPC, enabling connectivity between the Internet and the VPC # # ==== Parameters # * internet_gateway_id<~String> - The ID of the Internet gateway to attach # * vpc_id<~String> - The ID of the VPC # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - Returns true if the request succeeds. # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AttachInternetGateway.html] def attach_internet_gateway(internet_gateway_id, vpc_id) request( 'Action' => 'AttachInternetGateway', 'InternetGatewayId' => internet_gateway_id, 'VpcId' => vpc_id, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def attach_internet_gateway(internet_gateway_id, vpc_id) response = Excon::Response.new if internet_gateway_id && vpc_id response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else if !internet_gateway_id message << 'The request must contain the parameter internet_gateway_id' elsif !vpc_id message << 'The request must contain the parameter vpc_id' end raise Fog::Compute::AWS::Error.new(message) end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/detach_network_interface.rb0000644000004100000410000000332412261242551025417 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Detaches a network interface. # # ==== Parameters # * attachment_id<~String> - ID of the attachment to detach # * force<~Boolean> - Set to true to force a detachment # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - Returns true if the request succeeds. # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/2012-03-01/APIReference/ApiReference-query-DetachNetworkInterface.html] def detach_network_interface(attachment_id, force = false) request( 'Action' => 'DetachNetworkInterface', 'AttachmentId' => attachment_id, 'Force' => force, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def detach_network_interface(attachment_id, force = false) response = Excon::Response.new nic_id = self.data[:network_interfaces].select { |k,v| v['attachment']['attachmentId'] == attachment_id} .first.first if nic_id self.data[:network_interfaces][nic_id]["attachment"] = {} response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else raise Fog::Compute::AWS::NotFound.new("The network interface '#{network_interface_id}' does not exist") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_spot_price_history.rb0000644000004100000410000000255712261242551026175 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_spot_price_history' # Describe all or specified spot price history # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'spotPriceHistorySet'<~Array>: # * 'availabilityZone'<~String> - availability zone for instance # * 'instanceType'<~String> - the type of instance # * 'productDescription'<~String> - general description of AMI # * 'spotPrice'<~Float> - maximum price to launch one or more instances # * 'timestamp'<~Time> - date and time of request creation # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotPriceHistory.html] def describe_spot_price_history(filters = {}) params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeSpotPriceHistory', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeSpotPriceHistory.new }.merge!(params)) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_security_group.rb0000644000004100000410000000421312261242551025002 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/create_security_group' # Create a new security group # # ==== Parameters # * group_name<~String> - Name of the security group. # * group_description<~String> - Description of group. # * vpc_id<~String> - ID of the VPC # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # * 'groupId'<~String> - Id of created group # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSecurityGroup.html] def create_security_group(name, description, vpc_id=nil) request( 'Action' => 'CreateSecurityGroup', 'GroupName' => name, 'GroupDescription' => description, 'VpcId' => vpc_id, :parser => Fog::Parsers::Compute::AWS::CreateSecurityGroup.new ) end end class Mock def create_security_group(name, description, vpc_id=nil) response = Excon::Response.new unless self.data[:security_groups][name] data = { 'groupDescription' => description, 'groupName' => name, 'groupId' => Fog::AWS::Mock.security_group_id, 'ipPermissionsEgress' => [], 'ipPermissions' => [], 'ownerId' => self.data[:owner_id], 'vpcId' => vpc_id } self.data[:security_groups][name] = data response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'groupId' => data['groupId'], 'return' => true } response else raise Fog::Compute::AWS::Error.new("InvalidGroup.Duplicate => The security group '#{name}' already exists") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_dhcp_options.rb0000644000004100000410000000530112261242551024407 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/create_dhcp_options' # Creates a set of DHCP options for your VPC # # ==== Parameters # * DhcpConfigurationOptions<~Hash> - hash of key value dhcp options to assign # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateDhcpOptions.html] def create_dhcp_options(dhcp_configurations = {}) params = {} params.merge!(indexed_multidimensional_params(dhcp_configurations)) request({ 'Action' => 'CreateDhcpOptions', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::CreateDhcpOptions.new }.merge!(params)) end private def indexed_multidimensional_params(multi_params) params = {} multi_params.keys.each_with_index do |key, key_index| key_index += 1 params[format('DhcpConfiguration.%d.Key', key_index)] = key [*multi_params[key]].each_with_index do |value, value_index| value_index += 1 params[format('DhcpConfiguration.%d.Value.%d', key_index, value_index)] = value end end params end end class Mock def create_dhcp_options(dhcp_configurations = {}) params = {} params.merge!(indexed_multidimensional_params(dhcp_configurations)) Excon::Response.new.tap do |response| response.status = 200 self.data[:dhcp_options].push({ 'dhcpOptionsId' => Fog::AWS::Mock.dhcp_options_id, 'dhcpConfigurationSet' => {}, 'tagSet' => {} }) response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'dhcpOptionsSet' => self.data[:dhcp_options] } end end private def indexed_multidimensional_params(multi_params) params = {} multi_params.keys.each_with_index do |key, key_index| key_index += 1 params[format('DhcpConfiguration.%d.Key', key_index)] = key [*multi_params[key]].each_with_index do |value, value_index| value_index += 1 params[format('DhcpConfiguration.%d.Value.%d', key_index, value_index)] = value end end params end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_subnet.rb0000644000004100000410000000624712261242551023230 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/create_subnet' # Creates a Subnet with the CIDR block you specify. # # ==== Parameters # * vpcId<~String> - The ID of the VPC where you want to create the subnet. # * cidrBlock<~String> - The CIDR block you want the Subnet to cover (e.g., 10.0.0.0/16). # * options<~Hash>: # * AvailabilityZone<~String> - The Availability Zone you want the subnet in. Default: AWS selects a zone for you (recommended) # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'subnet'<~Array>: # * 'subnetId'<~String> - The Subnet's ID # * 'state'<~String> - The current state of the Subnet. ['pending', 'available'] # * 'cidrBlock'<~String> - The CIDR block the Subnet covers. # * 'AvailableIpAddressCount'<~Integer> - The number of unused IP addresses in the subnet (the IP addresses for any stopped # instances are considered unavailable) # * 'AvailabilityZone'<~String> - The Availability Zone the subnet is in # * 'tagSet'<~Array>: Tags assigned to the resource. # * 'key'<~String> - Tag's key # * 'value'<~String> - Tag's value # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/2011-07-15/APIReference/ApiReference-query-CreateSubnet.html] def create_subnet(vpcId, cidrBlock, options = {}) request({ 'Action' => 'CreateSubnet', 'VpcId' => vpcId, 'CidrBlock' => cidrBlock, :parser => Fog::Parsers::Compute::AWS::CreateSubnet.new }.merge!(options)) end end class Mock def create_subnet(vpcId, cidrBlock, options = {}) av_zone = options['AvailabilityZone'].nil? ? 'us-east-1c' : options['AvailabilityZone'] Excon::Response.new.tap do |response| if cidrBlock && vpcId response.status = 200 self.data[:subnets].push({ 'subnetId' => Fog::AWS::Mock.request_id, 'state' => 'pending', 'vpcId' => vpcId, 'cidrBlock' => cidrBlock, 'availableIpAddressCount' => "255", 'availabilityZone' => av_zone, 'tagSet' => {} }) response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'subnetSet' => self.data[:subnets] } else response.status = 400 response.body = { 'Code' => 'InvalidParameterValue' } if cidrBlock.empty? response.body['Message'] = "Invalid value '' for cidrBlock. Must be specified." end if vpcId.empty? response.body['Message'] = "Invalid value '' for vpcId. Must be specified." end end end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/purchase_reserved_instances_offering.rb0000644000004100000410000000534112261242551030036 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/purchase_reserved_instances_offering' # Purchases a Reserved Instance for use with your account. # # ==== Parameters # * reserved_instances_offering_id<~String> - ID of the Reserved Instance offering you want to purchase. # * instance_count<~Integer> - The number of Reserved Instances to purchase. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'reservedInstancesId'<~String> - Id of the purchased reserved instances. # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-PurchaseReservedInstancesOffering.html] def purchase_reserved_instances_offering(reserved_instances_offering_id, instance_count = 1) request({ 'Action' => 'PurchaseReservedInstancesOffering', 'ReservedInstancesOfferingId' => reserved_instances_offering_id, 'InstanceCount' => instance_count, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::PurchaseReservedInstancesOffering.new }) end end class Mock def purchase_reserved_instances_offering(reserved_instances_offering_id, instance_count = 1) response = Excon::Response.new response.status = 200 # Need to implement filters in the mock to find this there instead of here # Also there's no information about what to do when the specified reserved_instances_offering_id doesn't exist raise unless reserved_instance_offering = describe_reserved_instances_offerings.body["reservedInstancesOfferingsSet"].find { |offering| offering["reservedInstancesOfferingId"] == reserved_instances_offering_id } reserved_instances_id = Fog::AWS::Mock.reserved_instances_id reserved_instance_offering.delete('reservedInstancesOfferingId') self.data[:reserved_instances][reserved_instances_id] = reserved_instance_offering.merge({ 'reservedInstancesId' => reserved_instances_id, 'start' => Time.now, 'end' => Time.now, 'instanceCount' => instance_count, 'state' => 'payment-pending', 'tagSet' => [] }) response.body = { 'reservedInstancesId' => reserved_instances_id, 'requestId' => Fog::AWS::Mock.request_id } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/copy_snapshot.rb0000644000004100000410000000325212261242551023267 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/copy_snapshot' # Copy a snapshot to a different region # # ==== Parameters # * source_snapshot_id<~String> - Id of snapshot # * source_region<~String> - Region to move it from # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - id of request # * 'snapshotId'<~String> - id of snapshot # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CopySnapshot.html] def copy_snapshot(source_snapshot_id, source_region, description = nil) request( 'Action' => 'CopySnapshot', 'SourceSnapshotId'=> source_snapshot_id, 'SourceRegion' => source_region, 'Description' => description, :parser => Fog::Parsers::Compute::AWS::CopySnapshot.new ) end end class Mock # # Usage # # AWS[:compute].copy_snapshot("snap-1db0a957", 'us-east-1') # def copy_snapshot(source_snapshot_id, source_region, description = nil) response = Excon::Response.new response.status = 200 snapshot_id = Fog::AWS::Mock.snapshot_id data = { 'snapshotId' => snapshot_id, } self.data[:snapshots][snapshot_id] = data response.body = { 'requestId' => Fog::AWS::Mock.request_id }.merge!(data) response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_route_tables.rb0000755000004100000410000000750312261242551024734 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_route_tables' # Describe one or more of your route tables. # # ==== Parameters # * RouteTableId<~String> - One or more route table IDs. # * filters<~Hash> - List of filters to limit results with # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - The ID of the request. # * 'routeTableSet'<~Array>: # * 'routeTableId'<~String> - The route table's ID. # * 'vpcId'<~String> - The ID of the VPC for the route table. # * 'routeSet'<~Array>: # * 'destinationCidrBlock'<~String> - The CIDR address block used for the destination match. # * 'gatewayId'<~String> - The ID of a gateway attached to your VPC. # * 'instanceId'<~String> - The ID of a NAT instance in your VPC. # * 'instanceOwnerId'<~String> - The owner of the instance. # * 'networkInterfaceId'<~String> - The network interface ID. # * 'state'<~String> - The state of the route. The blackhole state indicates that the route's target isn't available. # * 'origin'<~String> - Describes how the route was created. # * 'associationSet'<~Array>: # * 'RouteTableAssociationId'<~String> - An identifier representing the association between a route table and a subnet. # * 'routeTableId'<~String> - The ID of the route table. # * 'subnetId'<~String> - The ID of the subnet. # * 'main'<~Boolean> - Indicates whether this is the main route table. # * 'propagatingVgwSet'<~Array>: # * 'gatewayID'<~String> - The ID of the virtual private gateway (VGW). # * 'tagSet'<~Array>: # * 'key'<~String> - The tag key. # * 'value'<~String> - The tag value. # # {Amazon API Reference}[http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeRouteTables.html] def describe_route_tables(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_route_tables with #{filters.class} param is deprecated, use describe_route_tables('route-table-id' => []) instead [light_black](#{caller.first})[/]") filters = {'route-table-id' => [*filters]} end params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeRouteTables', :parser => Fog::Parsers::Compute::AWS::DescribeRouteTables.new }.merge!(params)) end end class Mock def describe_route_tables(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_route_tables with #{filters.class} param is deprecated, use describe_route_tables('route-table-id' => []) instead [light_black](#{caller.first})[/]") filters = {'route-table-id' => [*filters]} end display_routes = self.data[:route_tables].dup aliases = { 'route-table-id' => 'routeTableId', 'vpc-id' => 'vpcId' } for filter_key, filter_value in filters filter_attribute = aliases[filter_key] case filter_attribute when 'routeTableId', 'vpcId' display_routes.reject! { |routetable| routetable[filter_attribute] != filter_value } end end Excon::Response.new( :status => 200, :body => { 'requestId' => Fog::AWS::Mock.request_id, 'routeTableSet' => display_routes } ) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/delete_route.rb0000755000004100000410000000501712261242551023062 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Deletes the specified route from the specified route table. # # ==== Parameters # * RouteTableId<~String> - The ID of the route table. # * DestinationCidrBlock<~String> - The CIDR range for the route. The value you specify must match the CIDR for the route exactly. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - The ID of the request. # * 'return'<~Boolean> - Returns true if the request succeeds. Otherwise, returns an error. # # {Amazon API Reference}[http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteRoute.html] def delete_route(route_table_id, destination_cidr_block) request( 'Action' => 'DeleteRoute', 'RouteTableId' => route_table_id, 'DestinationCidrBlock' => destination_cidr_block, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def delete_route(route_table_id, destination_cidr_block) route_table = self.data[:route_tables].find { |routetable| routetable["routeTableId"].eql? route_table_id } unless route_table.nil? route = route_table['routeSet'].find { |route| route["destinationCidrBlock"].eql? destination_cidr_block } if !route.nil? && route['gatewayId'] != "local" route_table['routeSet'].delete(route) response = Excon::Response.new response.status = 200 response.body = { 'requestId'=> Fog::AWS::Mock.request_id, 'return' => true } response elsif route['gatewayId'] == "local" # Cannot delete the default route raise Fog::Compute::AWS::Error, "InvalidParameterValue => cannot remove local route #{destination_cidr_block} in route table #{route_table_id}" else raise Fog::Compute::AWS::NotFound.new("no route with destination-cidr-block #{destination_cidr_block} in route table #{route_table_id}") end else raise Fog::Compute::AWS::NotFound.new("no route with destination-cidr-block #{destination_cidr_block} in route table #{route_table_id}") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/allocate_address.rb0000644000004100000410000000413312261242551023666 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/allocate_address' # Acquire an elastic IP address. # # ==== Parameters # * domain<~String> - Type of EIP, either standard or vpc # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'publicIp'<~String> - The acquired address # * 'requestId'<~String> - Id of the request # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AllocateAddress.html] def allocate_address(domain='standard') domain = domain == 'vpc' ? 'vpc' : 'standard' request( 'Action' => 'AllocateAddress', 'Domain' => domain, :parser => Fog::Parsers::Compute::AWS::AllocateAddress.new ) end end class Mock def allocate_address(domain = 'standard') domain = domain == 'vpc' ? 'vpc' : 'standard' response = Excon::Response.new if describe_addresses.body['addressesSet'].size < self.data[:limits][:addresses] response.status = 200 public_ip = Fog::AWS::Mock.ip_address data = { 'instanceId' => nil, 'publicIp' => public_ip, 'domain' => domain } if domain == 'vpc' data['allocationId'] = "eipalloc-#{Fog::Mock.random_hex(8)}" end self.data[:addresses][public_ip] = data response.body = data.reject {|k, v| k == 'instanceId' }.merge('requestId' => Fog::AWS::Mock.request_id) response else response.status = 400 response.body = "AddressLimitExceededToo many addresses allocated#{Fog::AWS::Mock.request_id}" raise(Excon::Errors.status_error({:expects => 200}, response)) end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_network_interfaces.rb0000644000004100000410000000736012261242551026136 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_network_interfaces' # Describe all or specified network interfaces # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'networkInterfaceSet'<~Array>: # * 'networkInterfaceId'<~String> - The ID of the network interface # * 'subnetId'<~String> - The ID of the subnet # * 'vpcId'<~String> - The ID of the VPC # * 'availabilityZone'<~String> - The availability zone # * 'description'<~String> - The description # * 'ownerId'<~String> - The ID of the person who created the interface # * 'requesterId'<~String> - The ID ot teh entity requesting this interface # * 'requesterManaged'<~String> - # * 'status'<~String> - "available" or "in-use" # * 'macAddress'<~String> - # * 'privateIpAddress'<~String> - IP address of the interface within the subnet # * 'privateDnsName'<~String> - The private DNS name # * 'sourceDestCheck'<~Boolean> - Flag indicating whether traffic to or from the instance is validated # * 'groupSet'<~Hash> - Associated security groups # * 'key'<~String> - ID of associated group # * 'value'<~String> - Name of associated group # * 'attachment'<~Hash>: - Describes the way this nic is attached # * 'attachmentID'<~String> # * 'instanceID'<~String> # * 'instanceOwnerId'<~String> # * 'deviceIndex'<~Integer> # * 'status'<~String> # * 'attachTime'<~String> # * 'deleteOnTermination'<~Boolean> # * 'association'<~Hash>: - Describes an eventual instance association # * 'attachmentID'<~String> - ID of the network interface attachment # * 'instanceID'<~String> - ID of the instance attached to the network interface # * 'publicIp'<~String> - Address of the Elastic IP address bound to the network interface # * 'ipOwnerId'<~String> - ID of the Elastic IP address owner # * 'tagSet'<~Array>: - Tags assigned to the resource. # * 'key'<~String> - Tag's key # * 'value'<~String> - Tag's value # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/2012-03-01/APIReference/index.html?ApiReference-query-DescribeNetworkInterfaces.html] def describe_network_interfaces(filters = {}) params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeNetworkInterfaces', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeNetworkInterfaces.new }.merge!(params)) end end class Mock def describe_network_interfaces(filters = {}) response = Excon::Response.new network_interface_info = self.data[:network_interfaces].values for filter_key, filter_value in filters network_interface_info = network_interface_info.reject{|nic| ![*filter_value].include?(nic[filter_key])} end response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'networkInterfaceSet' => network_interface_info } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_subnets.rb0000644000004100000410000000520612261242551023722 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_subnets' # Describe all or specified subnets # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'subnetSet'<~Array>: # * 'subnetId'<~String> - The Subnet's ID # * 'state'<~String> - The current state of the Subnet. ['pending', 'available'] # * 'vpcId'<~String> - The ID of the VPC the subnet is in # * 'cidrBlock'<~String> - The CIDR block the Subnet covers. # * 'availableIpAddressCount'<~Integer> - The number of unused IP addresses in the subnet (the IP addresses for any # stopped instances are considered unavailable) # * 'availabilityZone'<~String> - The Availability Zone the subnet is in. # * 'tagSet'<~Array>: Tags assigned to the resource. # * 'key'<~String> - Tag's key # * 'value'<~String> - Tag's value # * 'instanceTenancy'<~String> - The allowed tenancy of instances launched into the Subnet. # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/2011-07-15/APIReference/index.html?ApiReference-query-DescribeSubnets.html] def describe_subnets(filters = {}) unless filters.is_a?(Hash) Fog::Logger.warning("describe_subnets with #{filters.class} param is deprecated, use describe_subnets('subnet-id' => []) instead [light_black](#{caller.first})[/]") filters = {'subnet-id' => [*filters]} end params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeSubnets', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeSubnets.new }.merge!(params)) end end class Mock def describe_subnets(filters = {}) subnets = self.data[:subnets] # Transition from pending to available subnets.each do |subnet| case subnet['state'] when 'pending' subnet['state'] = 'available' end end if filters['subnet-id'] subnets = subnets.reject {|subnet| subnet['subnetId'] != filters['subnet-id']} end Excon::Response.new( :status => 200, :body => { 'requestId' => Fog::AWS::Mock.request_id, 'subnetSet' => subnets } ) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_volume.rb0000644000004100000410000001270312261242551023231 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/create_volume' # Create an EBS volume # # ==== Parameters # * availability_zone<~String> - availability zone to create volume in # * size<~Integer> - Size in GiBs for volume. Must be between 1 and 1024. # * options<~Hash> # * 'SnapshotId'<~String> - Optional, snapshot to create volume from # * 'VolumeType'<~String> - Optional, volume type. standard or io1, default is standard. # * 'Iops'<~Integer> - Number of IOPS the volume supports. Required if VolumeType is io1, must be between 1 and 4000. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'availabilityZone'<~String> - Availability zone for volume # * 'createTime'<~Time> - Timestamp for creation # * 'size'<~Integer> - Size in GiBs for volume # * 'snapshotId'<~String> - Snapshot volume was created from, if any # * 'status'<~String> - State of volume # * 'volumeId'<~String> - Reference to volume # * 'volumeType'<~String> - Type of volume # * 'iops'<~Integer> - Number of IOPS the volume supports # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVolume.html] def create_volume(availability_zone, size, options = {}) unless options.is_a?(Hash) Fog::Logger.deprecation("create_volume with a bare snapshot_id is deprecated, use create_volume(availability_zone, size, 'SnapshotId' => snapshot_id) instead [light_black](#{caller.first})[/]") options = { 'SnapshotId' => options } end request({ 'Action' => 'CreateVolume', 'AvailabilityZone' => availability_zone, 'Size' => size, :parser => Fog::Parsers::Compute::AWS::CreateVolume.new }.merge(options)) end end class Mock def create_volume(availability_zone, size, options = {}) unless options.is_a?(Hash) Fog::Logger.deprecation("create_volume with a bare snapshot_id is deprecated, use create_volume(availability_zone, size, 'SnapshotId' => snapshot_id) instead [light_black](#{caller.first})[/]") options = { 'SnapshotId' => options } end response = Excon::Response.new if availability_zone && (size || options['SnapshotId']) snapshot = self.data[:snapshots][options['SnapshotId']] if options['SnapshotId'] && !snapshot raise Fog::Compute::AWS::NotFound.new("The snapshot '#{options['SnapshotId']}' does not exist.") end if snapshot && size && size < snapshot['volumeSize'] raise Fog::Compute::AWS::NotFound.new("The snapshot '#{options['SnapshotId']}' has size #{snapshot['volumeSize']} which is greater than #{size}.") elsif snapshot && !size size = snapshot['volumeSize'] end if options['VolumeType'] == 'io1' iops = options['Iops'] if !iops raise Fog::Compute::AWS::Error.new("InvalidParameterCombination => The parameter iops must be specified for io1 volumes.") end if size < 10 raise Fog::Compute::AWS::Error.new("InvalidParameterValue => Volume of #{size}GiB is too small; minimum is 10GiB.") end if (iops_to_size_ratio = iops.to_f / size.to_f) > 10.0 raise Fog::Compute::AWS::Error.new("InvalidParameterValue => Iops to volume size ratio of #{"%.1f" % iops_to_size_ratio} is too high; maximum is 10.0") end if iops < 100 raise Fog::Compute::AWS::Error.new("VolumeIOPSLimit => Volume iops of #{iops} is too low; minimum is 100.") end if iops > 4000 raise Fog::Compute::AWS::Error.new("VolumeIOPSLimit => Volume iops of #{iops} is too high; maximum is 4000.") end end response.status = 200 volume_id = Fog::AWS::Mock.volume_id data = { 'availabilityZone' => availability_zone, 'attachmentSet' => [], 'createTime' => Time.now, 'iops' => options['Iops'], 'size' => size, 'snapshotId' => options['SnapshotId'], 'status' => 'creating', 'volumeId' => volume_id, 'volumeType' => options['VolumeType'] || 'standard' } self.data[:volumes][volume_id] = data response.body = { 'requestId' => Fog::AWS::Mock.request_id }.merge!(data.reject {|key,value| !['availabilityZone','createTime','size','snapshotId','status','volumeId','volumeType'].include?(key) }) else response.status = 400 response.body = { 'Code' => 'MissingParameter' } unless availability_zone response.body['Message'] = 'The request must contain the parameter availability_zone' else response.body['Message'] = 'The request must contain the parameter size' end end response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/associate_dhcp_options.rb0000644000004100000410000000345012261242551025122 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # # # ==== Parameters # * dhcp_options_id<~String> - The ID of the DHCP options you want to associate with the VPC, or "default" if you want the VPC # to use no DHCP options. # * vpc_id<~String> - The ID of the VPC # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - Returns true if the request succeeds. # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AssociateDhcpOptions.html] def associate_dhcp_options(dhcp_options_id, vpc_id) request( 'Action' => 'AssociateDhcpOptions', 'DhcpOptionsId' => dhcp_options_id, 'VpcId' => vpc_id, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def associate_dhcp_options(dhcp_options_id, vpc_id) response = Excon::Response.new if dhcp_options_id && vpc_id response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else if !dhcp_options_id message << 'The request must contain the parameter dhcp_options_id' elsif !vpc_id message << 'The request must contain the parameter vpc_id' end raise Fog::Compute::AWS::Error.new(message) end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_spot_datafeed_subscription.rb0000644000004100000410000000233412261242551027644 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/spot_datafeed_subscription' # Describe spot datafeed subscription # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'spotDatafeedSubscription'<~Hash>: # * 'bucket'<~String> - S3 bucket where data is stored # * 'fault'<~Hash>: # * 'code'<~String> - fault code # * 'reason'<~String> - fault reason # * 'ownerId'<~String> - AWS id of account owner # * 'prefix'<~String> - prefix for datafeed items # * 'state'<~String> - state of datafeed subscription # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotDatafeedSubscription.html] def describe_spot_datafeed_subscription request({ 'Action' => 'DescribeSpotDatafeedSubscription', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::SpotDatafeedSubscription.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_internet_gateways.rb0000644000004100000410000000450412261242551025773 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_internet_gateways' # Describe all or specified internet_gateways # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'InternetGatewaySet'<~Array>: # * 'internetGatewayId'<~String> - The ID of the Internet gateway. # * 'attachmentSet'<~Array>: - A list of VPCs attached to the Internet gateway # * 'vpcId'<~String> - The ID of the VPC the Internet gateway is attached to # * 'state'<~String> - The current state of the attachment # * 'tagSet'<~Array>: Tags assigned to the resource. # * 'key'<~String> - Tag's key # * 'value'<~String> - Tag's value # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-InternetGatewayType.html] def describe_internet_gateways(filters = {}) unless filters.is_a?(Hash) Fog::Logger.warning("describe_internet_gateways with #{filters.class} param is deprecated, use internet_gateways('internet-gateway-id' => []) instead [light_black](#{caller.first})[/]") filters = {'internet-gateway-id' => [*filters]} end params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeInternetGateways', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeInternetGateways.new }.merge!(params)) end end class Mock def describe_internet_gateways(filters = {}) internet_gateways = self.data[:internet_gateways].values if filters['internet-gateway-id'] internet_gateways = internet_gateways.reject {|internet_gateway| internet_gateway['internetGatewayId'] != filters['internet-gateway-id']} end Excon::Response.new( :status => 200, :body => { 'requestId' => Fog::AWS::Mock.request_id, 'internetGatewaySet' => internet_gateways } ) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/delete_volume.rb0000644000004100000410000000324712261242551023233 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Delete an EBS volume # # ==== Parameters # * volume_id<~String> - Id of volume to delete. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteVolume.html] def delete_volume(volume_id) request( 'Action' => 'DeleteVolume', 'VolumeId' => volume_id, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def delete_volume(volume_id) response = Excon::Response.new if volume = self.data[:volumes][volume_id] if volume["attachmentSet"].any? attach = volume["attachmentSet"].first raise Fog::Compute::AWS::Error.new("Client.VolumeInUse => Volume #{volume_id} is currently attached to #{attach["instanceId"]}") end self.data[:deleted_at][volume_id] = Time.now volume['status'] = 'deleting' response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else raise Fog::Compute::AWS::NotFound.new("The volume '#{volume_id}' does not exist.") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_availability_zones.rb0000644000004100000410000001214312261242551026125 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_availability_zones' # Describe all or specified availability zones # # ==== Params # * filters<~Hash> - List of filters to limit results with # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'availabilityZoneInfo'<~Array>: # * 'regionName'<~String> - Name of region # * 'zoneName'<~String> - Name of zone # * 'zoneState'<~String> - State of zone # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeAvailabilityZones.html] def describe_availability_zones(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_availability_zones with #{filters.class} param is deprecated, use describe_availability_zones('zone-name' => []) instead [light_black](#{caller.first})[/]") filters = {'public-ip' => [*filters]} end params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeAvailabilityZones', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeAvailabilityZones.new }.merge!(params)) end end class Mock def describe_availability_zones(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_availability_zones with #{filters.class} param is deprecated, use describe_availability_zones('zone-name' => []) instead [light_black](#{caller.first})[/]") filters = {'public-ip' => [*filters]} end response = Excon::Response.new all_zones = [ {"messageSet" => [], "regionName" => "us-east-1", "zoneName" => "us-east-1a", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "us-east-1", "zoneName" => "us-east-1b", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "us-east-1", "zoneName" => "us-east-1c", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "us-east-1", "zoneName" => "us-east-1d", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "us-east-1", "zoneName" => "us-east-1e", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "us-west-1", "zoneName" => "us-west-1a", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "us-west-1", "zoneName" => "us-west-1b", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "us-west-1", "zoneName" => "us-west-1c", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "us-west-2", "zoneName" => "us-west-2a", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "us-west-2", "zoneName" => "us-west-2b", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "sa-east-1", "zoneName" => "sa-east-1a", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "sa-east-1", "zoneName" => "sa-east-1b", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "eu-west-1", "zoneName" => "eu-west-1a", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "eu-west-1", "zoneName" => "eu-west-1b", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "eu-west-1", "zoneName" => "eu-west-1c", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "ap-northeast-1", "zoneName" => "ap-northeast-1a", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "ap-northeast-1", "zoneName" => "ap-northeast-1b", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "ap-southeast-1", "zoneName" => "ap-southeast-1a", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "ap-southeast-1", "zoneName" => "ap-southeast-1b", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "ap-southeast-2", "zoneName" => "ap-southeast-2a", "zoneState" => "available"}, {"messageSet" => [], "regionName" => "ap-southeast-2", "zoneName" => "ap-southeast-2b", "zoneState" => "available"}, ] availability_zone_info = all_zones.select { |zoneinfo| zoneinfo["regionName"] == @region } aliases = {'region-name' => 'regionName', 'zone-name' => 'zoneName', 'state' => 'zoneState'} for filter_key, filter_value in filters aliased_key = aliases[filter_key] availability_zone_info = availability_zone_info.reject{|availability_zone| ![*filter_value].include?(availability_zone[aliased_key])} end response.status = 200 response.body = { 'availabilityZoneInfo' => availability_zone_info, 'requestId' => Fog::AWS::Mock.request_id } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/delete_dhcp_options.rb0000644000004100000410000000350012261242551024405 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' #Deletes a set of DHCP options that you specify. Amazon VPC returns an error if the set of options you specify is currently #associated with a VPC. You can disassociate the set of options by associating either a new set of options or the default #options with the VPC. # # ==== Parameters # * dhcp_options_id<~String> - The ID of the DHCP options set you want to delete. # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - Returns true if the request succeeds. # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteDhcpOptions.html] def delete_dhcp_options(dhcp_options_id) request( 'Action' => 'DeleteDhcpOptions', 'DhcpOptionsId' => dhcp_options_id, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def delete_dhcp_options(dhcp_options_id) Excon::Response.new.tap do |response| if dhcp_options_id response.status = 200 self.data[:dhcp_options].reject! { |v| v['dhcpOptionsId'] == dhcp_options_id } response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } else message = 'MissingParameter => ' message << 'The request must contain the parameter dhcp_options_id' raise Fog::Compute::AWS::Error.new(message) end end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/disassociate_address.rb0000644000004100000410000000365412261242551024564 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Disassociate an elastic IP address from its instance (if any) # # ==== Parameters # * public_ip<~String> - Public ip to assign to instance # * association_id<~String> - Id associating eip to an network interface # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DisassociateAddress.html] def disassociate_address(public_ip=nil, association_id=nil) request( 'Action' => 'DisassociateAddress', 'PublicIp' => public_ip, 'AssociationId' => association_id, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def disassociate_address(public_ip) response = Excon::Response.new response.status = 200 if address = self.data[:addresses][public_ip] instance_id = address['instanceId'] instance = self.data[:instances][instance_id] instance['ipAddress'] = instance['originalIpAddress'] instance['dnsName'] = Fog::AWS::Mock.dns_name_for(instance['ipAddress']) address['instanceId'] = nil response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else raise Fog::Compute::AWS::Error.new("AuthFailure => The address '#{public_ip}' does not belong to you.") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_snapshot.rb0000644000004100000410000000446012261242551023562 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/create_snapshot' # Create a snapshot of an EBS volume and store it in S3 # # ==== Parameters # * volume_id<~String> - Id of EBS volume to snapshot # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'progress'<~String> - The percentage progress of the snapshot # * 'requestId'<~String> - id of request # * 'snapshotId'<~String> - id of snapshot # * 'startTime'<~Time> - timestamp when snapshot was initiated # * 'status'<~String> - state of snapshot # * 'volumeId'<~String> - id of volume snapshot targets # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSnapshot.html] def create_snapshot(volume_id, description = nil) request( 'Action' => 'CreateSnapshot', 'Description' => description, 'VolumeId' => volume_id, :parser => Fog::Parsers::Compute::AWS::CreateSnapshot.new ) end end class Mock # # Usage # # AWS[:compute].create_snapshot("vol-f7c23423", "latest snapshot") # def create_snapshot(volume_id, description = nil) response = Excon::Response.new if volume = self.data[:volumes][volume_id] response.status = 200 snapshot_id = Fog::AWS::Mock.snapshot_id data = { 'description' => description, 'ownerId' => self.data[:owner_id], 'progress' => nil, 'snapshotId' => snapshot_id, 'startTime' => Time.now, 'status' => 'pending', 'volumeId' => volume_id, 'volumeSize' => volume['size'] } self.data[:snapshots][snapshot_id] = data response.body = { 'requestId' => Fog::AWS::Mock.request_id }.merge!(data) else response.status = 400 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_images.rb0000644000004100000410000001242612261242551023506 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_images' # Describe all or specified images. # # ==== Params # * filters<~Hash> - List of filters to limit results with # * filters and/or the following # * 'ExecutableBy'<~String> - Only return images that the executable_by # user has explicit permission to launch # * 'ImageId'<~Array> - Ids of images to describe # * 'Owner'<~String> - Only return images belonging to owner. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'imagesSet'<~Array>: # * 'architecture'<~String> - Architecture of the image # * 'blockDeviceMapping'<~Array> - An array of mapped block devices # * 'description'<~String> - Description of image # * 'imageId'<~String> - Id of the image # * 'imageLocation'<~String> - Location of the image # * 'imageOwnerAlias'<~String> - Alias of the owner of the image # * 'imageOwnerId'<~String> - Id of the owner of the image # * 'imageState'<~String> - State of the image # * 'imageType'<~String> - Type of the image # * 'isPublic'<~Boolean> - Whether or not the image is public # * 'kernelId'<~String> - Kernel id associated with image, if any # * 'platform'<~String> - Operating platform of the image # * 'productCodes'<~Array> - Product codes for the image # * 'ramdiskId'<~String> - Ramdisk id associated with image, if any # * 'rootDeviceName'<~String> - Root device name, e.g. /dev/sda1 # * 'rootDeviceType'<~String> - Root device type, ebs or instance-store # * 'virtualizationType'<~String> - Type of virtualization # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImages.html] def describe_images(filters = {}) options = {} for key in ['ExecutableBy', 'ImageId', 'Owner'] if filters.is_a?(Hash) && filters.key?(key) options.merge!(Fog::AWS.indexed_request_param(key, filters.delete(key))) end end params = Fog::AWS.indexed_filters(filters).merge!(options) request({ 'Action' => 'DescribeImages', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeImages.new }.merge!(params)) end end class Mock def describe_images(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_images with #{filters.class} param is deprecated, use describe_images('image-id' => []) instead [light_black](#{caller.first})[/]") filters = {'image-id' => [*filters]} end if filters.keys.any? {|key| key =~ /^block-device/} Fog::Logger.warning("describe_images block-device-mapping filters are not yet mocked [light_black](#{caller.first})[/]") Fog::Mock.not_implemented end if owner = filters.delete('Owner') if owner == 'self' filters['owner-id'] = self.data[:owner_id] else filters['owner-alias'] = owner end end response = Excon::Response.new aliases = { 'architecture' => 'architecture', 'description' => 'description', 'hypervisor' => 'hypervisor', 'image-id' => 'imageId', 'image-type' => 'imageType', 'is-public' => 'isPublic', 'kernel-id' => 'kernelId', 'manifest-location' => 'manifestLocation', 'name' => 'name', 'owner-alias' => 'imageOwnerAlias', 'owner-id' => 'imageOwnerId', 'ramdisk-id' => 'ramdiskId', 'root-device-name' => 'rootDeviceName', 'root-device-type' => 'rootDeviceType', 'state' => 'imageState', 'virtualization-type' => 'virtualizationType' } image_set = visible_images.values image_set = apply_tag_filters(image_set, filters, 'imageId') for filter_key, filter_value in filters aliased_key = aliases[filter_key] image_set = image_set.reject{|image| ![*filter_value].include?(image[aliased_key])} end image_set = image_set.map do |image| case image['imageState'] when 'pending' if Time.now - image['registered'] >= Fog::Mock.delay image['imageState'] = 'available' end end image.reject { |key, value| ['registered'].include?(key) }.merge('tagSet' => self.data[:tag_sets][image['imageId']]) end response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'imagesSet' => image_set } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/delete_snapshot.rb0000644000004100000410000000261212261242551023556 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Delete a snapshot of an EBS volume that you own # # ==== Parameters # * snapshot_id<~String> - ID of snapshot to delete # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteSnapshot.html] def delete_snapshot(snapshot_id) request( 'Action' => 'DeleteSnapshot', 'SnapshotId' => snapshot_id, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def delete_snapshot(snapshot_id) response = Excon::Response.new if snapshot = self.data[:snapshots].delete(snapshot_id) response.status = true response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else raise Fog::Compute::AWS::NotFound.new("The snapshot '#{snapshot_id}' does not exist.") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/delete_tags.rb0000644000004100000410000000536412261242551022664 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Remove tags from resources # # ==== Parameters # * resources<~String> - One or more resources to remove tags from # * tags<~String> - hash of key value tag pairs to remove # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteTags.html] def delete_tags(resources, tags) resources = [*resources] params = {} params.merge!(Fog::AWS.indexed_param('ResourceId', resources)) # can not rely on indexed_param because nil values should be omitted tags.keys.each_with_index do |key, index| index += 1 # should start at 1 instead of 0 params.merge!("Tag.#{index}.Key" => key) unless tags[key].nil? params.merge!("Tag.#{index}.Value" => tags[key]) end end request({ 'Action' => 'DeleteTags', :parser => Fog::Parsers::Compute::AWS::Basic.new }.merge!(params)) end end class Mock def delete_tags(resources, tags) tagged = Array(resources).map do |resource_id| type = case resource_id when /^ami\-[a-z0-9]{8}$/i 'image' when /^i\-[a-z0-9]{8}$/i 'instance' when /^snap\-[a-z0-9]{8}$/i 'snapshot' when /^vol\-[a-z0-9]{8}$/i 'volume' end if type && ((type == 'image' && visible_images[resource_id]) || self.data[:"#{type}s"][resource_id]) { 'resourceId' => resource_id, 'resourceType' => type } else raise(Fog::Service::NotFound.new("The #{type} ID '#{resource_id}' does not exist")) end end tags.each do |key, value| self.data[:tags][key][value] = self.data[:tags][key][value] - tagged end tagged.each do |resource| tags.each do |key, value| tagset = self.data[:tag_sets][resource['resourceId']] tagset.delete(key) if tagset.has_key?(key) && (value.nil? || tagset[key] == value) end end response = Excon::Response.new response.status = true response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_route_table.rb0000755000004100000410000000466112261242551024236 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/create_route_table' # Creates a route table for the specified VPC. # # ==== Parameters # * VpcId<~String> - The ID of the VPC. # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of the request # * 'routeTable'<~Array> - Information about the newly created route table # * 'routeTableId'<~String> # * 'vpcId'<~String> # * 'routeSet'<~Array> # * 'item'<~Array> # * 'destinationCidrBlock'<~String> - The CIDR address block used for the destination match. # * 'gatewayId'<~String> - The ID of an Internet gateway attached to your VPC. # * 'state'<~String> - The state of the route. ['blackhole', 'available'] # # {Amazon API Reference}[http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateRouteTable.html] def create_route_table(vpc_id) request({ 'Action' => 'CreateRouteTable', 'VpcId' => vpc_id, :parser => Fog::Parsers::Compute::AWS::CreateRouteTable.new }) end end class Mock def create_route_table(vpc_id) response = Excon::Response.new vpc = self.data[:vpcs].find { |vpc| vpc["vpcId"].eql? vpc_id } unless vpc.nil? response.status = 200 route_table = { 'routeTableId' => "rtb-#{Fog::Mock.random_hex(8)}", 'vpcId' => vpc["vpcId"], 'routeSet' => [{ "destinationCidrBlock" => vpc["cidrBlock"], "gatewayId" => "local", "instanceId"=>nil, "instanceOwnerId"=>nil, "networkInterfaceId"=>nil, "state" => "pending", "origin" => "CreateRouteTable" }], 'associationSet' => [], 'tagSet' => {} } self.data[:route_tables].push(route_table) response.body = { 'requestId'=> Fog::AWS::Mock.request_id, 'routeTable' => [route_table] } response else raise Fog::Compute::AWS::NotFound.new("The vpc ID '#{vpc_id}' does not exist") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/monitor_instances.rb0000644000004100000410000000366712261242551024146 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/monitor_unmonitor_instances' # Monitor specified instance # http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-MonitorInstances.html # # ==== Parameters # * instance_ids<~Array> - Arrays of instances Ids to monitor # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'instancesSet': http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-MonitorInstancesResponseSetItemType.html # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-MonitorInstances.html] def monitor_instances(instance_ids) params = Fog::AWS.indexed_param('InstanceId', instance_ids) request({ 'Action' => 'MonitorInstances', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::MonitorUnmonitorInstances.new }.merge!(params)) end end class Mock def monitor_instances(instance_ids) response = Excon::Response.new response.status = 200 [*instance_ids].each do |instance_id| if instance = self.data[:instances][instance_id] instance['monitoring']['state'] = 'enabled' else raise Fog::Compute::AWS::NotFound.new("The instance ID '#{instance_ids}' does not exist") end end instances_set = [*instance_ids].inject([]) { |memo, id| memo << {'instanceId' => id, 'monitoring' => 'enabled'} } response.body = {'requestId' => 'some_request_id', 'instancesSet' => instances_set} response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_account_attributes.rb0000644000004100000410000000302612261242551026137 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_account_attributes' # Describe account attributes # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> = Id of request # * 'accountAttributeSet'<~Array>: # * 'attributeName'<~String> - supported-platforms # * 'attributeValueSet'<~Array>: # * 'attributeValue'<~String> - Value of attribute # # {Amazon API Reference}[http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeAccountAttributes.html] def describe_account_attributes(filters = {}) params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeAccountAttributes', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeAccountAttributes.new }.merge!(params)) end end class Mock def describe_account_attributes(filters = {}) account_attributes = self.data[:account_attributes] Excon::Response.new( :status => 200, :body => { 'requestId' => Fog::AWS::Mock.request_id, 'accountAttributeSet' => account_attributes } ) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/delete_route_table.rb0000755000004100000410000000350212261242551024226 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Deletes the specified route table. # # ==== Parameters # * RouteTableId<~String> - The ID of the route table. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - The ID of request. # * 'return'<~Boolean> - Returns true if the request succeeds. Otherwise, returns an error. # # {Amazon API Reference}[http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteRouteTable.html] def delete_route_table(route_table_id) request( 'Action' => 'DeleteRouteTable', 'RouteTableId' => route_table_id, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def delete_route_table(route_table_id) route_table = self.data[:route_tables].find { |routetable| routetable["routeTableId"].eql? route_table_id } if !route_table.nil? && route_table['associationSet'].empty? self.data[:route_tables].delete(route_table) response = Excon::Response.new response.status = 200 response.body = { 'requestId'=> Fog::AWS::Mock.request_id, 'return' => true } response elsif route_table.nil? raise Fog::Compute::AWS::NotFound.new("The routeTable ID '#{route_table_id}' does not exist") elsif !route_table['associationSet'].empty? raise Fog::Compute::AWS::Error, "DependencyViolation => The routeTable '#{route_table_id}' has dependencies and cannot be deleted." end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/start_instances.rb0000644000004100000410000000411512261242551023601 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/start_stop_instances' # Start specified instance # # ==== Parameters # * instance_id<~Array> - Id of instance to start # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * TODO: fill in the blanks # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-StartInstances.html] def start_instances(instance_id) params = Fog::AWS.indexed_param('InstanceId', instance_id) request({ 'Action' => 'StartInstances', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::StartStopInstances.new }.merge!(params)) end end class Mock def start_instances(instance_id) instance_ids = Array(instance_id) instance_set = self.data[:instances].values instance_set = apply_tag_filters(instance_set, {'instance_id' => instance_ids}, 'instanceId') instance_set = instance_set.find_all {|x| instance_ids.include?(x["instanceId"]) } if instance_set.empty? raise Fog::Compute::AWS::NotFound.new("The instance ID '#{instance_ids.first}' does not exist") else response = Excon::Response.new response.status = 200 response.body = { 'instancesSet' => instance_set.inject([]) do |ia, instance| ia << {'currentState' => { 'code' => 0, 'name' => 'pending' }, 'previousState' => instance['instanceState'], 'instanceId' => instance['instanceId'] } instance['instanceState'] = {'code'=>0, 'name'=>'pending'} ia end } response end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/assign_private_ip_addresses.rb0000644000004100000410000000457012261242551026145 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/assign_private_ip_addresses' # Assigns one or more secondary private IP addresses to the specified network interface. # # ==== Parameters # * NetworkInterfaceId<~String> - The ID of the network interface # * PrivateIpAddresses<~Array> - One or more IP addresses to be assigned as a secondary private IP address (conditional) # * SecondaryPrivateIpAddressCount<~String> - The number of secondary IP addresses to assign (conditional) # * AllowReassignment<~Boolean> - Whether to reassign an IP address # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - The ID of the request. # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AssignPrivateIpAddresses.html] def assign_private_ip_addresses(network_interface_id, options={}) if options['PrivateIpAddresses'] && options['SecondaryPrivateIpAddressCount'] raise Fog::Compute::AWS::Error.new("You may specify secondaryPrivateIpAddressCount or specific secondary private IP addresses, but not both.") end if private_ip_addresses = options.delete('PrivateIpAddresses') options.merge!(Fog::AWS.indexed_param('PrivateIpAddress.%d', [*private_ip_addresses])) end request({ 'Action' => 'AssignPrivateIpAddresses', 'NetworkInterfaceId' => network_interface_id, :parser => Fog::Parsers::Compute::AWS::AssignPrivateIpAddresses.new }.merge(options)) end end class Mock def assign_private_ip_addresses(network_interface_id, options={}) if options['PrivateIpAddresses'] && options['SecondaryPrivateIpAddressCount'] raise Fog::Compute::AWS::Error.new("You may specify secondaryPrivateIpAddressCount or specific secondary private IP addresses, but not both.") end response = Excon::Response.new response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/modify_vpc_attribute.rb0000644000004100000410000000464312261242551024625 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Modifies the specified attribute of the specified VPC. # # ==== Parameters # * vpc_id<~String> - The ID of the VPC. # * options<~Hash>: # * enableDnsSupport<~Boolean> - Indicates whether DNS resolution is supported for the VPC. If this attribute is true, the Amazon DNS # server resolves DNS hostnames for your instances to their corresponding IP addresses; otherwise, it does not. # * enableDnsHostnames<~Boolean> - Indicates whether the instances launched in the VPC get DNS hostnames. If this attribute is true, # instances in the VPC get DNS hostnames; otherwise, they do not. You can only set enableDnsHostnames to true if you also set the # EnableDnsSupport attribute to true. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyVpcAttribute.html] def modify_vpc_attribute(vpc_id, options = {}) request({ 'Action' => 'ModifyVpcAttribute', 'VpcId' => vpc_id, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new }.merge!(options)) end end class Mock def modify_vpc_attribute(vpc_id, options = {}) response = Excon::Response.new if options.size == 0 raise Fog::Compute::AWS::Error.new("InvalidParameterCombination => No attributes specified.") elsif options.size > 1 raise Fog::Compute::AWS::Error.new("InvalidParameterCombination => InvalidParameterCombination => Fields for multiple attribute types specified: #{options.keys.join(', ')}") elsif self.data[:vpcs].select{|x| x['vpcId'] == vpc_id}.size response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else raise Fog::Compute::AWS::NotFound.new("The vpc '#{vpc_id}' does not exist.") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/modify_volume_attribute.rb0000644000004100000410000000321012261242551025331 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Modifies a volume attribute. # # ==== Parameters # * volume_id<~String> - The ID of the volume. # * auto_enable_io_value<~Boolean> - This attribute exists to auto-enable the I/O operations to the volume. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyVolumeAttribute.html] def modify_volume_attribute(volume_id=nil, auto_enable_io_value=false) request( 'Action' => 'ModifyVolumeAttribute', 'VolumeId' => volume_id, 'AutoEnableIO.Value' => auto_enable_io_value, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def modify_volume_attribute(volume_id=nil, auto_enable_io_value=false) response = Excon::Response.new if volume = self.data[:volumes][volume_id] response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else raise Fog::Compute::AWS::NotFound.new("The volume '#{volume_id}' does not exist.") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_network_interface_attribute.rb0000644000004100000410000000574312261242551030041 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_network_interface_attribute' # Describes a network interface attribute value # # ==== Parameters # * network_interface_id<~String> - The ID of the network interface you want to describe an attribute of # * attribute<~String> - The attribute to describe, must be one of 'description', 'groupSet', 'sourceDestCheck' or 'attachment' # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'networkInterfaceId'<~String> - The ID of the network interface # * 'description'<~String> - The description (if requested) # * 'groupSet'<~Hash> - Associated security groups (if requested) # * 'key'<~String> - ID of associated group # * 'value'<~String> - Name of associated group # * 'sourceDestCheck'<~Boolean> - Flag indicating whether traffic to or from the instance is validated (if requested) # * 'attachment'<~Hash>: - Describes the way this nic is attached (if requested) # * 'attachmentID'<~String> # * 'instanceID'<~String> # * 'instanceOwnerId'<~String> # * 'deviceIndex'<~Integer> # * 'status'<~String> # * 'attachTime'<~String> # * 'deleteOnTermination<~Boolean> # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/2012-03-01/APIReference/ApiReference-query-DescribeNetworkInterfaceAttribute.html] def describe_network_interface_attribute(network_interface_id, attribute) request( 'Action' => 'DescribeNetworkInterfaceAttribute', 'NetworkInterfaceId' => network_interface_id, 'Attribute' => attribute, :parser => Fog::Parsers::Compute::AWS::DescribeNetworkInterfaceAttribute.new ) end end class Mock def describe_network_interface_attribute(network_interface_id, attribute) response = Excon::Response.new if self.data[:network_interfaces][network_interface_id] response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'networkInterfaceId' => network_interface_id } case attribute when 'description', 'groupSet', 'sourceDestCheck', 'attachment' response.body[attribute] = self.data[:network_interfaces][network_interface_id][attribute] else raise Fog::Compute::AWS::Error.new("Illegal attribute '#{attribute}' specified") end response else raise Fog::Compute::AWS::NotFound.new("The network interface '#{network_interface_id}' does not exist") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/run_instances.rb0000644000004100000410000002516512261242551023260 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/run_instances' # Launch specified instances # # ==== Parameters # * image_id<~String> - Id of machine image to load on instances # * min_count<~Integer> - Minimum number of instances to launch. If this # exceeds the count of available instances, no instances will be # launched. Must be between 1 and maximum allowed for your account # (by default the maximum for an account is 20) # * max_count<~Integer> - Maximum number of instances to launch. If this # exceeds the number of available instances, the largest possible # number of instances above min_count will be launched instead. Must # be between 1 and maximum allowed for you account # (by default the maximum for an account is 20) # * options<~Hash>: # * 'Placement.AvailabilityZone'<~String> - Placement constraint for instances # * 'Placement.GroupName'<~String> - Name of existing placement group to launch instance into # * 'Placement.Tenancy'<~String> - Tenancy option in ['dedicated', 'default'], defaults to 'default' # * 'BlockDeviceMapping'<~Array>: array of hashes # * 'DeviceName'<~String> - where the volume will be exposed to instance # * 'VirtualName'<~String> - volume virtual device name # * 'Ebs.SnapshotId'<~String> - id of snapshot to boot volume from # * 'Ebs.VolumeSize'<~String> - size of volume in GiBs required unless snapshot is specified # * 'Ebs.DeleteOnTermination'<~String> - specifies whether or not to delete the volume on instance termination # * 'Ebs.VolumeType'<~String> - Type of EBS volue. Valid options in ['standard', 'io1'] default is 'standard'. # * 'Ebs.Iops'<~String> - The number of I/O operations per second (IOPS) that the volume supports. Required when VolumeType is 'io1' # * 'ClientToken'<~String> - unique case-sensitive token for ensuring idempotency # * 'DisableApiTermination'<~Boolean> - specifies whether or not to allow termination of the instance from the api # * 'SecurityGroup'<~Array> or <~String> - Name of security group(s) for instances (not supported for VPC) # * 'SecurityGroupId'<~Array> or <~String> - id's of security group(s) for instances, use this or SecurityGroup # * 'InstanceInitiatedShutdownBehaviour'<~String> - specifies whether volumes are stopped or terminated when instance is shutdown, in [stop, terminate] # * 'InstanceType'<~String> - Type of instance to boot. Valid options # in ['t1.micro', 'm1.small', 'm1.large', 'm1.xlarge', 'c1.medium', 'c1.xlarge', 'm2.xlarge', m2.2xlarge', 'm2.4xlarge', 'cc1.4xlarge', 'cc2.8xlarge', 'cg1.4xlarge'] # default is 'm1.small' # * 'KernelId'<~String> - Id of kernel with which to launch # * 'KeyName'<~String> - Name of a keypair to add to booting instances # * 'Monitoring.Enabled'<~Boolean> - Enables monitoring, defaults to # disabled # * 'PrivateIpAddress<~String> - VPC option to specify ip address within subnet # * 'RamdiskId'<~String> - Id of ramdisk with which to launch # * 'SubnetId'<~String> - VPC option to specify subnet to launch instance into # * 'UserData'<~String> - Additional data to provide to booting instances # * 'EbsOptimized'<~Boolean> - Whether the instance is optimized for EBS I/O # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'groupSet'<~Array>: groups the instances are members in # * 'groupName'<~String> - Name of group # * 'instancesSet'<~Array>: returned instances # * instance<~Hash>: # * 'amiLaunchIndex'<~Integer> - reference to instance in launch group # * 'architecture'<~String> - architecture of image in [i386, x86_64] # * 'blockDeviceMapping'<~Array> # * 'attachTime'<~Time> - time of volume attachment # * 'deleteOnTermination'<~Boolean> - whether or not to delete volume on termination # * 'deviceName'<~String> - specifies how volume is exposed to instance # * 'status'<~String> - status of attached volume # * 'volumeId'<~String> - Id of attached volume # * 'dnsName'<~String> - public dns name, blank until instance is running # * 'imageId'<~String> - image id of ami used to launch instance # * 'instanceId'<~String> - id of the instance # * 'instanceState'<~Hash>: # * 'code'<~Integer> - current status code # * 'name'<~String> - current status name # * 'instanceType'<~String> - type of instance # * 'ipAddress'<~String> - public ip address assigned to instance # * 'kernelId'<~String> - Id of kernel used to launch instance # * 'keyName'<~String> - name of key used launch instances or blank # * 'launchTime'<~Time> - time instance was launched # * 'monitoring'<~Hash>: # * 'state'<~Boolean - state of monitoring # * 'placement'<~Hash>: # * 'availabilityZone'<~String> - Availability zone of the instance # * 'privateDnsName'<~String> - private dns name, blank until instance is running # * 'privateIpAddress'<~String> - private ip address assigned to instance # * 'productCodes'<~Array> - Product codes for the instance # * 'ramdiskId'<~String> - Id of ramdisk used to launch instance # * 'reason'<~String> - reason for most recent state transition, or blank # * 'rootDeviceName'<~String> - specifies how the root device is exposed to the instance # * 'rootDeviceType'<~String> - root device type used by AMI in [ebs, instance-store] # * 'ebsOptimized'<~Boolean> - Whether the instance is optimized for EBS I/O # * 'ownerId'<~String> - Id of owner # * 'requestId'<~String> - Id of request # * 'reservationId'<~String> - Id of reservation # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RunInstances.html] def run_instances(image_id, min_count, max_count, options = {}) if block_device_mapping = options.delete('BlockDeviceMapping') block_device_mapping.each_with_index do |mapping, index| for key, value in mapping options.merge!({ format("BlockDeviceMapping.%d.#{key}", index) => value }) end end end if security_groups = options.delete('SecurityGroup') options.merge!(Fog::AWS.indexed_param('SecurityGroup', [*security_groups])) end if security_group_ids = options.delete('SecurityGroupId') options.merge!(Fog::AWS.indexed_param('SecurityGroupId', [*security_group_ids])) end if options['UserData'] options['UserData'] = Base64.encode64(options['UserData']) end idempotent = !(options['ClientToken'].nil? || options['ClientToken'].empty?) request({ 'Action' => 'RunInstances', 'ImageId' => image_id, 'MinCount' => min_count, 'MaxCount' => max_count, :idempotent => idempotent, :parser => Fog::Parsers::Compute::AWS::RunInstances.new }.merge!(options)) end end class Mock def run_instances(image_id, min_count, max_count, options = {}) response = Excon::Response.new response.status = 200 group_set = [ (options['SecurityGroup'] || 'default') ].flatten instances_set = [] reservation_id = Fog::AWS::Mock.reservation_id if options['KeyName'] && describe_key_pairs('key-name' => options['KeyName']).body['keySet'].empty? raise Fog::Compute::AWS::NotFound.new("The key pair '#{options['KeyName']}' does not exist") end min_count.times do |i| instance_id = Fog::AWS::Mock.instance_id instance = { 'amiLaunchIndex' => i, 'associatePublicIP' => options['associatePublicIP'] || false, 'architecture' => 'i386', 'blockDeviceMapping' => [], 'clientToken' => options['clientToken'], 'dnsName' => nil, 'ebsOptimized' => options['EbsOptimized'] || false, 'hypervisor' => 'xen', 'imageId' => image_id, 'instanceId' => instance_id, 'instanceState' => { 'code' => 0, 'name' => 'pending' }, 'instanceType' => options['InstanceType'] || 'm1.small', 'kernelId' => options['KernelId'] || Fog::AWS::Mock.kernel_id, 'keyName' => options['KeyName'], 'launchTime' => Time.now, 'monitoring' => { 'state' => options['Monitoring.Enabled'] || false }, 'placement' => { 'availabilityZone' => options['Placement.AvailabilityZone'] || Fog::AWS::Mock.availability_zone(@region), 'groupName' => nil, 'tenancy' => options['Placement.Tenancy'] || 'default' }, 'privateDnsName' => nil, 'productCodes' => [], 'reason' => nil, 'rootDeviceType' => 'instance-store', 'virtualizationType' => 'paravirtual' } instances_set << instance self.data[:instances][instance_id] = instance.merge({ 'groupIds' => [], 'groupSet' => group_set, 'iamInstanceProfile' => {}, 'networkInterfaces' => [], 'ownerId' => self.data[:owner_id], 'privateIpAddress' => nil, 'reservationId' => reservation_id, 'stateReason' => {} }) end response.body = { 'groupSet' => group_set, 'instancesSet' => instances_set, 'ownerId' => self.data[:owner_id], 'requestId' => Fog::AWS::Mock.request_id, 'reservationId' => reservation_id } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/delete_subnet.rb0000644000004100000410000000314712261242551023223 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Deletes a subnet from a VPC. You must terminate all running instances in the subnet before deleting it, otherwise Amazon # VPC returns an error # # ==== Parameters # * subnet_id<~String> - The ID of the Subnet you want to delete. # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - Returns true if the request succeeds. # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/2011-07-15/APIReference/ApiReference-query-DeleteSubnet.html] def delete_subnet(subnet_id) request( 'Action' => 'DeleteSubnet', 'SubnetId' => subnet_id, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def delete_subnet(subnet_id) Excon::Response.new.tap do |response| if subnet_id self.data[:subnets].reject! { |v| v['subnetId'] == subnet_id } response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } else message = 'MissingParameter => ' message << 'The request must contain the parameter subnet_id' raise Fog::Compute::AWS::Error.new(message) end end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_placement_group.rb0000644000004100000410000000200112261242551025074 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Create a new placement group # # ==== Parameters # * group_name<~String> - Name of the placement group. # * strategy<~String> - Placement group strategy. Valid options in ['cluster'] # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreatePlacementGroup.html] def create_placement_group(name, strategy) request( 'Action' => 'CreatePlacementGroup', 'GroupName' => name, 'Strategy' => strategy, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_instance_status.rb0000644000004100000410000000311712261242551025445 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_instance_status' # http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstanceStatus.html # def describe_instance_status(filters = {}) raise ArgumentError.new("Filters must be a hash, but is a #{filters.class}.") unless filters.is_a?(Hash) next_token = filters.delete('nextToken') || filters.delete('NextToken') max_results = filters.delete('maxResults') || filters.delete('MaxResults') all_instances = filters.delete('includeAllInstances') || filters.delete('IncludeAllInstances') params = Fog::AWS.indexed_request_param('InstanceId', filters.delete('InstanceId')) params.merge!(Fog::AWS.indexed_filters(filters)) params['NextToken'] = next_token if next_token params['MaxResults'] = max_results if max_results params['IncludeAllInstances'] = all_instances if all_instances request({ 'Action' => 'DescribeInstanceStatus', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeInstanceStatus.new }.merge!(params)) end end class Mock def describe_instance_status(filters = {}) response = Excon::Response.new response.status = 200 response.body = { 'instanceStatusSet' => [], 'requestId' => Fog::AWS::Mock.request_id } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/deregister_image.rb0000644000004100000410000000270612261242551023700 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/deregister_image' # deregister an image # # ==== Parameters # * image_id<~String> - Id of image to deregister # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'return'<~Boolean> - Returns true if deregistration succeeded # * 'requestId'<~String> - Id of request # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeregisterImage.html] def deregister_image(image_id) request( 'Action' => 'DeregisterImage', 'ImageId' => image_id, :parser => Fog::Parsers::Compute::AWS::DeregisterImage.new ) end end class Mock def deregister_image(image_id) response = Excon::Response.new if image_id response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => "true" } response else message = 'MissingParameter => ' if !instance_id message << 'The request must contain the parameter image_id' end raise Fog::Compute::AWS::Error.new(message) end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/modify_instance_attribute.rb0000644000004100000410000000344112261242551025634 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Modify instance attributes # # ==== Parameters # * instance_id<~String> - Id of instance to modify # * attributes<~Hash>: # 'InstanceType.Value'<~String> - New instance type # 'Kernel.Value'<~String> - New kernel value # 'Ramdisk.Value'<~String> - New ramdisk value # 'UserData.Value'<~String> - New userdata value # 'DisableApiTermination.Value'<~Boolean> - Change api termination value # 'InstanceInitiatedShutdownBehavior.Value'<~String> - New instance initiated shutdown behaviour, in ['stop', 'terminate'] # 'SourceDestCheck.Value'<~Boolean> - New sourcedestcheck value # 'GroupId'<~Array> - One or more groups to add instance to (VPC only) # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyInstanceAttribute.html] # def modify_instance_attribute(instance_id, attributes) params = {} params.merge!(Fog::AWS.indexed_param('GroupId', attributes.delete('GroupId') || [])) params.merge!(attributes) request({ 'Action' => 'ModifyInstanceAttribute', 'InstanceId' => instance_id, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new }.merge!(params)) end def modify_instance_attributes(instance_id, attributes) Fog::Logger.deprecation("modify_instance_attributes method is deprecated, use 'modify_instance_attribute' instead") modify_instance_attribute(instance_id, attributes) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/register_image.rb0000644000004100000410000001161012261242551023361 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/register_image' # register an image # # ==== Parameters # * Name<~String> - Name of the AMI to be registered # * Description<~String> - AMI description # * Location<~String> - S3 manifest location (for S3 backed AMIs) # or # * RootDeviceName<~String> - Name of Root Device (for EBS snapshot backed AMIs) # * BlockDevices<~Array>: # * BlockDeviceOptions<~Hash>: # * DeviceName<~String> - Name of the Block Device # * VirtualName<~String> - Name of the Virtual Device # * SnapshotId<~String> - id of the EBS Snapshot # * VolumeSize<~Integer> - Size of the snapshot (optional) # * NoDevice<~Boolean> - Do not use an ebs device (def: true) # * DeleteOnTermation<~Boolean> - Delete EBS volume on instance term (def: true) # * Options<~Hash>: # * Architecture<~String> - i386 or x86_64 # * KernelId<~String> - kernelId # * RamdiskId<~String> - ramdiskId # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'imageId'<~String> - Id of newly created AMI # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RegisterImage.html] def register_image(name, description, location, block_devices=[], options={}) common_options = { 'Action' => 'RegisterImage', 'Name' => name, 'Description' => description, :parser => Fog::Parsers::Compute::AWS::RegisterImage.new } # This determines if we are doing a snapshot or a S3 backed AMI. if(location =~ /^\/dev\/sd[a-p]\d{0,2}$/) common_options['RootDeviceName'] = location else common_options['ImageLocation'] = location end block_devices.each_with_index do |bd, index| index += 1 ["DeviceName","VirtualName"].each do |n| common_options["BlockDeviceMapping.#{index}.#{n}"] = bd[n] if bd[n] end ["SnapshotId","VolumeSize","NoDevice","DeleteOnTermination"].each do |n| common_options["BlockDeviceMapping.#{index}.Ebs.#{n}"] = bd[n] if bd[n] end end request(common_options.merge!(options)) end end class Mock def register_image(name, description, location, block_devices=[], options={}) unless name.empty? image = { 'imageId' => Fog::AWS::Mock.image_id, 'imageLocation' => '', 'imageState' => 'pending', 'imageOwnerId' => self.data[:owner_id], 'isPublic' => false, 'productCodes' => [], 'architecture' => options['Architecture'] || 'i386', 'imageType' => 'machine', 'kernelId' => options['KernelId'] || Fog::AWS::Mock.kernel_id, 'ramdiskId' => options['RamdiskId'] || Fog::AWS::Mock.ramdisk_id, 'platform' => 'Linux', 'stateReason' => {}, 'imageOwnerAlias' => self.data[:owner_id], 'name' => name, 'description' => description, 'rootDeviceType' => '', 'rootDeviceName' => '', 'blockDeviceMapping' => [], 'virtualizationType' => 'paravirtual', 'hypervisor' => 'xen', 'registered' => Time.now } if location[/^\/dev\/sd[a-p]\d{0,2}$/] image['rootDeviceName'] = location image['rootDeviceType'] = 'ebs' else image['imageLocation'] = location end block_devices.each do |bd| block_device_mapping = { 'ebs' => {} } ["DeviceName","VirtualName"].each do |n| block_device_mapping[n] = bd[n] if bd[n] end ["SnapshotId","VolumeSize","NoDevice","DeleteOnTermination"].each do |n| block_device_mapping['ebs'][n] = bd[n] if bd[n] end image['blockDeviceMapping'] << block_device_mapping end self.data[:images][image['imageId']] = image response = Excon::Response.new response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'imageId' => image['imageId'] } response else message = 'MissingParameter => ' if name.empty? message << 'The request must contain the parameter name' end raise Fog::Compute::AWS::Error.new(message) end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/reset_network_interface_attribute.rb0000644000004100000410000000417512261242551027401 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Resets a network interface attribute value # # ==== Parameters # * network_interface_id<~String> - The ID of the network interface you want to describe an attribute of # * attribute<~String> - The attribute to reset, only 'sourceDestCheck' is supported. # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/2012-03-01/APIReference/ApiReference-query-DescribeNetworkInterfaceAttribute.html] def reset_network_interface_attribute(network_interface_id, attribute) if attribute != 'sourceDestCheck' raise Fog::Compute::AWS::Error.new("Illegal attribute '#{attribute}' specified") end request( 'Action' => 'ResetNetworkInterfaceAttribute', 'NetworkInterfaceId' => network_interface_id, 'Attribute' => attribute, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def reset_network_interface_attribute(network_interface_id, attribute) response = Excon::Response.new if self.data[:network_interfaces][network_interface_id] response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } if attribute == 'sourceDestCheck' self.data[:network_interfaces][network_interface_id]['sourceDestCheck'] = true else raise Fog::Compute::AWS::Error.new("Illegal attribute '#{attribute}' specified") end response else raise Fog::Compute::AWS::NotFound.new("The network interface '#{network_interface_id}' does not exist") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/associate_address.rb0000644000004100000410000001111612261242551024054 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/associate_address' # Associate an elastic IP address with an instance # # ==== Parameters # * instance_id<~String> - Id of instance to associate address with (conditional) # * public_ip<~String> - Public ip to assign to instance (conditional) # * network_interface_id<~String> - Id of a nic to associate address with (required in a vpc instance with more than one nic) (conditional) # * allocation_id<~String> - Allocation Id to associate address with (vpc only) (conditional) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # * 'associationId'<~String> - association Id for eip to node (vpc only) # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AssociateAddress.html] def associate_address(instance_id=nil, public_ip=nil, network_interface_id=nil, allocation_id=nil) # Cannot specify an allocation ip and a public IP at the same time. If you have an allocation Id presumably you are in a VPC # so we will null out the public IP public_ip = allocation_id.nil? ? public_ip : nil request( 'Action' => 'AssociateAddress', 'AllocationId' => allocation_id, 'InstanceId' => instance_id, 'NetworkInterfaceId' => network_interface_id, 'PublicIp' => public_ip, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::AssociateAddress.new ) end end class Mock def associate_address(instance_id=nil, public_ip=nil, network_interface_id=nil, allocation_id=nil) public_ip = allocation_id.nil? ? public_ip : nil response = Excon::Response.new response.status = 200 instance = self.data[:instances][instance_id] address = public_ip.nil? ? nil : self.data[:addresses][public_ip] if ((instance && address) || (instance && !allocation_id.nil?) || (!allocation_id.nil? && !network_interface_id.nil?)) if !allocation_id.nil? allocation_ip = describe_addresses( 'allocation-id' => "#{allocation_id}").body['addressesSet'].first if !allocation_ip.nil? public_ip = allocation_ip['publicIp'] end end if !address.nil? if current_instance = self.data[:instances][address['instanceId']] current_instance['ipAddress'] = current_instance['originalIpAddress'] end address['instanceId'] = instance_id end # detach other address (if any) if self.data[:addresses][instance['ipAddress']] self.data[:addresses][instance['ipAddress']]['instanceId'] = nil end if !public_ip.nil? instance['ipAddress'] = public_ip instance['dnsName'] = Fog::AWS::Mock.dns_name_for(public_ip) end response.status = 200 if !instance_id.nil? && !public_ip.nil? response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } elsif !allocation_id.nil? response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true, 'associationId' => Fog::AWS::Mock.request_id } end response #elsif ! network_interface_id.nil? && allocation_id.nil? # raise Fog::Compute::AWS::NotFound.new("You must specify an AllocationId when specifying a NetworkInterfaceID") #elsif instance.nil? && network_interface_id.nil? # raise Fog::Compute::AWS::Error.new("You must specify either an InstanceId or a NetworkInterfaceID") #elsif !instance && !network_interface_id # raise Fog::Compute::AWS::Error.new(" 2 You must specify either an InstanceId or a NetworkInterfaceID") elsif !instance raise Fog::Compute::AWS::NotFound.new("You must specify either an InstanceId or a NetworkInterfaceID") elsif !address raise Fog::Compute::AWS::Error.new("AuthFailure => The address '#{public_ip}' does not belong to you.") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_volume_status.rb0000644000004100000410000000260112261242551025145 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_volume_status' # http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumeStatus.html def describe_volume_status(filters = {}) raise ArgumentError.new("Filters must be a hash, but is a #{filters.class}.") unless filters.is_a?(Hash) next_token = filters.delete('nextToken') || filters.delete('NextToken') max_results = filters.delete('maxResults') || filters.delete('MaxResults') params = Fog::AWS.indexed_request_param('VolumeId', filters.delete('VolumeId')) params.merge!(Fog::AWS.indexed_filters(filters)) params['NextToken'] = next_token if next_token params['MaxResults'] = max_results if max_results request({ 'Action' => 'DescribeVolumeStatus', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeVolumeStatus.new }.merge!(params)) end end class Mock def describe_volume_status(filters = {}) response = Excon::Response.new response.status = 200 response.body = { 'volumeStatusSet' => [], 'requestId' => Fog::AWS::Mock.request_id } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_vpc.rb0000644000004100000410000000672512261242551022521 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/create_vpc' # Creates a VPC with the CIDR block you specify. # # ==== Parameters # * cidrBlock<~String> - The CIDR block you want the VPC to cover (e.g., 10.0.0.0/16). # * options<~Hash>: # * InstanceTenancy<~String> - The allowed tenancy of instances launched into the VPC. A value of default # means instances can be launched with any tenancy; a value of dedicated means instances must be launched with tenancy as dedicated. # please not that the documentation is incorrect instanceTenancy will not work while InstanceTenancy will # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'vpc'<~Array>: # * 'vpcId'<~String> - The VPC's ID # * 'state'<~String> - The current state of the VPC. ['pending', 'available'] # * 'cidrBlock'<~String> - The CIDR block the VPC covers. # * 'dhcpOptionsId'<~String> - The ID of the set of DHCP options. # * 'tagSet'<~Array>: Tags assigned to the resource. # * 'key'<~String> - Tag's key # * 'value'<~String> - Tag's value # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/2011-07-15/APIReference/index.html?ApiReference-query-CreateVpc.html] def create_vpc(cidrBlock, options = {}) request({ 'Action' => 'CreateVpc', 'CidrBlock' => cidrBlock, :parser => Fog::Parsers::Compute::AWS::CreateVpc.new }.merge!(options)) end end class Mock def create_vpc(cidrBlock) Excon::Response.new.tap do |response| if cidrBlock response.status = 200 vpc_id = Fog::AWS::Mock.request_id self.data[:vpcs].push({ 'vpcId' => vpc_id, 'state' => 'pending', 'cidrBlock' => cidrBlock, 'dhcpOptionsId' => Fog::AWS::Mock.request_id, 'tagSet' => {} }) #Creates a default route for the subnet default_route = self.route_tables.new(:vpc_id => vpc_id) default_route.save # You are not able to push a main route in the normal AWS, so we are re-implementing some of the # associate_route_table here in order to accomplish this. route_table = self.data[:route_tables].find { |routetable| routetable["routeTableId"].eql? default_route.id } # This pushes a main route to the associationSet # add_route_association(routeTableId, subnetId, main=false) is declared in assocate_route_table.rb assoc = add_route_association(default_route.id, nil, true) route_table["associationSet"].push(assoc) response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'vpcSet' => self.data[:vpcs] } else response.status = 400 response.body = { 'Code' => 'InvalidParameterValue' } if cidrBlock.empty? response.body['Message'] = "Invalid value '' for cidrBlock. Must be specified." end end end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/delete_key_pair.rb0000644000004100000410000000230012261242551023514 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Delete a key pair that you own # # ==== Parameters # * key_name<~String> - Name of the key pair. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteKeyPair.html] def delete_key_pair(key_name) request( 'Action' => 'DeleteKeyPair', 'KeyName' => key_name, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def delete_key_pair(key_name) response = Excon::Response.new self.data[:key_pairs].delete(key_name) response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_key_pairs.rb0000644000004100000410000000454412261242551024231 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_key_pairs' # Describe all or specified key pairs # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'keySet'<~Array>: # * 'keyName'<~String> - Name of key # * 'keyFingerprint'<~String> - Fingerprint of key # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeKeyPairs.html] def describe_key_pairs(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_key_pairs with #{filters.class} param is deprecated, use describe_key_pairs('key-name' => []) instead [light_black](#{caller.first})[/]") filters = {'key-name' => [*filters]} end params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeKeyPairs', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeKeyPairs.new }.merge!(params)) end end class Mock def describe_key_pairs(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_key_pairs with #{filters.class} param is deprecated, use describe_key_pairs('key-name' => []) instead [light_black](#{caller.first})[/]") filters = {'key-name' => [*filters]} end response = Excon::Response.new key_set = self.data[:key_pairs].values aliases = {'fingerprint' => 'keyFingerprint', 'key-name' => 'keyName'} for filter_key, filter_value in filters aliased_key = aliases[filter_key] key_set = key_set.reject{|key_pair| ![*filter_value].include?(key_pair[aliased_key])} end response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'keySet' => key_set.map do |key_pair| key_pair.reject {|key,value| !['keyFingerprint', 'keyName'].include?(key)} end } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_dhcp_options.rb0000644000004100000410000000405012261242551024724 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_dhcp_options' # Describe all or specified dhcp_options # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'DhcpOptionsSet'<~Array>: # * 'dhcpOptionsId'<~String> - The ID of the Dhcp Options # * 'dhcpConfigurationSet'<~Array>: - The list of options in the set. # * 'key'<~String> - The name of a DHCP option. # * 'valueSet'<~Array>: A set of values for a DHCP option. # * 'value'<~String> - The value of a DHCP option. # * 'tagSet'<~Array>: Tags assigned to the resource. # * 'key'<~String> - Tag's key # * 'value'<~String> - Tag's value # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-DhcpOptionsType.html] def describe_dhcp_options(filters = {}) unless filters.is_a?(Hash) Fog::Logger.warning("describe_dhcp_options with #{filters.class} param is deprecated, use dhcp_options('dhcp-options-id' => []) instead [light_black](#{caller.first})[/]") filters = {'dhcp-options-id' => [*filters]} end params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeDhcpOptions', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeDhcpOptions.new }.merge!(params)) end end class Mock def describe_dhcp_options(filters = {}) Excon::Response.new.tap do |response| response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'dhcpOptionsSet' => self.data[:dhcp_options] } end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/import_key_pair.rb0000644000004100000410000000343612261242551023577 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/import_key_pair' # Import an existing public key to create a new key pair # # ==== Parameters # * key_name<~String> - Unique name for key pair. # * public_key_material<~String> - RSA public key # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'keyFingerprint'<~String> - SHA-1 digest of DER encoded private key # * 'keyName'<~String> - Name of key # * 'requestId'<~String> - Id of request # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ImportKeyPair.html] def import_key_pair(key_name, public_key_material) request( 'Action' => 'ImportKeyPair', 'KeyName' => key_name, 'PublicKeyMaterial' => Base64::encode64(public_key_material), :parser => Fog::Parsers::Compute::AWS::ImportKeyPair.new ) end end class Mock def import_key_pair(key_name, public_key_material) response = Excon::Response.new unless self.data[:key_pairs][key_name] response.status = 200 data = { 'keyFingerprint' => Fog::AWS::Mock.key_fingerprint, 'keyName' => key_name } self.data[:key_pairs][key_name] = data response.body = { 'requestId' => Fog::AWS::Mock.request_id }.merge!(data) response else raise Fog::Compute::AWS::Error.new("InvalidKeyPair.Duplicate => The keypair '#{key_name}' already exists.") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/modify_network_interface_attribute.rb0000644000004100000410000000765312261242551027552 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Modifies a network interface attribute value # # ==== Parameters # * network_interface_id<~String> - The ID of the network interface you want to describe an attribute of # * attribute<~String> - The attribute to modify, must be one of 'description', 'groupSet', 'sourceDestCheck' or 'attachment' # * value<~Object> - New value of attribute, the actual tyep depends on teh attribute: # description - a string # groupSet - a list of group id's # sourceDestCheck - a boolean value # attachment - a hash with: # attachmentid - the attachment to change # deleteOnTermination - a boolean # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/2012-03-01/APIReference/ApiReference-query-ModifyNetworkInterfaceAttribute.html] def modify_network_interface_attribute(network_interface_id, attribute, value) params = {} case attribute when 'description' params['Description.Value'] = value when 'groupSet' params.merge!(Fog::AWS.indexed_param('SecurityGroupId.%d', value)) when 'sourceDestCheck' params['SourceDestCheck.Value'] = value when 'attachment' params['Attachment.AttachmentId'] = value['attachmentId'] params['Attachment.DeleteOnTermination'] = value['deleteOnTermination'] else raise Fog::Compute::AWS::Error.new("Illegal attribute '#{attribute}' specified") end request({ 'Action' => 'ModifyNetworkInterfaceAttribute', 'NetworkInterfaceId' => network_interface_id, :parser => Fog::Parsers::Compute::AWS::Basic.new }.merge!(params)) end end class Mock def modify_network_interface_attribute(network_interface_id, attribute, value) response = Excon::Response.new if self.data[:network_interfaces][network_interface_id] nic = self.data[:network_interfaces][network_interface_id] case attribute when 'description' nic['description'] = value.clone when 'groupSet' groups = {} value.each do |group_id| name = self.data[:security_groups].select { |k,v| v['groupId'] == group_id } .first.first if name.nil? raise Fog::Compute::AWS::Error.new("Unknown security group '#{group_id}' specified") end groups[group_id] = name end nic['groupSet'] = groups when 'sourceDestCheck' nic['sourceDestCheck'] = value when 'attachment' if nic['attachment'].nil? || value['attachmentId'] != nic['attachment']['attachmentId'] raise Fog::Compute::AWS::Error.new("Illegal attachment '#{value['attachmentId']}' specified") end nic['attachment']['deleteOnTermination'] = value['deleteOnTermination'] else raise Fog::Compute::AWS::Error.new("Illegal attribute '#{attribute}' specified") end response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else raise Fog::Compute::AWS::NotFound.new("The network interface '#{network_interface_id}' does not exist") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/revoke_security_group_ingress.rb0000644000004100000410000000771112261242551026572 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Remove permissions from a security group # # ==== Parameters # * group_name<~String> - Name of group, optional (can also be specifed as GroupName in options) # * options<~Hash>: # * 'GroupName'<~String> - Name of security group to modify # * 'GroupId'<~String> - Id of security group to modify # * 'SourceSecurityGroupName'<~String> - Name of security group to authorize # * 'SourceSecurityGroupOwnerId'<~String> - Name of owner to authorize # or # * 'CidrIp'<~String> - CIDR range # * 'FromPort'<~Integer> - Start of port range (or -1 for ICMP wildcard) # * 'IpProtocol'<~String> - Ip protocol, must be in ['tcp', 'udp', 'icmp'] # * 'ToPort'<~Integer> - End of port range (or -1 for ICMP wildcard) # or # * 'IpPermissions'<~Array>: # * permission<~Hash>: # * 'FromPort'<~Integer> - Start of port range (or -1 for ICMP wildcard) # * 'Groups'<~Array>: # * group<~Hash>: # * 'GroupName'<~String> - Name of security group to authorize # * 'UserId'<~String> - Name of owner to authorize # * 'IpProtocol'<~String> - Ip protocol, must be in ['tcp', 'udp', 'icmp'] # * 'IpRanges'<~Array>: # * ip_range<~Hash>: # * 'CidrIp'<~String> - CIDR range # * 'ToPort'<~Integer> - End of port range (or -1 for ICMP wildcard) # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RevokeSecurityGroupIngress.html] def revoke_security_group_ingress(group_name, options = {}) options = Fog::AWS.parse_security_group_options(group_name, options) if ip_permissions = options.delete('IpPermissions') options.merge!(indexed_ip_permissions_params(ip_permissions)) end request({ 'Action' => 'RevokeSecurityGroupIngress', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new }.merge!(options)) end end class Mock def revoke_security_group_ingress(group_name, options = {}) options = Fog::AWS.parse_security_group_options(group_name, options) if options.key?('GroupName') group_name = options['GroupName'] else group_name = self.data[:security_groups].reject { |k,v| v['groupId'] != options['GroupId'] } .keys.first end response = Excon::Response.new group = self.data[:security_groups][group_name] if group verify_permission_options(options, group['vpcId'] != nil) normalized_permissions = normalize_permissions(options) normalized_permissions.each do |permission| if matching_permission = find_matching_permission(group, permission) matching_permission['ipRanges'] -= permission['ipRanges'] matching_permission['groups'] -= permission['groups'] if matching_permission['ipRanges'].empty? && matching_permission['groups'].empty? group['ipPermissions'].delete(matching_permission) end end end response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else raise Fog::Compute::AWS::NotFound.new("The security group '#{group_name}' does not exist") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_vpcs.rb0000644000004100000410000000444112261242551023212 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_vpcs' # Describe all or specified vpcs # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'vpcSet'<~Array>: # * 'vpcId'<~String> - The VPC's ID # * 'state'<~String> - The current state of the VPC. ['pending', 'available'] # * 'cidrBlock'<~String> - The CIDR block the VPC covers. # * 'dhcpOptionsId'<~String> - The ID of the set of DHCP options. # * 'tagSet'<~Array>: Tags assigned to the resource. # * 'key'<~String> - Tag's key # * 'value'<~String> - Tag's value # * 'instanceTenancy'<~String> - The allowed tenancy of instances launched into the VPC. # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/2011-07-15/APIReference/index.html?ApiReference-query-DescribeVpcs.html] def describe_vpcs(filters = {}) unless filters.is_a?(Hash) Fog::Logger.warning("describe_vpcs with #{filters.class} param is deprecated, use describe_vpcs('vpc-id' => []) instead [light_black](#{caller.first})[/]") filters = {'vpc-id' => [*filters]} end params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeVpcs', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeVpcs.new }.merge!(params)) end end class Mock def describe_vpcs(filters = {}) vpcs = self.data[:vpcs] # Transition from pending to available vpcs.each do |vpc| case vpc['state'] when 'pending' vpc['state'] = 'available' end end if filters['vpc-id'] vpcs = vpcs.reject {|vpc| vpc['vpcId'] != filters['vpc-id']} end Excon::Response.new( :status => 200, :body => { 'requestId' => Fog::AWS::Mock.request_id, 'vpcSet' => vpcs } ) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/authorize_security_group_ingress.rb0000644000004100000410000002360312261242551027307 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Add permissions to a security group # # ==== Parameters # * group_name<~String> - Name of group, optional (can also be specifed as GroupName in options) # * options<~Hash>: # * 'GroupName'<~String> - Name of security group to modify # * 'GroupId'<~String> - Id of security group to modify # * 'SourceSecurityGroupName'<~String> - Name of security group to authorize # * 'SourceSecurityGroupOwnerId'<~String> - Name of owner to authorize # or # * 'CidrIp'<~String> - CIDR range # * 'FromPort'<~Integer> - Start of port range (or -1 for ICMP wildcard) # * 'IpProtocol'<~String> - Ip protocol, must be in ['tcp', 'udp', 'icmp'] # * 'ToPort'<~Integer> - End of port range (or -1 for ICMP wildcard) # or # * 'IpPermissions'<~Array>: # * permission<~Hash>: # * 'FromPort'<~Integer> - Start of port range (or -1 for ICMP wildcard) # * 'Groups'<~Array>: # * group<~Hash>: # * 'GroupName'<~String> - Name of security group to authorize # * 'UserId'<~String> - Name of owner to authorize # * 'IpProtocol'<~String> - Ip protocol, must be in ['tcp', 'udp', 'icmp'] # * 'IpRanges'<~Array>: # * ip_range<~Hash>: # * 'CidrIp'<~String> - CIDR range # * 'ToPort'<~Integer> - End of port range (or -1 for ICMP wildcard) # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AuthorizeSecurityGroupIngress.html] def authorize_security_group_ingress(group_name, options = {}) options = Fog::AWS.parse_security_group_options(group_name, options) if ip_permissions = options.delete('IpPermissions') options.merge!(indexed_ip_permissions_params(ip_permissions)) end request({ 'Action' => 'AuthorizeSecurityGroupIngress', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new }.merge!(options)) end private def indexed_ip_permissions_params(ip_permissions) params = {} ip_permissions.each_with_index do |permission, key_index| key_index += 1 params[format('IpPermissions.%d.IpProtocol', key_index)] = permission['IpProtocol'] params[format('IpPermissions.%d.FromPort', key_index)] = permission['FromPort'] params[format('IpPermissions.%d.ToPort', key_index)] = permission['ToPort'] (permission['Groups'] || []).each_with_index do |group, group_index| group_index += 1 params[format('IpPermissions.%d.Groups.%d.UserId', key_index, group_index)] = group['UserId'] params[format('IpPermissions.%d.Groups.%d.GroupName', key_index, group_index)] = group['GroupName'] params[format('IpPermissions.%d.Groups.%d.GroupId', key_index, group_index)] = group['GroupId'] end (permission['IpRanges'] || []).each_with_index do |ip_range, range_index| range_index += 1 params[format('IpPermissions.%d.IpRanges.%d.CidrIp', key_index, range_index)] = ip_range['CidrIp'] end end params.reject {|k, v| v.nil? } end end class Mock def authorize_security_group_ingress(group_name, options = {}) options = Fog::AWS.parse_security_group_options(group_name, options) if options.key?('GroupName') group_name = options['GroupName'] else group_name = self.data[:security_groups].reject { |k,v| v['groupId'] != options['GroupId'] } .keys.first end response = Excon::Response.new group = self.data[:security_groups][group_name] if group verify_permission_options(options, group['vpcId'] != nil) normalized_permissions = normalize_permissions(options) normalized_permissions.each do |permission| if matching_group_permission = find_matching_permission(group, permission) if permission['groups'].any? {|pg| matching_group_permission['groups'].include?(pg) } raise Fog::Compute::AWS::Error, "InvalidPermission.Duplicate => The permission '123' has already been authorized in the specified group" end if permission['ipRanges'].any? {|pr| matching_group_permission['ipRanges'].include?(pr) } raise Fog::Compute::AWS::Error, "InvalidPermission.Duplicate => The permission '123' has already been authorized in the specified group" end end end normalized_permissions.each do |permission| if matching_group_permission = find_matching_permission(group, permission) matching_group_permission['groups'] += permission['groups'] matching_group_permission['ipRanges'] += permission['ipRanges'] else group['ipPermissions'] << permission end end response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else raise Fog::Compute::AWS::NotFound.new("The security group '#{group_name}' does not exist") end end private def verify_permission_options(options, is_vpc) if options.size <= 1 raise Fog::Compute::AWS::Error.new("InvalidRequest => The request received was invalid.") end if !is_vpc && options['IpProtocol'] && !['tcp', 'udp', 'icmp'].include?(options['IpProtocol']) raise Fog::Compute::AWS::Error.new("InvalidPermission.Malformed => Unsupported IP protocol \"#{options['IpProtocol']}\" - supported: [tcp, udp, icmp]") end if !is_vpc && (options['IpProtocol'] && (!options['FromPort'] || !options['ToPort'])) raise Fog::Compute::AWS::Error.new("InvalidPermission.Malformed => TCP/UDP port (-1) out of range") end if options.has_key?('IpPermissions') if !options['IpPermissions'].is_a?(Array) || options['IpPermissions'].empty? raise Fog::Compute::AWS::Error.new("InvalidRequest => The request received was invalid.") end options['IpPermissions'].each {|p| verify_permission_options(p, is_vpc) } end end def normalize_permissions(options) normalized_permissions = [] if options['SourceSecurityGroupName'] source_group_id=self.data[:security_groups][options['SourceSecurityGroupName']]['groupId'] ['tcp', 'udp'].each do |protocol| normalized_permissions << { 'ipProtocol' => protocol, 'fromPort' => 1, 'toPort' => 65535, 'groups' => [{'groupName' => options['SourceSecurityGroupName'], 'userId' => options['SourceSecurityGroupOwnerId'] || self.data[:owner_id], 'groupId' => source_group_id }], 'ipRanges' => [] } end normalized_permissions << { 'ipProtocol' => 'icmp', 'fromPort' => -1, 'toPort' => -1, 'groups' => [{'groupName' => options['SourceSecurityGroupName'], 'userId' => options['SourceSecurityGroupOwnerId'] || self.data[:owner_id], 'groupId' => source_group_id }], 'ipRanges' => [] } elsif options['CidrIp'] normalized_permissions << { 'ipProtocol' => options['IpProtocol'], 'fromPort' => Integer(options['FromPort']), 'toPort' => Integer(options['ToPort']), 'groups' => [], 'ipRanges' => [{'cidrIp' => options['CidrIp']}] } elsif options['IpPermissions'] options['IpPermissions'].each do |permission| if ['tcp', 'udp', 'icmp'].include?(permission['IpProtocol']) normalized_permissions << { 'ipProtocol' => permission['IpProtocol'], 'fromPort' => Integer(permission['FromPort']), 'toPort' => Integer(permission['ToPort']), 'groups' => (permission['Groups'] || []).map {|g| {'groupName' => g['GroupName'], 'userId' => g['UserId'] || self.data[:owner_id], 'groupId' => self.data[:security_groups][g['GroupName']] && self.data[:security_groups][g['GroupName']]['groupId']} }, 'ipRanges' => (permission['IpRanges'] || []).map {|r| { 'cidrIp' => r['CidrIp'] } } } else normalized_permissions << { 'ipProtocol' => permission['IpProtocol'], 'groups' => (permission['Groups'] || []).map {|g| {'groupName' => g['GroupName'], 'userId' => g['UserId'] || self.data[:owner_id], 'groupId' => self.data[:security_groups][g['GroupName']]['groupId']} }, 'ipRanges' => (permission['IpRanges'] || []).map {|r| { 'cidrIp' => r['CidrIp'] } } } end end end normalized_permissions end def find_matching_permission(group, permission) group['ipPermissions'].detect {|group_permission| permission['ipProtocol'] == group_permission['ipProtocol'] && permission['fromPort'] == group_permission['fromPort'] && permission['toPort'] == group_permission['toPort'] } end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_spot_instance_requests.rb0000644000004100000410000000430012261242551027035 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/spot_instance_requests' # Describe all or specified spot instance requests # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'spotInstanceRequestSet'<~Array>: # * 'createTime'<~Time> - time of instance request creation # * 'instanceId'<~String> - instance id if one has been launched to fulfill request # * 'launchedAvailabilityZone'<~String> - availability zone of instance if one has been launched to fulfill request # * 'launchSpecification'<~Hash>: # * 'blockDeviceMapping'<~Hash> - list of block device mappings for instance # * 'groupSet'<~String> - security group(s) for instance # * 'keyName'<~String> - keypair name for instance # * 'imageId'<~String> - AMI for instance # * 'instanceType'<~String> - type for instance # * 'monitoring'<~Boolean> - monitoring status for instance # * 'subnetId'<~String> - VPC subnet ID for instance # * 'productDescription'<~String> - general description of AMI # * 'spotInstanceRequestId'<~String> - id of spot instance request # * 'spotPrice'<~Float> - maximum price for instances to be launched # * 'state'<~String> - spot instance request state # * 'type'<~String> - spot instance request type # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotInstanceRequests.html] def describe_spot_instance_requests(filters = {}) params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeSpotInstanceRequests', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::SpotInstanceRequests.new }.merge!(params)) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_tags.rb0000644000004100000410000000643612261242551023203 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_tags' # Describe all or specified tags # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'tagSet'<~Array>: # * 'resourceId'<~String> - id of resource tag belongs to # * 'resourceType'<~String> - type of resource tag belongs to # * 'key'<~String> - Tag's key # * 'value'<~String> - Tag's value # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeTags.html] def describe_tags(filters = {}) params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeTags', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeTags.new }.merge!(params)) end end class Mock def describe_tags(filters = {}) response = Excon::Response.new tag_set = deep_clone(self.data[:tags]) aliases = { 'key' => 'key', 'resource-id' => 'resourceId', 'resource-type' => 'resourceType', 'value' => 'value' } for filter_key, filter_value in filters filter_attribute = aliases[filter_key] case filter_attribute when 'key' tag_set.reject! { |k,_| k != filter_value } when 'value' tag_set.each { |k,values| values.reject! { |v, _| v != filter_value } } when 'resourceId' filter_resources(tag_set, 'resourceId', filter_value) when 'resourceType' filter_resources(tag_set, 'resourceType', filter_value) end end tagged_resources = [] tag_set.each do |key, values| values.each do |value, resources| resources.each do |resource| tagged_resources << resource.merge({ 'key' => key, 'value' => value }) end end end response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'tagSet' => tagged_resources } response end private def filter_resources(tag_set, filter, value) value_hash_list = tag_set.values value_hash_list.each do |value_hash| value_hash.each do |_, resource_list| resource_list.reject! { |resource| resource[filter] != value } end end end def deep_clone(obj) case obj when Hash obj.inject({}) { |h, pair| h[pair.first] = deep_clone(pair.last); h } when Array obj.map { |o| deep_clone(o) } else obj end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/attach_network_interface.rb0000644000004100000410000000400412261242551025427 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/attach_network_interface' # Attach a network interface # # ==== Parameters # * networkInterfaceId<~String> - ID of the network interface to attach # * instanceId<~String> - ID of the instance that will be attached to the network interface # * deviceIndex<~Integer> - index of the device for the network interface attachment on the instance # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'attachmentId'<~String> - ID of the attachment # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/2012-03-01/APIReference/index.html?ApiReference-query-AttachNetworkInterface.html] def attach_network_interface(nic_id, instance_id, device_index) request( 'Action' => 'AttachNetworkInterface', 'NetworkInterfaceId' => nic_id, 'InstanceId' => instance_id, 'DeviceIndex' => device_index, :parser => Fog::Parsers::Compute::AWS::AttachNetworkInterface.new ) end end class Mock def attach_network_interface(nic_id, instance_id, device_index) response = Excon::Response.new if self.data[:network_interfaces][nic_id] attachment = self.data[:network_interfaces][nic_id]['attachment'] attachment['attachmentId'] = Fog::AWS::Mock.request_id attachment['instanceId'] = instance_id response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'attachmentId' => attachment['attachmentId'] } else raise Fog::Compute::AWS::NotFound.new("The network interface '#{nic_id}' does not exist") end response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/detach_volume.rb0000644000004100000410000000456012261242551023220 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/detach_volume' # Detach an Amazon EBS volume from a running instance # # ==== Parameters # * volume_id<~String> - Id of amazon EBS volume to associate with instance # * options<~Hash>: # * 'Device'<~String> - Specifies how the device is exposed to the instance (e.g. "/dev/sdh") # * 'Force'<~Boolean> - If true forces detach, can cause data loss/corruption # * 'InstanceId'<~String> - Id of instance to associate volume with # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'attachTime'<~Time> - Time of attachment was initiated at # * 'device'<~String> - Device as it is exposed to the instance # * 'instanceId'<~String> - Id of instance for volume # * 'requestId'<~String> - Id of request # * 'status'<~String> - Status of volume # * 'volumeId'<~String> - Reference to volume # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DetachVolume.html] def detach_volume(volume_id, options = {}) request({ 'Action' => 'DetachVolume', 'VolumeId' => volume_id, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DetachVolume.new }.merge!(options)) end end class Mock def detach_volume(volume_id, options = {}) response = Excon::Response.new response.status = 200 if (volume = self.data[:volumes][volume_id]) if !volume['attachmentSet'].empty? data = volume['attachmentSet'].pop volume['status'] = 'available' response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id }.merge!(data) response else # real response has spacing issue below raise Fog::Compute::AWS::Error.new("IncorrectState => Volume '#{volume_id}'is in the 'available' state.") end else raise Fog::Compute::AWS::NotFound.new("The volume '#{volume_id}' does not exist.") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_addresses.rb0000644000004100000410000000444412261242551024217 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_addresses' # Describe all or specified IP addresses. # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'addressesSet'<~Array>: # * 'instanceId'<~String> - instance for ip address # * 'publicIp'<~String> - ip address for instance # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeAddresses.html] def describe_addresses(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_addresses with #{filters.class} param is deprecated, use describe_addresses('public-ip' => []) instead [light_black](#{caller.first})[/]") filters = {'public-ip' => [*filters]} end params = Fog::AWS.indexed_filters(filters) request({ 'Action' => 'DescribeAddresses', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeAddresses.new }.merge!(params)) end end class Mock def describe_addresses(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_addresses with #{filters.class} param is deprecated, use describe_addresses('public-ip' => []) instead [light_black](#{caller.first})[/]") filters = {'public-ip' => [*filters]} end response = Excon::Response.new addresses_set = self.data[:addresses].values aliases = {'public-ip' => 'publicIp', 'instance-id' => 'instanceId'} for filter_key, filter_value in filters aliased_key = aliases[filter_key] addresses_set = addresses_set.reject{|address| ![*filter_value].include?(address[aliased_key])} end response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'addressesSet' => addresses_set } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/detach_internet_gateway.rb0000644000004100000410000000351112261242551025255 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Detaches an Internet gateway to a VPC, enabling connectivity between the Internet and the VPC # # ==== Parameters # * internet_gateway_id<~String> - The ID of the Internet gateway to detach # * vpc_id<~String> - The ID of the VPC # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - Returns true if the request succeeds. # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DetachInternetGateway.html] def detach_internet_gateway(internet_gateway_id, vpc_id) request( 'Action' => 'DetachInternetGateway', 'InternetGatewayId' => internet_gateway_id, 'VpcId' => vpc_id, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def detach_internet_gateway(internet_gateway_id, vpc_id) response = Excon::Response.new if internet_gateway_id && vpc_id response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else if !internet_gateway_id message << 'The request must contain the parameter internet_gateway_id' elsif !vpc_id message << 'The request must contain the parameter vpc_id' end raise Fog::Compute::AWS::Error.new(message) end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/disassociate_route_table.rb0000755000004100000410000000407712261242551025447 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Disassociates a subnet from a route table. # # ==== Parameters # * AssociationId<~String> - The association ID representing the current association between the route table and subnet. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - The ID of the request. # * 'return'<~Boolean> - Returns true if the request succeeds. Otherwise, returns an error. # # {Amazon API Reference}[http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DisassociateRouteTable.html] def disassociate_route_table(association_id) request( 'Action' => 'DisassociateRouteTable', 'AssociationId' => association_id, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def disassociate_route_table(association_id) assoc_array = nil routetable = self.data[:route_tables].find { |routetable| assoc_array = routetable["associationSet"].find { |association| association['routeTableAssociationId'].eql? association_id } } if !assoc_array.nil? && assoc_array['main'] == false routetable['associationSet'].delete(assoc_array) response = Excon::Response.new response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response elsif assoc_array.nil? raise Fog::Compute::AWS::NotFound.new("The association ID '#{association_id}' does not exist") elsif assoc_array['main'] == true raise Fog::Compute::AWS::Error, "InvalidParameterValue => cannot disassociate the main route table association #{association_id}" end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/delete_internet_gateway.rb0000644000004100000410000000322512261242551025271 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' #Deletes an Internet gateway from your AWS account. The gateway must not be attached to a VPC # # ==== Parameters # * internet_gateway_id<~String> - The ID of the InternetGateway you want to delete. # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - Returns true if the request succeeds. # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteInternetGateway.html] def delete_internet_gateway(internet_gateway_id) request( 'Action' => 'DeleteInternetGateway', 'InternetGatewayId' => internet_gateway_id, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def delete_internet_gateway(internet_gateway_id) Excon::Response.new.tap do |response| if internet_gateway_id response.status = 200 self.data[:internet_gateways].delete(internet_gateway_id) response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } else message = 'MissingParameter => ' message << 'The request must contain the parameter internet_gateway_id' raise Fog::Compute::AWS::Error.new(message) end end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_spot_datafeed_subscription.rb0000644000004100000410000000270512261242551027331 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/spot_datafeed_subscription' # Create a spot datafeed subscription # # ==== Parameters # * bucket<~String> - bucket name to store datafeed in # * prefix<~String> - prefix to store data with # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'spotDatafeedSubscription'<~Hash>: # * 'bucket'<~String> - S3 bucket where data is stored # * 'fault'<~Hash>: # * 'code'<~String> - fault code # * 'reason'<~String> - fault reason # * 'ownerId'<~String> - AWS id of account owner # * 'prefix'<~String> - prefix for datafeed items # * 'state'<~String> - state of datafeed subscription # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSpotDatafeedSubscription.html] def create_spot_datafeed_subscription(bucket, prefix) request( 'Action' => 'CreateSpotDatafeedSubscription', 'Bucket' => bucket, 'Prefix' => prefix, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::SpotDatafeedSubscription.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_snapshots.rb0000644000004100000410000001173112261242551024261 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_snapshots' # Describe all or specified snapshots # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # * options<~Hash>: # * 'Owner'<~String> - Owner of snapshot in ['self', 'amazon', account_id] # * 'RestorableBy'<~String> - Account id of user who can create volumes from this snapshot # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'snapshotSet'<~Array>: # * 'progress'<~String>: The percentage progress of the snapshot # * 'snapshotId'<~String>: Id of the snapshot # * 'startTime'<~Time>: Timestamp of when snapshot was initiated # * 'status'<~String>: Snapshot state, in ['pending', 'completed'] # * 'volumeId'<~String>: Id of volume that snapshot contains # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSnapshots.html] def describe_snapshots(filters = {}, options = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_snapshots with #{filters.class} param is deprecated, use describe_snapshots('snapshot-id' => []) instead [light_black](#{caller.first})[/]") filters = {'snapshot-id' => [*filters]} end unless options.empty? Fog::Logger.deprecation("describe_snapshots with a second param is deprecated, use describe_snapshots(options) instead [light_black](#{caller.first})[/]") end for key in ['ExecutableBy', 'ImageId', 'Owner', 'RestorableBy'] if filters.has_key?(key) options[key] = filters.delete(key) end end options['RestorableBy'] ||= 'self' params = Fog::AWS.indexed_filters(filters).merge!(options) request({ 'Action' => 'DescribeSnapshots', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeSnapshots.new }.merge!(params)) end end class Mock def describe_snapshots(filters = {}, options = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_snapshots with #{filters.class} param is deprecated, use describe_snapshots('snapshot-id' => []) instead [light_black](#{caller.first})[/]") filters = {'snapshot-id' => [*filters]} end unless options.empty? Fog::Logger.deprecation("describe_snapshots with a second param is deprecated, use describe_snapshots(options) instead [light_black](#{caller.first})[/]") end response = Excon::Response.new snapshot_set = self.data[:snapshots].values if filters.delete('owner-alias') Fog::Logger.warning("describe_snapshots with owner-alias is not mocked [light_black](#{caller.first})[/]") end if (restorable_by = filters.delete('RestorableBy')) && restorable_by != 'self' Fog::Logger.warning("describe_snapshots with RestorableBy other than 'self' (wanted #{restorable_by.inspect}) is not mocked [light_black](#{caller.first})[/]") end snapshot_set = apply_tag_filters(snapshot_set, filters, 'snapshotId') aliases = { 'description' => 'description', 'owner-id' => 'ownerId', 'progress' => 'progress', 'snapshot-id' => 'snapshotId', 'start-time' => 'startTime', 'status' => 'status', 'volume-id' => 'volumeId', 'volume-size' => 'volumeSize' } for filter_key, filter_value in filters aliased_key = aliases[filter_key] snapshot_set = snapshot_set.reject{|snapshot| ![*filter_value].include?(snapshot[aliased_key])} end snapshot_set.each do |snapshot| case snapshot['status'] when 'in progress', 'pending' if Time.now - snapshot['startTime'] >= Fog::Mock.delay * 2 snapshot['progress'] = '100%' snapshot['status'] = 'completed' elsif Time.now - snapshot['startTime'] >= Fog::Mock.delay snapshot['progress'] = '50%' snapshot['status'] = 'in progress' else snapshot['progress'] = '0%' snapshot['status'] = 'in progress' end end end snapshot_set = snapshot_set.map {|snapshot| snapshot.merge('tagSet' => self.data[:tag_sets][snapshot['snapshotId']]) } response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'snapshotSet' => snapshot_set } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/attach_volume.rb0000644000004100000410000000637412261242551023241 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/attach_volume' # Attach an Amazon EBS volume with a running instance, exposing as specified device # # ==== Parameters # * instance_id<~String> - Id of instance to associate volume with # * volume_id<~String> - Id of amazon EBS volume to associate with instance # * device<~String> - Specifies how the device is exposed to the instance (e.g. "/dev/sdh") # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'attachTime'<~Time> - Time of attachment was initiated at # * 'device'<~String> - Device as it is exposed to the instance # * 'instanceId'<~String> - Id of instance for volume # * 'requestId'<~String> - Id of request # * 'status'<~String> - Status of volume # * 'volumeId'<~String> - Reference to volume # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AttachVolume.html] def attach_volume(instance_id, volume_id, device) request( 'Action' => 'AttachVolume', 'VolumeId' => volume_id, 'InstanceId' => instance_id, 'Device' => device, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::AttachVolume.new ) end end class Mock def attach_volume(instance_id, volume_id, device) response = Excon::Response.new if instance_id && volume_id && device response.status = 200 instance = self.data[:instances][instance_id] volume = self.data[:volumes][volume_id] if instance && volume unless volume['status'] == 'available' raise Fog::Compute::AWS::Error.new("Client.VolumeInUse => Volume #{volume_id} is unavailable") end data = { 'attachTime' => Time.now, 'device' => device, 'instanceId' => instance_id, 'status' => 'attaching', 'volumeId' => volume_id } volume['attachmentSet'] = [data] volume['status'] = 'attaching' response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id }.merge!(data) response elsif !instance raise Fog::Compute::AWS::NotFound.new("The instance ID '#{instance_id}' does not exist.") elsif !volume raise Fog::Compute::AWS::NotFound.new("The volume '#{volume_id}' does not exist.") end else message = 'MissingParameter => ' if !instance_id message << 'The request must contain the parameter instance_id' elsif !volume_id message << 'The request must contain the parameter volume_id' else message << 'The request must contain the parameter device' end raise Fog::Compute::AWS::Error.new(message) end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_internet_gateway.rb0000644000004100000410000000336412261242551025276 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/create_internet_gateway' # Creates an InternetGateway # # ==== Parameters # (none) # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'internetGateway'<~Array>: # * 'attachmentSet'<~Array>: A list of VPCs attached to the Internet gateway # * 'vpcId'<~String> - The ID of the VPC the Internet gateway is attached to. # * 'state'<~String> - The current state of the attachment. # * 'tagSet'<~Array>: Tags assigned to the resource. # * 'key'<~String> - Tag's key # * 'value'<~String> - Tag's value # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-InternetGatewayAttachmentType.html] def create_internet_gateway() request({ 'Action' => 'CreateInternetGateway', :parser => Fog::Parsers::Compute::AWS::CreateInternetGateway.new }) end end class Mock def create_internet_gateway() gateway_id = Fog::AWS::Mock.internet_gateway_id self.data[:internet_gateways][gateway_id] = { 'internetGatewayId' => gateway_id, 'attachmentSet' => {}, 'tagSet' => {} } Excon::Response.new( :status => 200, :body => { 'requestId' => Fog::AWS::Mock.request_id, 'internetGatewaySet' => [self.data[:internet_gateways][gateway_id]] } ) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/release_address.rb0000644000004100000410000000402012261242551023515 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Release an elastic IP address. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ReleaseAddress.html] # # non-VPC: requires public_ip only # VPC: requires allocation_id only def release_address(ip_or_allocation) field = if ip_or_allocation.to_s =~ /^(\d|\.)+$/ "PublicIp" else "AllocationId" end request( 'Action' => 'ReleaseAddress', field => ip_or_allocation, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end class Mock def release_address(public_ip_or_allocation_id) response = Excon::Response.new address = self.data[:addresses][public_ip_or_allocation_id] || self.data[:addresses].values.detect {|a| a['allocationId'] == public_ip_or_allocation_id } if address if address['allocationId'] && public_ip_or_allocation_id == address['publicIp'] raise Fog::Compute::AWS::Error, "InvalidParameterValue => You must specify an allocation id when releasing a VPC elastic IP address" end self.data[:addresses].delete(address['publicIp']) response.status = 200 response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'return' => true } response else raise Fog::Compute::AWS::Error.new("AuthFailure => The address '#{public_ip_or_allocation_id}' does not belong to you.") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/delete_spot_datafeed_subscription.rb0000644000004100000410000000142512261242551027326 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Delete a spot datafeed subscription # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteSpotDatafeedSubscription.html] def delete_spot_datafeed_subscription request( 'Action' => 'DeleteSpotDatafeedSubscription', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/terminate_instances.rb0000644000004100000410000000640712261242551024442 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/terminate_instances' # Terminate specified instances # # ==== Parameters # * instance_id<~Array> - Ids of instances to terminates # # ==== Returns # # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'instancesSet'<~Array>: # * 'instanceId'<~String> - id of the terminated instance # * 'previousState'<~Hash>: previous state of instance # * 'code'<~Integer> - previous status code # * 'name'<~String> - name of previous state # * 'shutdownState'<~Hash>: shutdown state of instance # * 'code'<~Integer> - current status code # * 'name'<~String> - name of current state # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-TerminateInstances.html] def terminate_instances(instance_id) params = Fog::AWS.indexed_param('InstanceId', instance_id) request({ 'Action' => 'TerminateInstances', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::TerminateInstances.new }.merge!(params)) end end class Mock def terminate_instances(instance_id) response = Excon::Response.new instance_id = [*instance_id] if (self.data[:instances].keys & instance_id).length == instance_id.length response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'instancesSet' => [] } response.status = 200 for id in instance_id instance = self.data[:instances][id] self.data[:deleted_at][id] = Time.now code = case instance['instanceState']['name'] when 'pending' 0 when 'running' 16 when 'shutting-down' 32 when 'terminated' 48 when 'stopping' 64 when 'stopped' 80 end state = { 'name' => 'shutting-down', 'code' => 32} response.body['instancesSet'] << { 'instanceId' => id, 'previousState' => instance['instanceState'], 'currentState' => state } instance['instanceState'] = state end describe_addresses.body['addressesSet'].each do |address| if instance_id.include?(address['instanceId']) disassociate_address(address['publicIp']) end end describe_volumes.body['volumeSet'].each do |volume| if volume['attachmentSet'].first && instance_id.include?(volume['attachmentSet'].first['instanceId']) detach_volume(volume['volumeId']) end end response else raise Fog::Compute::AWS::NotFound.new("The instance ID '#{instance_id}' does not exist") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/modify_snapshot_attribute.rb0000644000004100000410000000325212261242551025667 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Modify snapshot attributes # # ==== Parameters # * snapshot_id<~String> - Id of snapshot to modify # * attributes<~Hash>: # * 'Add.Group'<~Array> - One or more groups to grant volume create permission to # * 'Add.UserId'<~Array> - One or more account ids to grant volume create permission to # * 'Remove.Group'<~Array> - One or more groups to revoke volume create permission from # * 'Remove.UserId'<~Array> - One or more account ids to revoke volume create permission from # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifySnapshotAttribute.html] # def modify_snapshot_attribute(snapshot_id, attributes) params = {} params.merge!(Fog::AWS.indexed_param('CreateVolumePermission.Add.%d.Group', attributes['Add.Group'] || [])) params.merge!(Fog::AWS.indexed_param('CreateVolumePermission.Add.%d.UserId', attributes['Add.UserId'] || [])) params.merge!(Fog::AWS.indexed_param('CreateVolumePermission.Remove.%d.Group', attributes['Remove.Group'] || [])) params.merge!(Fog::AWS.indexed_param('CreateVolumePermission.Remove.%d.UserId', attributes['Remove.UserId'] || [])) request({ 'Action' => 'ModifySnapshotAttribute', 'SnapshotId' => snapshot_id, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new }.merge!(params)) end end end end end fog-1.19.0/lib/fog/aws/requests/compute/associate_route_table.rb0000755000004100000410000000504712261242551024745 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/associate_route_table' # Associates a subnet with a route table. # # ==== Parameters # * RouteTableId<~String> - The ID of the route table # * SubnetId<~String> - The ID of the subnet # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - The ID of the request # * 'associationId'<~String> - The route table association ID (needed to disassociate the route table) # # {Amazon API Reference}[http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AssociateRouteTable.html] def associate_route_table(routeTableId, subnetId) request( 'Action' => 'AssociateRouteTable', 'RouteTableId' => routeTableId, 'SubnetId' => subnetId, :parser => Fog::Parsers::Compute::AWS::AssociateRouteTable.new ) end end class Mock def associate_route_table(routeTableId, subnetId) routetable = self.data[:route_tables].find { |routetable| routetable["routeTableId"].eql? routeTableId } subnet = self.data[:subnets].find { |subnet| subnet["subnetId"].eql? subnetId } if !routetable.nil? && !subnet.nil? response = Excon::Response.new response.status = 200 association = add_route_association(routeTableId, subnetId) routetable["associationSet"].push(association) response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'associationId' => association['routeTableAssociationId'] } response elsif routetable.nil? raise Fog::Compute::AWS::NotFound.new("The routeTable ID '#{routeTableId}' does not exist") else raise Fog::Compute::AWS::NotFound.new("The subnet ID '#{subnetId}' does not exist") end end private def add_route_association(routeTableId, subnetId, main=nil) response = { "routeTableAssociationId" => "rtbassoc-#{Fog::Mock.random_hex(8)}", "routeTableId" => routeTableId, "subnetId" => nil, "main" => false } if main response['main'] = true else response['subnetId'] = subnetId end response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/describe_instances.rb0000644000004100000410000002760012261242551024230 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/describe_instances' # Describe all or specified instances # # ==== Parameters # * filters<~Hash> - List of filters to limit results with # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'reservationSet'<~Array>: # * 'groupSet'<~Array> - Group names for reservation # * 'ownerId'<~String> - AWS Access Key ID of reservation owner # * 'reservationId'<~String> - Id of the reservation # * 'instancesSet'<~Array>: # * instance<~Hash>: # * 'architecture'<~String> - architecture of image in [i386, x86_64] # * 'amiLaunchIndex'<~Integer> - reference to instance in launch group # * 'blockDeviceMapping'<~Array> # * 'attachTime'<~Time> - time of volume attachment # * 'deleteOnTermination'<~Boolean> - whether or not to delete volume on termination # * 'deviceName'<~String> - specifies how volume is exposed to instance # * 'status'<~String> - status of attached volume # * 'volumeId'<~String> - Id of attached volume # * 'dnsName'<~String> - public dns name, blank until instance is running # * 'ebsOptimized'<~Boolean> - Whether the instance is optimized for EBS I/O # * 'imageId'<~String> - image id of ami used to launch instance # * 'instanceId'<~String> - id of the instance # * 'instanceState'<~Hash>: # * 'code'<~Integer> - current status code # * 'name'<~String> - current status name # * 'instanceType'<~String> - type of instance # * 'ipAddress'<~String> - public ip address assigned to instance # * 'kernelId'<~String> - id of kernel used to launch instance # * 'keyName'<~String> - name of key used launch instances or blank # * 'launchTime'<~Time> - time instance was launched # * 'monitoring'<~Hash>: # * 'state'<~Boolean - state of monitoring # * 'placement'<~Hash>: # * 'availabilityZone'<~String> - Availability zone of the instance # * 'platform'<~String> - Platform of the instance (e.g., Windows). # * 'productCodes'<~Array> - Product codes for the instance # * 'privateDnsName'<~String> - private dns name, blank until instance is running # * 'privateIpAddress'<~String> - private ip address assigned to instance # * 'rootDeviceName'<~String> - specifies how the root device is exposed to the instance # * 'rootDeviceType'<~String> - root device type used by AMI in [ebs, instance-store] # * 'ramdiskId'<~String> - Id of ramdisk used to launch instance # * 'reason'<~String> - reason for most recent state transition, or blank # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html] def describe_instances(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_instances with #{filters.class} param is deprecated, use describe_instances('instance-id' => []) instead [light_black](#{caller.first})[/]") filters = {'instance-id' => [*filters]} end params = {} if filters['instance-id'] instance_ids = filters.delete('instance-id') instance_ids = [instance_ids] unless instance_ids.is_a?(Array) instance_ids.each_with_index do |id, index| params.merge!("InstanceId.#{index}" => id) end end params.merge!(Fog::AWS.indexed_filters(filters)) request({ 'Action' => 'DescribeInstances', :idempotent => true, :parser => Fog::Parsers::Compute::AWS::DescribeInstances.new }.merge!(params)) end end class Mock def describe_instances(filters = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("describe_instances with #{filters.class} param is deprecated, use describe_instances('instance-id' => []) instead [light_black](#{caller.first})[/]") filters = {'instance-id' => [*filters]} end response = Excon::Response.new instance_set = self.data[:instances].values instance_set = apply_tag_filters(instance_set, filters, 'instanceId') aliases = { 'architecture' => 'architecture', 'availability-zone' => 'availabilityZone', 'client-token' => 'clientToken', 'dns-name' => 'dnsName', 'group-id' => 'groupId', 'image-id' => 'imageId', 'instance-id' => 'instanceId', 'instance-lifecycle' => 'instanceLifecycle', 'instance-type' => 'instanceType', 'ip-address' => 'ipAddress', 'kernel-id' => 'kernelId', 'key-name' => 'key-name', 'launch-index' => 'launchIndex', 'launch-time' => 'launchTime', 'monitoring-state' => 'monitoringState', 'owner-id' => 'ownerId', 'placement-group-name' => 'placementGroupName', 'platform' => 'platform', 'private-dns-name' => 'privateDnsName', 'private-ip-address' => 'privateIpAddress', 'product-code' => 'productCode', 'ramdisk-id' => 'ramdiskId', 'reason' => 'reason', 'requester-id' => 'requesterId', 'reservation-id' => 'reservationId', 'root-device-name' => 'rootDeviceName', 'root-device-type' => 'rootDeviceType', 'spot-instance-request-id' => 'spotInstanceRequestId', 'subnet-id' => 'subnetId', 'virtualization-type' => 'virtualizationType', 'vpc-id' => 'vpcId' } block_device_mapping_aliases = { 'attach-time' => 'attachTime', 'delete-on-termination' => 'deleteOnTermination', 'device-name' => 'deviceName', 'status' => 'status', 'volume-id' => 'volumeId', } instance_state_aliases = { 'code' => 'code', 'name' => 'name' } state_reason_aliases = { 'code' => 'code', 'message' => 'message' } for filter_key, filter_value in filters if block_device_mapping_key = filter_key.split('block-device-mapping.')[1] aliased_key = block_device_mapping_aliases[block_device_mapping_key] instance_set = instance_set.reject{|instance| !instance['blockDeviceMapping'].detect {|block_device_mapping| [*filter_value].include?(block_device_mapping[aliased_key])}} elsif instance_state_key = filter_key.split('instance-state-')[1] aliased_key = instance_state_aliases[instance_state_key] instance_set = instance_set.reject{|instance| ![*filter_value].include?(instance['instanceState'][aliased_key])} elsif state_reason_key = filter_key.split('state-reason-')[1] aliased_key = state_reason_aliases[state_reason_key] instance_set = instance_set.reject{|instance| ![*filter_value].include?(instance['stateReason'][aliased_key])} elsif filter_key == "group-name" instance_set = instance_set.reject {|instance| !instance['groupSet'].include?(filter_value)} else aliased_key = aliases[filter_key] instance_set = instance_set.reject {|instance| ![*filter_value].include?(instance[aliased_key])} end end brand_new_instances = instance_set.find_all do |instance| instance['instanceState']['name'] == 'pending' && Time.now - instance['launchTime'] < Fog::Mock.delay * 2 end # Error if filtering for a brand new instance directly if (filters['instance-id'] || filters['instanceId']) && !brand_new_instances.empty? raise Fog::Compute::AWS::NotFound.new("The instance ID '#{brand_new_instances.first['instanceId']}' does not exist") end # Otherwise don't include it in the list instance_set = instance_set.reject {|instance| brand_new_instances.include?(instance) } response.status = 200 reservation_set = {} instance_set.each do |instance| case instance['instanceState']['name'] when 'pending' if Time.now - instance['launchTime'] >= Fog::Mock.delay * 2 instance['ipAddress'] = Fog::AWS::Mock.ip_address instance['originalIpAddress'] = instance['ipAddress'] instance['dnsName'] = Fog::AWS::Mock.dns_name_for(instance['ipAddress']) instance['privateIpAddress'] = Fog::AWS::Mock.private_ip_address instance['privateDnsName'] = Fog::AWS::Mock.private_dns_name_for(instance['privateIpAddress']) instance['instanceState'] = { 'code' => 16, 'name' => 'running' } end when 'rebooting' instance['instanceState'] = { 'code' => 16, 'name' => 'running' } when 'stopping' instance['instanceState'] = { 'code' => 0, 'name' => 'stopping' } instance['stateReason'] = { 'code' => 0 } when 'shutting-down' if Time.now - self.data[:deleted_at][instance['instanceId']] >= Fog::Mock.delay * 2 self.data[:deleted_at].delete(instance['instanceId']) self.data[:instances].delete(instance['instanceId']) elsif Time.now - self.data[:deleted_at][instance['instanceId']] >= Fog::Mock.delay instance['instanceState'] = { 'code' => 48, 'name' => 'terminating' } end when 'terminating' if Time.now - self.data[:deleted_at][instance['instanceId']] >= Fog::Mock.delay self.data[:deleted_at].delete(instance['instanceId']) self.data[:instances].delete(instance['instanceId']) end end if self.data[:instances][instance['instanceId']] reservation_set[instance['reservationId']] ||= { 'groupSet' => instance['groupSet'], 'groupIds' => instance['groupIds'], 'instancesSet' => [], 'ownerId' => instance['ownerId'], 'reservationId' => instance['reservationId'] } reservation_set[instance['reservationId']]['instancesSet'] << instance.reject{|key,value| !['amiLaunchIndex', 'architecture', 'blockDeviceMapping', 'clientToken', 'dnsName', 'ebsOptimized', 'hypervisor', 'iamInstanceProfile', 'imageId', 'instanceId', 'instanceState', 'instanceType', 'ipAddress', 'kernelId', 'keyName', 'launchTime', 'monitoring', 'networkInterfaces', 'ownerId', 'placement', 'platform', 'privateDnsName', 'privateIpAddress', 'productCodes', 'ramdiskId', 'reason', 'rootDeviceType', 'stateReason', 'virtualizationType'].include?(key)}.merge('tagSet' => self.data[:tag_sets][instance['instanceId']]) end end response.body = { 'requestId' => Fog::AWS::Mock.request_id, 'reservationSet' => reservation_set.values } response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/create_route.rb0000755000004100000410000001120312261242551023055 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Creates a route in a route table within a VPC. # # ==== Parameters # * RouteTableId<~String> - The ID of the route table for the route. # * DestinationCidrBlock<~String> - The CIDR address block used for the destination match. Routing decisions are based on the most specific match. # * GatewayId<~String> - The ID of an Internet gateway attached to your VPC. # * InstanceId<~String> - The ID of a NAT instance in your VPC. The operation fails if you specify an instance ID unless exactly one network interface is attached. # * NetworkInterfaceId<~String> - The ID of a network interface. # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of the request # * 'return'<~Boolean> - Returns true if the request succeeds. Otherwise, returns an error. # # {Amazon API Reference}[http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateRoute.html] def create_route(route_table_id, destination_cidr_block, internet_gateway_id=nil, instance_id=nil, network_interface_id=nil) request_vars = { 'Action' => 'CreateRoute', 'RouteTableId' => route_table_id, 'DestinationCidrBlock' => destination_cidr_block, :parser => Fog::Parsers::Compute::AWS::Basic.new } if internet_gateway_id request_vars['GatewayId'] = internet_gateway_id elsif instance_id request_vars['InstanceId'] = instance_id elsif network_interface_id request_vars['NetworkInterfaceId'] = network_interface_id end request(request_vars) end end class Mock def create_route(route_table_id, destination_cidr_block, internet_gateway_id=nil, instance_id=nil, network_interface_id=nil) instance_owner_id = nil route_table = self.data[:route_tables].find { |routetable| routetable["routeTableId"].eql? route_table_id } if !route_table.nil? && destination_cidr_block if !internet_gateway_id.nil? || !instance_id.nil? || !network_interface_id.nil? if !internet_gateway_id.nil? && self.internet_gateways.all('internet-gateway-id'=>internet_gateway_id).first.nil? raise Fog::Compute::AWS::NotFound.new("The gateway ID '#{internet_gateway_id}' does not exist") elsif !instance_id.nil? && self.servers.all('instance-id'=>instance_id).first.nil? raise Fog::Compute::AWS::NotFound.new("The instance ID '#{instance_id}' does not exist") elsif !network_interface_id.nil? && self.network_interfaces.all('networkInterfaceId'=>network_interface_id).first.nil? raise Fog::Compute::AWS::NotFound.new("The networkInterface ID '#{network_interface_id}' does not exist") elsif !route_table['routeSet'].find { |route| route['destinationCidrBlock'].eql? destination_cidr_block }.nil? raise Fog::Compute::AWS::Error, "RouteAlreadyExists => The route identified by #{destination_cidr_block} already exists." else response = Excon::Response.new route_table['routeSet'].push({ "destinationCidrBlock" => destination_cidr_block, "gatewayId" => internet_gateway_id, "instanceId"=>instance_id, "instanceOwnerId"=>instance_owner_id, "networkInterfaceId"=>network_interface_id, "state" => "pending", "origin" => "CreateRoute" }) response.status = 200 response.body = { 'requestId'=> Fog::AWS::Mock.request_id, 'return' => true } response end else message = 'MissingParameter => ' message << 'The request must contain either a gateway id, a network interface id, or an instance id' raise Fog::Compute::AWS::Error.new(message) end elsif route_table.nil? raise Fog::Compute::AWS::NotFound.new("The routeTable ID '#{route_table_id}' does not exist") elsif destination_cidr_block.empty? raise Fog::Compute::AWS::InvalidParameterValue.new("Value () for parameter destinationCidrBlock is invalid. This is not a valid CIDR block.") end end end end end end fog-1.19.0/lib/fog/aws/requests/compute/copy_image.rb0000644000004100000410000000417712261242551022521 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/copy_image' # Copy an image to a different region # # ==== Parameters # * source_image_id<~String> - The ID of the AMI to copy # * source_region<~String> - The name of the AWS region that contains the AMI to be copied # * name<~String> - The name of the new AMI in the destination region # * description<~String> - The description to set on the new AMI in the destination region # * client_token<~String> - Unique, case-sensitive identifier you provide to ensure idempotency of the request # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - id of request # * 'imageId'<~String> - id of image # # {Amazon API Reference}[http://docs.aws.amazon.com/AWSEC2/latest/CommandLineReference/ApiReference-cmd-CopyImage.html] def copy_image(source_image_id, source_region, name = nil, description = nil, client_token = nil) request( 'Action' => 'CopyImage', 'SourceImageId' => source_image_id, 'SourceRegion' => source_region, 'Name' => name, 'Description' => description, 'ClientToken' => client_token, :parser => Fog::Parsers::Compute::AWS::CopyImage.new ) end end class Mock # # Usage # # AWS[:compute].copy_image("ami-1aad5273", 'us-east-1') # def copy_image(source_image_id, source_region, name = nil, description = nil, client_token = nil) response = Excon::Response.new response.status = 200 image_id = Fog::AWS::Mock.image_id data = { 'imageId' => image_id, } self.data[:images][image_id] = data response.body = { 'requestId' => Fog::AWS::Mock.request_id }.merge!(data) response end end end end end fog-1.19.0/lib/fog/aws/requests/compute/delete_placement_group.rb0000644000004100000410000000160412261242551025103 0ustar www-datawww-datamodule Fog module Compute class AWS class Real require 'fog/aws/parsers/compute/basic' # Delete a placement group that you own # # ==== Parameters # * group_name<~String> - Name of the placement group. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'requestId'<~String> - Id of request # * 'return'<~Boolean> - success? # # {Amazon API Reference}[http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeletePlacementGroup.html] def delete_placement_group(name) request( 'Action' => 'DeletePlacementGroup', 'GroupName' => name, :idempotent => true, :parser => Fog::Parsers::Compute::AWS::Basic.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/0000755000004100000410000000000012261242551020640 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/elasticache/describe_reserved_cache_nodes.rb0000644000004100000410000000242012261242551027155 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/describe_reserved_cache_nodes' # Describe all or specified reserved Elasticache nodes # http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_DescribeReservedCacheNodes.html # ==== Parameters # * ReservedCacheNodeId <~String> - ID of node to retrieve information for. If absent, information for all nodes is returned. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def describe_reserved_cache_nodes(identifier=nil, opts={}) params = {} params['ReservedCacheNodeId'] = identifier if identifier if opts[:marker] params['Marker'] = opts[:marker] end if opts[:max_records] params['MaxRecords'] = opts[:max_records] end request({ 'Action' => 'DescribeReservedCacheNodes', :parser => Fog::Parsers::AWS::Elasticache::DescribeReservedCacheNodes.new }.merge(params)) end end class Mock def describe_db_reserved_instances(identifier=nil, opts={}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/reboot_cache_cluster.rb0000644000004100000410000000336212261242551025347 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/single_cache_cluster' # Reboots some or all of an existing cache cluster's nodes # Returns a cache cluster description # # === Required Parameters # * id <~String> - The ID of the existing cluster to be rebooted # === Optional Parameters # * nodes_to_reboot <~Array> - Array of node IDs to reboot # === Returns # * response <~Excon::Response>: # * body <~Hash> def reboot_cache_cluster(id, nodes_to_reboot) # Construct CacheNodeIdsToReboot parameters in the format: # CacheNodeIdsToReboot.member.N => "node_id" node_ids = nodes_to_reboot || [] node_id_params = node_ids.inject({}) do |node_hash, node_id| index = node_ids.index(node_id) + 1 node_hash["CacheNodeIdsToReboot.member.#{index}"] = node_id node_hash end # Merge the CacheNodeIdsToReboot parameters with the normal options request(node_id_params.merge( 'Action' => 'RebootCacheCluster', 'CacheClusterId' => id, :parser => Fog::Parsers::AWS::Elasticache::SingleCacheCluster.new )) end end class Mock def reboot_cache_cluster(id, nodes_to_reboot) response = Excon::Response.new response.body = { 'CacheCluster' => self.data[:clusters][id].merge({ 'CacheClusterStatus' => 'rebooting cache cluster nodes' }), 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/reset_cache_parameter_group.rb0000644000004100000410000000307012261242551026706 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/reset_parameter_group' # Resets an existing cache parameter group # Returns a the name of the modified parameter group # # === Required Parameters # * id <~String> - The ID of the parameter group to be modified # === Optional Parameters # * parameter_names <~Array> - The parameters to reset # === Returns # * response <~Excon::Response>: # * body <~Hash> def reset_cache_parameter_group(id, parameter_names = []) # Construct Parameter resets in the format: # ParameterNameValues.member.N => "param_name" parameter_changes = parameter_names.inject({}) do |new_args, param| index = parameter_names.index(param) + 1 new_args["ParameterNameValues.member.#{index}"] = param new_args end if parameter_changes.empty? parameter_changes = {'ResetAllParameters' => 'true'} end # Merge the Cache Security Group parameters with the normal options request(parameter_changes.merge( 'Action' => 'ResetCacheParameterGroup', 'CacheParameterGroupName' => id, :parser => Fog::Parsers::AWS::Elasticache::ResetParameterGroup.new )) end end class Mock def reset_cache_parameter_group(id, parameter_names) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/delete_cache_cluster.rb0000644000004100000410000000222212261242551025311 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/describe_cache_clusters' # Deletes a Cache Cluster # # === Parameter (required): # * id <~String> - The ID of the cache cluster to delete # === Returns # * response <~Excon::Response>: # * body <~Hash> def delete_cache_cluster(cluster_id) request( 'Action' => 'DeleteCacheCluster', 'CacheClusterId' => cluster_id, :parser => Fog::Parsers::AWS::Elasticache::DescribeCacheClusters.new ) end end class Mock def delete_cache_cluster(cluster_id) response = Excon::Response.new cluster = self.data[:clusters][cluster_id] cluster['CacheClusterStatus'] = 'deleting' response.body = { 'CacheClusters' => self.data[:clusters].values, 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } self.data[:clusters].delete(cluster_id) response end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/describe_engine_default_parameters.rb0000644000004100000410000000227012261242551030222 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/describe_engine_default_parameters' # Returns the default engine and system parameter information # for the specified cache engine. # # === Parameters (optional) # * options <~Hash>: # * :engine <~String> - the engine whose parameters are requested # * :marker <~String> - marker provided in the previous request # * :max_records <~Integer> - the maximum number of records to include def describe_engine_default_parameters(options = {}) request({ 'Action' => 'DescribeEngineDefaultParameters', 'CacheParameterGroupFamily' => options[:engine] || 'memcached1.4', 'Marker' => options[:marker], 'MaxRecords' => options[:max_records], :parser => Fog::Parsers::AWS::Elasticache::DescribeEngineDefaultParameters.new }) end end class Mock def describe_engine_defalut_parameters(options = {}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/describe_events.rb0000644000004100000410000000340112261242551024327 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/event_list' # Returns a list of service events # # For more information see: # http://docs.amazonwebservices.com/AmazonElastiCache/latest/APIReference/API_DescribeEvents.html # # === Parameters (optional) # * options <~Hash> (optional): # * :start_time <~DateTime> - starting time for event records # * :end_time <~DateTime> - ending time for event records # * :duration <~Integer> - time span for event records # * :marker <~String> - marker provided in the previous request # * :max_records <~Integer> - the maximum number of records to include # * :source_identifier <~String> - identifier of the event source # * :source_type <~String> - event type, one of: # (cache-cluster | cache-parameter-group | cache-security-group) # === Returns # * response <~Excon::Response>: # * body <~Hash> def describe_events(options = {}) request( 'Action' => 'DescribeEvents', 'StartTime' => options[:start_time], 'EndTime' => options[:end_time], 'Duration' => options[:duration], 'Marker' => options[:marker], 'MaxRecords' => options[:max_records], 'SourceIdentifier' => options[:source_identifier], 'SourceType' => options[:source_type], :parser => Fog::Parsers::AWS::Elasticache::EventListParser.new ) end end class Mock def describe_events Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/create_cache_parameter_group.rb0000644000004100000410000000223212261242551027026 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/single_parameter_group' # creates a cache parameter group # # === Parameters # * name <~String> - The name for the Cache Parameter Group # === Optional Parameters # * description <~String> - The description for the Cache Parameter Group # * family <~String> - The description for the Cache Parameter Group # === Returns # * response <~Excon::Response>: # * body <~Hash> def create_cache_parameter_group(name, description = name, family = 'memcached1.4') request({ 'Action' => 'CreateCacheParameterGroup', 'CacheParameterGroupName' => name, 'Description' => description, 'CacheParameterGroupFamily' => family, :parser => Fog::Parsers::AWS::Elasticache::SingleParameterGroup.new }) end end class Mock def create_cache_parameter_group(name, description = name, family = 'memcached1.4') Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/delete_cache_security_group.rb0000644000004100000410000000212712261242551026717 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/base' # deletes a cache security group # # === Parameters # * name <~String> - The name for the Cache Security Group # === Returns # * response <~Excon::Response>: # * body <~Hash> def delete_cache_security_group(name) request({ 'Action' => 'DeleteCacheSecurityGroup', 'CacheSecurityGroupName' => name, :parser => Fog::Parsers::AWS::Elasticache::Base.new }) end end class Mock def delete_cache_security_group(name) if self.data[:security_groups].delete(name) Excon::Response.new( { :status => 200, :body => { 'ResponseMetadata'=>{ 'RequestId'=> Fog::AWS::Mock.request_id } } } ) else raise Fog::AWS::RDS::NotFound.new("DBSecurityGroupNotFound => #{name} not found") end end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/describe_cache_parameters.rb0000644000004100000410000000232212261242551026312 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/describe_cache_parameters' # Returns a list of CacheParameterGroup descriptions # # === Parameters (optional) # * name <~String> - The name of an existing cache parameter group # * options <~Hash> (optional): # * :marker <~String> - marker provided in the previous request # * :max_records <~Integer> - the maximum number of records to include # * :source <~String> - the parameter types to return. def describe_cache_parameters(name = nil, options = {}) request({ 'Action' => 'DescribeCacheParameters', 'CacheParameterGroupName' => name, 'Marker' => options[:marker], 'MaxRecords' => options[:max_records], 'Source' => options[:source], :parser => Fog::Parsers::AWS::Elasticache::DescribeCacheParameters.new }) end end class Mock def describe_cache_parameters(name = nil, options = {}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/describe_cache_security_groups.rb0000644000004100000410000000502312261242551027416 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/describe_security_groups' # Returns a list of CacheSecurityGroup descriptions # # === Parameters (optional) # * name <~String> - The name of an existing cache security group # * options <~Hash> (optional): # * :marker <~String> - marker provided in the previous request # * :max_records <~Integer> - the maximum number of records to include def describe_cache_security_groups(name = nil, options = {}) request({ 'Action' => 'DescribeCacheSecurityGroups', 'CacheSecurityGroupName' => name, 'Marker' => options[:marker], 'MaxRecords' => options[:max_records], :parser => Fog::Parsers::AWS::Elasticache::DescribeSecurityGroups.new }.merge(options)) end end class Mock def describe_cache_security_groups(name = nil, opts={}) if name sec_group_set = [self.data[:security_groups][name]].compact raise Fog::AWS::Elasticache::NotFound.new("Security Group #{name} not found") if sec_group_set.empty? else sec_group_set = self.data[:security_groups].values end # TODO: refactor to not delete items that we're iterating over. Causes # model tests to fail (currently pending) sec_group_set.each do |sec_group| # TODO: refactor to not delete items that we're iterating over. Causes # model tests to fail (currently pending) sec_group["EC2SecurityGroups"].each do |ec2_secg| if ec2_secg["Status"] == "authorizing" || ec2_secg["Status"] == "revoking" ec2_secg[:tmp] ||= Time.now + Fog::Mock.delay * 2 if ec2_secg[:tmp] <= Time.now ec2_secg["Status"] = "authorized" if ec2_secg["Status"] == "authorizing" ec2_secg.delete(:tmp) sec_group["EC2SecurityGroups"].delete(ec2_secg) if ec2_secg["Status"] == "revoking" end end end end Excon::Response.new( { :status => 200, :body => { "ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id }, "CacheSecurityGroups" => sec_group_set } } ) end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/authorize_cache_security_group_ingress.rb0000644000004100000410000000416012261242551031220 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/single_security_group' # Authorize ingress to a CacheSecurityGroup using EC2 Security Groups # # === Parameters # * name <~String> - The name of the cache security group # * ec2_name <~String> - The name of the EC2 security group to authorize # * ec2_owner_id <~String> - The AWS Account Number of the EC2 security group # === Returns # * response <~Excon::Response>: # * body <~Hash> def authorize_cache_security_group_ingress(name, ec2_name, ec2_owner_id) request({ 'Action' => 'AuthorizeCacheSecurityGroupIngress', 'CacheSecurityGroupName' => name, 'EC2SecurityGroupName' => ec2_name, 'EC2SecurityGroupOwnerId' => ec2_owner_id, :parser => Fog::Parsers::AWS::Elasticache::SingleSecurityGroup.new }) end end class Mock def authorize_cache_security_group_ingress(name, ec2_name, ec2_owner_id) opts = { 'EC2SecurityGroupName' => ec2_name, 'EC2SecurityGroupOwnerId' => ec2_owner_id } if sec_group = self.data[:security_groups][name] if sec_group['EC2SecurityGroups'].detect{|h| h['EC2SecurityGroupName'] == opts['EC2SecurityGroupName']} raise Fog::AWS::Elasticache::AuthorizationAlreadyExists.new("AuthorizationAlreadyExists => #{opts['EC2SecurityGroupName']} is alreay defined") end sec_group['EC2SecurityGroups'] << opts.merge({'Status' => 'authorizing'}) Excon::Response.new( { :status => 200, :body => { 'ResponseMetadata'=>{ 'RequestId'=> Fog::AWS::Mock.request_id }, 'CacheSecurityGroup' => sec_group } } ) else raise Fog::AWS::Elasticache::NotFound.new("CacheSecurityGroupNotFound => #{name} not found") end end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/modify_cache_parameter_group.rb0000644000004100000410000000316612261242551027061 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/modify_parameter_group' # Modifies an existing cache parameter group # Returns a the name of the modified parameter group # # === Required Parameters # * id <~String> - The ID of the parameter group to be modified # * new_parameters <~Hash> - The parameters to modify, and their values # === Returns # * response <~Excon::Response>: # * body <~Hash> def modify_cache_parameter_group(id, new_parameters) # Construct Parameter Modifications in the format: # ParameterNameValues.member.N.ParameterName => "param_name" # ParameterNameValues.member.N.ParameterValue => "param_value" n = 0 # n is the parameter index parameter_changes = new_parameters.inject({}) do |new_args,pair| n += 1 new_args["ParameterNameValues.member.#{n}.ParameterName"] = pair[0] new_args["ParameterNameValues.member.#{n}.ParameterValue"] = pair[1] new_args end # Merge the Cache Security Group parameters with the normal options request(parameter_changes.merge( 'Action' => 'ModifyCacheParameterGroup', 'CacheParameterGroupName' => id, :parser => Fog::Parsers::AWS::Elasticache::ModifyParameterGroup.new )) end end class Mock def modify_cache_parameter_group(id, new_parameters) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/delete_cache_parameter_group.rb0000644000004100000410000000136612261242551027034 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/base' # deletes a cache parameter group # # === Parameters # * name <~String> - The name for the Cache Parameter Group # === Returns # * response <~Excon::Response>: # * body <~Hash> def delete_cache_parameter_group(name) request({ 'Action' => 'DeleteCacheParameterGroup', 'CacheParameterGroupName' => name, :parser => Fog::Parsers::AWS::Elasticache::Base.new }) end end class Mock def delete_cache_parameter_group(name) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/modify_cache_cluster.rb0000644000004100000410000001131012261242551025334 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/single_cache_cluster' # Modifies an existing cache cluster # Returns a cache cluster description # # === Required Parameters # * id <~String> - The ID of the existing cluster to be modified # === Optional Parameters # * options <~Hash> - All optional parameters should be set in this Hash: # * :apply_immediately <~TrueFalseClass> - whether to apply changes now # * :auto_minor_version_upgrade <~TrueFalseClass> # * :num_nodes <~Integer> - The number of nodes in the Cluster # * :nodes_to_remove <~Array> - Array of node IDs to delete # * :security_group_names <~Array> - Array of Elasticache::SecurityGroup names # * :parameter_group_name <~String> - Name of the Cluster's ParameterGroup # * :engine_version <~String> - The Cluster's caching software version # * :notification_topic_arn <~String> - Amazon SNS Resource Name # * :notification_topic_status <~String> - Amazon SNS Topic status # * :preferred_maintenance_window <~String> # === Returns # * response <~Excon::Response>: # * body <~Hash> def modify_cache_cluster(id, options = {}) # Construct Cache Security Group parameters in the format: # CacheSecurityGroupNames.member.N => "security_group_name" group_names = options[:security_group_names] || [] sec_group_params = group_names.inject({}) do |group_hash, name| index = group_names.index(name) + 1 group_hash["CacheSecurityGroupNames.member.#{index}"] = name group_hash end # Construct CacheNodeIdsToRemove parameters in the format: # CacheNodeIdsToRemove.member.N => "node_id" node_ids = options[:nodes_to_remove] || [] node_id_params = node_ids.inject({}) do |node_hash, node_id| index = node_ids.index(node_id) + 1 node_hash["CacheNodeIdsToRemove.member.#{index}"] = node_id node_hash end # Merge the Cache Security Group parameters with the normal options request(node_id_params.merge(sec_group_params.merge( 'Action' => 'ModifyCacheCluster', 'CacheClusterId' => id.strip, 'ApplyImmediately' => options[:apply_immediately], 'NumCacheNodes' => options[:num_nodes], 'AutoMinorVersionUpgrade' => options[:auto_minor_version_upgrade], 'CacheParameterGroupName' => options[:parameter_group_name], 'EngineVersion' => options[:engine_version], 'NotificationTopicArn' => options[:notification_topic_arn], 'NotificationTopicStatus' => options[:notification_topic_status], 'PreferredMaintenanceWindow' => options[:preferred_maintenance_window], :parser => Fog::Parsers::AWS::Elasticache::SingleCacheCluster.new ))) end end class Mock def modify_cache_cluster(id, options = {}) response = Excon::Response.new cluster = self.data[:clusters][id] pending_values = Hash.new # For any given option, update the cluster's corresponding value { :auto_minor_version_upgrade => 'AutoMinorVersionUpgrade', :preferred_maintenance_window => 'PreferredMaintenanceWindow', :engine_version => 'EngineVersion', :num_nodes => 'NumCacheNodes', }.each do |option, cluster_key| if options[option] != nil cluster[cluster_key] = options[option].to_s pending_values[cluster_key] = options[option] end end cache['CacheParameterGroup'] = { 'CacheParameterGroupName' => options[:parameter_group_name] } if options[:parameter_group_name] if options[:num_nodes] || options[:engine_version] cluster['CacheNodes'] = create_cache_nodes(cluster['CacheClusterId'], options[:num_nodes]) cluster['NumCacheNodes'] = cluster['CacheNodes'].size end if options[:nodes_to_remove] pending_values['CacheNodeId'] = options[:nodes_to_remove].join(',') end response.body = { 'CacheCluster' => cluster.merge({ 'PendingModifiedValues' => pending_values }), 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/describe_cache_clusters.rb0000644000004100000410000000350612261242551026020 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/describe_cache_clusters' # Returns a list of Cache Cluster descriptions # # === Parameters (optional) # * id - The ID of an existing cache cluster # * options <~Hash> (optional): # * :marker <~String> - marker provided in the previous request # * :max_records <~Integer> - the maximum number of records to include # * :show_node_info <~Boolean> - whether to show node info # === Returns # * response <~Excon::Response>: # * body <~Hash> def describe_cache_clusters(id = nil, options = {}) request({ 'Action' => 'DescribeCacheClusters', 'CacheClusterId' => id, 'Marker' => options[:marker], 'MaxRecords' => options[:max_records], 'ShowCacheNodeInfo' => options[:show_node_info], :parser => Fog::Parsers::AWS::Elasticache::DescribeCacheClusters.new }) end end class Mock def describe_cache_clusters(id = nil, options = {}) response = Excon::Response.new all_clusters = self.data[:clusters].values.map do |cluster| cluster.merge!(options[:show_node_info] ? { 'CacheClusterCreateTime' => DateTime.now - 60, 'PreferredAvailabilityZone' => 'us-east-1a' } : {}) end if (id != nil) && (all_clusters.empty?) raise Fog::AWS::Elasticache::NotFound end response.body = { 'CacheClusters' => all_clusters, 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/create_cache_security_group.rb0000644000004100000410000000312612261242551026720 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/single_security_group' # creates a cache security group # # === Parameters # * name <~String> - The name for the Cache Security Group # * description <~String> - The description for the Cache Security Group # === Returns # * response <~Excon::Response>: # * body <~Hash> def create_cache_security_group(name, description = name) request({ 'Action' => 'CreateCacheSecurityGroup', 'CacheSecurityGroupName' => name, 'Description' => description, :parser => Fog::Parsers::AWS::Elasticache::SingleSecurityGroup.new }) end end class Mock def create_cache_security_group(name, description = name) if self.data[:security_groups][name] raise Fog::AWS::Elasticache::IdentifierTaken.new("CacheClusterAlreadyExists => The security group '#{name}' already exists") end data = { 'CacheSecurityGroupName' => name, 'Description' => description, 'EC2SecurityGroups' => [], 'OwnerId' => '0123456789' } self.data[:security_groups][name] = data Excon::Response.new( { :body => { 'ResponseMetadata'=>{ 'RequestId'=> Fog::AWS::Mock.request_id }, 'CacheSecurityGroup' => data } } ) end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/describe_cache_parameter_groups.rb0000644000004100000410000000216712261242551027535 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/describe_parameter_groups' # Returns a list of CacheParameterGroup descriptions # # === Parameters (optional) # * name <~String> - The name of an existing cache parameter group # * options <~Hash> (optional): # * :marker <~String> - marker provided in the previous request # * :max_records <~Integer> - the maximum number of records to include def describe_cache_parameter_groups(name = nil, options = {}) request({ 'Action' => 'DescribeCacheParameterGroups', 'CacheParameterGroupName' => name, 'Marker' => options[:marker], 'MaxRecords' => options[:max_records], :parser => Fog::Parsers::AWS::Elasticache::DescribeParameterGroups.new }.merge(options)) end end class Mock def describe_cache_parameter_groups(name = nil, options = {}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/revoke_cache_security_group_ingress.rb0000644000004100000410000000214712261242551030504 0ustar www-datawww-data module Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/single_security_group' # Revoke ingress to a CacheSecurityGroup using EC2 Security Groups # # === Parameters # * name <~String> - The name of the cache security group # * ec2_name <~String> - The name of the EC2 security group to revoke # * ec2_owner_id <~String> - The AWS Account Number of the EC2 security group # === Returns # * response <~Excon::Response>: # * body <~Hash> def revoke_cache_security_group_ingress(name, ec2_name, ec2_owner_id) request({ 'Action' => 'RevokeCacheSecurityGroupIngress', 'CacheSecurityGroupName' => name, 'EC2SecurityGroupName' => ec2_name, 'EC2SecurityGroupOwnerId' => ec2_owner_id, :parser => Fog::Parsers::AWS::Elasticache::SingleSecurityGroup.new }) end end class Mock def revoke_cache_security_group_ingress Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/elasticache/create_cache_cluster.rb0000644000004100000410000001034212261242551025314 0ustar www-datawww-datamodule Fog module AWS class Elasticache class Real require 'fog/aws/parsers/elasticache/single_cache_cluster' # creates a cache cluster # # === Required Parameters # * id <~String> - A unique cluster ID - 20 characters max. # === Optional Parameters # * options <~Hash> - All optional parameters should be set in this Hash: # * :node_type <~String> - The size (flavor) of the cache Nodes # * :security_group_names <~Array> - Array of Elasticache::SecurityGroup names # * :num_nodes <~Integer> - The number of nodes in the Cluster # * :auto_minor_version_upgrade <~TrueFalseClass> # * :parameter_group_name <~String> - Name of the Cluster's ParameterGroup # * :engine <~String> - The Cluster's caching software (memcached) # * :engine_version <~String> - The Cluster's caching software version # * :notification_topic_arn <~String> - Amazon SNS Resource Name # * :port <~Integer> - The memcached port number # * :preferred_availablility_zone <~String> # * :preferred_maintenance_window <~String> # === Returns # * response <~Excon::Response>: # * body <~Hash> def create_cache_cluster(id, options = {}) # Construct Cache Security Group parameters in the format: # CacheSecurityGroupNames.member.N => "security_group_name" group_names = options[:security_group_names] || ['default'] sec_group_params = group_names.inject({}) do |group_hash, name| index = group_names.index(name) + 1 group_hash["CacheSecurityGroupNames.member.#{index}"] = name group_hash end # Merge the Cache Security Group parameters with the normal options request(sec_group_params.merge( 'Action' => 'CreateCacheCluster', 'CacheClusterId' => id.strip, 'CacheNodeType' => options[:node_type] || 'cache.m1.large', 'Engine' => options[:engine] || 'memcached', 'NumCacheNodes' => options[:num_nodes] || 1, 'AutoMinorVersionUpgrade' => options[:auto_minor_version_upgrade], 'CacheParameterGroupName' => options[:parameter_group_name], 'EngineVersion' => options[:engine_version], 'NotificationTopicArn' => options[:notification_topic_arn], 'Port' => options[:port], 'PreferredAvailabilityZone' => options[:preferred_availablility_zone], 'PreferredMaintenanceWindow' => options[:preferred_maintenance_window], :parser => Fog::Parsers::AWS::Elasticache::SingleCacheCluster.new )) end end class Mock def create_cache_cluster(id, options = {}) response = Excon::Response.new cluster = { # create an in-memory representation of this cluster 'CacheClusterId' => id.strip, 'NumCacheNodes' => options[:num_nodes] || 1, 'CacheNodeType' => options[:node_type] || 'cache.m1.large', 'Engine' => options[:engine] || 'memcached', 'EngineVersion' => options[:engine_version] || '1.4.5', 'CacheClusterStatus' => 'available', 'CacheNodes' => create_cache_nodes(id.strip, options[:num_nodes]), 'CacheSecurityGroups' => [], 'CacheParameterGroup' => { 'CacheParameterGroupName' => options[:parameter_group_name] || 'default.memcached1.4' }, 'PendingModifiedValues' => {}, 'AutoMinorVersionUpgrade' => options[:auto_minor_version_upgrade] || 'true', 'PreferredMaintenanceWindow' => options[:preferred_maintenance_window] || 'sun:05:00-sun:09:00', } self.data[:clusters][id] = cluster # store the in-memory cluster response.body = { 'CacheCluster' => cluster.merge({'CacheClusterStatus' => 'creating'}), 'ResponseMetadata' => { 'RequestId' => Fog::AWS::Mock.request_id } } response end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_formation/0000755000004100000410000000000012261242551021557 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/cloud_formation/describe_stacks.rb0000644000004100000410000000226212261242551025236 0ustar www-datawww-datamodule Fog module AWS class CloudFormation class Real require 'fog/aws/parsers/cloud_formation/describe_stacks' # Describe stacks. # # @param options [Hash] # @option options StackName [String] Name of the stack to describe. # # @return [Excon::Response] # * body [Hash]: # * Stacks [Array] - Matching stacks # * stack [Hash]: # * StackName [String] - # * StackId [String] - # * CreationTime [String] - # * StackStatus [String] - # * DisableRollback [String] - # * Outputs [Array] - # * output [Hash]: # * OutputKey [String] - # * OutputValue [String] - # # @see http://docs.amazonwebservices.com/AWSCloudFormation/latest/APIReference/API_DescribeStacks.html def describe_stacks(options = {}) request({ 'Action' => 'DescribeStacks', :parser => Fog::Parsers::AWS::CloudFormation::DescribeStacks.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_formation/validate_template.rb0000644000004100000410000000167312261242551025577 0ustar www-datawww-datamodule Fog module AWS class CloudFormation class Real require 'fog/aws/parsers/cloud_formation/validate_template' # Describe stacks. # # @param [Hash] options # @option options [String] TemplateBody template structure # @option options [String] TemplateURL template url # # @return [Excon::Response] # * body [Hash]: # * Description [String] - description found within the template # * Parameters [String] - list of template parameter structures # # @see http://docs.amazonwebservices.com/AWSCloudFormation/latest/APIReference/API_ValidateTemplate.html # def validate_template(options = {}) request({ 'Action' => 'ValidateTemplate', :parser => Fog::Parsers::AWS::CloudFormation::ValidateTemplate.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_formation/list_stack_resources.rb0000644000004100000410000000211712261242551026337 0ustar www-datawww-datamodule Fog module AWS class CloudFormation class Real require 'fog/aws/parsers/cloud_formation/list_stack_resources' # List stack resources. # # @param options [Hash] # @option options StackName [String] Name of the stack to describe. # # @return [Excon::Response] # * body [Hash]: # * StackResourceSummaries [Array] - Matching stacks # * resources [Hash]: # * ResourceStatus [String] - # * LogicalResourceId [String] - # * PhysicalResourceId [String] - # * ResourceType [String] - # * LastUpdatedTimestamp [Time] - # # # @see http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_ListStacks.html def list_stack_resources(options = {}) request({ 'Action' => 'ListStackResources', :parser => Fog::Parsers::AWS::CloudFormation::ListStackResources.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_formation/list_stacks.rb0000644000004100000410000000201312261242551024423 0ustar www-datawww-datamodule Fog module AWS class CloudFormation class Real require 'fog/aws/parsers/cloud_formation/list_stacks' # List stacks. # # @param options [Hash] # # @return [Excon::Response] # * body [Hash]: # * StackSummaries [Array] - Matching stacks # * stack [Hash]: # * StackId [String] - # * StackName [String] - # * TemplateDescription [String] - # * CreationTime [Time] - # * DeletionTime [Time] - # * StackStatus [String] - # * DeletionTime [String] - # # # @see http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_ListStacks.html def list_stacks(options = {}) request({ 'Action' => 'ListStacks', :parser => Fog::Parsers::AWS::CloudFormation::ListStacks.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_formation/update_stack.rb0000644000004100000410000000400612261242551024553 0ustar www-datawww-datamodule Fog module AWS class CloudFormation class Real require 'fog/aws/parsers/cloud_formation/update_stack' # Update a stack. # # @param [String] stack_name Name of the stack to update. # @param [Hash] options # * TemplateBody [String] Structure containing the template body. # or (one of the two Template parameters is required) # * TemplateURL [String] URL of file containing the template body. # * Parameters [Hash] Hash of providers to supply to template. # * Capabilities [Array] List of capabilties the stack is granted. Currently CAPABILITY_IAM for allowing the creation of IAM resources. # # @return [Excon::Response] # * body [Hash]: # * StackId [String] - Id of the stack being updated # # @see http://docs.amazonwebservices.com/AWSCloudFormation/latest/APIReference/API_UpdateStack.html # def update_stack(stack_name, options = {}) params = { 'StackName' => stack_name, } if options['Parameters'] options['Parameters'].keys.each_with_index do |key, index| index += 1 # params are 1-indexed params.merge!({ "Parameters.member.#{index}.ParameterKey" => key, "Parameters.member.#{index}.ParameterValue" => options['Parameters'][key] }) end end if options['TemplateBody'] params['TemplateBody'] = options['TemplateBody'] elsif options['TemplateURL'] params['TemplateURL'] = options['TemplateURL'] end if options['Capabilities'] params.merge!(Fog::AWS.indexed_param("Capabilities.member", [*options['Capabilities']])) end request({ 'Action' => 'UpdateStack', :parser => Fog::Parsers::AWS::CloudFormation::UpdateStack.new }.merge!(params)) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_formation/describe_stack_events.rb0000644000004100000410000000261112261242551026435 0ustar www-datawww-datamodule Fog module AWS class CloudFormation class Real require 'fog/aws/parsers/cloud_formation/describe_stack_events' # Describe stack events. # # @param stack_name [String] stack name to return events for. # @param options [Hash] # @option options NextToken [String] Identifies the start of the next list of events, if there is one. # # @return [Excon::Response] # * body [Hash]: # * StackEvents [Array] - Matching resources # * event [Hash]: # * EventId [String] - # * StackId [String] - # * StackName [String] - # * LogicalResourceId [String] - # * PhysicalResourceId [String] - # * ResourceType [String] - # * Timestamp [Time] - # * ResourceStatus [String] - # * ResourceStatusReason [String] - # # @see http://docs.amazonwebservices.com/AWSCloudFormation/latest/APIReference/API_DescribeStackEvents.html def describe_stack_events(stack_name, options = {}) request({ 'Action' => 'DescribeStackEvents', 'StackName' => stack_name, :parser => Fog::Parsers::AWS::CloudFormation::DescribeStackEvents.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_formation/get_template.rb0000644000004100000410000000142712261242551024562 0ustar www-datawww-datamodule Fog module AWS class CloudFormation class Real require 'fog/aws/parsers/cloud_formation/get_template' # Describe stacks. # # @param stack_name [String] stack name to get template from # # @return [Excon::Response] # * body [Hash]: # * TemplateBody [String] - structure containing the template body (json) # # @see http://docs.amazonwebservices.com/AWSCloudFormation/latest/APIReference/API_GetTemplate.html def get_template(stack_name) request( 'Action' => 'GetTemplate', 'StackName' => stack_name, :parser => Fog::Parsers::AWS::CloudFormation::GetTemplate.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_formation/create_stack.rb0000644000004100000410000000631012261242551024534 0ustar www-datawww-datamodule Fog module AWS class CloudFormation class Real require 'fog/aws/parsers/cloud_formation/create_stack' # Create a stack. # # * stack_name [String] Name of the stack to create. # * options [Hash]: # * TemplateBody [String] Structure containing the template body. # or (one of the two Template parameters is required) # * TemplateURL [String] URL of file containing the template body. # * DisableRollback [Boolean] Controls rollback on stack creation failure, defaults to false. # * NotificationARNs [Array] List of SNS topics to publish events to. # * Parameters [Hash] Hash of providers to supply to template # * TimeoutInMinutes [Integer] Minutes to wait before status is set to CREATE_FAILED # * Capabilities [Array] List of capabilties the stack is granted. Currently CAPABILITY_IAM for allowing the creation of IAM resources # # @return [Excon::Response]: # * body [Hash: # * StackId [String] - Id of the new stack # # @see http://docs.amazonwebservices.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html def create_stack(stack_name, options = {}) params = { 'StackName' => stack_name, } if options['DisableRollback'] params['DisableRollback'] = options['DisableRollback'] end if options['NotificationARNs'] params.merge!(Fog::AWS.indexed_param("NotificationARNs.member", [*options['NotificationARNs']])) end if options['Parameters'] options['Parameters'].keys.each_with_index do |key, index| index += 1 # params are 1-indexed params.merge!({ "Parameters.member.#{index}.ParameterKey" => key, "Parameters.member.#{index}.ParameterValue" => options['Parameters'][key] }) end end num_tags = 0 if options['Tags'] options['Tags'].keys.each_with_index do |key, index| index += 1 # tags are 1-indexed num_tags += 1 # 10 tag max params.merge!({ "Tags.member.#{index}.Key" => key, "Tags.member.#{index}.Value" => options['Tags'][key] }) end end if num_tags > 10 raise ArgumentError.new("a maximum of 10 tags can be specified <#{num_tags}>") end if options['TemplateBody'] params['TemplateBody'] = options['TemplateBody'] elsif options['TemplateURL'] params['TemplateURL'] = options['TemplateURL'] end if options['TimeoutInMinutes'] params['TimeoutInMinutes'] = options['TimeoutInMinutes'] end if options['Capabilities'] params.merge!(Fog::AWS.indexed_param("Capabilities.member", [*options['Capabilities']])) end request({ 'Action' => 'CreateStack', :parser => Fog::Parsers::AWS::CloudFormation::CreateStack.new }.merge!(params)) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_formation/delete_stack.rb0000644000004100000410000000122412261242551024532 0ustar www-datawww-datamodule Fog module AWS class CloudFormation class Real require 'fog/aws/parsers/cloud_formation/basic' # Delete a stack. # # @param stack_name String] Name of the stack to create. # # @return [Excon::Response] # # @see http://docs.amazonwebservices.com/AWSCloudFormation/latest/APIReference/API_DeleteStack.html def delete_stack(stack_name) request( 'Action' => 'DeleteStack', 'StackName' => stack_name, :parser => Fog::Parsers::AWS::CloudFormation::Basic.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/cloud_formation/describe_stack_resources.rb0000644000004100000410000000270412261242551027146 0ustar www-datawww-datamodule Fog module AWS class CloudFormation class Real require 'fog/aws/parsers/cloud_formation/describe_stack_resources' # Describe stack resources. # # @param options Hash]: # * PhysicalResourceId [String] name or unique identifier that corresponds to a physical instance ID # or (one of PhysicalResourceId and StackName is required) # * StackName [String] Only return events related to this stack name # * LogicalResourceId [String] Logical name of the resource as specified in the template # # @return [Excon::Response] # * body [Hash]: # * StackResources [Array] - Matching resources # * resource [Hash]: # * StackId [String] - # * StackName [String] - # * LogicalResourceId [String] - # * PhysicalResourceId [String] - # * ResourceType [String] - # * Timestamp [Time] - # * ResourceStatus [String] - # # @see http://docs.amazonwebservices.com/AWSCloudFormation/latest/APIReference/API_DescribeStackResources.html def describe_stack_resources(options = {}) request({ 'Action' => 'DescribeStackResources', :parser => Fog::Parsers::AWS::CloudFormation::DescribeStackResources.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/sns/0000755000004100000410000000000012261242551017176 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/sns/list_topics.rb0000644000004100000410000000120412261242551022054 0ustar www-datawww-datamodule Fog module AWS class SNS class Real require 'fog/aws/parsers/sns/list_topics' # List topics # # ==== Parameters # * options<~Hash>: # * 'NextToken'<~String> - Token returned from previous request, used for pagination # # ==== See Also # http://docs.amazonwebservices.com/sns/latest/api/API_ListTopics.html # def list_topics(options = {}) request({ 'Action' => 'ListTopics', :parser => Fog::Parsers::AWS::SNS::ListTopics.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/sns/delete_topic.rb0000644000004100000410000000113412261242551022162 0ustar www-datawww-datamodule Fog module AWS class SNS class Real require 'fog/aws/parsers/sns/delete_topic' # Delete a topic # # ==== Parameters # * arn<~String> - The Arn of the topic to delete # # ==== See Also # http://docs.amazonwebservices.com/sns/latest/api/API_DeleteTopic.html # def delete_topic(arn) request({ 'Action' => 'DeleteTopic', 'TopicArn' => arn.strip, :parser => Fog::Parsers::AWS::SNS::DeleteTopic.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/sns/subscribe.rb0000644000004100000410000000153312261242551021506 0ustar www-datawww-datamodule Fog module AWS class SNS class Real require 'fog/aws/parsers/sns/subscribe' # Create a subscription # # ==== Parameters # * arn<~String> - Arn of topic to subscribe to # * endpoint<~String> - Endpoint to notify # * protocol<~String> - Protocol to notify endpoint with, in ['email', 'email-json', 'http', 'https', 'sqs'] # # ==== See Also # http://docs.amazonwebservices.com/sns/latest/api/API_Subscribe.html # def subscribe(arn, endpoint, protocol) request({ 'Action' => 'Subscribe', 'Endpoint' => endpoint, 'Protocol' => protocol, 'TopicArn' => arn.strip, :parser => Fog::Parsers::AWS::SNS::Subscribe.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/sns/get_topic_attributes.rb0000644000004100000410000000122512261242551023746 0ustar www-datawww-datamodule Fog module AWS class SNS class Real require 'fog/aws/parsers/sns/get_topic_attributes' # Get attributes of a topic # # ==== Parameters # * arn<~Hash>: The Arn of the topic to get attributes for # # ==== See Also # http://docs.amazonwebservices.com/sns/latest/api/API_GetTopicAttributes.html # def get_topic_attributes(arn) request({ 'Action' => 'GetTopicAttributes', 'TopicArn' => arn.strip, :parser => Fog::Parsers::AWS::SNS::GetTopicAttributes.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/sns/remove_permission.rb0000644000004100000410000000074412261242551023275 0ustar www-datawww-datamodule Fog module AWS class SNS class Real require 'fog/aws/parsers/sns/remove_permission' def remove_permission(options = {}) request({ 'Action' => 'RemovePermission', :parser => Fog::Parsers::AWS::SNS::RemovePermission.new }.merge!(options)) end end class Mock def remove_permission(options = {}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/sns/confirm_subscription.rb0000644000004100000410000000170112261242551023763 0ustar www-datawww-datamodule Fog module AWS class SNS class Real require 'fog/aws/parsers/sns/confirm_subscription' # Confirm a subscription # # ==== Parameters # * arn<~String> - Arn of topic to confirm subscription to # * token<~String> - Token sent to endpoint during subscribe action # * options<~Hash>: # * AuthenticateOnUnsubscribe<~Boolean> - whether or not unsubscription should be authenticated, defaults to false # # ==== See Also # http://docs.amazonwebservices.com/sns/latest/api/API_ConfirmSubscription.html # def confirm_subscription(arn, token, options = {}) request({ 'Action' => 'ConfirmSubscription', 'Token' => token, 'TopicArn' => arn.strip, :parser => Fog::Parsers::AWS::SNS::ConfirmSubscription.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/sns/set_topic_attributes.rb0000644000004100000410000000170412261242551023764 0ustar www-datawww-datamodule Fog module AWS class SNS class Real require 'fog/aws/parsers/sns/set_topic_attributes' # Set attributes of a topic # # ==== Parameters # * arn<~Hash> - The Arn of the topic to get attributes for # * attribute_name<~String> - Name of attribute to set, in ['DisplayName', 'Policy'] # * attribute_value<~String> - Value to set attribute to # # ==== See Also # http://docs.amazonwebservices.com/sns/latest/api/API_SetTopicAttributes.html # def set_topic_attributes(arn, attribute_name, attribute_value) request({ 'Action' => 'SetTopicAttributes', 'AttributeName' => attribute_name, 'AttributeValue' => attribute_value, 'TopicArn' => arn.strip, :parser => Fog::Parsers::AWS::SNS::SetTopicAttributes.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/sns/publish.rb0000644000004100000410000000161512261242551021174 0ustar www-datawww-datamodule Fog module AWS class SNS class Real require 'fog/aws/parsers/sns/publish' # Send a message to a topic # # ==== Parameters # * arn<~String> - Arn of topic to send message to # * message<~String> - Message to send to topic # * options<~Hash>: # * MessageStructure<~String> - message structure, in ['json'] # * Subject<~String> - value to use for subject when delivering by email # # ==== See Also # http://docs.amazonwebservices.com/sns/latest/api/API_Publish.html # def publish(arn, message, options = {}) request({ 'Action' => 'Publish', 'Message' => message, 'TopicArn' => arn.strip, :parser => Fog::Parsers::AWS::SNS::Publish.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/sns/create_topic.rb0000644000004100000410000000111412261242551022161 0ustar www-datawww-datamodule Fog module AWS class SNS class Real require 'fog/aws/parsers/sns/create_topic' # Create a topic # # ==== Parameters # * name<~String> - Name of topic to create # # ==== See Also # http://docs.amazonwebservices.com/sns/latest/api/API_CreateTopic.html # def create_topic(name) request({ 'Action' => 'CreateTopic', 'Name' => name, :parser => Fog::Parsers::AWS::SNS::CreateTopic.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/sns/add_permission.rb0000644000004100000410000000072512261242551022527 0ustar www-datawww-datamodule Fog module AWS class SNS class Real require 'fog/aws/parsers/sns/add_permission' def add_permission(options = {}) request({ 'Action' => 'AddPermission', :parser => Fog::Parsers::AWS::SNS::AddPermission.new }.merge!(options)) end end class Mock def add_permission(options = {}) Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/aws/requests/sns/unsubscribe.rb0000644000004100000410000000116212261242551022047 0ustar www-datawww-datamodule Fog module AWS class SNS class Real require 'fog/aws/parsers/sns/unsubscribe' # Delete a subscription # # ==== Parameters # * arn<~String> - Arn of subscription to delete # # ==== See Also # http://docs.amazonwebservices.com/sns/latest/api/API_Unsubscribe.html # def unsubscribe(arn) request({ 'Action' => 'Unsubscribe', 'SubscriptionArn' => arn.strip, :parser => Fog::Parsers::AWS::SNS::Unsubscribe.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/sns/list_subscriptions_by_topic.rb0000644000004100000410000000150212261242551025353 0ustar www-datawww-datamodule Fog module AWS class SNS class Real require 'fog/aws/parsers/sns/list_subscriptions' # List subscriptions for a topic # # ==== Parameters # * arn<~String> - Arn of topic to list subscriptions for # * options<~Hash>: # * 'NextToken'<~String> - Token returned from previous request, used for pagination # # ==== See Also # http://docs.amazonwebservices.com/sns/latest/api/API_ListSubscriptionsByTopic.html # def list_subscriptions_by_topic(arn, options = {}) request({ 'Action' => 'ListSubscriptionsByTopic', 'TopicArn' => arn.strip, :parser => Fog::Parsers::AWS::SNS::ListSubscriptions.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/sns/list_subscriptions.rb0000644000004100000410000000125412261242551023467 0ustar www-datawww-datamodule Fog module AWS class SNS class Real require 'fog/aws/parsers/sns/list_subscriptions' # List subscriptions # # ==== Parameters # * options<~Hash>: # * 'NextToken'<~String> - Token returned from previous request, used for pagination # # ==== See Also # http://docs.amazonwebservices.com/sns/latest/api/API_ListSubscriptions.html # def list_subscriptions(options = {}) request({ 'Action' => 'ListSubscriptions', :parser => Fog::Parsers::AWS::SNS::ListSubscriptions.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/0000755000004100000410000000000012261242551017141 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/iam/list_account_aliases.rb0000644000004100000410000000057012261242551023660 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/list_account_aliases' def list_account_aliases(options = {}) request({ 'Action' => 'ListAccountAliases', :parser => Fog::Parsers::AWS::IAM::ListAccountAliases.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/create_group.rb0000644000004100000410000000370112261242551022146 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/create_group' # Create a new group # # ==== Parameters # * group_name<~String>: name of the group to create (do not include path) # * path<~String>: optional path to group, defaults to '/' # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Group'<~Hash>: # * Arn<~String> - # * GroupId<~String> - # * GroupName<~String> - # * Path<~String> - # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_CreateGroup.html # def create_group(group_name, path = '/') request( 'Action' => 'CreateGroup', 'GroupName' => group_name, 'Path' => path, :parser => Fog::Parsers::AWS::IAM::CreateGroup.new ) end end class Mock def create_group(group_name, path = '/') if data[:groups].has_key? group_name raise Fog::AWS::IAM::EntityAlreadyExists.new("Group with name #{group_name} already exists.") else data[:groups][group_name][:path] = path Excon::Response.new.tap do |response| response.body = { 'Group' => { 'GroupId' => (data[:groups][group_name][:group_id]).strip, 'GroupName' => group_name, 'Path' => path, 'Arn' => (data[:groups][group_name][:arn]).strip }, 'RequestId' => Fog::AWS::Mock.request_id } response.status = 200 end end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/list_access_keys.rb0000644000004100000410000000442612261242551023023 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/list_access_keys' # List access_keys # # ==== Parameters # * options<~Hash>: # * 'Marker'<~String> - used to paginate subsequent requests # * 'MaxItems'<~Integer> - limit results to this number per page # * 'UserName'<~String> - optional: username to lookup access keys for, defaults to current user # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'AccessKeys'<~Array> - Matching access keys # * access_key<~Hash>: # * AccessKeyId<~String> - # * Status<~String> - # * 'IsTruncated<~Boolean> - Whether or not results were truncated # * 'Marker'<~String> - appears when IsTruncated is true as the next marker to use # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_ListAccessKeys.html # def list_access_keys(options = {}) request({ 'Action' => 'ListAccessKeys', :parser => Fog::Parsers::AWS::IAM::ListAccessKeys.new }.merge!(options)) end end class Mock def list_access_keys(options = {}) #FIXME: Doesn't do anything with options, aside from UserName if user = options['UserName'] if data[:users].has_key? user access_keys_data = data[:users][user][:access_keys] else raise Fog::AWS::IAM::NotFound.new("The user with name #{user} cannot be found.") end else access_keys_data = data[:access_keys] end Excon::Response.new.tap do |response| response.body = { 'AccessKeys' => access_keys_data.map do |akey| {'Status' => akey['Status'], 'AccessKeyId' => akey['AccessKeyId']} end, 'IsTruncated' => false, 'RequestId' => Fog::AWS::Mock.request_id } response.status = 200 end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/get_user.rb0000644000004100000410000000354012261242551021305 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/get_user' # Get User # # ==== Parameters # * username # * options<~Hash>: # * 'UserName'<~String>: Name of the User. Defaults to current user # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'User'<~Hash> - User # * Arn<~String> - # * UserId<~String> - # * UserName<~String> - # * Path<~String> - # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_Getuser.html # def get_user(username, options = {}) request({ 'Action' => 'GetUser', 'UserName' => username, :parser => Fog::Parsers::AWS::IAM::GetUser.new }.merge!(options)) end end class Mock def get_user(user, options = {}) raise Fog::AWS::IAM::NotFound.new( "The user with name #{user} cannot be found." ) unless self.data[:users].key?(user) Excon::Response.new.tap do |response| response.body = {'User' => { 'UserId' => data[:users][user][:user_id], 'Path' => data[:users][user][:path], 'UserName' => user, 'Arn' => (data[:users][user][:arn]).strip, 'CreateDate' => data[:users][user][:created_at] }, 'RequestId' => Fog::AWS::Mock.request_id } response.status = 200 end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/delete_role.rb0000644000004100000410000000136512261242551021756 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Delete a role # # ==== Parameters # * role_name<~String>: name of the role to delete # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_DeleteRole.html # def delete_role(role_name) request( 'Action' => 'DeleteRole', 'RoleName' => role_name, :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/delete_role_policy.rb0000644000004100000410000000162412261242551023333 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Remove a policy from a role # # ==== Parameters # * role_name<~String>: name of the role # * policy_name<~String>: name of policy document # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_DeleteRolePolicy.html # def delete_role_policy(role_name, policy_name) request( 'Action' => 'DeleteRolePolicy', 'PolicyName' => policy_name, 'RoleName' => role_name, :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/get_login_profile.rb0000644000004100000410000000172712261242551023164 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/login_profile' # Retrieves the login profile for a user # # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_CreateLoginProfile.html # ==== Parameters # * user_name<~String> - Name of user to retrieve the login profile for # * password<~String> - The new password for this user # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'LoginProfile'<~Hash> # * UserName<~String> # * CreateDate # * 'RequestId'<~String> - Id of the request # # def get_login_profile(user_name) request({ 'Action' => 'GetLoginProfile', 'UserName' => user_name, :parser => Fog::Parsers::AWS::IAM::LoginProfile.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/get_instance_profile.rb0000644000004100000410000000257412261242551023661 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/instance_profile' # Retrieves information about an instance profile # # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_GetInstanceProfile.html # ==== Parameters # * instance_profile_name<~String> - Name of instance_profile to retrieve the information for # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'InstanceProfile'<~Hash>: # * Arn<~String> - # * CreateDate<~Date> # * InstanceProfileId<~String> - # * InstanceProfileName<~String> - # * Path<~String> - # * Roles<~Array> - # role<~Hash>: # * 'Arn'<~String> - # * 'AssumeRolePolicyDocument'<~String< # * 'Path'<~String> - # * 'RoleId'<~String> - # * 'RoleName'<~String> - # * 'RequestId'<~String> - Id of the request def get_instance_profile(instance_profile_name) request({ 'Action' => 'GetInstanceProfile', 'InstanceProfileName' => instance_profile_name, :parser => Fog::Parsers::AWS::IAM::InstanceProfile.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/put_role_policy.rb0000644000004100000410000000215312261242551022677 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Add or update a policy for a role # # ==== Parameters # * role_name<~String>: name of the role # * policy_name<~String>: name of policy document # * policy_document<~Hash>: policy document, see: http://docs.amazonwebservices.com/IAM/latest/UserGuide/PoliciesOverview.html # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_PutRolePolicy.html # def put_role_policy(role_name, policy_name, policy_document) request( 'Action' => 'PutRolePolicy', 'RoleName' => role_name, 'PolicyName' => policy_name, 'PolicyDocument' => Fog::JSON.encode(policy_document), :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/list_server_certificates.rb0000644000004100000410000000372712261242551024565 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/list_server_certificates' # List server certificates # # ==== Parameters # * options<~Hash>: # * 'Marker'<~String> - The marker from the previous result (for pagination) # * 'MaxItems'<~String> - The maximum number of server certificates you want in the response # * 'PathPrefix'<~String> - The path prefix for filtering the results # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Certificates'<~Array> - Matching server certificates # * server_certificate<~Hash>: # * Arn<~String> - # * Path<~String> - # * ServerCertificateId<~String> - # * ServerCertificateName<~String> - # * UploadDate<~Time> - # * 'IsTruncated'<~Boolean> - Whether or not the results were truncated # * 'Marker'<~String> - appears when IsTruncated is true as the next marker to use # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/index.html?API_ListServerCertificates.html # def list_server_certificates(options = {}) request({ 'Action' => 'ListServerCertificates', :parser => Fog::Parsers::AWS::IAM::ListServerCertificates.new }.merge!(options)) end end class Mock def list_server_certificates(options = {}) certificates = self.data[:server_certificates].values certificates = certificates.select { |certificate| certificate['Path'] =~ Regexp.new("^#{options['PathPrefix']}") } if options['PathPrefix'] response = Excon::Response.new response.status = 200 response.body = { 'Certificates' => certificates } response end end end end end fog-1.19.0/lib/fog/aws/requests/iam/delete_group_policy.rb0000644000004100000410000000163312261242551023526 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Remove a policy from a group # # ==== Parameters # * group_name<~String>: name of the group # * policy_name<~String>: name of policy document # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_DeleteGroupPolicy.html # def delete_group_policy(group_name, policy_name) request( 'Action' => 'DeleteGroupPolicy', 'GroupName' => group_name, 'PolicyName' => policy_name, :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/get_role_policy.rb0000644000004100000410000000207112261242551022645 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/get_role_policy' # Get Role Policy # # ==== Parameters # * 'PolicyName'<~String>: Name of the policy to get # * 'RoleName'<~String>: Name of the Role who the policy is associated with. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * PolicyDocument<~String> The policy document. # * PolicyName<~String> The name of the policy. # * RoleName<~String> The Role the policy is associated with. # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_GetRolePolicy.html # def get_role_policy(role_name, policy_name) request({ 'Action' => 'GetRolePolicy', 'PolicyName' => policy_name, 'RoleName' => role_name, :parser => Fog::Parsers::AWS::IAM::GetRolePolicy.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/update_server_certificate.rb0000644000004100000410000000472512261242551024710 0ustar www-datawww-datamodule Fog module AWS class IAM class Real # Updates the name and/or the path of the specified server certificate. # # ==== Parameters # * server_certificate_name<~String> - The name of the server # certificate that you want to update. # * options<~Hash>: # * 'NewPath'<~String> - The new path for the server certificate. # Include this only if you are updating the server certificate's # path. # * 'NewServerCertificateName'<~String> - The new name for the server # certificate. Include this only if you are updating the server # certificate's name. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/index.html?API_UpdateServerCertificate.html # def update_server_certificate(server_certificate_name, options = {}) request({ 'Action' => 'UpdateServerCertificate', 'ServerCertificateName' => server_certificate_name, :parser => Fog::Parsers::AWS::IAM::Basic.new }.merge!(options)) end end class Mock def update_server_certificate(server_certificate_name, options = {}) new_server_certificate_name = options['NewServerCertificateName'] if self.data[:server_certificates][new_server_certificate_name] raise Fog::AWS::IAM::EntityAlreadyExists.new("The Server Certificate with name #{server_certificate_name} already exists.") end unless certificate = self.data[:server_certificates].delete(server_certificate_name) raise Fog::AWS::IAM::NotFound.new("The Server Certificate with name #{server_certificate_name} cannot be found.") end if new_server_certificate_name certificate['ServerCertificateName'] = new_server_certificate_name end if new_path = options['NewPath'] certificate['Path'] = new_path end self.data[:server_certificates][certificate['ServerCertificateName']] = certificate Excon::Response.new.tap do |response| response.body = { 'RequestId' => Fog::AWS::Mock.request_id } response.status = 200 end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/get_group_policy.rb0000644000004100000410000000377712261242551023056 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/get_group_policy' # Get Group Policy # # ==== Parameters # * 'PolicyName'<~String>: Name of the policy to get # * 'GroupName'<~String>: Name of the Group who the policy is associated with. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * PolicyDocument<~String> The policy document. # * PolicyName<~String> The name of the policy. # * GroupName<~String> The Group the policy is associated with. # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_GetGroupPolicy.html # def get_group_policy(policy_name, group_name) request({ 'Action' => 'GetGroupPolicy', 'PolicyName' => policy_name, 'GroupName' => group_name, :parser => Fog::Parsers::AWS::IAM::GetGroupPolicy.new }) end end class Mock def get_group_policy(policy_name, group_name) raise Fog::AWS::IAM::NotFound.new("The group with name #{group_name} cannot be found.") unless self.data[:groups].key?(group_name) raise Fog::AWS::IAM::NotFound.new("The policy with name #{policy_name} cannot be found.") unless self.data[:groups][group_name][:policies].key?(policy_name) Excon::Response.new.tap do |response| response.body = { 'Policy' => { 'PolicyName' => policy_name, 'GroupName' => group_name, 'PolicyDocument' => data[:groups][group_name][:policies][policy_name] }, 'IsTruncated' => false, 'RequestId' => Fog::AWS::Mock.request_id } response.status = 200 end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/add_user_to_group.rb0000644000004100000410000000321012261242551023166 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Add a user to a group # # ==== Parameters # * group_name<~String>: name of the group # * user_name<~String>: name of user to add # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_AddUserToGroup.html # def add_user_to_group(group_name, user_name) request( 'Action' => 'AddUserToGroup', 'GroupName' => group_name, 'UserName' => user_name, :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end class Mock def add_user_to_group(group_name, user_name) if data[:groups].has_key? group_name if data[:users].has_key? user_name unless data[:groups][group_name][:members].include?(user_name) data[:groups][group_name][:members] << user_name end Excon::Response.new.tap do |response| response.status = 200 response.body = { 'RequestId' => Fog::AWS::Mock.request_id } end else raise Fog::AWS::IAM::NotFound.new("The user with name #{user_name} cannot be found.") end else raise Fog::AWS::IAM::NotFound.new("The group with name #{group_name} cannot be found.") end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/delete_group.rb0000644000004100000410000000266712261242551022157 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Delete a group # # ==== Parameters # * group_name<~String>: name of the group to delete # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_DeleteGroup.html # def delete_group(group_name) request( 'Action' => 'DeleteGroup', 'GroupName' => group_name, :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end class Mock def delete_group(group_name) if data[:groups].has_key? group_name if data[:groups][group_name][:members].empty? data[:groups].delete group_name Excon::Response.new.tap do |response| response.status = 200 response.body = { 'RequestId' => Fog::AWS::Mock.request_id } end else raise Fog::AWS::IAM::Error.new("DeleteConflict => Cannot delete entity, must delete users in group first.") end else raise Fog::AWS::IAM::NotFound.new("The group with name #{group_name} cannot be found.") end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/update_signing_certificate.rb0000644000004100000410000000205012261242551025025 0ustar www-datawww-datamodule Fog module AWS class IAM class Real # Update a Signing Certificate # # ==== Parameters # * certificate_id<~String> - Required. ID of the Certificate to update. # * status<~String> - Required. Active/Inactive # * options<~Hash>: # * user_name<~String> - Name of the user the signing certificate belongs to. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/index.html?API_UpdateSigningCertificate.html # def update_signing_certificate(certificate_id, status, options = {}) request({ 'Action' => 'UpdateSigningCertificate', 'CertificateId' => certificate_id, 'Status' => status, :parser => Fog::Parsers::AWS::IAM::Basic.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/upload_signing_certificate.rb0000644000004100000410000000234612261242551025037 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/upload_signing_certificate' # Upload signing certificate for user (by default detects user from access credentials) # # ==== Parameters # * options<~Hash>: # * 'UserName'<~String> - name of the user to upload certificate for (do not include path) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Certificate'<~Hash>: # * 'CertificateId'<~String> - # * 'UserName'<~String> - # * 'CertificateBody'<~String> - # * 'Status'<~String> - # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/index.html?API_UploadSigningCertificate.html # def upload_signing_certificate(certificate, options = {}) request({ 'Action' => 'UploadSigningCertificate', 'CertificateBody' => certificate, :parser => Fog::Parsers::AWS::IAM::UploadSigningCertificate.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/update_access_key.rb0000644000004100000410000000351312261242551023143 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Update an access key for a user # # ==== Parameters # * access_key_id<~String> - Access key id to delete # * status<~String> - status of keys in ['Active', 'Inactive'] # * options<~Hash>: # * 'UserName'<~String> - name of the user to create (do not include path) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_UpdateAccessKey.html # def update_access_key(access_key_id, status, options = {}) request({ 'AccessKeyId' => access_key_id, 'Action' => 'UpdateAccessKey', 'Status' => status, :parser => Fog::Parsers::AWS::IAM::Basic.new }.merge!(options)) end end class Mock def update_access_key(access_key_id, status, options = {}) if user = options['UserName'] if data[:users].has_key? user access_keys_data = data[:users][user][:access_keys] else raise Fog::AWS::IAM::NotFound.new('The user with name #{user_name} cannot be found.') end else access_keys_data = data[:access_keys] end key = access_keys_data.detect{|k| k["AccessKeyId"] == access_key_id} key["Status"] = status Excon::Response.new.tap do |response| response.status = 200 response.body = { 'AccessKey' => key, 'RequestId' => Fog::AWS::Mock.request_id } end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/get_role.rb0000644000004100000410000000171012261242551021265 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/single_role' # Get the specified role # # ==== Parameters # role_name<~String> # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * Role<~Hash>: # * 'Arn'<~String> - # * 'AssumeRolePolicyDocument'<~String< # * 'Path'<~String> - # * 'RoleId'<~String> - # * 'RoleName'<~String> - # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_GetRole.html # def get_role(role_name) request( 'Action' => 'GetRole', 'RoleName' => role_name, :parser => Fog::Parsers::AWS::IAM::SingleRole.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/update_group.rb0000644000004100000410000000255312261242551022171 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/update_group' # Update a Group # # ==== Parameters # * group_name<~String> - Required. Name of the Group to update. If you're changing the name of the Group, this is the original Group name. # * options<~Hash>: # * new_path<~String> - New path for the Group. Include this parameter only if you're changing the Group's path. # * new_group_name<~String> - New name for the Group. Include this parameter only if you're changing the Group's name. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # * 'Group'<~Hash> - Changed Group info # * 'Arn'<~String> - # * 'Path'<~String> - # * 'GroupId'<~String> - # * 'GroupName'<~String> - # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/index.html?API_UpdateGroup.html # def update_group(group_name, options = {}) request({ 'Action' => 'UpdateGroup', 'GroupName' => group_name, :parser => Fog::Parsers::AWS::IAM::UpdateGroup.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/create_user.rb0000644000004100000410000000410712261242551021771 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/create_user' # Create a new user # # ==== Parameters # * user_name<~String>: name of the user to create (do not include path) # * path<~String>: optional path to group, defaults to '/' # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'User'<~Hash>: # * 'Arn'<~String> - # * 'Path'<~String> - # * 'UserId'<~String> - # * 'UserName'<~String> - # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_CreateUser.html # def create_user(user_name, path = '/') request( 'Action' => 'CreateUser', 'UserName' => user_name, 'Path' => path, :parser => Fog::Parsers::AWS::IAM::CreateUser.new ) end end class Mock def create_user(user_name, path='/') if data[:users].has_key? user_name raise Fog::AWS::IAM::EntityAlreadyExists.new "User with name #{user_name} already exists." else data[:users][user_name][:path] = path Excon::Response.new.tap do |response| response.status = 200 response.body = { 'User' => { "UserId" => data[:users][user_name][:user_id], "Path" => path, "UserName" => user_name, "Arn" => (data[:users][user_name][:arn]).strip, "CreateDate" => data[:users][user_name][:created_at] }, 'RequestId' => Fog::AWS::Mock.request_id } end end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/delete_signing_certificate.rb0000644000004100000410000000175612261242551025021 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Upload signing certificate for user (by default detects user from access credentials) # # ==== Parameters # * options<~Hash>: # * 'UserName'<~String> - name of the user to upload certificate for (do not include path) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/index.html?API_DeleteSigningCertificate.html # def delete_signing_certificate(certificate_id, options = {}) request({ 'Action' => 'DeleteSigningCertificate', 'CertificateId' => certificate_id, :parser => Fog::Parsers::AWS::IAM::Basic.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/create_access_key.rb0000644000004100000410000000431112261242551023121 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/create_access_key' # Create a access keys for user (by default detects user from access credentials) # # ==== Parameters # * options<~Hash>: # * 'UserName'<~String> - name of the user to create (do not include path) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'AccessKey'<~Hash>: # * 'AccessKeyId'<~String> - # * 'UserName'<~String> - # * 'SecretAccessKey'<~String> - # * 'Status'<~String> - # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_CreateAccessKey.html # def create_access_key(options = {}) request({ 'Action' => 'CreateAccessKey', :parser => Fog::Parsers::AWS::IAM::CreateAccessKey.new }.merge!(options)) end end class Mock def create_access_key(options) #FIXME: Not 100% correct as AWS will use the signing credentials when there is no 'UserName' in the options hash # Also doesn't raise an error when there are too many keys if user = options['UserName'] if data[:users].has_key? user access_keys_data = data[:users][user][:access_keys] else raise Fog::AWS::IAM::NotFound.new('The user with name #{user_name} cannot be found.') end else access_keys_data = data[:access_keys] end key = { 'SecretAccessKey' => Fog::Mock.random_base64(40), 'Status' => 'Active', 'AccessKeyId' => Fog::AWS::Mock.key_id(20), } if user key["UserName"] = user end access_keys_data << key Excon::Response.new.tap do |response| response.status = 200 response.body = { 'AccessKey' => key, 'RequestId' => Fog::AWS::Mock.request_id } end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/list_instance_profiles.rb0000644000004100000410000000335312261242551024234 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/list_instance_profiles' # Lists instance profiles # # ==== Parameters # * options<~Hash>: # * 'Marker'<~String>: used to paginate subsequent requests # * 'MaxItems'<~Integer>: limit results to this number per page # * 'PathPrefix'<~String>: prefix for filtering results # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'InstanceProfiles'<~Array>: # * instance_profile <~Hash>: # * Arn<~String> - # * CreateDate<~Date> # * InstanceProfileId<~String> - # * InstanceProfileName<~String> - # * Path<~String> - # * Roles<~Array> - # role<~Hash>: # * 'Arn'<~String> - # * 'AssumeRolePolicyDocument'<~String< # * 'Path'<~String> - # * 'RoleId'<~String> - # * 'RoleName'<~String> - # * 'IsTruncated<~Boolean> - Whether or not results were truncated # * 'Marker'<~String> - appears when IsTruncated is true as the next marker to use # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_ListInstanceProfiles.html # def list_instance_profiles(options={}) request({ 'Action' => 'ListInstanceProfiles', :parser => Fog::Parsers::AWS::IAM::ListInstanceProfiles.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/put_group_policy.rb0000644000004100000410000000344012261242551023072 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Add or update a policy for a group # # ==== Parameters # * group_name<~String>: name of the group # * policy_name<~String>: name of policy document # * policy_document<~Hash>: policy document, see: http://docs.amazonwebservices.com/IAM/latest/UserGuide/PoliciesOverview.html # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_PutGroupPolicy.html # def put_group_policy(group_name, policy_name, policy_document) request( 'Action' => 'PutGroupPolicy', 'GroupName' => group_name, 'PolicyName' => policy_name, 'PolicyDocument' => Fog::JSON.encode(policy_document), :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end class Mock #FIXME: You can't actually use the credentials for anything elsewhere in Fog #FIXME: Doesn't do any validation on the policy def put_group_policy(group_name, policy_name, policy_document) if data[:groups].has_key? group_name data[:groups][group_name][:policies][policy_name] = policy_document Excon::Response.new.tap do |response| response.body = { 'RequestId' => Fog::AWS::Mock.request_id } response.status = 200 end else raise Fog::AWS::IAM::NotFound.new("The group with name #{group_name} cannot be found.") end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/create_instance_profile.rb0000644000004100000410000000305212261242551024335 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/instance_profile' # Create a new instance_profile # # ==== Parameters # * instance_profile_name<~String>: name of the instance profile to create (do not include path) # * path<~String>: optional path to group, defaults to '/' # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'InstanceProfile'<~Hash>: # * Arn<~String> - # * CreateDate<~Date> # * InstanceProfileId<~String> - # * InstanceProfileName<~String> - # * Path<~String> - # * Roles<~Array> - # role<~Hash>: # * 'Arn'<~String> - # * 'AssumeRolePolicyDocument'<~String< # * 'Path'<~String> - # * 'RoleId'<~String> - # * 'RoleName'<~String> - # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_CreateInstanceProfile.html # def create_instance_profile(instance_profile_name, path='/', options={}) request({ 'Action' => 'CreateInstanceProfile', 'InstanceProfileName' => instance_profile_name, 'Path' => path, :parser => Fog::Parsers::AWS::IAM::InstanceProfile.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/list_instance_profiles_for_role.rb0000644000004100000410000000356012261242551026123 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/list_instance_profiles' # Lists the instance profiles that have the specified associated role # # ==== Parameters # * options<~Hash>: # * 'Marker'<~String>: used to paginate subsequent requests # * 'MaxItems'<~Integer>: limit results to this number per page # * 'RoleName'<~String>: The name of the role to list instance profiles for. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'InstanceProfiles'<~Array>: # * instance_profile <~Hash>: # * Arn<~String> - # * CreateDate<~Date> # * InstanceProfileId<~String> - # * InstanceProfileName<~String> - # * Path<~String> - # * Roles<~Array> - # role<~Hash>: # * 'Arn'<~String> - # * 'AssumeRolePolicyDocument'<~String< # * 'Path'<~String> - # * 'RoleId'<~String> - # * 'RoleName'<~String> - # * 'IsTruncated<~Boolean> - Whether or not results were truncated # * 'Marker'<~String> - appears when IsTruncated is true as the next marker to use # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_ListInstanceProfilesForRole.html # def list_instance_profiles_for_role(role_name,options={}) request({ 'Action' => 'ListInstanceProfilesForRole', 'RoleName' => role_name, :parser => Fog::Parsers::AWS::IAM::ListInstanceProfiles.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/delete_server_certificate.rb0000644000004100000410000000242012261242551024656 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Deletes the specified server certificate. # # ==== Parameters # * server_certificate_name<~String>: The name of the server certificate you want to delete. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_DeleteServerCertificate.html # def delete_server_certificate(server_certificate_name) request({ 'Action' => 'DeleteServerCertificate', 'ServerCertificateName' => server_certificate_name, :parser => Fog::Parsers::AWS::IAM::Basic.new }) end end class Mock def delete_server_certificate(server_certificate_name) response = Excon::Response.new response.status = 200 response.body = { 'RequestId' => Fog::AWS::Mock.request_id } self.data[:server_certificates].delete(server_certificate_name) response end end end end end fog-1.19.0/lib/fog/aws/requests/iam/list_user_policies.rb0000644000004100000410000000365212261242551023374 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/list_policies' # List policies for a user # # ==== Parameters # * user_name<~String> - Name of user to list policies for # * options<~Hash>: Optional # * 'Marker'<~String>: used to paginate subsequent requests # * 'MaxItems'<~Integer>: limit results to this number per page # * 'PathPrefix'<~String>: prefix for filtering results # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'PolicyNames'<~Array> - Matching policy names # * 'IsTruncated<~Boolean> - Whether or not results were truncated # * 'Marker'<~String> - appears when IsTruncated is true as the next marker to use # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_ListUserPolicies.html # def list_user_policies(user_name, options = {}) request({ 'Action' => 'ListUserPolicies', 'UserName' => user_name, :parser => Fog::Parsers::AWS::IAM::ListPolicies.new }.merge!(options)) end end class Mock def list_user_policies(user_name, options = {}) #FIXME: doesn't use options atm if data[:users].has_key? user_name Excon::Response.new.tap do |response| response.body = { 'PolicyNames' => data[:users][user_name][:policies].keys, 'IsTruncated' => false, 'RequestId' => Fog::AWS::Mock.request_id } response.status = 200 end else raise Fog::AWS::IAM::NotFound.new("The user with name #{user_name} cannot be found.") end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/list_signing_certificates.rb0000644000004100000410000000251412261242551024706 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/list_signing_certificates' # List signing certificates for user (by default detects user from access credentials) # # ==== Parameters # * options<~Hash>: # * 'UserName'<~String> - name of the user to list certificates for (do not include path) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'SigningCertificates'<~Array> - Matching signing certificates # * signing_certificate<~Hash>: # * CertificateId<~String> - # * Status<~String> - # * 'IsTruncated'<~Boolean> - Whether or not the results were truncated # * 'Marker'<~String> - appears when IsTruncated is true as the next marker to use # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/index.html?API_ListSigningCertificates.html # def list_signing_certificates(options = {}) request({ 'Action' => 'ListSigningCertificates', :parser => Fog::Parsers::AWS::IAM::ListSigningCertificates.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/put_user_policy.rb0000644000004100000410000000342212261242551022714 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Add or update a policy for a user # # ==== Parameters # * user_name<~String>: name of the user # * policy_name<~String>: name of policy document # * policy_document<~Hash>: policy document, see: http://docs.amazonwebservices.com/IAM/latest/UserGuide/PoliciesOverview.html # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_PutUserPolicy.html # def put_user_policy(user_name, policy_name, policy_document) request( 'Action' => 'PutUserPolicy', 'PolicyName' => policy_name, 'PolicyDocument' => Fog::JSON.encode(policy_document), 'UserName' => user_name, :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end class Mock #FIXME: You can't actually use the credentials for anything elsewhere in Fog #FIXME: Doesn't do any validation on the policy def put_user_policy(user_name, policy_name, policy_document) if data[:users].has_key? user_name data[:users][user_name][:policies][policy_name] = policy_document Excon::Response.new.tap do |response| response.body = { 'RequestId' => Fog::AWS::Mock.request_id } response.status = 200 end else raise Fog::AWS::IAM::NotFound.new("The user with name #{user_name} cannot be found.") end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/add_role_to_instance_profile.rb0000644000004100000410000000173312261242551025351 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Add a role to an instance profile # # ==== Parameters # * instance_profile_name<~String>: Name of the instance profile to update. # * role_name<~String>:Name of the role to add. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_AddRoleToInstanceProfile.html # def add_role_to_instance_profile(role_name, instance_profile_name) request( 'Action' => 'AddRoleToInstanceProfile', 'InstanceProfileName' => instance_profile_name, 'RoleName' => role_name, :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/remove_user_from_group.rb0000644000004100000410000000313212261242551024257 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Remove a user from a group # # ==== Parameters # * group_name<~String>: name of the group # * user_name<~String>: name of user to remove # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_RemoveUserFromGroup.html # def remove_user_from_group(group_name, user_name) request( 'Action' => 'RemoveUserFromGroup', 'GroupName' => group_name, 'UserName' => user_name, :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end class Mock def remove_user_from_group(group_name, user_name) if data[:groups].has_key? group_name if data[:users].has_key? user_name data[:groups][group_name][:members].delete_if { |item| item == user_name } Excon::Response.new.tap do |response| response.status = 200 response.body = { 'RequestId' => Fog::AWS::Mock.request_id } end else raise Fog::AWS::IAM::NotFound.new("The user with name #{user_name} cannot be found.") end else raise Fog::AWS::IAM::NotFound.new("The group with name #{group_name} cannot be found.") end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/remove_role_from_instance_profile.rb0000644000004100000410000000217112261242551026434 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # removes a role from an instance profile # # Make sure you do not have any Amazon EC2 instances running with the role you are about to remove from the instance profile. # ==== Parameters # * instance_profile_name<~String>: Name of the instance profile to update. # * role_name<~String>:Name of the role to remove. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_RemoveRoleFromInstanceProfile.html # def remove_role_from_instance_profile(role_name, instance_profile_name) request( 'Action' => 'RemoveRoleFromInstanceProfile', 'InstanceProfileName' => instance_profile_name, 'RoleName' => role_name, :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/list_users.rb0000644000004100000410000000420012261242551021656 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/list_users' # List users # # ==== Parameters # * options<~Hash>: # * 'Marker'<~String>: used to paginate subsequent requests # * 'MaxItems'<~Integer>: limit results to this number per page # * 'PathPrefix'<~String>: prefix for filtering results # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Users'<~Array> - Matching groups # * user<~Hash>: # * Arn<~String> - # * Path<~String> - # * UserId<~String> - # * UserName<~String> - # * 'IsTruncated<~Boolean> - Whether or not results were truncated # * 'Marker'<~String> - appears when IsTruncated is true as the next marker to use # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_ListUsers.html # def list_users(options = {}) request({ 'Action' => 'ListUsers', :parser => Fog::Parsers::AWS::IAM::ListUsers.new }.merge!(options)) end end class Mock def list_users(options = {}) #FIXME: none of the options are currently supported Excon::Response.new.tap do |response| response.body = {'Users' => data[:users].map do |user, data| { 'UserId' => data[:user_id], 'Path' => data[:path], 'UserName' => user, 'Arn' => (data[:arn]).strip, 'CreateDate' => data[:created_at]} end, 'IsTruncated' => false, 'RequestId' => Fog::AWS::Mock.request_id } response.status = 200 end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/update_login_profile.rb0000644000004100000410000000161612261242551023664 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Updates a login profile for a user # # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_UpdateLoginProfile.html # ==== Parameters # * user_name<~String> - Name of user to change the login profile for # * password<~String> - The new password for this user # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # def update_login_profile(user_name, password) request({ 'Action' => 'UpdateLoginProfile', 'UserName' => user_name, 'Password' => password, :parser => Fog::Parsers::AWS::IAM::Basic.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/upload_server_certificate.rb0000644000004100000410000000763712261242551024717 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/upload_server_certificate' # Uploads a server certificate entity for the AWS Account. # Includes a public key certificate, a private key, and an optional certificate chain, which should all be PEM-encoded. # # ==== Parameters # * certificate<~Hash>: The contents of the public key certificate in PEM-encoded format. # * private_key<~Hash>: The contents of the private key in PEM-encoded format. # * name<~Hash>: The name for the server certificate. Do not include the path in this value. # * options<~Hash>: # * 'CertificateChain'<~String> - The contents of the certificate chain. Typically a concatenation of the PEM-encoded public key certificates of the chain. # * 'Path'<~String> - The path for the server certificate. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Certificate'<~Hash>: # * 'Arn'<~String> - # * 'Path'<~String> - # * 'ServerCertificateId'<~String> - # * 'ServerCertificateName'<~String> - # * 'UploadDate'<~Time> # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/index.html?API_UploadServerCertificate.html # def upload_server_certificate(certificate, private_key, name, options = {}) request({ 'Action' => 'UploadServerCertificate', 'CertificateBody' => certificate, 'PrivateKey' => private_key, 'ServerCertificateName' => name, :parser => Fog::Parsers::AWS::IAM::UploadServerCertificate.new }.merge!(options)) end end class Mock def upload_server_certificate(certificate, private_key, name, options = {}) if certificate.nil? || certificate.empty? || private_key.nil? || private_key.empty? raise Fog::AWS::IAM::ValidationError.new end response = Excon::Response.new # Validate cert and key begin # must be an RSA private key raise OpenSSL::PKey::RSAError unless private_key =~ /BEGIN RSA PRIVATE KEY/ cert = OpenSSL::X509::Certificate.new(certificate) chain = OpenSSL::X509::Certificate.new(options['CertificateChain']) if options['CertificateChain'] key = OpenSSL::PKey::RSA.new(private_key) rescue OpenSSL::X509::CertificateError, OpenSSL::PKey::RSAError => e message = if e.is_a?(OpenSSL::X509::CertificateError) "Invalid Public Key Certificate." else "Invalid Private Key." end raise Fog::AWS::IAM::MalformedCertificate.new(message) end unless cert.check_private_key(key) raise Fog::AWS::IAM::KeyPairMismatch.new end if self.data[:server_certificates][name] raise Fog::AWS::IAM::EntityAlreadyExists.new("The Server Certificate with name #{name} already exists.") else response.status = 200 path = options['Path'] || "/" data = { 'Arn' => Fog::AWS::Mock.arn('iam', self.data[:owner_id], "server-certificate/#{name}"), 'Path' => path, 'ServerCertificateId' => Fog::AWS::IAM::Mock.server_certificate_id, 'ServerCertificateName' => name, 'UploadDate' => Time.now } self.data[:server_certificates][name] = data response.body = { 'Certificate' => data, 'RequestId' => Fog::AWS::Mock.request_id } end response end end end end end fog-1.19.0/lib/fog/aws/requests/iam/get_user_policy.rb0000644000004100000410000000374612261242551022674 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/get_user_policy' # Get User Policy # # ==== Parameters # * 'PolicyName'<~String>: Name of the policy to get # * 'UserName'<~String>: Name of the User who the policy is associated with. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * PolicyDocument<~String> The policy document. # * PolicyName<~String> The name of the policy. # * UserName<~String> The User the policy is associated with. # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_GetUserPolicy.html # def get_user_policy(policy_name, user_name) request({ 'Action' => 'GetUserPolicy', 'PolicyName' => policy_name, 'UserName' => user_name, :parser => Fog::Parsers::AWS::IAM::GetUserPolicy.new }) end end class Mock def get_user_policy(policy_name, user_name) raise Fog::AWS::IAM::NotFound.new("The user with name #{user_name} cannot be found.") unless self.data[:users].key?(user_name) raise Fog::AWS::IAM::NotFound.new("The policy with name #{policy_name} cannot be found.") unless self.data[:users][user_name][:policies].key?(policy_name) Excon::Response.new.tap do |response| response.body = { 'Policy' => { 'PolicyName' => policy_name, 'UserName' => user_name, 'PolicyDocument' => data[:users][user_name][:policies][policy_name] }, 'IsTruncated' => false, 'RequestId' => Fog::AWS::Mock.request_id } response.status = 200 end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/list_groups.rb0000644000004100000410000000407112261242551022042 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/list_groups' # List groups # # ==== Parameters # * options<~Hash>: # * 'Marker'<~String>: used to paginate subsequent requests # * 'MaxItems'<~Integer>: limit results to this number per page # * 'PathPrefix'<~String>: prefix for filtering results # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Groups'<~Array> - Matching groups # * group<~Hash>: # * Arn<~String> - # * GroupId<~String> - # * GroupName<~String> - # * Path<~String> - # * 'IsTruncated<~Boolean> - Whether or not results were truncated # * 'Marker'<~String> - appears when IsTruncated is true as the next marker to use # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_ListGroups.html # def list_groups(options = {}) request({ 'Action' => 'ListGroups', :parser => Fog::Parsers::AWS::IAM::ListGroups.new }.merge!(options)) end end class Mock def list_groups(options = {} ) #FIXME: Doesn't observe options Excon::Response.new.tap do |response| response.status = 200 response.body = { 'Groups' => data[:groups].map do |name, group| { 'GroupId' => group[:group_id], 'GroupName' => name, 'Path' => group[:path], 'Arn' => (group[:arn]).strip } end, 'IsTruncated' => false, 'RequestId' => Fog::AWS::Mock.request_id } end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/list_roles.rb0000644000004100000410000000254012261242551021646 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/list_roles' # Lists roles # # ==== Parameters # * options<~Hash>: # * 'Marker'<~String>: used to paginate subsequent requests # * 'MaxItems'<~Integer>: limit results to this number per page # * 'PathPrefix'<~String>: prefix for filtering results # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * Roles<~Array> - # role<~Hash>: # * 'Arn'<~String> - # * 'AssumeRolePolicyDocument'<~String< # * 'Path'<~String> - # * 'RoleId'<~String> - # * 'RoleName'<~String> - # * 'IsTruncated<~Boolean> - Whether or not results were truncated # * 'Marker'<~String> - appears when IsTruncated is true as the next marker to use # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_ListRoles.html # def list_roles(options={}) request({ 'Action' => 'ListRoles', :parser => Fog::Parsers::AWS::IAM::ListRoles.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/list_role_policies.rb0000644000004100000410000000241212261242551023350 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/list_policies' # Lists the names of policies associated with a role # # ==== Parameters # * role_name<~String>: the role to list policies for # * options<~Hash>: # * 'Marker'<~String>: used to paginate subsequent requests # * 'MaxItems'<~Integer>: limit results to this number per page # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'PolicyNames'<~Array>: # * policy_name <~String> # * 'IsTruncated<~Boolean> - Whether or not results were truncated # * 'Marker'<~String> - appears when IsTruncated is true as the next marker to use # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_ListRoleProfiles.html # def list_role_policies(role_name,options={}) request({ 'Action' => 'ListRolePolicies', 'RoleName' => role_name, :parser => Fog::Parsers::AWS::IAM::ListPolicies.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/delete_instance_profile.rb0000644000004100000410000000153612261242551024341 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Delete a instance_profile # # ==== Parameters # * instance_profile_name<~String>: name of the instance_profile to delete # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_DeleteInstanceProfile.html # def delete_instance_profile(instance_profile_name) request( 'Action' => 'DeleteInstanceProfile', 'InstanceProfileName' => instance_profile_name, :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/delete_user.rb0000644000004100000410000000231212261242551021764 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Delete a user # # ==== Parameters # * user_name<~String>: name of the user to delete # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_DeleteUser.html # def delete_user(user_name) request( 'Action' => 'DeleteUser', 'UserName' => user_name, :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end class Mock def delete_user(user_name) if data[:users].has_key? user_name data[:users].delete user_name Excon::Response.new.tap do |response| response.body = { 'RequestId' => Fog::AWS::Mock.request_id } response.status = 200 end else raise Fog::AWS::IAM::NotFound.new("The user with name #{user_name} cannot be found.") end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/list_groups_for_user.rb0000644000004100000410000000516112261242551023747 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/list_groups_for_user' # List groups_for_user # # ==== Parameters # * user_name<~String> - the username you want to look up group membership for # * options<~Hash>: # * 'Marker'<~String> - used to paginate subsequent requests # * 'MaxItems'<~Integer> - limit results to this number per page # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'GroupsForUser'<~Array> - Groups for a user # * group_for_user<~Hash>: # * 'Arn' - # * 'GroupId' - # * 'GroupName' - # * 'Path' - # * 'IsTruncated'<~Boolean> - Whether or not results were truncated # * 'Marker'<~String> - appears when IsTruncated is true as the next marker to use # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_ListGroupsForUser.html # def list_groups_for_user(user_name, options = {}) request({ 'Action' => 'ListGroupsForUser', 'UserName' => user_name, :parser => Fog::Parsers::AWS::IAM::ListGroupsForUser.new }.merge!(options)) end end class Mock def list_groups_for_user(user_name, options = {}) #FIXME: Does not consider options if data[:users].has_key? user_name Excon::Response.new.tap do |response| response.status = 200 response.body = { 'GroupsForUser' => data[:groups].select do |name, group| group[:members].include? user_name end.map do |name, group| { 'GroupId' => group[:group_id], 'GroupName' => name, 'Path' => group[:path], 'Arn' => (group[:arn]).strip } end, 'IsTruncated' => false, 'RequestId' => Fog::AWS::Mock.request_id } end else raise Fog::AWS::IAM::NotFound.new("The user with name #{user_name} cannot be found.") end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/create_login_profile.rb0000644000004100000410000000200412261242551023635 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/login_profile' # Creates a login profile for a user # # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_CreateLoginProfile.html # ==== Parameters # * user_name<~String> - Name of user to create a login profile for # * password<~String> - The new password for this user # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'LoginProfile'<~Hash> # * UserName<~String> # * CreateDate # * 'RequestId'<~String> - Id of the request # # def create_login_profile(user_name, password) request({ 'Action' => 'CreateLoginProfile', 'UserName' => user_name, 'Password' => password, :parser => Fog::Parsers::AWS::IAM::LoginProfile.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/get_server_certificate.rb0000644000004100000410000000245712261242551024205 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/upload_server_certificate' # Gets the specified server certificate. # # ==== Parameters # * server_certificate_name<~String>: The name of the server certificate you want to get. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_GetServerCertificate.html # def get_server_certificate(name) request({ 'Action' => 'GetServerCertificate', 'ServerCertificateName' => name, :parser => Fog::Parsers::AWS::IAM::UploadServerCertificate.new }) end end class Mock def get_server_certificate(name) raise Fog::AWS::IAM::NotFound unless certificate = self.data[:server_certificates][name] response = Excon::Response.new response.status = 200 response.body = { 'Certificate' => certificate, 'RequestId' => Fog::AWS::Mock.request_id } response end end end end end fog-1.19.0/lib/fog/aws/requests/iam/delete_account_alias.rb0000644000004100000410000000057012261242551023617 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' def delete_account_alias(account_alias) request( 'Action' => 'DeleteAccountAlias', 'AccountAlias' => account_alias, :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/get_group.rb0000644000004100000410000000516112261242551021464 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/get_group' # Get Group # # ==== Parameters # * 'GroupName'<~String>: Name of the Group # * options<~Hash>: # * 'Marker'<~String>: Use this only when paginating results, and only in a subsequent request after you've received a response where the results are truncated. Set it to the value of the Marker element in the response you just received. # * 'MaxItems'<~String>: Use this only when paginating results to indicate the maximum number of User names you want in the response. If there are additional User names beyond the maximum you specify, the IsTruncated response element is true. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Group'<~Hash> - Group # * 'Path'<~String> # * 'GroupName'<~String> # * 'Arn'<~String> # * 'Users'<~Hash>? - List of users belonging to the group. # * 'User'<~Hash> - User # * Arn<~String> - # * UserId<~String> - # * UserName<~String> - # * Path<~String> - # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/index.html?API_GetGroup.html # def get_group(group_name, options = {}) request({ 'Action' => 'GetGroup', 'GroupName' => group_name, :parser => Fog::Parsers::AWS::IAM::GetGroup.new }.merge!(options)) end end class Mock def get_group(group_name, options = {}) raise Fog::AWS::IAM::NotFound.new( "The user with name #{group_name} cannot be found." ) unless self.data[:groups].key?(group_name) Excon::Response.new.tap do |response| response.body = { 'Group' => { 'GroupId' => data[:groups][group_name][:group_id], 'Path' => data[:groups][group_name][:path], 'GroupName' => group_name, 'Arn' => (data[:groups][group_name][:arn]).strip }, 'Users' => data[:groups][group_name][:members].map { |user| get_user(user).body['User'] }, 'RequestId' => Fog::AWS::Mock.request_id } response.status = 200 end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/delete_login_profile.rb0000644000004100000410000000144312261242551023642 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Deletes a user's login profile # # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_DeleteLoginProfile.html # ==== Parameters # * user_name<~String> - Name of user whose login profile you want to delete # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # def delete_login_profile(user_name) request({ 'Action' => 'DeleteLoginProfile', 'UserName' => user_name, :parser => Fog::Parsers::AWS::IAM::Basic.new }) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/list_group_policies.rb0000644000004100000410000000246512261242551023553 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/list_policies' # List policies for a group # # ==== Parameters # * group_name<~String> - Name of group to list policies for # * options<~Hash>: Optional # * 'Marker'<~String>: used to paginate subsequent requests # * 'MaxItems'<~Integer>: limit results to this number per page # * 'PathPrefix'<~String>: prefix for filtering results # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'PolicyNames'<~Array> - Matching policy names # * 'IsTruncated<~Boolean> - Whether or not results were truncated # * 'Marker'<~String> - appears when IsTruncated is true as the next marker to use # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_ListGroupPolicies.html # def list_group_policies(group_name, options = {}) request({ 'Action' => 'ListGroupPolicies', 'GroupName' => group_name, :parser => Fog::Parsers::AWS::IAM::ListPolicies.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/update_user.rb0000644000004100000410000000252612261242551022013 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/update_user' # Update a user # # ==== Parameters # * user_name<~String> - Required. Name of the User to update. If you're changing the name of the User, this is the original User name. # * options<~Hash>: # * new_path<~String> - New path for the User. Include this parameter only if you're changing the User's path. # * new_user_name<~String> - New name for the User. Include this parameter only if you're changing the User's name. # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # * 'User'<~Hash> - Changed user info # * 'Arn'<~String> - # * 'Path'<~String> - # * 'UserId'<~String> - # * 'UserName'<~String> - # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/index.html?API_UpdateUser.html # def update_user(user_name, options = {}) request({ 'Action' => 'UpdateUser', 'UserName' => user_name, :parser => Fog::Parsers::AWS::IAM::UpdateUser.new }.merge!(options)) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/create_role.rb0000644000004100000410000000325012261242551021752 0ustar www-datawww-datamodule Fog module AWS class IAM # At the moment this is the only policy you can use EC2_ASSUME_ROLE_POLICY = <<-JSON { "Version":"2008-10-17", "Statement":[ { "Effect":"Allow", "Principal":{ "Service":["ec2.amazonaws.com"] }, "Action":["sts:AssumeRole"] } ] } JSON class Real require 'fog/aws/parsers/iam/single_role' # Creates a new role for your AWS account # # ==== Parameters # * RoleName<~String>: name of the role to create # * AssumeRolePolicyDocument<~String>: The policy that grants an entity permission to assume the role. # * Path<~String>: This parameter is optional. If it is not included, it defaults to a slash (/). # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Role'<~Hash>: # * 'Arn'<~String> - # * 'AssumeRolePolicyDocument'<~String< # * 'Path'<~String> - # * 'RoleId'<~String> - # * 'RoleName'<~String> - # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_CreateRole.html # def create_role(role_name, assume_role_policy_document, path = '/') request( 'Action' => 'CreateRole', 'RoleName' => role_name, 'AssumeRolePolicyDocument' => assume_role_policy_document, 'Path' => path, :parser => Fog::Parsers::AWS::IAM::SingleRole.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/iam/delete_access_key.rb0000644000004100000410000000317112261242551023123 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Delete an access key # # ==== Parameters # * access_key_id<~String> - Access key id to delete # * options<~Hash>: # * 'UserName'<~String> - name of the user to create (do not include path) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_DeleteAccessKey.html # def delete_access_key(access_key_id, options = {}) request({ 'AccessKeyId' => access_key_id, 'Action' => 'DeleteAccessKey', :parser => Fog::Parsers::AWS::IAM::Basic.new }.merge!(options)) end end class Mock def delete_access_key(access_key_id, options = {}) user_name = options['UserName'] if user_name && data[:users].has_key?(user_name) && data[:users][user_name][:access_keys].any? { |akey| akey['AccessKeyId'] == access_key_id } data[:users][user_name][:access_keys].delete_if { |akey| akey['AccessKeyId'] == access_key_id } Excon::Response.new.tap do |response| response.body = { 'RequestId' => Fog::AWS::Mock.request_id } response.status = 200 end else raise Fog::AWS::IAM::NotFound.new("The Access Key with id #{access_key_id} cannot be found.") end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/delete_user_policy.rb0000644000004100000410000000273112261242551023350 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' # Remove a policy from a user # # ==== Parameters # * user_name<~String>: name of the user # * policy_name<~String>: name of policy document # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'RequestId'<~String> - Id of the request # # ==== See Also # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_DeleteUserPolicy.html # def delete_user_policy(user_name, policy_name) request( 'Action' => 'DeleteUserPolicy', 'PolicyName' => policy_name, 'UserName' => user_name, :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end class Mock def delete_user_policy(user_name, policy_name) if data[:users].has_key?(user_name) && data[:users][user_name][:policies].has_key?(policy_name) data[:users][user_name][:policies].delete policy_name Excon::Response.new.tap do |response| response.body = { 'RequestId' => Fog::AWS::Mock.request_id } response.status = 200 end else raise Fog::AWS::IAM::NotFound.new("The user policy with name #{policy_name} cannot be found.") end end end end end end fog-1.19.0/lib/fog/aws/requests/iam/create_account_alias.rb0000644000004100000410000000057112261242551023621 0ustar www-datawww-datamodule Fog module AWS class IAM class Real require 'fog/aws/parsers/iam/basic' def create_account_alias(account_alias) request( 'Action' => 'CreateAccountAlias', 'AccountAlias' => account_alias, :parser => Fog::Parsers::AWS::IAM::Basic.new ) end end end end end fog-1.19.0/lib/fog/aws/requests/simpledb/0000755000004100000410000000000012261242551020172 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/requests/simpledb/batch_put_attributes.rb0000644000004100000410000000463712261242551024750 0ustar www-datawww-datamodule Fog module AWS class SimpleDB class Real # Put items attributes into a SimpleDB domain # # ==== Parameters # * domain_name<~String> - Name of domain. Must be between 3 and 255 of the # following characters: a-z, A-Z, 0-9, '_', '-' and '.'. # * items<~Hash> - Keys are the items names and may use any UTF-8 # characters valid in xml. Control characters and sequences not allowed # in xml are not valid. Can be up to 1024 bytes long. Values are the # attributes to add to the given item and may use any UTF-8 characters # valid in xml. Control characters and sequences not allowed in xml are # not valid. Each name and value can be up to 1024 bytes long. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'BoxUsage' # * 'RequestId' def batch_put_attributes(domain_name, items, replace_attributes = Hash.new([])) request({ 'Action' => 'BatchPutAttributes', 'DomainName' => domain_name, :parser => Fog::Parsers::AWS::SimpleDB::Basic.new(@nil_string) }.merge!(encode_batch_attributes(items, replace_attributes))) end end class Mock def batch_put_attributes(domain_name, items, replace_attributes = Hash.new([])) response = Excon::Response.new if self.data[:domains][domain_name] for item_name, attributes in items do for key, value in attributes do self.data[:domains][domain_name][item_name] ||= {} if replace_attributes[item_name] && replace_attributes[item_name].include?(key) self.data[:domains][domain_name][item_name][key.to_s] = [] else self.data[:domains][domain_name][item_name][key.to_s] ||= [] end self.data[:domains][domain_name][item_name][key.to_s] << value.to_s end end response.status = 200 response.body = { 'BoxUsage' => Fog::AWS::Mock.box_usage, 'RequestId' => Fog::AWS::Mock.request_id } else response.status = 400 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/simpledb/domain_metadata.rb0000644000004100000410000000527612261242551023640 0ustar www-datawww-datamodule Fog module AWS class SimpleDB class Real require 'fog/aws/parsers/simpledb/domain_metadata' # List metadata for SimpleDB domain # # ==== Parameters # * domain_name<~String> - Name of domain. Must be between 3 and 255 of the # following characters: a-z, A-Z, 0-9, '_', '-' and '.'. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'AttributeNameCount' - number of unique attribute names in domain # * 'AttributeNamesSizeBytes' - total size of unique attribute names, in bytes # * 'AttributeValueCount' - number of all name/value pairs in domain # * 'AttributeValuesSizeBytes' - total size of attributes, in bytes # * 'BoxUsage' # * 'ItemCount' - number of items in domain # * 'ItemNameSizeBytes' - total size of item names in domain, in bytes # * 'RequestId' # * 'Timestamp' - last update time for metadata. def domain_metadata(domain_name) request( 'Action' => 'DomainMetadata', 'DomainName' => domain_name, :idempotent => true, :parser => Fog::Parsers::AWS::SimpleDB::DomainMetadata.new(@nil_string) ) end end class Mock def domain_metadata(domain_name) response = Excon::Response.new if domain = self.data[:domains][domain_name] response.status = 200 attribute_names = [] attribute_values = [] for item in domain.values for key, values in item attribute_names << key for value in values attribute_values << value end end end response.body = { 'AttributeNameCount' => attribute_names.length, 'AttributeNamesSizeBytes' => attribute_names.join('').length, 'AttributeValueCount' => attribute_values.length, 'AttributeValuesSizeBytes' => attribute_values.join('').length, 'BoxUsage' => Fog::AWS::Mock.box_usage, 'ItemCount' => domain.keys.length, 'ItemNamesSizeBytes' => domain.keys.join('').length, 'RequestId' => Fog::AWS::Mock.request_id, 'Timestamp' => Time.now } else response.status = 400 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/simpledb/delete_attributes.rb0000644000004100000410000000514012261242551024227 0ustar www-datawww-datamodule Fog module AWS class SimpleDB class Real # List metadata for SimpleDB domain # # ==== Parameters # * domain_name<~String> - Name of domain. Must be between 3 and 255 of the # following characters: a-z, A-Z, 0-9, '_', '-' and '.'. # * item_name<~String> - Name of the item. May use any UTF-8 characters valid # in xml. Control characters and sequences not allowed in xml are not # valid. Can be up to 1024 bytes long. # * attributes<~Hash> - Name/value pairs to remove from the item. Defaults to # nil, which will delete the entire item. Attribute names and values may # use any UTF-8 characters valid in xml. Control characters and sequences # not allowed in xml are not valid. Each name and value can be up to 1024 # bytes long. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'BoxUsage' # * 'RequestId' def delete_attributes(domain_name, item_name, attributes = nil) request({ 'Action' => 'DeleteAttributes', 'DomainName' => domain_name, 'ItemName' => item_name, :parser => Fog::Parsers::AWS::SimpleDB::Basic.new(@nil_string) }.merge!(encode_attributes(attributes))) end end class Mock def delete_attributes(domain_name, item_name, attributes = nil) response = Excon::Response.new if self.data[:domains][domain_name] if self.data[:domains][domain_name][item_name] if attributes for key, value in attributes if self.data[:domains][domain_name][item_name][key] if value.nil? || value.empty? self.data[:domains][domain_name][item_name].delete(key) else for v in value self.data[:domains][domain_name][item_name][key].delete(v) end end end end else self.data[:domains][domain_name][item_name].clear end end response.status = 200 response.body = { 'BoxUsage' => Fog::AWS::Mock.box_usage, 'RequestId' => Fog::AWS::Mock.request_id } else response.status = 400 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/simpledb/create_domain.rb0000644000004100000410000000213612261242551023313 0ustar www-datawww-datamodule Fog module AWS class SimpleDB class Real # Create a SimpleDB domain # # ==== Parameters # * domain_name<~String>:: Name of domain. Must be between 3 and 255 of the # following characters: a-z, A-Z, 0-9, '_', '-' and '.'. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'BoxUsage' # * 'RequestId' def create_domain(domain_name) request( 'Action' => 'CreateDomain', 'DomainName' => domain_name, :idempotent => true, :parser => Fog::Parsers::AWS::SimpleDB::Basic.new(@nil_string) ) end end class Mock def create_domain(domain_name) response = Excon::Response.new self.data[:domains][domain_name] = {} response.status = 200 response.body = { 'BoxUsage' => Fog::AWS::Mock.box_usage, 'RequestId' => Fog::AWS::Mock.request_id } response end end end end end fog-1.19.0/lib/fog/aws/requests/simpledb/put_attributes.rb0000644000004100000410000000615312261242551023602 0ustar www-datawww-datamodule Fog module AWS class SimpleDB class Real # Put item attributes into a SimpleDB domain # # ==== Parameters # * domain_name<~String> - Name of domain. Must be between 3 and 255 of the # following characters: a-z, A-Z, 0-9, '_', '-' and '.'. # * item_name<~String> - Name of the item. May use any UTF-8 characters valid # in xml. Control characters and sequences not allowed in xml are not # valid. Can be up to 1024 bytes long. # * attributes<~Hash> - Name/value pairs to add to the item. Attribute names # and values may use any UTF-8 characters valid in xml. Control characters # and sequences not allowed in xml are not valid. Each name and value can # be up to 1024 bytes long. # * options<~Hash> - Accepts the following keys. # :replace => [Array of keys to replace] # :expect => {name/value pairs for performing conditional put} # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'BoxUsage' # * 'RequestId' def put_attributes(domain_name, item_name, attributes, options = {}) options[:expect] = {} unless options[:expect] options[:replace] = [] unless options[:replace] request({ 'Action' => 'PutAttributes', 'DomainName' => domain_name, 'ItemName' => item_name, :parser => Fog::Parsers::AWS::SimpleDB::Basic.new(@nil_string) }.merge!(encode_attributes(attributes, options[:replace], options[:expect]))) end end class Mock def put_attributes(domain_name, item_name, attributes, options = {}) options[:expect] = {} unless options[:expect] options[:replace] = [] unless options[:replace] response = Excon::Response.new if self.data[:domains][domain_name] options[:expect].each do |ck, cv| if self.data[:domains][domain_name][item_name][ck] != [cv] response.status = 409 raise(Excon::Errors.status_error({:expects => 200}, response)) end end attributes.each do |key, value| self.data[:domains][domain_name][item_name] ||= {} self.data[:domains][domain_name][item_name][key.to_s] = [] unless self.data[:domains][domain_name][item_name][key.to_s] if options[:replace].include?(key.to_s) self.data[:domains][domain_name][item_name][key.to_s] = [*value].map {|x| x.to_s} else self.data[:domains][domain_name][item_name][key.to_s] += [*value].map {|x| x.to_s} end end response.status = 200 response.body = { 'BoxUsage' => Fog::AWS::Mock.box_usage, 'RequestId' => Fog::AWS::Mock.request_id } else response.status = 400 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/requests/simpledb/select.rb0000644000004100000410000000325512261242551022003 0ustar www-datawww-datamodule Fog module AWS class SimpleDB class Real require 'fog/aws/parsers/simpledb/select' # Select item data from SimpleDB # # ==== Parameters # * select_expression<~String> - Expression to query domain with. # * options<~Hash>: # * ConsistentRead<~Boolean> - When set to true, ensures most recent data is returned. Defaults to false. # * NextToken<~String> - Offset token to start list, defaults to nil. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'BoxUsage'<~Float> # * 'RequestId'<~String> # * 'Items'<~Hash> - list of attribute name/values for the items formatted as # { 'item_name' => { 'attribute_name' => ['attribute_value'] }} # * 'NextToken'<~String> - offset to start with if there are are more domains to list def select(select_expression, options = {}) if options.is_a?(String) Fog::Logger.deprecation("get_attributes with string next_token param is deprecated, use 'AttributeName' => attributes) instead [light_black](#{caller.first})[/]") options = {'NextToken' => options} end options['NextToken'] ||= nil request( 'Action' => 'Select', 'ConsistentRead' => !!options['ConsistentRead'], 'NextToken' => options['NextToken'], 'SelectExpression' => select_expression, :idempotent => true, :parser => Fog::Parsers::AWS::SimpleDB::Select.new(@nil_string) ) end end end end end fog-1.19.0/lib/fog/aws/requests/simpledb/list_domains.rb0000644000004100000410000000333312261242551023206 0ustar www-datawww-datamodule Fog module AWS class SimpleDB class Real require 'fog/aws/parsers/simpledb/list_domains' # List SimpleDB domains # # ==== Parameters # * options<~Hash> - options, defaults to {} # * 'MaxNumberOfDomains'<~Integer> - number of domains to return # between 1 and 100, defaults to 100 # * 'NextToken'<~String> - Offset token to start listing, defaults to nil # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'BoxUsage' # * 'Domains' - array of domain names. # * 'NextToken' - offset to start with if there are are more domains to list # * 'RequestId' def list_domains(options = {}) request({ 'Action' => 'ListDomains', :idempotent => true, :parser => Fog::Parsers::AWS::SimpleDB::ListDomains.new(@nil_string) }.merge!(options)) end end class Mock def list_domains(options = {}) response = Excon::Response.new keys = self.data[:domains].keys max = options['MaxNumberOfDomains'] || keys.size offset = options['NextToken'] || 0 domains = [] for key, value in self.data[:domains].keys[offset...max] domains << key end response.status = 200 response.body = { 'BoxUsage' => Fog::AWS::Mock.box_usage, 'Domains' => domains, 'RequestId' => Fog::AWS::Mock.request_id } if max < keys.size response.body['NextToken'] = max + 1 end response end end end end end fog-1.19.0/lib/fog/aws/requests/simpledb/delete_domain.rb0000644000004100000410000000217312261242551023313 0ustar www-datawww-datamodule Fog module AWS class SimpleDB class Real # Delete a SimpleDB domain # # ==== Parameters # * domain_name<~String>:: Name of domain. Must be between 3 and 255 of the # following characters: a-z, A-Z, 0-9, '_', '-' and '.'. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'BoxUsage' # * 'RequestId' def delete_domain(domain_name) request( 'Action' => 'DeleteDomain', 'DomainName' => domain_name, :idempotent => true, :parser => Fog::Parsers::AWS::SimpleDB::Basic.new(@nil_string) ) end end class Mock def delete_domain(domain_name) response = Excon::Response.new if self.data[:domains].delete(domain_name) response.status = 200 response.body = { 'BoxUsage' => Fog::AWS::Mock.box_usage, 'RequestId' => Fog::AWS::Mock.request_id } end response end end end end end fog-1.19.0/lib/fog/aws/requests/simpledb/get_attributes.rb0000644000004100000410000000704312261242551023550 0ustar www-datawww-datamodule Fog module AWS class SimpleDB class Real require 'fog/aws/parsers/simpledb/get_attributes' # List metadata for SimpleDB domain # # ==== Parameters # * domain_name<~String> - Name of domain. Must be between 3 and 255 of the # following characters: a-z, A-Z, 0-9, '_', '-' and '.'. # * item_name<~String> - Name of the item. May use any UTF-8 characters valid # in xml. Control characters and sequences not allowed in xml are not # valid. Can be up to 1024 bytes long. # * options<~Hash>: # * AttributeName<~Array> - Attributes to return from the item. Defaults to # {}, which will return all attributes. Attribute names and values may use # any UTF-8 characters valid in xml. Control characters and sequences not # allowed in xml are not valid. Each name and value can be up to 1024 # bytes long. # * ConsistentRead<~Boolean> - When set to true, ensures most recent data is returned. Defaults to false. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Attributes' - list of attribute name/values for the item # * 'BoxUsage' # * 'RequestId' def get_attributes(domain_name, item_name, options = {}) if options.is_a?(Array) Fog::Logger.deprecation("get_attributes with array attributes param is deprecated, use 'AttributeName' => attributes) instead [light_black](#{caller.first})[/]") options = {'AttributeName' => options} end options['AttributeName'] ||= [] request({ 'Action' => 'GetAttributes', 'ConsistentRead' => !!options['ConsistentRead'], 'DomainName' => domain_name, 'ItemName' => item_name, :idempotent => true, :parser => Fog::Parsers::AWS::SimpleDB::GetAttributes.new(@nil_string) }.merge!(encode_attribute_names(options['AttributeName']))) end end class Mock def get_attributes(domain_name, item_name, options = {}) if options.is_a?(Array) Fog::Logger.deprecation("get_attributes with array attributes param is deprecated, use 'AttributeName' => attributes) instead [light_black](#{caller.first})[/]") options['AttributeName'] ||= options if options.is_a?(Array) end options['AttributeName'] ||= [] response = Excon::Response.new if self.data[:domains][domain_name] object = {} if !options['AttributeName'].empty? for attribute in options['AttributeName'] if self.data[:domains][domain_name].has_key?(item_name) && self.data[:domains][domain_name][item_name].has_key?(attribute) object[attribute] = self.data[:domains][domain_name][item_name][attribute] end end elsif self.data[:domains][domain_name][item_name] object = self.data[:domains][domain_name][item_name] end response.status = 200 response.body = { 'Attributes' => object, 'BoxUsage' => Fog::AWS::Mock.box_usage, 'RequestId' => Fog::AWS::Mock.request_id } else response.status = 400 raise(Excon::Errors.status_error({:expects => 200}, response)) end response end end end end end fog-1.19.0/lib/fog/aws/beanstalk.rb0000644000004100000410000001200312261242551017005 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class ElasticBeanstalk < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods class InvalidParameterError < Fog::Errors::Error; end requires :aws_access_key_id, :aws_secret_access_key recognizes :region, :host, :path, :port, :scheme, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at request_path 'fog/aws/requests/beanstalk' request :check_dns_availability request :create_application request :create_application_version request :create_configuration_template request :create_environment request :create_storage_location request :delete_application request :delete_application_version request :delete_configuration_template request :delete_environment_configuration request :describe_applications request :describe_application_versions request :describe_configuration_options request :describe_configuration_settings request :describe_environment_resources request :describe_environments request :describe_events request :list_available_solution_stacks request :rebuild_environment request :request_environment_info request :restart_app_server request :retrieve_environment_info request :swap_environment_cnames request :terminate_environment request :update_application request :update_application_version request :update_configuration_template request :update_environment request :validate_configuration_settings model_path 'fog/aws/models/beanstalk' model :application collection :applications model :environment collection :environments model :event collection :events model :template collection :templates model :version collection :versions class Mock def initialize(options={}) Fog::Mock.not_implemented end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods def initialize(options={}) require 'fog/core/parser' @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} options[:region] ||= 'us-east-1' @host = options[:host] || "elasticbeanstalk.#{options[:region]}.amazonaws.com" @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end def reload @connection.reset end # Returns an array of available solutions stack details def solution_stacks list_available_solution_stacks.body['ListAvailableSolutionStacksResult']['SolutionStackDetails'] end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) end def request(params) refresh_credentials_if_expired idempotent = params.delete(:idempotent) parser = params.delete(:parser) body = AWS.signed_params( params, { :aws_access_key_id => @aws_access_key_id, :aws_session_token => @aws_session_token, :hmac => @hmac, :host => @host, :path => @path, :port => @port, :version => '2010-12-01' } ) begin @connection.request({ :body => body, :expects => 200, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded' }, :idempotent => idempotent, :host => @host, :method => 'POST', :parser => parser }) rescue Excon::Errors::HTTPStatusError => error match = Fog::AWS::Errors.match_error(error) raise if match.empty? raise case match[:code] when 'InvalidParameterValue' Fog::AWS::ElasticBeanstalk::InvalidParameterError.slurp(error, match[:message]) else Fog::AWS::ElasticBeanstalk::Error.slurp(error, "#{match[:code]} => #{match[:message]}") end end end end end end end fog-1.19.0/lib/fog/aws/parsers/0000755000004100000410000000000012261242551016177 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/sts/0000755000004100000410000000000012261242551017010 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/sts/assume_role.rb0000644000004100000410000000121112261242551021646 0ustar www-datawww-datamodule Fog module Parsers module AWS module STS class AssumeRole < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'SessionToken', 'SecretAccessKey', 'Expiration', 'AccessKeyId' @response[name] = @value.strip when 'Arn', 'AssumedRoleId' @response[name] = @value.strip when 'PackedPolicySize' @response[name] = @value when 'RequestId' @response[name] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sts/get_session_token.rb0000644000004100000410000000127112261242551023060 0ustar www-datawww-datamodule Fog module Parsers module AWS module STS class GetSessionToken < Fog::Parsers::Base # http://docs.amazonwebservices.com/IAM/latest/UserGuide/index.html?CreatingFedTokens.html def reset @response = {} end def end_element(name) case name when 'SessionToken', 'SecretAccessKey', 'Expiration', 'AccessKeyId' @response[name] = @value.strip when 'Arn', 'FederatedUserId', 'PackedPolicySize' @response[name] = @value.strip when 'RequestId' @response[name] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sqs/0000755000004100000410000000000012261242551017005 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/sqs/list_queues.rb0000644000004100000410000000076712261242551021706 0ustar www-datawww-datamodule Fog module Parsers module AWS module SQS class ListQueues < Fog::Parsers::Base def reset @response = { 'QueueUrls' => [], 'ResponseMetadata' => {} } end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = @value when 'QueueUrl' @response['QueueUrls'] << @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sqs/create_queue.rb0000644000004100000410000000074412261242551022006 0ustar www-datawww-datamodule Fog module Parsers module AWS module SQS class CreateQueue < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = @value when 'QueueUrl' @response['QueueUrl'] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sqs/receive_message.rb0000644000004100000410000000234212261242551022461 0ustar www-datawww-datamodule Fog module Parsers module AWS module SQS class ReceiveMessage < Fog::Parsers::Base def reset @message = { 'Attributes' => {} } @response = { 'ResponseMetadata' => {}, 'Message' => []} end def end_element(name) case name when 'RequestId' @response['ResponseMetadata']['RequestId'] = @value when 'Message' @response['Message'] << @message @message = { 'Attributes' => {} } when 'Body', 'MD5OfBody', 'MessageId', 'ReceiptHandle' @message[name] = @value when 'Name' @current_attribute_name = @value when 'Value' case @current_attribute_name when 'ApproximateFirstReceiveTimestamp', 'SentTimestamp' @message['Attributes'][@current_attribute_name] = Time.at(@value.to_i / 1000.0) when 'ApproximateReceiveCount' @message['Attributes'][@current_attribute_name] = @value.to_i else @message['Attributes'][@current_attribute_name] = @value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sqs/send_message.rb0000644000004100000410000000107712261242551021774 0ustar www-datawww-datamodule Fog module Parsers module AWS module SQS class SendMessage < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = @value when 'MessageId' @response['MessageId'] = @value when 'MD5OfMessageBody' @response['MD5OfMessageBody'] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sqs/get_queue_attributes.rb0000644000004100000410000000207312261242551023565 0ustar www-datawww-datamodule Fog module Parsers module AWS module SQS class GetQueueAttributes < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {}, 'Attributes' => {}} end def end_element(name) case name when 'RequestId' @response['ResponseMetadata']['RequestId'] = @value when 'Name' @current_attribute_name = @value when 'Value' case @current_attribute_name when 'ApproximateNumberOfMessages', 'ApproximateNumberOfMessagesNotVisible', 'MaximumMessageSize', 'MessageRetentionPeriod', 'VisibilityTimeout' @response['Attributes'][@current_attribute_name] = @value.to_i when 'CreatedTimestamp', 'LastModifiedTimestamp' @response['Attributes'][@current_attribute_name] = Time.at(@value.to_i) else @response['Attributes'][@current_attribute_name] = @value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sqs/basic.rb0000644000004100000410000000062412261242551020415 0ustar www-datawww-datamodule Fog module Parsers module AWS module SQS class Basic < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/0000755000004100000410000000000012261242551017643 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/storage/get_service.rb0000644000004100000410000000126212261242551022470 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class GetService < Fog::Parsers::Base def reset @bucket = {} @response = { 'Owner' => {}, 'Buckets' => [] } end def end_element(name) case name when 'Bucket' @response['Buckets'] << @bucket @bucket = {} when 'CreationDate' @bucket['CreationDate'] = Time.parse(value) when 'DisplayName', 'ID' @response['Owner'][name] = value when 'Name' @bucket[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/get_bucket_tagging.rb0000644000004100000410000000134612261242551024010 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class GetBucketTagging < Fog::Parsers::Base def reset @in_tag = {} @response = {'BucketTagging' => {}} end def start_element(name, *args) super if name == 'Tag' @in_tag = {} end end def end_element(name) case name when 'Tag' @response['BucketTagging'].merge!(@in_tag) @in_tag = {} when 'Key' @in_tag[value] = nil when 'Value' @in_tag = {@in_tag.keys.first => value} end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/initiate_multipart_upload.rb0000644000004100000410000000061412261242551025444 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class InitiateMultipartUpload < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'Bucket', 'Key', 'UploadId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/get_bucket_website.rb0000644000004100000410000000077712261242551024041 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class GetBucketWebsite < Fog::Parsers::Base def reset @response = { 'ErrorDocument' => {}, 'IndexDocument' => {} } end def end_element(name) case name when 'Key' @response['ErrorDocument'][name] = value when 'Suffix' @response['IndexDocument'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/get_bucket_location.rb0000644000004100000410000000050112261242551024170 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class GetBucketLocation < Fog::Parsers::Base def end_element(name) case name when 'LocationConstraint' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/list_parts.rb0000644000004100000410000000201712261242551022354 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class ListParts < Fog::Parsers::Base def reset @part = {} @response = { 'Initiator' => {}, 'Part' => [] } end def end_element(name) case name when 'Bucket', 'Key', 'NextPartNumberMarker', 'PartNumberMarker', 'StorageClass', 'UploadId' @response[name] = value when 'DisplayName', 'ID' @response['Initiator'][name] = value when 'ETag' @part[name] = value when 'IsTruncated' @response[name] = value == 'true' when 'LastModified' @part[name] = Time.parse(value) when 'MaxParts' @response[name] = value.to_i when 'Part' @response['Part'] << @part @part = {} when 'PartNumber', 'Size' @part[name] = value.to_i end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/list_multipart_uploads.rb0000644000004100000410000000300412261242551024770 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class ListMultipartUploads < Fog::Parsers::Base def reset @upload = { 'Initiator' => {}, 'Owner' => {} } @response = { 'Upload' => [] } end def start_element(name, attrs = []) super case name when 'Initiator' @in_initiator = true when 'Owner' @in_owner = true end end def end_element(name) case name when 'Bucket', 'KeyMarker', 'NextKeyMarker', 'NextUploadIdMarker', 'UploadIdMarker' @response[name] = value when 'DisplayName', 'ID' if @in_initiator @upload['Initiator'][name] = value elsif @in_owner @upload['Owner'][name] = value end when 'Initiated' @upload[name] = Time.parse(value) when 'Initiator' @in_initiator = false when 'IsTruncated' @response[name] = value == 'true' when 'Key', 'StorageClass', 'UploadId' @upload[name] = value when 'MaxUploads' @response[name] = value.to_i when 'Owner' @in_owner = false when 'Upload' @response['Upload'] << @upload @upload = { 'Initiator' => {}, 'Owner' => {} } end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/copy_object.rb0000644000004100000410000000061412261242551022471 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class CopyObject < Fog::Parsers::Base def end_element(name) case name when 'ETag' @response[name] = value.gsub('"', '') when 'LastModified' @response[name] = Time.parse(value) end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/get_bucket_versioning.rb0000644000004100000410000000067612261242551024560 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class GetBucketVersioning < Fog::Parsers::Base def reset @response = { 'VersioningConfiguration' => {} } end def end_element(name) case name when 'Status', 'MfaDelete' @response['VersioningConfiguration'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/get_bucket_object_versions.rb0000644000004100000410000000477012261242551025572 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class GetBucketObjectVersions < Fog::Parsers::Base def reset @delete_marker = { 'Owner' => {} } @version = { 'Owner' => {} } @in_delete_marke = false @in_version = false @response = { 'Versions' => [] } end def start_element(name, attrs = []) super case name when 'DeleteMarker' @in_delete_marker = true when 'Version' @in_version = true end end def end_element(name) case name when 'DeleteMarker' @response['Versions'] << {'DeleteMarker' => @delete_marker } @delete_marker = { 'Owner' => {} } @in_delete_marker = false when 'Version' @response['Versions'] << {'Version' => @version } @version = { 'Owner' => {} } @in_version = false when 'DisplayName', 'ID' if @in_delete_marker @delete_marker elsif @in_version @version end['Owner'][name] = value when 'ETag' @version[name] = value.gsub('"', '') when 'IsLatest' if @in_delete_marker @delete_marker elsif @in_version @version end['IsLatest'] = if value == 'true' true else false end when 'IsTruncated' if value == 'true' @response['IsTruncated'] = true else @response['IsTruncated'] = false end when 'LastModified' if @in_delete_marker @delete_marker elsif @in_version @version end['LastModified'] = Time.parse(value) when 'MaxKeys' @response['MaxKeys'] = value.to_i when 'Size' @version['Size'] = value.to_i when 'Key', 'KeyMarker', 'Name', 'NextKeyMarker', 'NextVersionIdMarker', 'Prefix', 'StorageClass', 'VersionId', 'VersionIdMarker' if @in_delete_marker @delete_marker elsif @in_version @version else @response end[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/get_request_payment.rb0000644000004100000410000000046412261242551024260 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class GetRequestPayment < Fog::Parsers::Base def end_element(name) case name when 'Payer' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/get_bucket_lifecycle.rb0000644000004100000410000000334112261242551024324 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class GetBucketLifecycle < Fog::Parsers::Base def reset @expiration = {} @transition = {} @rule = {} @response = { 'Rules' => [] } end def start_element(name, attrs=[]) super case name when 'Expiration' @in_expiration = true when 'Transition' @in_transition = true end end def end_element(name) if @in_expiration case name when 'Days' @expiration[name] = value.to_i when 'Date' @expiration[name] = value when 'Expiration' @rule['Expiration'] = @expiration @in_expiration = false @expiration = {} end elsif @in_transition case name when 'StorageClass', @transition['StorageClass'] = value when 'Date' @transition[name] = value when 'Days' @transition[name] = value.to_i when 'Transition' @rule['Transition'] = @transition @in_transition = false @transition = {} end else case name when 'ID', 'Prefix' @rule[name] = value when 'Status' @rule['Enabled'] = value == 'Enabled' when 'Rule' @response['Rules'] << @rule @rule = {} end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/complete_multipart_upload.rb0000644000004100000410000000064712261242551025454 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class CompleteMultipartUpload < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'Bucket', 'ETag', 'Key', 'Location', 'Code', 'Message' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/access_control_list.rb0000644000004100000410000000222112261242551024221 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class AccessControlList < Fog::Parsers::Base def reset @in_access_control_list = false @grant = { 'Grantee' => {} } @response = { 'Owner' => {}, 'AccessControlList' => [] } end def start_element(name, attrs = []) super if name == 'AccessControlList' @in_access_control_list = true end end def end_element(name) case name when 'AccessControlList' @in_access_control_list = false when 'Grant' @response['AccessControlList'] << @grant @grant = { 'Grantee' => {} } when 'DisplayName', 'ID' if @in_access_control_list @grant['Grantee'][name] = value else @response['Owner'][name] = value end when 'Permission' @grant[name] = value when 'URI' @grant['Grantee'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/cors_configuration.rb0000644000004100000410000000205612261242551024070 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class CorsConfiguration < Fog::Parsers::Base def reset @in_cors_configuration_list = false @cors_rule = {} @response = { 'CORSConfiguration' => [] } end def start_element(name, attrs = []) super if name == 'CORSConfiguration' @in_cors_configuration_list = true end end def end_element(name) case name when 'CORSConfiguration' @in_cors_configuration_list = false when 'CORSRule' @response['CORSConfiguration'] << @cors_rule @cors_rule = {} when 'MaxAgeSeconds' @cors_rule[name] = value.to_i when 'ID' @cors_rule[name] = value when 'AllowedOrigin', 'AllowedMethod', 'AllowedHeader', 'ExposeHeader' (@cors_rule[name] ||= []) << value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/get_bucket.rb0000644000004100000410000000325112261242551022305 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class GetBucket < Fog::Parsers::Base def reset @object = { 'Owner' => {} } @response = { 'Contents' => [], 'CommonPrefixes' => [] } end def start_element(name, attrs = []) super case name when 'CommonPrefixes' @in_common_prefixes = true end end def end_element(name) case name when 'CommonPrefixes' @in_common_prefixes = false when 'Contents' @response['Contents'] << @object @object = { 'Owner' => {} } when 'DisplayName', 'ID' @object['Owner'][name] = value when 'ETag' @object[name] = value.gsub('"', '') when 'IsTruncated' if value == 'true' @response['IsTruncated'] = true else @response['IsTruncated'] = false end when 'LastModified' @object['LastModified'] = Time.parse(value) when 'Marker', 'Name' @response[name] = value when 'MaxKeys' @response['MaxKeys'] = value.to_i when 'Prefix' if @in_common_prefixes @response['CommonPrefixes'] << value else @response[name] = value end when 'Size' @object['Size'] = value.to_i when 'Delimiter', 'Key', 'StorageClass' @object[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/get_bucket_logging.rb0000644000004100000410000000213412261242551024012 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class GetBucketLogging < Fog::Parsers::Base def reset @grant = { 'Grantee' => {} } @response = { 'BucketLoggingStatus' => {} } end def end_element(name) case name when 'DisplayName', 'ID' if @in_access_control_list @grant['Grantee'][name] = value else @response['Owner'][name] = value end when 'Grant' @response['BucketLoggingStatus']['LoggingEnabled']['TargetGrants'] << @grant @grant = { 'Grantee' => {} } when 'LoggingEnabled' @response['BucketLoggingStatus']['LoggingEnabled'] = { 'TargetGrants' => [] } when 'Permission' @grant[name] = value when 'TargetBucket', 'TargetPrefix' @response['BucketLoggingStatus'][name] = value when 'URI' @grant['Grantee'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/storage/delete_multiple_objects.rb0000644000004100000410000000234112261242551025056 0ustar www-datawww-datamodule Fog module Parsers module Storage module AWS class DeleteMultipleObjects < Fog::Parsers::Base def reset @deleted = { 'Deleted' => {} } @error = { 'Error' => {} } @response = { 'DeleteResult' => [] } end def start_element(name, attrs = []) super case name when 'Deleted' @in_deleted = true end end def end_element(name) case name when 'Deleted' @response['DeleteResult'] << @deleted @deleted = { 'Deleted' => {} } @in_deleted = false when 'Error' @response['DeleteResult'] << @error @error = { 'Error' => {} } when 'Key', 'VersionId' if @in_deleted @deleted['Deleted'][name] = value else @error['Error'][name] = value end when 'DeleteMarker', 'DeletemarkerVersionId' @deleted['Deleted'][name] = value when 'Code', 'Message' @error['Error'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/emr/0000755000004100000410000000000012261242551016762 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/emr/set_termination_protection.rb0000644000004100000410000000047012261242551024762 0ustar www-datawww-datamodule Fog module Parsers module AWS module EMR class SetTerminationProtection < Fog::Parsers::Base def end_element(name) case name when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/emr/add_instance_groups.rb0000644000004100000410000000111312261242551023316 0ustar www-datawww-datamodule Fog module Parsers module AWS module EMR class AddInstanceGroups < Fog::Parsers::Base def start_element(name, attrs = []) super case name when 'InstanceGroupIds' @response['InstanceGroupIds'] = [] end end def end_element(name) case name when 'JobFlowId' @response[name] = value when 'member' @response['InstanceGroupIds'] << value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/emr/terminate_job_flows.rb0000644000004100000410000000046112261242551023344 0ustar www-datawww-datamodule Fog module Parsers module AWS module EMR class TerminateJobFlows < Fog::Parsers::Base def end_element(name) case name when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/emr/run_job_flow.rb0000644000004100000410000000055512261242551022001 0ustar www-datawww-datamodule Fog module Parsers module AWS module EMR class RunJobFlow < Fog::Parsers::Base def end_element(name) case name when 'JobFlowId' @response[name] = value when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/emr/add_job_flow_steps.rb0000644000004100000410000000045712261242551023144 0ustar www-datawww-datamodule Fog module Parsers module AWS module EMR class AddJobFlowSteps < Fog::Parsers::Base def end_element(name) case name when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/emr/describe_job_flows.rb0000644000004100000410000001165512261242551023143 0ustar www-datawww-datamodule Fog module Parsers module AWS module EMR class DescribeJobFlows < Fog::Parsers::Base def reset @context = [] @contexts = ['BootstrapActions', 'ExecutionStatusDetail', 'Instances', 'Steps', 'InstanceGroups', 'Args'] @response = { 'JobFlows' => [] } @bootstrap_actions = {'ScriptBootstrapActionConfig' => {'Args' => []}} @instance = { 'InstanceGroups' => [], 'Placement' => {}} @step = { 'ExecutionStatusDetail' => {}, 'StepConfig' => { 'HadoopJarStepConfig' => { 'Args' => [], 'Properties' => [] } } } @flow = {'Instances' => [], 'ExecutionStatusDetail' => {}, 'BootstrapActions' => [], 'Steps' => []} @instance_group_detail = {} @execution_status_detail = {} end def start_element(name, attrs = []) super if @contexts.include?(name) @context.push(name) end end def end_element(name) if @context.last == 'BootstrapActions' case name when 'Name' @bootstrap_actions[name] = value when 'Path' @bootstrap_actions['ScriptBootstrapActionConfig'][name] = value when 'BootstrapActions' @flow['BootstrapActions'] = @bootstrap_actions @bootstrap_actions = {'ScriptBootstrapActionConfig' => {'Args' => []}} end end if @context.last == 'ExecutionStatusDetail' case name when 'CreationDateTime', 'EndDateTime', 'LastStateChangeReason', 'ReadyDateTime', 'StartDateTime', 'State' @execution_status_detail[name] = value when 'ExecutionStatusDetail' if @context.include?('Steps') @step['ExecutionStatusDetail'] = @execution_status_detail else @flow['ExecutionStatusDetail'] = @execution_status_detail end @execution_status_detail = {} end end if @context.last == 'Instances' case name when 'AvailabilityZone' @instance['Placement'][name] = value when 'Ec2KeyName', 'HadoopVersion', 'InstanceCount', 'KeepJobFlowAliveWhenNoSteps', 'MasterInstanceId', 'MasterInstanceType', 'MasterPublicDnsName', 'NormalizedInstanceHours', 'SlaveInstanceType', 'TerminationProtected' @instance[name] = value when 'member' @instance['InstanceGroups'] << @instance_group_detail @instance_group_detail = {} when 'Instances' @flow['Instances'] = @instance @instance = { 'InstanceGroups' => [], 'Placement' => {}} end end if @context.last == 'InstanceGroups' case name when 'member' @instance['InstanceGroups'] << @instance_group_detail @instance_group_detail = {} else @instance_group_detail[name] = value end end if @context.last == 'Args' if name == 'member' if @context.include?('Steps') @step['StepConfig']['HadoopJarStepConfig']['Args'] << value.strip else @bootstrap_actions['ScriptBootstrapActionConfig']['Args'] << value end end end if @context.last == 'Steps' case name when 'ActionOnFailure', 'Name' @step[name] = value when 'Jar', 'MainClass' @step['StepConfig']['HadoopJarStepConfig'][name] = value when 'member' @flow['Steps'] << @step @step = { 'ExecutionStatusDetail' => {}, 'StepConfig' => { 'HadoopJarStepConfig' => { 'Args' => [], 'Properties' => [] } } } end end if @context.empty? case name when 'AmiVersion', 'JobFlowId', 'LogUri', 'Name' @flow[name] = value when 'member' @response['JobFlows'] << @flow @flow = {'Instances' => [], 'ExecutionStatusDetail' => {}, 'BootstrapActions' => [], 'Steps' => []} end end if @context.last == name @context.pop end end end end end end end fog-1.19.0/lib/fog/aws/parsers/emr/modify_instance_groups.rb0000644000004100000410000000046412261242551024065 0ustar www-datawww-datamodule Fog module Parsers module AWS module EMR class ModifyInstanceGroups < Fog::Parsers::Base def end_element(name) case name when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/0000755000004100000410000000000012261242551020647 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/auto_scaling/describe_policies.rb0000644000004100000410000000334212261242551024645 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class DescribePolicies < Fog::Parsers::Base def reset reset_scaling_policy reset_alarm @results = { 'ScalingPolicies' => [] } @response = { 'DescribePoliciesResult' => {}, 'ResponseMetadata' => {} } @in_alarms = false end def reset_scaling_policy @scaling_policy = { 'Alarms' => [] } end def reset_alarm @alarm = {} end def start_element(name, attrs = []) super case name when 'Alarms' @in_alarms = true end end def end_element(name) case name when 'AlarmARN', 'AlarmName' @alarm[name] = value when 'AdjustmentType', 'AutoScalingGroupName', 'PolicyARN', 'PolicyName' @scaling_policy[name] = value when 'Cooldown', 'MinAdjustmentStep', 'ScalingAdjustment' @scaling_policy[name] = value.to_i when 'NextToken' @results[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribePoliciesResponse' @response['DescribePoliciesResult'] = @results when 'Alarms' @in_alarms = false when 'member' if @in_alarms @scaling_policy['Alarms'] << @alarm reset_alarm else @results['ScalingPolicies'] << @scaling_policy reset_scaling_policy end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/terminate_instance_in_auto_scaling_group.rb0000644000004100000410000000201712261242551031502 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class TerminateInstanceInAutoScalingGroup < Fog::Parsers::Base def reset @results = { 'Activity' => {} } @response = { 'TerminateInstanceInAutoScalingGroupResult' => {}, 'ResponseMetadata' => {} } end def end_element(name) case name when 'ActivityId', 'AutoScalingGroupName', 'Cause', 'Description', 'StatusCode', 'StatusMessage' @results['Activity'][name] = value when 'EndTime', 'StartTime' @results['Activity'][name] = Time.parse(value) when 'Progress' @results['Activity'][name] = value.to_i when 'RequestId' @response['ResponseMetadata'][name] = value when 'TerminateInstanceInAutoScalingGroupResponse' @response['TerminateInstanceInAutoScalingGroupResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/put_notification_configuration.rb0000644000004100000410000000101312261242551027474 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class PutNotificationConfiguration < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/describe_auto_scaling_notification_types.rb0000644000004100000410000000225512261242551031502 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class DescribeAutoScalingNotificationTypes < Fog::Parsers::Base def reset @results = { 'AutoScalingNotificationTypes' => [] } @response = { 'DescribeAutoScalingNotificationTypesResult' => {}, 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super case name when 'AutoScalingNotificationTypes' @in_auto_scaling_notification_types = true end end def end_element(name) case name when 'member' if @in_auto_scaling_notification_types @results['AutoScalingNotificationTypes'] << value end when 'AutoScalingNotificationTypes' @in_auto_scaling_notification_types = false when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribeAutoScalingNotificationTypesResponse' @response['DescribeAutoScalingNotificationTypesResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/describe_metric_collection_types.rb0000644000004100000410000000315512261242551027762 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class DescribeMetricCollectionTypes < Fog::Parsers::Base def reset reset_granularity reset_metric @results = { 'Granularities' => [], 'Metrics' => [] } @response = { 'DescribeMetricCollectionTypesResult' => {}, 'ResponseMetadata' => {} } end def reset_granularity @granularity = {} end def reset_metric @metric = {} end def start_element(name, attrs = []) super case name when 'Granularities' @in_granularities = true when 'Metrics' @in_metrics = true end end def end_element(name) case name when 'member' if @in_granularities @results['Granularities'] << @granularity reset_granularity elsif @in_metrics @results['Metrics'] << @metric reset_metric end when 'Granularity' @granularity[name] = value when 'Granularities' @in_granularities = false when 'Metric' @metric[name] = value when 'Metrics' @in_metrics = false when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribeMetricCollectionTypesResult' @response[name] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/describe_launch_configurations.rb0000644000004100000410000000621712261242551027426 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class DescribeLaunchConfigurations < Fog::Parsers::Base def reset reset_launch_configuration reset_block_device_mapping reset_ebs @results = { 'LaunchConfigurations' => [] } @response = { 'DescribeLaunchConfigurationsResult' => {}, 'ResponseMetadata' => {} } end def reset_launch_configuration @launch_configuration = { 'BlockDeviceMappings' => [], 'InstanceMonitoring' => {}, 'SecurityGroups' => [] } end def reset_block_device_mapping @block_device_mapping = {} end def reset_ebs @ebs = {} end def start_element(name, attrs = []) super case name when 'BlockDeviceMappings' @in_block_device_mappings = true when 'SecurityGroups' @in_security_groups = true end end def end_element(name) case name when 'member' if @in_block_device_mappings @launch_configuration['BlockDeviceMappings'] << @block_device_mapping reset_block_device_mapping elsif @in_security_groups @launch_configuration['SecurityGroups'] << value else @results['LaunchConfigurations'] << @launch_configuration reset_launch_configuration end when 'DeviceName', 'VirtualName' @block_device_mapping[name] = value when 'SnapshotId', 'VolumeSize' @ebs[name] = value when 'Ebs' @block_device_mapping[name] = @ebs reset_ebs when 'Enabled' @launch_configuration['InstanceMonitoring'][name] = (value == 'true') when 'CreatedTime' @launch_configuration[name] = Time.parse(value) when 'ImageId', 'InstanceType', 'KeyName' @launch_configuration[name] = value when 'LaunchConfigurationARN', 'LaunchConfigurationName' @launch_configuration[name] = value when 'KernelId', 'RamdiskId', 'UserData' @launch_configuration[name] = value when 'IamInstanceProfile' @launch_configuration[name] = value when 'SpotPrice' @launch_configuration[name] = value.to_f when 'AssociatePublicIpAddress' @in_associate_public_ip = false when 'BlockDeviceMappings' @in_block_device_mappings = false when 'LaunchConfigurations' @in_launch_configurations = false when 'SecurityGroups' @in_security_groups = false when 'NextToken' @results[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribeLaunchConfigurationsResponse' @response['DescribeLaunchConfigurationsResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/describe_notification_configurations.rb0000644000004100000410000000225712261242551030642 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class DescribeNotificationConfigurations < Fog::Parsers::Base def reset reset_notification_configuration @results = { 'NotificationConfigurations' => [] } @response = { 'DescribeNotificationConfigurationsResult' => {}, 'ResponseMetadata' => {} } end def reset_notification_configuration @notification_configuration = {} end def end_element(name) case name when 'member' @results['NotificationConfigurations'] << @notification_configuration reset_notification_configuration when 'AutoScalingGroupName','NotificationType', 'TopicARN' @notification_configuration[name] = value when 'NextToken' @results[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribeNotificationConfigurationsResponse' @response['DescribeNotificationConfigurationsResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/describe_termination_policy_types.rb0000644000004100000410000000215112261242551030167 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class DescribeTerminationPolicyTypes < Fog::Parsers::Base def reset @results = { 'TerminationPolicyTypes' => [] } @response = { 'DescribeTerminationPolicyTypesResult' => {}, 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super case name when 'TerminationPolicyTypes' @in_termination_policy_types = true end end def end_element(name) case name when 'member' if @in_termination_policy_types @results['TerminationPolicyTypes'] << value end when 'TerminationPolicyTypes' @in_termination_policy_types = false when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribeTerminationPolicyTypesResponse' @response['DescribeTerminationPolicyTypesResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/describe_scaling_process_types.rb0000644000004100000410000000233612261242551027442 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class DescribeScalingProcessTypes < Fog::Parsers::Base def reset reset_process_type @results = { 'Processes' => [] } @response = { 'DescribeScalingProcessTypesResult' => {}, 'ResponseMetadata' => {} } end def reset_process_type @process_type = {} end def start_element(name, attrs = []) super case name when 'Processes' @in_processes = true end end def end_element(name) case name when 'member' if @in_processes @results['Processes'] << @process_type reset_process_type end when 'ProcessName' @process_type[name] = value when 'Processes' @in_processes = false when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribeScalingProcessTypesResponse' @response['DescribeScalingProcessTypesResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/describe_auto_scaling_instances.rb0000644000004100000410000000227612261242551027562 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class DescribeAutoScalingInstances < Fog::Parsers::Base def reset reset_auto_scaling_instance @results = { 'AutoScalingInstances' => [] } @response = { 'DescribeAutoScalingInstancesResult' => {}, 'ResponseMetadata' => {} } end def reset_auto_scaling_instance @auto_scaling_instance = {} end def end_element(name) case name when 'member' @results['AutoScalingInstances'] << @auto_scaling_instance reset_auto_scaling_instance when 'AutoScalingGroupName', 'AvailabilityZone', 'HealthStatus', 'InstanceId', 'LaunchConfigurationName', 'LifecycleState' @auto_scaling_instance[name] = value when 'NextToken' @results[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribeAutoScalingInstancesResponse' @response['DescribeAutoScalingInstancesResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/describe_tags.rb0000644000004100000410000000175412261242551024001 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class DescribeTags < Fog::Parsers::Base def reset reset_tag @results = { 'Tags' => [] } @response = { 'DescribeTagsResult' => {}, 'ResponseMetadata' => {} } end def reset_tag @tag = {} end def end_element(name) case name when 'member' @results['Tags'] << @tag reset_tag when 'Key', 'ResourceId', 'ResourceType', 'Value' @tag[name] = value when 'PropagateAtLaunch' @tag[name] = (value == 'true') when 'NextToken' @results[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribeTagsResponse' @response['DescribeTagsResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/describe_scheduled_actions.rb0000644000004100000410000000264712261242551026525 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class DescribeScheduledActions < Fog::Parsers::Base def reset reset_scheduled_update_group_action @results = { 'ScheduledUpdateGroupActions' => [] } @response = { 'DescribeScheduledActionsResult' => {}, 'ResponseMetadata' => {} } end def reset_scheduled_update_group_action @scheduled_update_group_action = {} end def end_element(name) case name when 'member' @results['ScheduledUpdateGroupActions'] << @scheduled_update_group_action reset_scheduled_update_group_action when 'AutoScalingGroupName', 'ScheduledActionARN', 'ScheduledActionName', 'Recurrence' @scheduled_update_group_action[name] = value when 'DesiredCapacity', 'MaxSize', 'MinSize' @scheduled_update_group_action[name] = value.to_i when 'Time', 'StartTime', 'EndTime' @scheduled_update_group_action[name] = Time.parse(value) when 'NextToken' @results[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribeScheduledActionsResponse' @response['DescribeScheduledActionsResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/describe_adjustment_types.rb0000644000004100000410000000242012261242551026434 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class DescribeAdjustmentTypes < Fog::Parsers::Base def reset reset_adjustment_type @results = { 'AdjustmentTypes' => [] } @response = { 'DescribeAdjustmentTypesResult' => {}, 'ResponseMetadata' => {} } end def reset_adjustment_type @adjustment_type = {} end def start_element(name, attrs = []) super case name when 'AdjustmentTypes' @in_adjustment_types = true end end def end_element(name) case name when 'member' if @in_adjustment_types @results['AdjustmentTypes'] << @adjustment_type reset_adjustment_type end when 'AdjustmentType' @adjustment_type[name] = value when 'AdjustmentTypes' @in_adjustment_types = false when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribeAdjustmentTypesResponse' @response['DescribeAdjustmentTypesResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/basic.rb0000644000004100000410000000075312261242551022262 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class Basic < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/describe_scaling_activities.rb0000644000004100000410000000232712261242551026704 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class DescribeScalingActivities < Fog::Parsers::Base def reset reset_activity @results = { 'Activities' => [] } @response = { 'DescribeScalingActivitiesResult' => {}, 'ResponseMetadata' => {} } end def reset_activity @activity = {} end def end_element(name) case name when 'member' @results['Activities'] << @activity reset_activity when 'ActivityId', 'AutoScalingGroupName', 'Cause', 'Description', 'StatusCode', 'StatusMessage' @activity[name] = value when 'EndTime', 'StartTime' @activity[name] = Time.parse(value) when 'Progress' @activity[name] = value.to_i when 'NextToken' @results[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribeScalingActivitiesResponse' @response['DescribeScalingActivitiesResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/describe_auto_scaling_groups.rb0000644000004100000410000001175112261242551027110 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class DescribeAutoScalingGroups < Fog::Parsers::Base def reset reset_auto_scaling_group reset_enabled_metric reset_instance reset_suspended_process reset_tag @results = { 'AutoScalingGroups' => [] } @response = { 'DescribeAutoScalingGroupsResult' => {}, 'ResponseMetadata' => {} } end def reset_auto_scaling_group @auto_scaling_group = { 'AvailabilityZones' => [], 'EnabledMetrics' => [], 'Instances' => [], 'LoadBalancerNames' => [], 'SuspendedProcesses' => [], 'Tags' => [], 'TerminationPolicies' => [] } end def reset_enabled_metric @enabled_metric = {} end def reset_instance @instance = {} end def reset_suspended_process @suspended_process = {} end def reset_tag @tag = {} end def start_element(name, attrs = []) super case name when 'member' when 'AvailabilityZones' @in_availability_zones = true when 'EnabledMetrics' @in_enabled_metrics = true when 'Instances' @in_instances = true when 'LoadBalancerNames' @in_load_balancer_names = true when 'SuspendedProcesses' @in_suspended_processes = true when 'Tags' @in_tags = true when 'TerminationPolicies' @in_termination_policies = true end end def end_element(name) case name when 'member' if @in_availability_zones @auto_scaling_group['AvailabilityZones'] << value elsif @in_enabled_metrics @auto_scaling_group['EnabledMetrics'] << @enabled_metric reset_enabled_metric elsif @in_instances @auto_scaling_group['Instances'] << @instance reset_instance elsif @in_load_balancer_names @auto_scaling_group['LoadBalancerNames'] << value elsif @in_suspended_processes @auto_scaling_group['SuspendedProcesses'] << @suspended_process reset_suspended_process elsif @in_tags @auto_scaling_group['Tags'] << @tag reset_tag elsif @in_termination_policies @auto_scaling_group['TerminationPolicies'] << value else @results['AutoScalingGroups'] << @auto_scaling_group reset_auto_scaling_group end when 'AvailabilityZones' @in_availability_zones = false when 'Granularity', 'Metric' @enabled_metric[name] = value when 'EnabledMetrics' @in_enabled_metrics = false when 'AvailabilityZone', 'HealthStatus', 'InstanceId', 'LifecycleState' @instance[name] = value when 'Instances' @in_instances = false when 'LoadBalancerNames' @in_load_balancer_names = false when 'ProcessName', 'SuspensionReason' @suspended_process[name] = value when 'SuspendedProcesses' @in_suspended_processes = false when 'Key', 'ResourceId', 'ResourceType', 'Value' @tag[name] = value when 'PropagateAtLaunch' @tag[name] = (value == 'true') when 'Tags' @in_tags = false when 'TerminationPolicies' @in_termination_policies = false when 'LaunchConfigurationName' if @in_instances @instance[name] = value else @auto_scaling_group[name] = value end when 'AutoScalingGroupARN', 'AutoScalingGroupName' @auto_scaling_group[name] = value when 'CreatedTime' @auto_scaling_group[name] = Time.parse(value) when 'DefaultCooldown', 'DesiredCapacity', 'HealthCheckGracePeriod' @auto_scaling_group[name] = value.to_i when 'HealthCheckType' @auto_scaling_group[name] = value when 'MaxSize', 'MinSize' @auto_scaling_group[name] = value.to_i when 'PlacementGroup', 'VPCZoneIdentifier' @auto_scaling_group[name] = value when 'NextToken' @results[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribeAutoScalingGroupsResponse' @response['DescribeAutoScalingGroupsResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/auto_scaling/put_scaling_policy.rb0000644000004100000410000000121512261242551025062 0ustar www-datawww-datamodule Fog module Parsers module AWS module AutoScaling class PutScalingPolicy < Fog::Parsers::Base def reset @results = {} @response = { 'PutScalingPolicyResult' => {}, 'ResponseMetadata' => {} } end def end_element(name) case name when 'PolicyARN' @results[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value when 'PutScalingPolicyResponse' @response['PutScalingPolicyResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/redshift/0000755000004100000410000000000012261242551020007 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/redshift/cluster_security_group_parser.rb0000644000004100000410000000272412261242551026541 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class ClusterSecurityGroupParser < Fog::Parsers::Base # :cluster_security_group_name - (String) # :description - (String) # :ec_2_security_groups - (Array) # :status - (String) # :ec2_security_group_name - (String) # :ec2_security_group_owner_id - (String) # :ip_ranges - (Array) # :status - (String) # :cidrip - (String) def reset @cluster_security_group = fresh_cluster_security_group end def fresh_cluster_security_group {'EC2SecurityGroups' => [], 'IPRanges' => []} end def start_element(name, attrs = []) super case name when 'EC2SecurityGroups', 'IPRanges' @list = {} @list_name = name end end def end_element(name) super case name when 'ClusterSecurityGroupName', 'Description' @cluster_security_group[name] = value when 'EC2SecurityGroupName', 'EC2SecurityGroupOwnerId', 'CIDRIP', 'Status' @list[name] = value when 'EC2SecurityGroup', 'IPRange' @cluster_security_group[@list_name] << {name => @list} @list = {} end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/describe_reserved_node_offerings.rb0000644000004100000410000000424212261242551027064 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class DescribeReservedNodeOfferings < Fog::Parsers::Base # :marker - (String) # :reserved_node_offerings - (Array) # :reserved_node_offering_id - (String) # :node_type - (String) # :duration - (Integer) # :fixed_price - (Numeric) # :usage_price - (Numeric) # :currency_code - (String) # :offering_type - (String) # :recurring_charges - (Array) # :recurring_charge_amount - (Numeric) # :recurring_charge_frequency - (String) def reset @response = { 'ReservedNodeOfferings' => [] } end def fresh_reserved_node_offering {'RecurringCharges' => []} end def start_element(name, attrs = []) super case name when 'ReservedNodeOfferings' @reserved_node_offering = fresh_reserved_node_offering when 'RecurringCharges' @recurring_charge = {} end end def end_element(name) super case name when 'Marker' @response[name] = value when 'Duration' @reserved_node_offering[name] = value.to_i when 'FixedPrice', 'UsagePrice' @reserved_node_offering[name] = value.to_f when 'CurrencyCode', 'OfferingType', 'NodeType', 'ReservedNodeOfferingId' @reserved_node_offering[name] = value when 'RecurringChargeAmount' @recurring_charge[name] = value.to_f when 'RecurringChargeFrequency' @recurring_charge[name] = value when 'RecurringCharge' @reserved_node_offering['RecurringCharges'] << {name => @recurring_charge} @recurring_charge = {} when 'ReservedNodeOffering' @response['ReservedNodeOfferings'] << {name => @reserved_node_offering} @reserved_node_offering = fresh_reserved_node_offering end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/describe_cluster_security_groups.rb0000644000004100000410000000201412261242551027200 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS require 'fog/aws/parsers/redshift/cluster_security_group_parser' class DescribeClusterSecurityGroups < ClusterSecurityGroupParser # :marker - (String) # :cluster_security_groups - (Array) def reset @response = { 'ClusterSecurityGroups' => [] } end def start_element(name, attrs = []) super case name when 'ClusterSecurityGroups' @cluster_security_group = fresh_cluster_security_group end end def end_element(name) super case name when 'Marker' @response[name] = value when 'ClusterSecurityGroup' @response['ClusterSecurityGroups'] << { name => @cluster_security_group } @cluster_security_group = fresh_cluster_security_group end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/create_cluster_security_group.rb0000644000004100000410000000125312261242551026504 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS require 'fog/aws/parsers/redshift/cluster_security_group_parser' class CreateClusterSecurityGroup < ClusterSecurityGroupParser # :cluster_security_group def reset super @response = {} end def start_element(name, attrs = []) super end def end_element(name) super case name when 'ClusterSecurityGroup' @response['ClusterSecurityGroup'] = @cluster_security_group end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/describe_cluster_versions.rb0000644000004100000410000000303112261242551025602 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class DescribeClusterVersions < Fog::Parsers::Base # :marker - (String) # :cluster_versions - (Array) # :cluster_version - (String) # :cluster_parameter_group_family - (String) # :description - (String) def reset @response = { 'ClusterVersions' => [] } @cluster_version_depth = 0 end def start_element(name, attrs = []) super case name when 'ClusterVersions' @cluster_version = {} when 'ClusterVersion' # Sadly, there are two nodes of different type named cluster_version # that are nested, so we keep track of which one we're in @cluster_version_depth += 1 end end def end_element(name) super case name when 'Marker' @response[name] = value when 'ClusterVersion' @cluster_version_depth -= 1 if @cluster_version_depth == 0 @response['ClusterVersions'] << {name => @cluster_version} @cluster_version = {} else @cluster_version[name] = value end when 'ClusterParameterGroupFamily', 'Description' @cluster_version[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/redshift/describe_cluster_subnet_groups.rb0000644000004100000410000000346712261242551026646 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class DescribeClusterSubnetGroups < Fog::Parsers::Base # :marker - (String) # :cluster_subnet_groups - (Array) # :cluster_subnet_group_name - (String) # :description - (String) # :vpc_id - (String) # :subnet_group_status - (String) # :subnets - (Array) # :subnet_identifier - (String) # :subnet_availability_zone - (Hash) # :name - (String) # :subnet_status - (String) def reset @response = { 'ClusterSubnetGroups' => [] } end def start_element(name, attrs = []) super case name when 'ClusterSubnetGroups' @cluster_subnet_group = {'Subnets' => []} end end def end_element(name) super case name when 'Marker' @response[name] = value when 'ClusterSubnetGroup' @response['ClusterSubnetGroups'] << {name => @cluster_subnet_group} @cluster_subnet_group = {'Subnets' => []} when 'ClusterSubnetGroupName', 'Description', 'VpcId', 'SubnetGroupStatus' @cluster_subnet_group[name] = value when 'Subnet' @cluster_subnet_group['Subnets'] << {name => @subnet} if @subnet @subnet = {} when 'SubnetAvailabilityZone' @subnet['SubnetAvailabilityZone'] = {} when 'Name' @subnet['SubnetAvailabilityZone']['Name'] = value when 'SubnetIdentifier', 'SubnetStatus' @subnet[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/redshift/cluster.rb0000644000004100000410000000103012261242551022007 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS require 'fog/aws/parsers/redshift/cluster_parser' class Cluster < ClusterParser def reset super @response = {} end def start_element(name, attrs = []) super end def end_element(name) super case name when 'Cluster' @response = {name => @cluster} end end end end end end end fog-1.19.0/lib/fog/aws/parsers/redshift/revoke_cluster_security_group_ingress.rb0000644000004100000410000000126212261242551030266 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS require 'fog/aws/parsers/redshift/cluster_security_group_parser' class RevokeClusterSecurityGroupIngress < ClusterSecurityGroupParser # :cluster_security_group def reset super @response = {} end def start_element(name, attrs = []) super end def end_element(name) super case name when 'ClusterSecurityGroup' @response['ClusterSecurityGroup'] = @cluster_security_group end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/describe_events.rb0000644000004100000410000000205512261242551023502 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class DescribeEvents < Fog::Parsers::Base # :marker - (String) # :events - (Array) # :source_identifier - (String) # :source_type - (String) # :message - (String) # :date - (Time) def reset @response = { 'Events' => [] } end def start_element(name, attrs = []) super case name when 'Events' @event = {} end end def end_element(name) super case name when 'Marker' @response[name] = value when 'SourceIdentifier', 'SourceType', 'Message' @event[name] = value when 'Date' @event[name] = Time.parse(value) when 'Event' @response['Events'] << {name => @event} @event = {} end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/purchase_reserved_node_offering.rb0000644000004100000410000000347712261242551026744 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class PurchaseReservedNodeOffering < Fog::Parsers::Base # :reserved_node_id - (String) # :reserved_node_offering_id - (String) # :node_type - (String) # :start_time - (Time) # :duration - (Integer) # :fixed_price - (Numeric) # :usage_price - (Numeric) # :currency_code - (String) # :node_count - (Integer) # :state - (String) # :offering_type - (String) # :recurring_charges - (Array) # :recurring_charge_amount - (Numeric) # :recurring_charge_frequency - (String) def reset @response = { 'RecurringCharges' => [] } end def start_element(name, attrs = []) super case name when 'RecurringCharges' @recurring_charge = {} end end def end_element(name) super case name when 'ReservedNodeId', 'ReservedNodeOfferingId', 'NodeType', 'CurrencyCode', 'State', 'OfferingType' @response[name] = value when 'Duration', 'NodeCount' @response[name] = value.to_i when 'FixedPrice', 'UsagePrice' @response[name] = value.to_f when 'StartTime' @response[name] = Time.parse(value) when 'RecurringChargeAmount' @recurring_charge[name] = value.to_f when 'RecurringChargeFrequency' @recurring_charge[name] = value when 'RecurringCharge' @response['RecurringCharges'] << {name => @recurring_charge} @recurring_charge = {} end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/describe_clusters.rb0000644000004100000410000000115112261242551024036 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS require 'fog/aws/parsers/redshift/cluster_parser' class DescribeClusters < ClusterParser def reset super @response = {"ClusterSet" => []} end def start_element(name, attrs = []) super end def end_element(name) super case name when 'Cluster' @response["ClusterSet"] << {name => @cluster} @cluster = fresh_cluster end end end end end end end fog-1.19.0/lib/fog/aws/parsers/redshift/update_cluster_parameter_group_parser.rb0000644000004100000410000000117012261242551030206 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class UpdateClusterParameterGroupParser < Fog::Parsers::Base # :parameter_group_name - (String) # :parameter_group_status - (String) def reset @response = {} end def start_element(name, attrs = []) super end def end_element(name) super case name when 'ParameterGroupName', 'ParameterGroupStatus' @response[name] = value end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/describe_resize.rb0000644000004100000410000000371112261242551023477 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class DescribeResize < Fog::Parsers::Base # :target_node_type - (String) # :target_number_of_nodes - (Integer) # :target_cluster_type - (String) # :status - (String) # :import_tables_completed - (Array) # :import_tables_in_progress - (Array) # :import_tables_not_started - (Array) def reset @response = { 'ImportTablesCompleted' => [], 'ImportTablesInProgress' => [], 'ImportTablesNotStarted' => []} end def start_element(name, attrs = []) super case name when 'ImportTablesCompleted' @in_import_tables_completed = true when 'ImportTablesInProgress' @in_import_tables_in_progress = true when 'ImportTablesNotStarted' @in_import_tables_not_started = true end end def end_element(name) super case name when 'TargetNodeType', 'TargetClusterType', 'Status' @response[name] = value when 'TargetNumberOfNodes' @response[name] = value.to_i when 'ImportTablesCompleted' @in_import_tables_completed = false when 'ImportTablesInProgress' @in_import_tables_in_progress = false when 'ImportTablesNotStarted' @in_import_tables_not_started = false when 'member' if @in_import_tables_completed @response['ImportTablesCompleted'] << value end if @in_import_tables_not_started @response['ImportTablesNotStarted'] << value end if @in_import_tables_in_progress @response['ImportTablesInProgress'] << value end end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/describe_orderable_cluster_options.rb0000644000004100000410000000322612261242551027452 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class DescribeOrderableClusterOptions < Fog::Parsers::Base # :marker - (String) # :orderable_cluster_options - (Array) # :cluster_version - (String) # :cluster_type - (String) # :node_type - (String) # :availability_zones - (Array) # :name - (String) def reset @response = { 'OrderableClusterOptions' => [] } end def fresh_orderable_cluster_option {'AvailabilityZones' => []} end def start_element(name, attrs = []) super case name when 'OrderableClusterOptions' @orderable_cluster_option = fresh_orderable_cluster_option when 'AvailabilityZones' @availability_zone = {} end end def end_element(name) super case name when 'Marker' @response[name] = value when 'ClusterVersion', 'ClusterType', 'NodeType' @orderable_cluster_option[name] = value when 'Name' @availability_zone[name] = value when 'AvailabilityZone' @orderable_cluster_option['AvailabilityZones'] << {name => @availability_zone} @availability_zone = {} when 'OrderableClusterOption' @response['OrderableClusterOptions'] << {name => @orderable_cluster_option} @orderable_cluster_option = fresh_orderable_cluster_option end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/cluster_parser.rb0000644000004100000410000001340112261242551023370 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class ClusterParser < Fog::Parsers::Base # :cluster_identifier - (String) # :node_type - (String) # :cluster_status - (String) # :modify_status - (String) # :master_username - (String) # :db_name - (String) # :endpoint - (Hash) # :address - (String) # :port - (Integer) # :cluster_create_time - (Time) # :automated_snapshot_retention_period - (Integer) # :cluster_security_groups - (Array) # :cluster_security_group_name - (String) # :status - (String) # :vpc_security_groups - (Array) # :vpc_security_group_id - (String) # :status - (String) # :cluster_parameter_groups - (Array) # :parameter_group_name - (String) # :parameter_apply_status - (String) # :cluster_subnet_group_name - (String) # :vpc_id - (String) # :availability_zone - (String) # :preferred_maintenance_window - (String) # :pending_modified_values - (Hash) # :master_user_password - (String) # :node_type - (String) # :number_of_nodes - (Integer) # :cluster_type - (String) # :cluster_version - (String) # :automated_snapshot_retention_period - (Integer) # :cluster_version - (String) # :allow_version_upgrade - (Boolean) # :number_of_nodes - (Integer) # :publicly_accessible - (Boolean) # :encrypted - (Boolean) # :restore_status - (Hash) # :status - (String) # :current_restore_rate_in_mega_bytes_per_second - (Numeric) # :snapshot_size_in_mega_bytes - (Integer) # :progress_in_mega_bytes - (Integer) # :elapsed_time_in_seconds - (Integer) # :estimated_time_to_completion_in_seconds - (Integer) def reset @cluster = fresh_cluster end def fresh_cluster { 'ClusterParameterGroups' => [], 'ClusterSecurityGroups' => [], 'VpcSecurityGroups' => [], 'EndPoint' => {}, 'PendingModifiedValues'=> {}, 'RestoreStatus' => {}} end def start_element(name, attrs = []) super case name when 'ClusterSecurityGroups' @in_cluster_security_groups = true @cluster_security_group = {} when 'ClusterParameterGroups' @cluster_parameter_group = {} when 'VpcSecurityGroups' @in_vpc_security_groups = true @vpc_security_group = {} when 'PendingModifiedValues' @in_pending_modified_values = true end end def end_element(name) case name when 'AvailabilityZone', 'ClusterIdentifier', 'ClusterStatus', 'ClusterSubnetGroupName', 'DBName', 'MasterUsername', 'ModifyStatus', 'PreferredMaintenanceWindow', 'VpcId' @cluster[name] = value when 'ClusterCreateTime' @cluster[name] = Time.parse(value) when 'AllowVersionUpgrade', 'Encrypted', 'PubliclyAccessible' @cluster[name] = (value == "true") when 'Address' @cluster['EndPoint'][name] = value when 'Port' @cluster['EndPoint'][name] = value.to_i when 'NodeType', 'ClusterVersion' if @in_pending_modified_values @cluster['PendingModifiedValues'][name] = value else @cluster[name] = value end when 'NumberOfNodes', 'AutomatedSnapshotRetentionPeriod' if @in_pending_modified_values @cluster['PendingModifiedValues'][name] = value.to_i else @cluster[name] = value.to_i end when 'MasterUserPassword', 'ClusterType' @cluster['PendingModifiedValues'][name] = value when 'Status' if @in_vpc_security_groups @vpc_security_group[name] = value elsif @in_cluster_security_groups @cluster_security_group[name] = value else @cluster['RestoreStatus'][name] = value end when 'ParameterGroupName', 'ParameterApplyStatus' @cluster_parameter_group[name] = value when 'ClusterSecurityGroupName' @cluster_security_group[name] = value when 'VpcSecurityGroupId' @vpc_security_group[name] = value when 'SnapshotSizeInMegaBytes', 'ProgressInMegaBytes', 'ElapsedTimeInSeconds', 'EstimatedTimeToCompletionInSeconds' @cluster['RestoreStatus'][name] = value.to_i when 'CurrentRestoreRateInMegaBytesPerSecond' @cluster['RestoreStatus'][name] = value.to_f when 'ClusterSecurityGroups' @in_cluster_security_groups = false when 'VpcSecurityGroups' @in_vpc_security_groups = false when 'PendingModifiedValues' @in_pending_modified_values = false when 'ClusterParameterGroup' @cluster['ClusterParameterGroups'] << {name => @cluster_parameter_group} @cluster_parameter_group = {} when 'ClusterSecurityGroup' @cluster['ClusterSecurityGroups'] << {name => @cluster_security_group} @cluster_security_group = {} when 'VpcSecurityGroup' @cluster['VpcSecurityGroups'] << {name => @vpc_security_group} @vpc_security_group = {} end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/describe_reserved_nodes.rb0000644000004100000410000000446612261242551025215 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class DescribeReservedNodes < Fog::Parsers::Base # :marker - (String) # :reserved_nodes - (Array) # :reserved_node_id - (String) # :reserved_node_offering_id - (String) # :node_type - (String) # :start_time - (Time) # :duration - (Integer) # :fixed_price - (Numeric) # :usage_price - (Numeric) # :currency_code - (String) # :node_count - (Integer) # :state - (String) # :offering_type - (String) # :recurring_charges - (Array) # :recurring_charge_amount - (Numeric) # :recurring_charge_frequency - (String) def reset @response = { 'ReservedNodes' => [] } end def fresh_reserved_nodes {'RecurringCharges' => []} end def start_element(name, attrs = []) super case name when 'ReservedNodes' @reserved_node = fresh_reserved_nodes when 'RecurringCharges' @recurring_charge = {} end end def end_element(name) super case name when 'Marker' @response[name] = value when 'Duration', 'NodeCount' @reserved_node[name] = value.to_i when 'StartTime' @reserved_node[name] = Time.parse(value) when 'FixedPrice', 'UsagePrice' @reserved_node[name] = value.to_f when 'CurrencyCode', 'OfferingType', 'NodeType', 'ReservedNodeOfferingId', 'ReservedNodeId', 'State' @reserved_node[name] = value when 'RecurringChargeAmount' @recurring_charge[name] = value.to_f when 'RecurringChargeFrequency' @recurring_charge[name] = value when 'RecurringCharge' @reserved_node['RecurringCharges'] << {name => @recurring_charge} @recurring_charge = {} when 'ReservedNode' @response['ReservedNodes'] << {name => @reserved_node} @reserved_node = fresh_reserved_nodes end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/describe_cluster_snapshots.rb0000644000004100000410000000154212261242551025761 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS require 'fog/aws/parsers/redshift/cluster_snapshot_parser' class DescribeClusterSnapshots < ClusterSnapshotParser # :marker - (String) # :snapshots - (Array) def reset @response = { 'Snapshots' => [] } end def start_element(name, attrs = []) super case name when 'Snapshots' @snapshot = fresh_snapshot end end def end_element(name) super case name when 'Marker' @response[name] = value when 'Snapshot' @response['Snapshots'] << @snapshot @snapshot = fresh_snapshot end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/describe_default_cluster_parameters.rb0000644000004100000410000000265212261242551027611 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class DescribeDefaultClusterParameters < Fog::Parsers::Base # :marker - (String) # :parameter_group_family - (String) # :parameters - (Array) # :parameter_name - (String) # :parameter_value - (String) # :description - (String) # :source - (String) # :data_type - (String) # :allowed_values - (String) # :is_modifiable - (Boolean) # :minimum_engine_version - (String) def reset @response = { 'Parameters' => [] } end def start_element(name, attrs = []) super case name when 'Parameters' @parameter = {} end end def end_element(name) super case name when 'Marker', 'ParameterGroupFamily' @response[name] = value when 'ParameterName', 'ParameterValue', 'Description', 'Source', 'DataType', 'AllowedValues', 'MinimumEngineVersion' @parameter[name] = value when 'IsModifiable' @parameter[name] = (value == "true") when 'Parameter' @response['Parameters'] << {name => @parameter} @parameter = {} end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/cluster_snapshot_parser.rb0000644000004100000410000000473412261242551025320 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class ClusterSnapshotParser < Fog::Parsers::Base # :snapshot_identifier - (String) # :cluster_identifier - (String) # :snapshot_create_time - (Time) # :status - (String) # :port - (Integer) # :availability_zone - (String) # :cluster_create_time - (Time) # :master_username - (String) # :cluster_version - (String) # :snapshot_type - (String) # :node_type - (String) # :number_of_nodes - (Integer) # :db_name - (String) # :vpc_id - (String) # :encrypted - (Boolean) # :accounts_with_restore_access - (Array) # :account_id - (String) # :owner_account - (String) # :total_backup_size_in_mega_bytes - (Numeric) # :actual_incremental_backup_size_in_mega_bytes - (Numeric) # :backup_progress_in_mega_bytes - (Numeric) # :current_backup_rate_in_mega_bytes_per_second - (Numeric) # :estimated_seconds_to_completion - (Integer) # :elapsed_time_in_seconds - (Integer) def reset @snapshot = fresh_snapshot end def fresh_snapshot {'Snapshot' => { 'AccountsWithRestoreAccess' => [] }} end def start_element(name, attrs = []) super end def end_element(name) super case name when 'SnapshotIdentifier', 'ClusterIdentifier', 'Status', 'AvailabilityZone', 'MasterUsername', 'ClusterVersion', 'SnapshotType', 'NodeType', 'DBName', 'VpcId', 'OwnerAccount' @snapshot['Snapshot'][name] = value when 'Port', 'NumberOfNodes', 'ElapsedTimeInSeconds', 'EstimatedSecondsToCompletion' @snapshot['Snapshot'][name] = value.to_i when 'SnapshotCreateTime', 'ClusterCreateTime' @snapshot['Snapshot'][name] = Time.parse(value) when 'Encrypted' @snapshot['Snapshot'][name] = (value == "true") when 'TotalBackupSizeInMegaBytes', 'ActualIncrementalBackupSizeInMegaBytes', 'BackupProgressInMegaBytes', 'CurrentBackupRateInMegaBytesPerSecond' @snapshot['Snapshot'][name] = value.to_f when 'AccountId' @snapshot['Snapshot']['AccountsWithRestoreAccess'] << value end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/describe_cluster_parameter_groups.rb0000644000004100000410000000213012261242551027310 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class DescribeClusterParameterGroups < Fog::Parsers::Base # :marker - (String) # :parameter_groups - (Array) # :parameter_group_name - (String) # :parameter_group_family - (String) # :description - (String) def reset @response = { 'ParameterGroups' => [] } end def start_element(name, attrs = []) super case name when 'ParameterGroups' @parameter_group = {} end end def end_element(name) super case name when 'Marker' @response[name] = value when 'ParameterGroupName', 'ParameterGroupFamily', 'Description' @parameter_group[name] = value when 'ClusterParameterGroup' @response['ParameterGroups'] << {name => @parameter_group} @parameter_group = {} end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/describe_cluster_parameters.rb0000644000004100000410000000253412261242551026104 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class DescribeClusterParameters < Fog::Parsers::Base # :marker - (String) # :parameters - (Array) # :parameter_name - (String) # :parameter_value - (String) # :description - (String) # :source - (String) # :data_type - (String) # :allowed_values - (String) # :is_modifiable - (Boolean) # :minimum_engine_version - (String) def reset @response = { 'Parameters' => [] } end def start_element(name, attrs = []) super case name when 'Parameters' @parameter = {} end end def end_element(name) super case name when 'Marker' @response[name] = value when 'ParameterName', 'ParameterValue', 'Description', 'Source', 'DataType', 'AllowedValues', 'MinimumEngineVersion' @parameter[name] = value when 'IsModifiable' @parameter[name] = (value == "true") when 'Parameter' @response['Parameters'] << {name => @parameter} @parameter = {} end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/create_cluster_parameter_group.rb0000644000004100000410000000132212261242551026612 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class CreateClusterParameterGroup < Fog::Parsers::Base # :parameter_group_name - (String) # :parameter_group_family - (String) # :description - (String) def reset @response = {'ClusterParameterGroup'=>{}} end def start_element(name, attrs = []) super end def end_element(name) super case name when 'ParameterGroupName', 'ParameterGroupFamily', 'Description' @response['ClusterParameterGroup'][name] = value end end end end end end endfog-1.19.0/lib/fog/aws/parsers/redshift/cluster_subnet_group_parser.rb0000644000004100000410000000260412261242551026167 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS class ClusterSubnetGroupParser < Fog::Parsers::Base # :cluster_subnet_group_name - (String) # :description - (String) # :vpc_id - (String) # :subnet_group_status - (String) # :subnets - (Array) # :subnet_identifier - (String) # :subnet_availability_zone - (Hash) # :name - (String) # :subnet_status - (String) def reset @response = { 'Subnets' => [] } end def fresh_subnet {'SubnetAvailabilityZone'=>{}} end def start_element(name, attrs = []) super case name when 'Subnets' @subnet = fresh_subnet end end def end_element(name) super case name when 'ClusterSubnetGroupName', 'Desciption', 'VpcId', 'SubnetGroupStatus' @response[name] = value when 'SubnetIdentifier', 'SubnetStatus' @subnet[name] = value when 'Name' @subnet['SubnetAvailabilityZone'][name] = value when 'Subnet' @response['Subnets'] << {name => @subnet} @subnet = fresh_subnet end end end end end end end fog-1.19.0/lib/fog/aws/parsers/redshift/cluster_snapshot.rb0000644000004100000410000000123312261242551023733 0ustar www-datawww-datamodule Fog module Parsers module Redshift module AWS require 'fog/aws/parsers/redshift/cluster_snapshot_parser' class ClusterSnapshot < ClusterSnapshotParser # :parameter_group_name - (String) # :parameter_group_status - (String) def reset super @response = {} end def start_element(name, attrs = []) super end def end_element(name) super case name when 'Snapshot' @response = @snapshot end end end end end end endfog-1.19.0/lib/fog/aws/parsers/beanstalk/0000755000004100000410000000000012261242551020143 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/beanstalk/create_application_version.rb0000644000004100000410000000130212261242551026057 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class CreateApplicationVersion < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("CreateApplicationVersionResult") tag 'ApplicationVersion', :object tag 'ApplicationName', :string tag 'DateCreated', :datetime tag 'DateUpdated', :datetime tag 'Description', :string tag 'SourceBundle', :object tag 'S3Bucket', :string tag 'S3Key', :string tag 'VersionLabel', :string end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/check_dns_availability.rb0000644000004100000410000000064712261242551025152 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class CheckDNSAvailability < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("CheckDNSAvailabilityResult") tag 'FullyQualifiedCNAME', :string tag 'Available', :boolean end end end end end endfog-1.19.0/lib/fog/aws/parsers/beanstalk/create_application.rb0000644000004100000410000000117412261242551024321 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class CreateApplication < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("CreateApplicationResult") tag 'Application', :object tag 'Versions', :string, :list tag 'ConfigurationTemplates', :string, :list tag 'ApplicationName', :string tag 'Description', :string tag 'DateCreated', :datetime tag 'DateUpdated', :datetime end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/describe_application_versions.rb0000644000004100000410000000132012261242551026557 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class DescribeApplicationVersions < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("DescribeApplicationVersionsResult") tag 'ApplicationVersions', :object, :list tag 'ApplicationName', :string tag 'DateCreated', :datetime tag 'DateUpdated', :datetime tag 'Description', :string tag 'SourceBundle', :object tag 'S3Bucket', :string tag 'S3Key', :string tag 'VersionLabel', :string end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/update_application.rb0000644000004100000410000000117412261242551024340 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class UpdateApplication < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("UpdateApplicationResult") tag 'Application', :object tag 'Versions', :string, :list tag 'ConfigurationTemplates', :string, :list tag 'ApplicationName', :string tag 'Description', :string tag 'DateCreated', :datetime tag 'DateUpdated', :datetime end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/describe_environment_resources.rb0000644000004100000410000000227512261242551026774 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class DescribeEnvironmentResources < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("DescribeEnvironmentResourcesResult") tag 'EnvironmentResources', :object tag 'AutoScalingGroups', :object, :list tag 'Name', :string tag 'EnvironmentName', :string tag 'Instances', :object, :list tag 'Id', :string tag 'LaunchConfigurations', :object, :list tag 'LoadBalancers', :object, :list tag 'Resources', :object, :list tag 'Description', :string tag 'LogicalResourceId', :string tag 'PhysicalResourceId', :string tag 'Type', :string tag 'Properties', :object, :list tag 'RuntimeSources', :object, :list tag 'Parameter', :string tag 'Versions', :object, :list tag 'ApplicationName', :string tag 'VersionLabel', :string tag 'Triggers', :object, :list end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/describe_events.rb0000644000004100000410000000131612261242551023635 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class DescribeEvents < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("DescribeEventsResult") tag 'Events', :object, :list tag 'ApplicationName', :string tag 'EnvironmentName', :string tag 'EventDate', :datetime tag 'Message', :string tag 'RequestId', :string tag 'Severity', :string tag 'TemplateName', :string tag 'VersionLabel', :string tag 'NextToken', :string end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/update_configuration_template.rb0000644000004100000410000000151612261242551026577 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class UpdateConfigurationTemplate < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("UpdateConfigurationTemplateResult") tag 'ApplicationName', :string tag 'DateCreated', :datetime tag 'DateUpdated', :datetime tag 'DeploymentStatus', :string tag 'Description', :string tag 'EnvironmentName', :string tag 'OptionSettings', :object, :list tag 'Namespace', :string tag 'OptionName', :string tag 'Value', :string tag 'SolutionStackName', :string tag 'TemplateName', :string end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/parser.rb0000644000004100000410000000522412261242551021767 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk class BaseParser < Fog::Parsers::Base def initialize(result_name) @result_name = result_name # Set before super, since super calls reset super() @tags = {} @list_tags = {} end def reset @response = { @result_name => {}, 'ResponseMetadata' => {} } # Push root object to top of stack @parse_stack = [ { :type => :object, :value => @response[@result_name]} ] end def tag name, *traits if traits.delete(:list) @list_tags[name] = true end if traits.length == 1 @tags[name] = traits.last else raise "Too many traits specified, only specify :list or a type" end end def start_element(name, attrs = []) super if name == 'member' if @parse_stack.last[:type] == :object @parse_stack.last[:value] << {} # Push any empty object end elsif @list_tags.has_key?(name) set_value(name, [], :array) # Set an empty array @parse_stack.push({ :type => @tags[name], :value => get_parent[name] }) elsif @tags[name] == :object set_value(name, {}, :object) @parse_stack.push({ :type => @tags[name], :value => get_parent[name] }) end end def end_element(name) case name when 'member' if @parse_stack.last[:type] != :object @parse_stack.last[:value] << value end when 'RequestId' @response['ResponseMetadata'][name] = value else if @list_tags.has_key?(name) || @tags[name] == :object @parse_stack.pop() elsif @tags.has_key?(name) set_value(name, value, @tags[name]) end end end def get_parent parent = @parse_stack.last[:value] parent.is_a?(Array) ? parent.last : parent end def set_value(name, value, type) case type when :datetime get_parent[name] = Time.parse value when :boolean get_parent[name] = value == "true" # True only if value is true when :integer get_parent[name] = value.to_i else get_parent[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/terminate_environment.rb0000644000004100000410000000214012261242551025101 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class TerminateEnvironment < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("TerminateEnvironmentResult") tag 'ApplicationName', :string tag 'CNAME', :string tag 'DateCreated', :datetime tag 'DateUpdated', :datetime tag 'Description', :string tag 'EndpointURL', :string tag 'EnvironmentId', :string tag 'EnvironmentName', :string tag 'Health', :string tag 'Resources', :object tag 'LoadBalancer', :object tag 'Domain', :string tag 'LoadBalancerName', :string tag 'Listeners', :object, :list tag 'Port', :integer tag 'Protocol', :string tag 'SolutionStackName', :string tag 'Status', :string tag 'TemplateName', :string tag 'VersionLabel', :string end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/list_available_solution_stacks.rb0000644000004100000410000000105312261242551026746 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class ListAvailableSolutionStacks < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("ListAvailableSolutionStacksResult") tag 'SolutionStackDetails', :object, :list tag 'PermittedFileTypes', :string, :list tag 'SolutionStackName', :string tag 'SolutionStacks', :string, :list end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/describe_configuration_options.rb0000644000004100000410000000164212261242551026755 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class DescribeConfigurationOptions < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("DescribeConfigurationOptionsResult") tag 'SolutionStackName', :string tag 'Options', :object, :list tag 'ChangeSeverity', :string tag 'DefaultValue', :string tag 'MaxLength', :integer tag 'MaxValue', :integer tag 'MinValue', :integer tag 'Name', :string tag 'Namespace', :string tag 'Regex', :object tag 'Label', :string tag 'Pattern', :string tag 'UserDefined', :boolean tag 'ValueOptions', :string, :list tag 'ValueType', :string end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/create_storage_location.rb0000644000004100000410000000057112261242551025352 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class CreateStorageLocation < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("CreateStorageLocationResult") tag 'S3Bucket', :string end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/empty.rb0000644000004100000410000000065012261242551021627 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk class Empty < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/describe_applications.rb0000644000004100000410000000121212261242551025012 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class DescribeApplications < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("DescribeApplicationsResult") tag 'Applications', :object, :list tag 'Versions', :string, :list tag 'ConfigurationTemplates', :string, :list tag 'ApplicationName', :string tag 'Description', :string tag 'DateCreated', :datetime tag 'DateUpdated', :datetime end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/validate_configuration_settings.rb0000644000004100000410000000104212261242551027125 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class ValidateConfigurationSettings < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("ValidateConfigurationSettingsResult") tag 'Messages', :object, :list tag 'Message', :string tag 'Namespace', :string tag 'OptionName', :string tag 'Severity', :string end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/create_configuration_template.rb0000644000004100000410000000151612261242551026560 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class CreateConfigurationTemplate < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("CreateConfigurationTemplateResult") tag 'ApplicationName', :string tag 'DateCreated', :datetime tag 'DateUpdated', :datetime tag 'DeploymentStatus', :string tag 'Description', :string tag 'EnvironmentName', :string tag 'OptionSettings', :object, :list tag 'Namespace', :string tag 'OptionName', :string tag 'Value', :string tag 'SolutionStackName', :string tag 'TemplateName', :string end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/update_environment.rb0000644000004100000410000000213212261242551024374 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class UpdateEnvironment < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("UpdateEnvironmentResult") tag 'ApplicationName', :string tag 'CNAME', :string tag 'DateCreated', :datetime tag 'DateUpdated', :datetime tag 'Description', :string tag 'EndpointURL', :string tag 'EnvironmentId', :string tag 'EnvironmentName', :string tag 'Health', :string tag 'Resources', :object tag 'LoadBalancer', :object tag 'Domain', :string tag 'LoadBalancerName', :string tag 'Listeners', :object, :list tag 'Port', :integer tag 'Protocol', :string tag 'SolutionStackName', :string tag 'Status', :string tag 'TemplateName', :string tag 'VersionLabel', :string end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/update_application_version.rb0000644000004100000410000000130212261242551026076 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class UpdateApplicationVersion < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("UpdateApplicationVersionResult") tag 'ApplicationVersion', :object tag 'ApplicationName', :string tag 'DateCreated', :datetime tag 'DateUpdated', :datetime tag 'Description', :string tag 'SourceBundle', :object tag 'S3Bucket', :string tag 'S3Key', :string tag 'VersionLabel', :string end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/describe_environments.rb0000644000004100000410000000221712261242551025061 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class DescribeEnvironments < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("DescribeEnvironmentsResult") tag 'Environments', :object, :list tag 'ApplicationName', :string tag 'CNAME', :string tag 'DateCreated', :datetime tag 'DateUpdated', :datetime tag 'Description', :string tag 'EndpointURL', :string tag 'EnvironmentId', :string tag 'EnvironmentName', :string tag 'Health', :string tag 'Resources', :object tag 'LoadBalancer', :object tag 'Domain', :string tag 'LoadBalancerName', :string tag 'Listeners', :object, :list tag 'Port', :integer tag 'Protocol', :string tag 'SolutionStackName', :string tag 'Status', :string tag 'TemplateName', :string tag 'VersionLabel', :string end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/describe_configuration_settings.rb0000644000004100000410000000161212261242551027117 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class DescribeConfigurationSettings < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("DescribeConfigurationSettingsResult") tag 'ConfigurationSettings', :object, :list tag 'ApplicationName', :string tag 'DateCreated', :datetime tag 'DateUpdated', :datetime tag 'DeploymentStatus', :string tag 'Description', :string tag 'EnvironmentName', :string tag 'OptionSettings', :object, :list tag 'Namespace', :string tag 'OptionName', :string tag 'Value', :string tag 'SolutionStackName', :string tag 'TemplateName', :string end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/retrieve_environment_info.rb0000644000004100000410000000105012261242551025750 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class RetrieveEnvironmentInfo < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("RetrieveEnvironmentInfoResult") tag 'EnvironmentInfo', :object, :list tag 'Ec2InstanceId', :string tag 'InfoType', :string tag 'Message', :string tag 'SampleTimestamp', :datetime end end end end end end fog-1.19.0/lib/fog/aws/parsers/beanstalk/create_environment.rb0000644000004100000410000000213212261242551024355 0ustar www-datawww-datamodule Fog module Parsers module AWS module ElasticBeanstalk require 'fog/aws/parsers/beanstalk/parser' class CreateEnvironment < Fog::Parsers::AWS::ElasticBeanstalk::BaseParser def initialize super("CreateEnvironmentResult") tag 'ApplicationName', :string tag 'CNAME', :string tag 'DateCreated', :datetime tag 'DateUpdated', :datetime tag 'Description', :string tag 'EndpointURL', :string tag 'EnvironmentId', :string tag 'EnvironmentName', :string tag 'Health', :string tag 'Resources', :object tag 'LoadBalancer', :object tag 'Domain', :string tag 'LoadBalancerName', :string tag 'Listeners', :object, :list tag 'Port', :integer tag 'Protocol', :string tag 'SolutionStackName', :string tag 'Status', :string tag 'TemplateName', :string tag 'VersionLabel', :string end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_watch/0000755000004100000410000000000012261242551020473 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/cloud_watch/disable_alarm_actions.rb0000644000004100000410000000077512261242551025330 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudWatch class DisableAlarmActions < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_watch/get_metric_statistics.rb0000644000004100000410000000216712261242551025422 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudWatch class GetMetricStatistics < Fog::Parsers::Base def reset @response = { 'GetMetricStatisticsResult' => {'Datapoints' => []}, 'ResponseMetadata' => {} } reset_datapoint end def reset_datapoint @datapoint = {} end def start_element(name, attrs = []) super end def end_element(name) case name when 'Average', 'Maximum', 'Minimum', 'SampleCount', 'Sum' @datapoint[name] = value.to_f when 'Unit' @datapoint[name] = value when 'Timestamp' @datapoint[name] = Time.parse value when 'member' @response['GetMetricStatisticsResult']['Datapoints'] << @datapoint reset_datapoint when 'Label' @response['GetMetricStatisticsResult'][name] = value when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_watch/put_metric_data.rb0000644000004100000410000000076112261242551024170 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudWatch class PutMetricData < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_watch/list_metrics.rb0000644000004100000410000000273112261242551023524 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudWatch class ListMetrics < Fog::Parsers::Base def reset @response = { 'ListMetricsResult' => {'Metrics' => []}, 'ResponseMetadata' => {} } reset_metric end def reset_metric @metric = {'Dimensions' => []} end def reset_dimension @dimension = {} end def start_element(name, attrs = []) super case name when 'Dimensions' @in_dimensions = true when 'member' if @in_dimensions reset_dimension end end end def end_element(name) case name when 'Name', 'Value' @dimension[name] = value when 'Namespace', 'MetricName' @metric[name] = value when 'Dimensions' @in_dimensions = false when 'NextMarker', 'NextToken' @response['ListMetricsResult'][name] = value when 'RequestId' @response['ResponseMetadata'][name] = value when 'member' if !@in_dimensions @response['ListMetricsResult']['Metrics'] << @metric reset_metric else @metric['Dimensions'] << @dimension end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_watch/delete_alarms.rb0000644000004100000410000000076012261242551023624 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudWatch class DeleteAlarms < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_watch/describe_alarms_for_metric.rb0000644000004100000410000000461312261242551026354 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudWatch class DescribeAlarmsForMetric < Fog::Parsers::Base def reset @response = { 'DescribeAlarmsForMetricResult' => {'MetricAlarms' => []}, 'ResponseMetadata' => {} } reset_metric_alarms end def reset_metric_alarms @metric_alarms = {'Dimensions' => []} end def reset_dimension @dimension = {} end def start_element(name, attrs = []) super case name when 'Dimensions' @in_dimensions = true when 'member' if @in_dimensions reset_dimension end end end def end_element(name) case name when 'Name', 'Value' @dimension[name] = value when 'Period', 'EvaluationPeriods' @metric_alarms[name] = value.to_i when 'Threshold' @metric_alarms[name] = value.to_f when 'AlarmActions', 'OKActions', 'InsufficientDataActions' @metric_alarms[name] = value.to_s.strip when 'AlarmName', 'Namespace', 'MetricName', 'AlarmDescription', 'AlarmArn', 'Unit', 'StateValue', 'Statistic', 'ComparisonOperator', 'StateReason', 'ActionsEnabled' @metric_alarms[name] = value when 'StateUpdatedTimestamp', 'AlarmConfigurationUpdatedTimestamp' @metric_alarms[name] = Time.parse value when 'Dimensions' @in_dimensions = false when 'NextToken' @response['ResponseMetadata'][name] = value when 'RequestId' @response['ResponseMetadata'][name] = value when 'member' if !@in_dimensions if @metric_alarms.has_key?('AlarmName') @response['DescribeAlarmsForMetricResult']['MetricAlarms'] << @metric_alarms reset_metric_alarms elsif @response['DescribeAlarmsForMetricResult']['MetricAlarms'].last != nil @response['DescribeAlarmsForMetricResult']['MetricAlarms'].last.merge!( @metric_alarms) end else @metric_alarms['Dimensions'] << @dimension end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_watch/set_alarm_state.rb0000644000004100000410000000076712261242551024201 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudWatch class SetAlarmState < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_watch/enable_alarm_actions.rb0000644000004100000410000000077412261242551025152 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudWatch class EnableAlarmActions < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_watch/put_metric_alarm.rb0000644000004100000410000000076712261242551024361 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudWatch class PutMetricAlarm < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value.strip end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_watch/describe_alarms.rb0000644000004100000410000000473712261242551024152 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudWatch class DescribeAlarms < Fog::Parsers::Base def reset @response = { 'DescribeAlarmsResult' => {'MetricAlarms' => []}, 'ResponseMetadata' => {} } reset_metric_alarms end def reset_metric_alarms @metric_alarms = {'Dimensions' => []} end def reset_dimension @dimension = {} end def start_element(name, attrs = []) super case name when 'Dimensions' @in_dimensions = true when 'member' if @in_dimensions reset_dimension end end end def end_element(name) case name when 'Name', 'Value' @dimension[name] = value when 'AlarmConfigurationUpdatedTimestamp', 'StateUpdatedTimestamp' @metric_alarms[name] = Time.parse value when 'Period', 'EvaluationPeriods' @metric_alarms[name] = value.to_i when 'Threshold' @metric_alarms[name] = value.to_f when 'AlarmActions', 'OKActions', 'InsufficientDataActions' @metric_alarms[name] = value.to_s.strip when 'AlarmName', 'Namespace', 'MetricName', 'AlarmDescription', 'AlarmArn', 'Unit', 'StateValue', 'Statistic', 'ComparisonOperator', 'StateReason', 'ActionsEnabled' @metric_alarms[name] = value when 'StateUpdatedTimestamp', 'AlarmConfigurationUpdatedTimestamp' @metric_alarms[name] = Time.parse value when 'Dimensions' @in_dimensions = false when 'RequestId' @response['ResponseMetadata'][name] = value when 'NextToken' @response['ResponseMetadata'][name] = value when 'member' if !@in_dimensions if @metric_alarms.has_key?('AlarmName') @response['DescribeAlarmsResult']['MetricAlarms'] << @metric_alarms reset_metric_alarms elsif @response['DescribeAlarmsResult']['MetricAlarms'].last != nil @response['DescribeAlarmsResult']['MetricAlarms'].last.merge!( @metric_alarms) end else @metric_alarms['Dimensions'] << @dimension end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_watch/describe_alarm_history.rb0000644000004100000410000000217212261242551025537 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudWatch class DescribeAlarmHistory < Fog::Parsers::Base def reset @response = { 'DescribeAlarmHistoryResult' => {'AlarmHistoryItems' => []}, 'ResponseMetadata' => {} } reset_alarm_history_item end def reset_alarm_history_item @alarm_history_item = {} end def start_element(name, attrs = []) super end def end_element(name) case name when 'AlarmName', 'HistoryItemType', 'HistorySummary' @alarm_history_item[name] = value when 'Timestamp' @alarm_history_item[name] = Time.parse value when 'RequestId' @response['ResponseMetadata'][name] = value when 'NextToken' @response['ResponseMetadata'][name] = value when 'member' @response['DescribeAlarmHistoryResult']['AlarmHistoryItems'] << @alarm_history_item reset_alarm_history_item end end end end end end end fog-1.19.0/lib/fog/aws/parsers/ses/0000755000004100000410000000000012261242551016771 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/ses/delete_verified_email_address.rb0000644000004100000410000000065112261242551025313 0ustar www-datawww-datamodule Fog module Parsers module AWS module SES class DeleteVerifiedEmailAddress < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/ses/list_verified_email_addresses.rb0000644000004100000410000000103512261242551025351 0ustar www-datawww-datamodule Fog module Parsers module AWS module SES class ListVerifiedEmailAddresses < Fog::Parsers::Base def reset @response = { 'VerifiedEmailAddresses' => [], 'ResponseMetadata' => {} } end def end_element(name) case name when 'member' @response['VerifiedEmailAddresses'] << value when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/ses/get_send_statistics.rb0000644000004100000410000000132712261242551023363 0ustar www-datawww-datamodule Fog module Parsers module AWS module SES class GetSendStatistics < Fog::Parsers::Base def reset @response = { 'SendDataPoints' => [], 'ResponseMetadata' => {} } @send_data_point = {} end def end_element(name) case name when "Bounces", "Complaints", "DeliveryAttempts", "Rejects", "Timestamp" @send_data_point[name] = value when 'member' @response['SendDataPoints'] << @send_data_point @send_data_point = {} when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/ses/send_raw_email.rb0000644000004100000410000000073612261242551022275 0ustar www-datawww-datamodule Fog module Parsers module AWS module SES class SendRawEmail < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def end_element(name) case name when 'MessageId' @response[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/ses/verify_domain_identity.rb0000644000004100000410000000075612261242551024072 0ustar www-datawww-datamodule Fog module Parsers module AWS module SES class VerifyDomainIdentity < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def end_element(name) case name when 'VerificationToken' @response[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/ses/send_email.rb0000644000004100000410000000073312261242551021421 0ustar www-datawww-datamodule Fog module Parsers module AWS module SES class SendEmail < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def end_element(name) case name when 'MessageId' @response[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/ses/verify_email_address.rb0000644000004100000410000000064112261242551023477 0ustar www-datawww-datamodule Fog module Parsers module AWS module SES class VerifyEmailAddress < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/ses/get_send_quota.rb0000644000004100000410000000100412261242551022312 0ustar www-datawww-datamodule Fog module Parsers module AWS module SES class GetSendQuota < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def end_element(name) case name when "Max24HourSend", "MaxSendRate", "SentLast24Hours" @response[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/dns/0000755000004100000410000000000012261242551016763 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/dns/list_resource_record_sets.rb0000644000004100000410000000340312261242551024566 0ustar www-datawww-datamodule Fog module Parsers module DNS module AWS class ListResourceRecordSets < Fog::Parsers::Base def reset @resource_record = [] @resource_record_set = {} @resource_record_set['ResourceRecords'] = [] @alias_target = {} @response = {} @response['ResourceRecordSets'] = [] @section = :resource_record_set end def end_element(name) if @section == :resource_record_set case name when 'Type', 'TTL', 'SetIdentifier', 'Weight', 'Region' @resource_record_set[name] = value when 'Name' @resource_record_set[name] = value.gsub('\\052', '*') when 'Value' @resource_record_set['ResourceRecords'] << value when 'AliasTarget' @resource_record_set[name] = @alias_target @alias_target = {} when 'HostedZoneId', 'DNSName' @alias_target[name] = value when 'ResourceRecordSet' @response['ResourceRecordSets'] << @resource_record_set @resource_record_set = {} @resource_record_set['ResourceRecords'] = [] when 'ResourceRecordSets' @section = :main end elsif @section == :main case name when 'MaxItems' @response[name] = value.to_i when 'NextRecordName', 'NextRecordType', 'NextRecordIdentifier' @response[name] = value when 'IsTruncated' @response[name] = value == 'true' end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/dns/list_hosted_zones.rb0000644000004100000410000000154112261242551023050 0ustar www-datawww-datamodule Fog module Parsers module DNS module AWS class ListHostedZones < Fog::Parsers::Base def reset @hosted_zones = [] @zone = {} @response = {} end def end_element(name) case name when 'Id' @zone[name] = value.sub('/hostedzone/', '') when 'Name', 'CallerReference', 'Comment' @zone[name] = value when 'HostedZone' @hosted_zones << @zone @zone = {} when 'HostedZones' @response['HostedZones'] = @hosted_zones when 'MaxItems' @response[name] = value.to_i when 'IsTruncated', 'Marker', 'NextMarker' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/dns/get_hosted_zone.rb0000644000004100000410000000225512261242551022474 0ustar www-datawww-datamodule Fog module Parsers module DNS module AWS class GetHostedZone < Fog::Parsers::Base def reset @hosted_zone = {} @name_servers = [] @response = {} @section = :hosted_zone end def end_element(name) if @section == :hosted_zone case name when 'Id' @hosted_zone[name]= value.sub('/hostedzone/', '') when 'Name', 'CallerReference', 'Comment' @hosted_zone[name]= value when 'HostedZone' @response['HostedZone'] = @hosted_zone @hosted_zone = {} @section = :name_servers when 'ResourceRecordSetCount' @response['ResourceRecordSetCount'] = value.to_i end elsif @section == :name_servers case name when 'NameServer' @name_servers << value when 'NameServers' @response['NameServers'] = @name_servers @name_servers = {} end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/dns/delete_hosted_zone.rb0000644000004100000410000000067212261242551023160 0ustar www-datawww-datamodule Fog module Parsers module DNS module AWS class DeleteHostedZone < Fog::Parsers::Base def reset @response = {} @response['ChangeInfo'] = {} end def end_element(name) case name when 'Id', 'Status', 'SubmittedAt' @response['ChangeInfo'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/dns/create_hosted_zone.rb0000644000004100000410000000300412261242551023151 0ustar www-datawww-datamodule Fog module Parsers module DNS module AWS class CreateHostedZone < Fog::Parsers::Base def reset @hosted_zone = {} @change_info = {} @name_servers = [] @response = {} @section = :hosted_zone end def end_element(name) if @section == :hosted_zone case name when 'Id' @hosted_zone[name] = value.sub('/hostedzone/', '') when 'Name', 'CallerReference', 'Comment' @hosted_zone[name]= value when 'HostedZone' @response['HostedZone'] = @hosted_zone @hosted_zone = {} @section = :change_info end elsif @section == :change_info case name when 'Id' @change_info[name]= value.sub('/change/', '') when 'Status', 'SubmittedAt' @change_info[name] = value when 'ChangeInfo' @response['ChangeInfo'] = @change_info @change_info = {} @section = :name_servers end elsif @section == :name_servers case name when 'NameServer' @name_servers << value when 'NameServers' @response['NameServers'] = @name_servers @name_servers = {} end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/dns/change_resource_record_sets.rb0000644000004100000410000000074012261242551025041 0ustar www-datawww-datamodule Fog module Parsers module DNS module AWS class ChangeResourceRecordSets < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'Id' @response[name] = value.sub('/change/', '') when 'Status', 'SubmittedAt' @response[name] = value end end end end end end endfog-1.19.0/lib/fog/aws/parsers/dns/get_change.rb0000644000004100000410000000072012261242551021373 0ustar www-datawww-datamodule Fog module Parsers module DNS module AWS class GetChange < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'Id' @response[name] = value.sub('/change/', '') when 'Status', 'SubmittedAt' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/0000755000004100000410000000000012261242551016741 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/elb/enable_availability_zones_for_load_balancer.rb0000644000004100000410000000120612261242551030157 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class EnableAvailabilityZonesForLoadBalancer < Fog::Parsers::Base def reset @response = { 'EnableAvailabilityZonesForLoadBalancerResult' => { 'AvailabilityZones' => [] }, 'ResponseMetadata' => {} } end def end_element(name) case name when 'member' @response['EnableAvailabilityZonesForLoadBalancerResult']['AvailabilityZones'] << value when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/describe_load_balancer_policies.rb0000644000004100000410000000353012261242551025564 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class DescribeLoadBalancerPolicies < Fog::Parsers::Base def reset reset_policy reset_policy_attribute_description @results = { 'PolicyDescriptions' => [] } @response = { 'DescribeLoadBalancerPoliciesResult' => {}, 'ResponseMetadata' => {} } end def reset_policy @policy = { 'PolicyAttributeDescriptions' => [], 'PolicyName' => '', 'PolicyTypeName' => '' } end def reset_policy_attribute_description @policy_attribute_description = { 'AttributeName' => '', 'AttributeValue' => '' } end def start_element(name, attrs = []) super case name when 'PolicyAttributeDescriptions' @in_policy_attributes = true end end def end_element(name) case name when 'member' if @in_policy_attributes @policy['PolicyAttributeDescriptions'] << @policy_attribute_description reset_policy_attribute_description elsif !@in_policy_attributes @results['PolicyDescriptions'] << @policy reset_policy end when 'PolicyName', 'PolicyTypeName' @policy[name] = value when 'PolicyAttributeDescriptions' @in_policy_attributes = false when 'AttributeName', 'AttributeValue' @policy_attribute_description[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribeLoadBalancerPoliciesResponse' @response['DescribeLoadBalancerPoliciesResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/describe_load_balancers.rb0000644000004100000410000001460012261242551024060 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class DescribeLoadBalancers < Fog::Parsers::Base def reset reset_load_balancer reset_listener_description reset_stickiness_policy reset_backend_server_description @results = { 'LoadBalancerDescriptions' => [] } @response = { 'DescribeLoadBalancersResult' => {}, 'ResponseMetadata' => {} } end def reset_load_balancer @load_balancer = { 'Subnets' => [], 'SecurityGroups' => [], 'ListenerDescriptions' => [], 'Instances' => [], 'AvailabilityZones' => [], 'Policies' => {'AppCookieStickinessPolicies' => [], 'LBCookieStickinessPolicies' => [], 'OtherPolicies' => []}, 'HealthCheck' => {}, 'SourceSecurityGroup' => {}, 'BackendServerDescriptions' => [] } end def reset_listener_description @listener_description = { 'PolicyNames' => [], 'Listener' => {} } end def reset_backend_server_description @backend_server_description = {} end def reset_stickiness_policy @stickiness_policy = {} end def start_element(name, attrs = []) super case name when 'ListenerDescriptions' @in_listeners = true when 'Instances' @in_instances = true when 'AvailabilityZones' @in_availability_zones = true when 'SecurityGroups' @in_security_groups = true when 'Subnets' @in_subnets = true when 'PolicyNames' @in_policy_names = true when 'Policies' @in_policies = true when 'LBCookieStickinessPolicies' @in_lb_cookies = true when 'AppCookieStickinessPolicies' @in_app_cookies = true when 'AppCookieStickinessPolicies' @in_app_cookies = true when 'OtherPolicies' @in_other_policies = true when 'BackendServerDescriptions' @in_backend_server_descriptions = true end end def end_element(name) case name when 'member' if @in_policy_names && @in_listeners @listener_description['PolicyNames'] << value elsif @in_availability_zones @load_balancer['AvailabilityZones'] << value elsif @in_security_groups @load_balancer['SecurityGroups'] << value elsif @in_subnets @load_balancer['Subnets'] << value elsif @in_listeners @load_balancer['ListenerDescriptions'] << @listener_description reset_listener_description elsif @in_app_cookies @load_balancer['Policies']['AppCookieStickinessPolicies'] << @stickiness_policy reset_stickiness_policy elsif @in_lb_cookies @load_balancer['Policies']['LBCookieStickinessPolicies'] << @stickiness_policy reset_stickiness_policy elsif @in_other_policies @load_balancer['Policies']['OtherPolicies'] << value elsif @in_backend_server_descriptions && @in_policy_names @backend_server_description['PolicyNames'] ||= [] @backend_server_description['PolicyNames'] << value elsif @in_backend_server_descriptions && !@in_policy_names @load_balancer['BackendServerDescriptions'] << @backend_server_description reset_backend_server_description elsif !@in_instances && !@in_policies && !@in_backend_server_descriptions @results['LoadBalancerDescriptions'] << @load_balancer reset_load_balancer end when 'BackendServerDescriptions' @in_backend_server_descriptions = false when 'InstancePort' if @in_backend_server_descriptions @backend_server_description[name] = value.to_i elsif @in_listeners @listener_description['Listener'][name] = value.to_i end when 'CanonicalHostedZoneName', 'CanonicalHostedZoneNameID', 'LoadBalancerName', 'DNSName', 'Scheme' @load_balancer[name] = value when 'CreatedTime' @load_balancer[name] = Time.parse(value) when 'ListenerDescriptions' @in_listeners = false when 'PolicyNames' @in_policy_names = false when 'Protocol', 'SSLCertificateId', 'InstanceProtocol' @listener_description['Listener'][name] = value when 'LoadBalancerPort' @listener_description['Listener'][name] = value.to_i when 'Instances' @in_instances = false when 'InstanceId' @load_balancer['Instances'] << value when 'VPCId' @load_balancer[name] = value when 'AvailabilityZones' @in_availability_zones = false when 'SecurityGroups' @in_security_groups = false when 'Subnets' @in_subnets = false when 'Policies' @in_policies = false when 'AppCookieStickinessPolicies' @in_app_cookies = false when 'LBCookieStickinessPolicies' @in_lb_cookies = false when 'OtherPolicies' @in_other_policies = false when 'OwnerAlias', 'GroupName' @load_balancer['SourceSecurityGroup'][name] = value when 'Interval', 'HealthyThreshold', 'Timeout', 'UnhealthyThreshold' @load_balancer['HealthCheck'][name] = value.to_i when 'Target' @load_balancer['HealthCheck'][name] = value when 'PolicyName', 'CookieName' @stickiness_policy[name] = value when 'CookieExpirationPeriod' @stickiness_policy[name] = value.to_i when 'RequestId' @response['ResponseMetadata'][name] = value when 'NextMarker' @results['NextMarker'] = value when 'DescribeLoadBalancersResponse' @response['DescribeLoadBalancersResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/configure_health_check.rb0000644000004100000410000000154612261242551023737 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class ConfigureHealthCheck < Fog::Parsers::Base def reset @health_check = {} @response = { 'ConfigureHealthCheckResult' => {}, 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) case name when 'Target' @health_check[name] = value when 'Interval', 'Timeout', 'UnhealthyThreshold', 'HealthyThreshold' @health_check[name] = value.to_i when 'HealthCheck' @response['ConfigureHealthCheckResult'][name] = @health_check when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/describe_instance_health.rb0000644000004100000410000000141612261242551024261 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class DescribeInstanceHealth < Fog::Parsers::Base def reset @response = { 'DescribeInstanceHealthResult' => { 'InstanceStates' => [] }, 'ResponseMetadata' => {} } @instance_state = {} end def end_element(name) case name when 'Description', 'State', 'InstanceId', 'ReasonCode' @instance_state[name] = value when 'member' @response['DescribeInstanceHealthResult']['InstanceStates'] << @instance_state @instance_state = {} when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/delete_load_balancer.rb0000644000004100000410000000070412261242551023357 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class DeleteLoadBalancer < Fog::Parsers::Base def reset @response = { 'DeleteLoadBalancerResult' => nil, 'ResponseMetadata' => {} } end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/register_instances_with_load_balancer.rb0000644000004100000410000000116512261242551027045 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class RegisterInstancesWithLoadBalancer < Fog::Parsers::Base def reset @response = { 'RegisterInstancesWithLoadBalancerResult' => { 'Instances' => [] }, 'ResponseMetadata' => {} } end def end_element(name) case name when 'InstanceId' @response['RegisterInstancesWithLoadBalancerResult']['Instances'] << {name => value} when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/deregister_instances_from_load_balancer.rb0000644000004100000410000000117312261242551027345 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class DeregisterInstancesFromLoadBalancer < Fog::Parsers::Base def reset @response = { 'DeregisterInstancesFromLoadBalancerResult' => { 'Instances' => [] }, 'ResponseMetadata' => {} } end def end_element(name) case name when 'InstanceId' @response['DeregisterInstancesFromLoadBalancerResult']['Instances'] << {name => value} when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/detach_load_balancer_from_subnets.rb0000644000004100000410000000112712261242551026133 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class DetachLoadBalancerFromSubnets < Fog::Parsers::Base def reset @response = { 'DetachLoadBalancerFromSubnetsResult' => { 'Subnets' => [] }, 'ResponseMetadata' => {} } end def end_element(name) case name when 'member' @response['DetachLoadBalancerFromSubnetsResult']['Subnets'] << value when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/empty.rb0000644000004100000410000000074312261242551020430 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class Empty < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/describe_load_balancer_attributes.rb0000644000004100000410000000217312261242551026145 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class DescribeLoadBalancerAttributes < Fog::Parsers::Base def reset @response = { 'DescribeLoadBalancerAttributesResult' => { 'LoadBalancerAttributes' => {} }, 'ResponseMetadata' => {} } @stack = [] end def start_element(name, attrs = []) super case name when 'CrossZoneLoadBalancing' @cross_zone_load_balancing = {} end end def end_element(name) case name when 'Enabled' if @cross_zone_load_balancing @cross_zone_load_balancing['Enabled'] = value == 'true' ? true : false end when 'CrossZoneLoadBalancing' @response['DescribeLoadBalancerAttributesResult']['LoadBalancerAttributes']['CrossZoneLoadBalancing'] = @cross_zone_load_balancing @cross_zone_load_balancing = nil when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/disable_availability_zones_for_load_balancer.rb0000644000004100000410000000121112261242551030330 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class DisableAvailabilityZonesForLoadBalancer < Fog::Parsers::Base def reset @response = { 'DisableAvailabilityZonesForLoadBalancerResult' => { 'AvailabilityZones' => [] }, 'ResponseMetadata' => {} } end def end_element(name) case name when 'member' @response['DisableAvailabilityZonesForLoadBalancerResult']['AvailabilityZones'] << value when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/attach_load_balancer_to_subnets.rb0000644000004100000410000000112112261242551025620 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class AttachLoadBalancerToSubnets < Fog::Parsers::Base def reset @response = { 'AttachLoadBalancerToSubnetsResult' => { 'Subnets' => [] }, 'ResponseMetadata' => {} } end def end_element(name) case name when 'member' @response['AttachLoadBalancerToSubnetsResult']['Subnets'] << value when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/create_load_balancer.rb0000644000004100000410000000104012261242551023352 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class CreateLoadBalancer < Fog::Parsers::Base def reset @response = { 'CreateLoadBalancerResult' => {}, 'ResponseMetadata' => {} } end def end_element(name) case name when 'DNSName' @response['CreateLoadBalancerResult'][name] = value when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/describe_load_balancer_policy_types.rb0000644000004100000410000000437512261242551026510 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class DescribeLoadBalancerPolicyTypes < Fog::Parsers::Base def reset reset_policy_type reset_policy_attribute_type_description @results = { 'PolicyTypeDescriptions' => [] } @response = { 'DescribeLoadBalancerPolicyTypesResult' => {}, 'ResponseMetadata' => {} } end def reset_policy_type @policy_type = { 'Description' => '', 'PolicyAttributeTypeDescriptions' => [], 'PolicyTypeName' => '' } end def reset_policy_attribute_type_description @policy_attribute_type_description = { 'AttributeName' => '', 'AttributeType' => '', 'Cardinality' => '', 'DefaultValue' => '', 'Description' => '' } end def start_element(name, attrs = []) super case name when 'PolicyAttributeTypeDescriptions' @in_policy_attribute_types = true end end def end_element(name) case name when 'member' if @in_policy_attribute_types @policy_type['PolicyAttributeTypeDescriptions'] << @policy_attribute_type_description reset_policy_attribute_type_description elsif !@in_policy_attribute_types @results['PolicyTypeDescriptions'] << @policy_type reset_policy_type end when 'Description' if @in_policy_attribute_types @policy_attribute_type_description[name] = value else @policy_type[name] = value end when 'PolicyTypeName' @policy_type[name] = value when 'PolicyAttributeTypeDescriptions' @in_policy_attribute_types = false when 'AttributeName', 'AttributeType', 'Cardinality', 'DefaultValue' @policy_attribute_type_description[name] = value when 'RequestId' @response['ResponseMetadata'][name] = value when 'DescribeLoadBalancerPolicyTypesResponse' @response['DescribeLoadBalancerPolicyTypesResult'] = @results end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elb/apply_security_groups_to_load_balancer.rb0000644000004100000410000000116112261242551027270 0ustar www-datawww-datamodule Fog module Parsers module AWS module ELB class ApplySecurityGroupsToLoadBalancer < Fog::Parsers::Base def reset @response = { 'ApplySecurityGroupsToLoadBalancerResult' => { 'SecurityGroups' => [] }, 'ResponseMetadata' => {} } end def end_element(name) case name when 'member' @response['ApplySecurityGroupsToLoadBalancerResult']['SecurityGroups'] << value when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cdn/0000755000004100000410000000000012261242551016743 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/cdn/distribution.rb0000644000004100000410000000376712261242551022024 0ustar www-datawww-datamodule Fog module Parsers module CDN module AWS class Distribution < Fog::Parsers::Base def reset @response = { 'DistributionConfig' => { 'CNAME' => [], 'Logging' => {}, 'TrustedSigners' => [] } } end def start_element(name, attrs = []) super case name when 'CustomOrigin', 'S3Origin' @origin = name @response['DistributionConfig'][@origin] = {} end end def end_element(name) case name when 'AwsAccountNumber' @response['DistributionConfig']['TrustedSigners'] << value when 'Bucket', 'Prefix' @response['DistributionConfig']['Logging'][name] = value when 'CNAME' @response['DistributionConfig']['CNAME'] << value when 'DNSName', 'OriginAccessIdentity', 'OriginProtocolPolicy' @response['DistributionConfig'][@origin][name] = value when 'DomainName', 'Id', 'Status' @response[name] = value when 'CallerReference', 'Comment', 'DefaultRootObject', 'Origin', 'OriginAccessIdentity' @response['DistributionConfig'][name] = value when 'Enabled' if value == 'true' @response['DistributionConfig'][name] = true else @response['DistributionConfig'][name] = false end when 'HTTPPort', 'HTTPSPort' @response['DistributionConfig'][@origin][name] = value.to_i when 'InProgressInvalidationBatches' @response[name] = value.to_i when 'LastModifiedTime' @response[name] = Time.parse(value) when 'Protocol' @response['DistributionConfig']['RequireProtocols'] = value when 'Self' @response['DistributionConfig']['TrustedSigners'] << 'Self' end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cdn/streaming_distribution.rb0000644000004100000410000000420312261242551024057 0ustar www-datawww-datamodule Fog module Parsers module CDN module AWS class StreamingDistribution < Fog::Parsers::Base def reset @response = { 'StreamingDistributionConfig' => { 'CNAME' => [], 'Logging' => {}, 'TrustedSigners' => [] } } end def start_element(name, attrs = []) super case name when 'CustomOrigin', 'S3Origin' @origin = name @response['StreamingDistributionConfig'][@origin] = {} end end def end_element(name) case name when 'AwsAccountNumber' @response['StreamingDistributionConfig']['TrustedSigners'] << @value when 'Bucket', 'Prefix' @response['StreamingDistributionConfig']['Logging'][name] = @value when 'CNAME' @response['StreamingDistributionConfig']['CNAME'] << @value when 'DNSName', 'OriginAccessIdentity', 'OriginProtocolPolicy' @response['StreamingDistributionConfig'][@origin][name] = @value when 'DomainName', 'Id', 'Status' @response[name] = @value when 'CallerReference', 'Comment', 'DefaultRootObject', 'Origin', 'OriginAccessIdentity' @response['StreamingDistributionConfig'][name] = @value when 'Enabled' if @value == 'true' @response['StreamingDistributionConfig'][name] = true else @response['StreamingDistributionConfig'][name] = false end when 'HTTPPort', 'HTTPSPort' @response['StreamingDistributionConfig'][@origin][name] = @value.to_i when 'InProgressInvalidationBatches' @response[name] = @value.to_i when 'LastModifiedTime' @response[name] = Time.parse(@value) when 'Protocol' @response['StreamingDistributionConfig']['RequireProtocols'] = @value when 'Self' @response['StreamingDistributionConfig']['TrustedSigners'] << 'Self' end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cdn/get_invalidation_list.rb0000644000004100000410000000177412261242551023654 0ustar www-datawww-datamodule Fog module Parsers module CDN module AWS class GetInvalidationList < Fog::Parsers::Base def reset @invalidation_summary = { } @response = { 'InvalidationSummary' => [] } end def start_element(name, attrs = []) super end def end_element(name) case name when 'InvalidationSummary' @response['InvalidationSummary'] << @invalidation_summary @invalidation_summary = {} when 'Id', 'Status' @invalidation_summary[name] = @value when 'IsTruncated' if @value == 'true' @response[name] = true else @response[name] = false end when 'Marker', 'NextMarker' @response[name] = @value when 'MaxItems' @response[name] = @value.to_i end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cdn/post_invalidation.rb0000644000004100000410000000113512261242551023016 0ustar www-datawww-datamodule Fog module Parsers module CDN module AWS class PostInvalidation < Fog::Parsers::Base def reset @response = { 'InvalidationBatch' => { 'Path' => [] } } end def end_element(name) case name when 'CallerReference' @response['InvalidationBatch'][name] = value when 'CreateTime', 'Id', 'Status' @response[name] = value when 'Path' @response['InvalidationBatch'][name] << value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cdn/get_invalidation.rb0000644000004100000410000000125312261242551022611 0ustar www-datawww-datamodule Fog module Parsers module CDN module AWS class GetInvalidation < Fog::Parsers::Base def reset @response = { 'InvalidationBatch' => { 'Path' => [] } } end def start_element(name, attrs = []) super end def end_element(name) case name when 'Path' @response['InvalidationBatch'][name] << value when 'Id', 'Status', 'CreateTime' @response[name] = value when 'CallerReference' @response['InvalidationBatch'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cdn/get_distribution_list.rb0000644000004100000410000000355612261242551023712 0ustar www-datawww-datamodule Fog module Parsers module CDN module AWS class GetDistributionList < Fog::Parsers::Base def reset @distribution_summary = { 'CNAME' => [], 'TrustedSigners' => [] } @response = { 'DistributionSummary' => [] } end def start_element(name, attrs = []) super case name when 'CustomOrigin', 'S3Origin' @origin = name @distribution_summary[@origin] = {} end end def end_element(name) case name when 'DistributionSummary' @response['DistributionSummary'] << @distribution_summary @distribution_summary = { 'CNAME' => [], 'TrustedSigners' => [] } when 'Comment', 'DomainName', 'Id', 'Origin', 'Status' @distribution_summary[name] = value when 'CNAME' @distribution_summary[name] << value when 'DNSName', 'OriginAccessIdentity', 'OriginProtocolPolicy' @distribution_summary[@origin][name] = value when 'Enabled' if value == 'true' @distribution_summary[name] = true else @distribution_summary[name] = false end when 'HTTPPort', 'HTTPSPort' @distribution_summary[@origin][name] = value.to_i when 'LastModifiedTime' @distribution_summary[name] = Time.parse(value) when 'IsTruncated' if value == 'true' @response[name] = true else @response[name] = false end when 'Marker', 'NextMarker' @response[name] = value when 'MaxItems' @response[name] = value.to_i end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cdn/get_streaming_distribution_list.rb0000644000004100000410000000337712261242551025764 0ustar www-datawww-datamodule Fog module Parsers module CDN module AWS class GetStreamingDistributionList < Fog::Parsers::Base def reset @distribution_summary = { 'CNAME' => [], 'TrustedSigners' => [] } @response = { 'StreamingDistributionSummary' => [] } end def start_element(name, attrs = []) super case name when 'S3Origin' @origin = name @distribution_summary[@origin] = {} end end def end_element(name) case name when 'StreamingDistributionSummary' @response['StreamingDistributionSummary'] << @distribution_summary @distribution_summary = { 'CNAME' => [], 'TrustedSigners' => [] } when 'Comment', 'DomainName', 'Id', 'Status' @distribution_summary[name] = @value when 'CNAME' @distribution_summary[name] << @value when 'DNSName', 'OriginAccessIdentity' @distribution_summary[@origin][name] = @value when 'Enabled' if @value == 'true' @distribution_summary[name] = true else @distribution_summary[name] = false end when 'LastModifiedTime' @distribution_summary[name] = Time.parse(@value) when 'IsTruncated' if @value == 'true' @response[name] = true else @response[name] = false end when 'Marker', 'NextMarker' @response[name] = @value when 'MaxItems' @response[name] = @value.to_i end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/0000755000004100000410000000000012261242551016767 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/rds/delete_db_security_group.rb0000644000004100000410000000116512261242551024371 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/snapshot_parser' class DeleteDBSecurityGroup < Fog::Parsers::AWS::RDS::SnapshotParser def reset @response = { 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/delete_db_instance.rb0000644000004100000410000000147612261242551023117 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/db_parser' class DeleteDBInstance < Fog::Parsers::AWS::RDS::DbParser def reset @response = { 'DeleteDBInstanceResult' => {}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBInstance' @response['DeleteDBInstanceResult']['DBInstance'] = @db_instance @db_instance = fresh_instance when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/modify_db_parameter_group.rb0000644000004100000410000000123012261242551024520 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS class ModifyDbParameterGroup < Fog::Parsers::Base def reset @response = { 'ModifyDBParameterGroupResult' => {}, 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBParameterGroupName' @response['ModifyDBParameterGroupResult']['DBParameterGroupName'] = value when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/describe_db_log_files.rb0000644000004100000410000000233612261242551023570 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS class DescribeDBLogFiles < Fog::Parsers::Base attr_reader :rds_id def initialize(rds_id) @rds_id = rds_id super() end def reset @response = { 'DescribeDBLogFilesResult' => {'DBLogFiles' => []}, 'ResponseMetadata' => {} } fresh_log_file end def fresh_log_file @db_log_file = {'DBInstanceIdentifier' => @rds_id} end def start_element(name, attrs = []) super end def end_element(name) case name when 'LastWritten' then @db_log_file[name] = Time.at(value.to_i / 1000) when 'LogFileName' then @db_log_file[name] = value when 'Size' then @db_log_file[name] = value.to_i when 'DescribeDBLogFilesDetails' @response['DescribeDBLogFilesResult']['DBLogFiles'] << @db_log_file fresh_log_file when 'Marker' then @response['DescribeDBLogFilesResult'][name] = value when 'RequestId' then @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/snapshot_parser.rb0000644000004100000410000000263012261242551022530 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS class SnapshotParser < Fog::Parsers::Base def reset @db_snapshot = fresh_snapshot end def fresh_snapshot {} end def start_element(name, attrs = []) super end def end_element(name) case name when 'AllocatedStorage' then @db_snapshot['AllocatedStorage'] = value.to_i when 'AvailabilityZone' then @db_snapshot['AvailabilityZone'] = value when 'DBInstanceIdentifier' then @db_snapshot['DBInstanceIdentifier'] = value when 'DBSnapshotIdentifier' then @db_snapshot['DBSnapshotIdentifier'] = value when 'Engine' then @db_snapshot['Engine'] = value when 'EngineVersion' then @db_snapshot['EngineVersion'] = value when 'InstanceCreateTime' then @db_snapshot['InstanceCreateTime'] = Time.parse value when 'MasterUsername' then @db_snapshot['MasterUsername'] = value when 'Port' then @db_snapshot['Port'] = value.to_i when 'SnapshotCreateTime' then @db_snapshot['SnapshotCreateTime'] = Time.parse value when 'SnapshotType' then @db_snapshot['SnapshotType'] = value when 'Status' then @db_snapshot['Status'] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/revoke_db_security_group_ingress.rb0000644000004100000410000000156612261242551026161 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/security_group_parser' class RevokeDBSecurityGroupIngress < Fog::Parsers::AWS::RDS::SecurityGroupParser def reset @response = { 'RevokeDBSecurityGroupIngressResult' => {}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBSecurityGroup' then @response['RevokeDBSecurityGroupIngressResult']['DBSecurityGroup'] = @security_group @security_group = fresh_security_group when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/restore_db_instance_from_db_snapshot.rb0000644000004100000410000000147412261242551026745 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/db_parser' class RestoreDBInstanceFromDBSnapshot < Fog::Parsers::AWS::RDS::DbParser def reset @response = { 'RestoreDBInstanceFromDBSnapshot' => {}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBInstance' @response['RestoreDBInstanceFromDBSnapshot']['DBInstance'] = @db_instance @db_instance = fresh_instance when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/create_db_instance_read_replica.rb0000644000004100000410000000153012261242551025601 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/db_parser' class CreateDBInstanceReadReplica < Fog::Parsers::AWS::RDS::DbParser def reset @response = { 'CreateDBInstanceReadReplicaResult' => {}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBInstance' @response['CreateDBInstanceReadReplicaResult']['DBInstance'] = @db_instance @db_instance = fresh_instance when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/create_db_parameter_group.rb0000644000004100000410000000176212261242551024506 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS class CreateDbParameterGroup < Fog::Parsers::Base def reset @response = { 'CreateDBParameterGroupResult' => {}, 'ResponseMetadata' => {} } @db_parameter_group = {} end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBParameterGroupFamily' @db_parameter_group['DBParameterGroupFamily'] = value when 'Description' @db_parameter_group['Description'] = value when 'DBParameterGroupName' @db_parameter_group['DBParameterGroupName'] = value when 'DBParameterGroup' @response['CreateDBParameterGroupResult']['DBParameterGroup']= @db_parameter_group when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/describe_db_security_groups.rb0000644000004100000410000000175012261242551025072 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/security_group_parser' class DescribeDBSecurityGroups < Fog::Parsers::AWS::RDS::SecurityGroupParser def reset @response = { 'DescribeDBSecurityGroupsResult' => {'DBSecurityGroups' => []}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBSecurityGroup' then @response['DescribeDBSecurityGroupsResult']['DBSecurityGroups'] << @security_group @security_group = fresh_security_group when 'Marker' @response['DescribeDBSecurityGroupsResult']['Marker'] = value when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/restore_db_instance_to_point_in_time.rb0000644000004100000410000000147212261242551026753 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/db_parser' class RestoreDBInstanceToPointInTime < Fog::Parsers::AWS::RDS::DbParser def reset @response = { 'RestoreDBInstanceToPointInTime' => {}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBInstance' @response['RestoreDBInstanceToPointInTime']['DBInstance'] = @db_instance @db_instance = fresh_instance when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/subnet_group_parser.rb0000644000004100000410000000210112261242551023376 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS class SubnetGroupParser < Fog::Parsers::Base def reset @db_subnet_group = fresh_subnet_group end def start_element(name, attrs = []) super end def end_element(name) case name when 'VpcId' then @db_subnet_group['VpcId'] = value when 'SubnetGroupStatus' then @db_subnet_group['SubnetGroupStatus'] = value when 'DBSubnetGroupDescription' then @db_subnet_group['DBSubnetGroupDescription'] = value when 'DBSubnetGroupName' then @db_subnet_group['DBSubnetGroupName'] = value when 'SubnetIdentifier' then @db_subnet_group['Subnets'] << value when 'Marker' @response['DescribeDBSubnetGroupsResult']['Marker'] = value when 'RequestId' @response['ResponseMetadata'][name] = value end end def fresh_subnet_group {'Subnets' => []} end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/describe_db_parameter_groups.rb0000644000004100000410000000224112261242551025177 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS class DescribeDBParameterGroups < Fog::Parsers::Base def reset @response = { 'DescribeDBParameterGroupsResult' => {'DBParameterGroups' => []}, 'ResponseMetadata' => {} } @db_parameter_group = {} end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBParameterGroupFamily' then @db_parameter_group['DBParameterGroupFamily'] = value when 'Description' then @db_parameter_group['Description'] = value when 'DBParameterGroupName' then @db_parameter_group['DBParameterGroupName'] = value when 'DBParameterGroup' then @response['DescribeDBParameterGroupsResult']['DBParameterGroups'] << @db_parameter_group @db_parameter_group = {} when 'Marker' @response['DescribeDBParameterGroupsResult']['Marker'] = value when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/describe_db_instances.rb0000644000004100000410000000164212261242551023613 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/db_parser' class DescribeDBInstances < Fog::Parsers::AWS::RDS::DbParser def reset @response = { 'DescribeDBInstancesResult' => {'DBInstances' => []}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBInstance' @response['DescribeDBInstancesResult']['DBInstances'] << @db_instance @db_instance = fresh_instance when 'Marker' @response['DescribeDBInstancesResult']['Marker'] = value when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/reboot_db_instance.rb0000644000004100000410000000147612261242551023147 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/db_parser' class RebootDBInstance < Fog::Parsers::AWS::RDS::DbParser def reset @response = { 'RebootDBInstanceResult' => {}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBInstance' @response['RebootDBInstanceResult']['DBInstance'] = @db_instance @db_instance = fresh_instance when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/create_db_snapshot.rb0000644000004100000410000000146612261242551023152 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/snapshot_parser' class CreateDBSnapshot < Fog::Parsers::AWS::RDS::SnapshotParser def reset @response = { 'CreateDBSnapshotResult' => {}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBSnapshot' then @response['CreateDBSnapshotResult']['DBSnapshot'] = @db_snapshot @db_snapshot = fresh_snapshot when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/tag_list_parser.rb0000644000004100000410000000163112261242551022477 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS # parses an XML-formatted list of resource tags from AWS class TagListParser < Fog::Parsers::Base # each tag is modeled as a String pair (2-element Array) def reset @this_key = nil @this_value = nil @tags = Hash.new @response = {'ListTagsForResourceResult' => {'TagList' => {}}} end def end_element(name) super case name when 'Tag' @tags[@this_key] = @this_value @this_key, @this_value = nil, nil when 'Key' @this_key = value when 'Value' @this_value = value when 'TagList' @response['ListTagsForResourceResult']['TagList'] = @tags end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/describe_db_engine_versions.rb0000644000004100000410000000177612261242551025031 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/db_engine_version_parser' class DescribeDBEngineVersions < Fog::Parsers::AWS::RDS::DBEngineVersionParser def reset @response = { 'DescribeDBEngineVersionsResult' => {'DBEngineVersions' => []}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBEngineVersion' then @response['DescribeDBEngineVersionsResult']['DBEngineVersions'] << @db_engine_version @db_engine_version = fresh_engine_version when 'Marker' @response['DescribeDBEngineVersionsResult']['Marker'] = @value when 'RequestId' @response['ResponseMetadata'][name] = @value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/describe_db_parameters.rb0000644000004100000410000000272712261242551023774 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS class DescribeDBParameters < Fog::Parsers::Base def reset @response = { 'DescribeDBParametersResult' =>{}, 'ResponseMetadata' => {} } @parameter = {} @parameters = [] end def start_element(name, attrs = []) super end def end_element(name) case name when 'ParameterValue' then @parameter['ParameterValue'] = value when 'DataType' then @parameter['DataType'] = value when 'AllowedValues' then @parameter['AllowedValues'] = value when 'Source' then @parameter['Source'] = value when 'IsModifiable' then @parameter['IsModifiable'] = value == 'true' ? true : false when 'Description' then @parameter['Description'] = value when 'ApplyType' then @parameter['ApplyType'] = value when 'ParameterName' then @parameter['ParameterName'] = value when 'Parameter' @parameters << @parameter @parameter = {} when 'Marker' @response['DescribeDBParametersResult']['Marker'] = value when 'Parameters' @response['DescribeDBParametersResult']['Parameters'] = @parameters when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/delete_db_subnet_group.rb0000644000004100000410000000124112261242551024015 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/subnet_group_parser' class DeleteDBSubnetGroup < Fog::Parsers::AWS::RDS::SubnetGroupParser def reset @response = { 'DeleteDBSubnetGroupResponse' => {}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/download_db_logfile_portion.rb0000644000004100000410000000105212261242551025041 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS class DownloadDBLogFilePortion < Fog::Parsers::Base def reset @response = { 'DownloadDBLogFilePortionResult' => {}, 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) key = (name == 'RequestId') ? 'ResponseMetadata' : 'DownloadDBLogFilePortionResult' @response[key][name] = value end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/describe_db_reserved_instances.rb0000644000004100000410000000233512261242551025512 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS class DescribeDBReservedInstances < Fog::Parsers::Base def reset @reserved_instance = {} @response = { 'ReservedDBInstances' => [] } end def end_element(name) case name when 'ReservedDBInstanceId', 'ReservedDBInstancesOfferingId', 'DBInstanceClass', 'ProductDescription', 'State' @reserved_instance[name] = @value when 'Duration', 'DBInstanceCount' @reserved_instance[name] = @value.to_i when 'FixedPrice', 'UsagePrice' @reserved_instance[name] = @value.to_f when 'ReservedDBInstance' @response['ReservedDBInstances'] << @reserved_instance @reserved_instance = {} when 'Marker' @response[name] = @value when 'MultiAZ' if @value == 'false' @reserved_instance[name] = false else @reserved_instance[name] = true end when 'StartTime' @reserved_instance[name] = Time.parse(@value) end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/describe_orderable_db_instance_options.rb0000644000004100000410000000360312261242551027221 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS class DescribeOrderableDBInstanceOptions < Fog::Parsers::Base def reset @response = { 'DescribeOrderableDBInstanceOptionsResult' => {'OrderableDBInstanceOptions' => []}, 'ResponseMetadata' => {} } @db_instance_option = {} @db_instance_options = [] end def start_element(name, attrs = []) case name when 'AvailabilityZones' then @availability_zones = [] when 'AvailabilityZone' then @availability_zone = {} end super end def end_element(name) case name when 'MultiAZCapable', 'ReadReplicaCapable', 'Vpc' then @db_instance_option[name] = to_boolean(value) when 'Engine', 'LicenseModel', 'EngineVersion', 'DBInstanceClass' then @db_instance_option[name] = value when 'AvailabilityZones' then @db_instance_option[name] = @availability_zones when 'AvailabilityZone' then @availability_zones << @availability_zone unless @availability_zone.empty? when 'Name' then @availability_zone[name] = value when 'ProvisionedIopsCapable' then @availability_zone[name] = to_boolean(value) when 'OrderableDBInstanceOption' @db_instance_options << @db_instance_option @db_instance_option = {} when 'OrderableDBInstanceOptions' @response['DescribeOrderableDBInstanceOptionsResult']['OrderableDBInstanceOptions'] = @db_instance_options when 'Marker' then @response['DescribeOrderableDBInstanceOptionsResult'][name] = value when 'RequestId' then @response['ResponseMetadata'][name] = value end end def to_boolean(v) (v =~ /\A\s*(true|yes|1|y)\s*$/i) == 0 end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/create_db_subnet_group.rb0000644000004100000410000000152212261242551024020 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/subnet_group_parser' class CreateDBSubnetGroup < Fog::Parsers::AWS::RDS::SubnetGroupParser def reset @response = { 'CreateDBSubnetGroupResult' => {}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBSubnetGroup' then @response['CreateDBSubnetGroupResult']['DBSubnetGroup'] = @db_subnet_group @db_subnet_group = fresh_subnet_group when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/db_engine_version_parser.rb0000644000004100000410000000206312261242551024350 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS class DBEngineVersionParser < Fog::Parsers::Base def reset @db_engine_version = fresh_engine_version end def fresh_engine_version {} end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBEngineDescription' then @db_engine_version['DBEngineDescription'] = @value when 'DBEngineVersionDescription' then @db_engine_version['DBEngineVersionDescription'] = @value when 'DBParameterGroupFamily' then @db_engine_version['DBParameterGroupFamily'] = @value when 'DBEngineVersionIdentifier' then @db_engine_version['DBEngineVersionIdentifier'] = @value when 'Engine' then @db_engine_version['Engine'] = @value when 'EngineVersion' then @db_engine_version['EngineVersion'] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/delete_db_parameter_group.rb0000644000004100000410000000102712261242551024477 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS class DeleteDbParameterGroup < Fog::Parsers::Base def reset @response = { 'ResponseMetadata' => {} } @db_parameter_group = {} end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/create_db_security_group.rb0000644000004100000410000000154012261242551024367 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/security_group_parser' class CreateDBSecurityGroup < Fog::Parsers::AWS::RDS::SecurityGroupParser def reset @response = { 'CreateDBSecurityGroupResult' => {}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBSecurityGroup' then @response['CreateDBSecurityGroupResult']['DBSecurityGroup'] = @security_group @security_group = fresh_security_group when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/describe_db_snapshots.rb0000644000004100000410000000166712261242551023655 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/snapshot_parser' class DescribeDBSnapshots < Fog::Parsers::AWS::RDS::SnapshotParser def reset @response = { 'DescribeDBSnapshotsResult' => {'DBSnapshots' => []}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBSnapshot' then @response['DescribeDBSnapshotsResult']['DBSnapshots'] << @db_snapshot @db_snapshot = fresh_snapshot when 'Marker' @response['DescribeDBSnapshotsResult']['Marker'] = value when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/base.rb0000644000004100000410000000112012261242551020220 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS # Base parser for ResponseMetadata, RequestId class Base < Fog::Parsers::Base def reset super @response = { 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/describe_db_subnet_groups.rb0000644000004100000410000000172012261242551024520 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/subnet_group_parser' class DescribeDBSubnetGroups < Fog::Parsers::AWS::RDS::SubnetGroupParser def reset @response = { 'DescribeDBSubnetGroupsResult' => {'DBSubnetGroups' => []}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBSubnetGroup' @response['DescribeDBSubnetGroupsResult']['DBSubnetGroups'] << @db_subnet_group @db_subnet_group = fresh_subnet_group when 'Marker' @response['DescribeDBSubnetGroupsResult']['Marker'] = value when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/security_group_parser.rb0000644000004100000410000000215312261242551023754 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS class SecurityGroupParser < Fog::Parsers::Base def reset @security_group = fresh_security_group end def fresh_security_group {'EC2SecurityGroups' => [], 'IPRanges' => []} end def start_element(name, attrs = []) super case name when 'EC2SecurityGroup', 'IPRange'; then @ingress = {} end end def end_element(name) case name when 'DBSecurityGroupDescription' then @security_group['DBSecurityGroupDescription'] = value when 'DBSecurityGroupName' then @security_group['DBSecurityGroupName'] = value when 'OwnerId' then @security_group['OwnerId'] = value when 'EC2SecurityGroup', 'IPRange' @security_group["#{name}s"] << @ingress unless @ingress.empty? when 'EC2SecurityGroupName', 'EC2SecurityGroupOwnerId', 'CIDRIP', 'Status' @ingress[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/delete_db_snapshot.rb0000644000004100000410000000145712261242551023151 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/snapshot_parser' class DeleteDBSnapshot < Fog::Parsers::AWS::RDS::SnapshotParser def reset @response = { 'DeleteDBSnapshotResult' => {}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value when 'DBSnapshot' @response['DeleteDBSnapshotResult']['DBSnapshot'] = @db_snapshot @db_snapshot = fresh_snapshot else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/authorize_db_security_group_ingress.rb0000644000004100000410000000157612261242551026701 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/security_group_parser' class AuthorizeDBSecurityGroupIngress < Fog::Parsers::AWS::RDS::SecurityGroupParser def reset @response = { 'AuthorizeDBSecurityGroupIngressResult' => {}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBSecurityGroup' then @response['AuthorizeDBSecurityGroupIngressResult']['DBSecurityGroup'] = @security_group @security_group = fresh_security_group when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/create_db_instance.rb0000644000004100000410000000146712261242551023120 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/db_parser' class CreateDBInstance < Fog::Parsers::AWS::RDS::DbParser def reset @response = { 'CreateDBInstanceResult' => {}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBInstance' @response['CreateDBInstanceResult']['DBInstance'] = @db_instance @db_instance = fresh_instance when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/modify_db_instance.rb0000644000004100000410000000145712261242551023143 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/db_parser' class ModifyDBInstance < Fog::Parsers::AWS::RDS::DbParser def reset @response = { 'ModifyDBInstanceResult' => {}, 'ResponseMetadata' => {} } super end def start_element(name, attrs = []) super end def end_element(name) case name when 'DBInstance' @response['ModifyDBInstanceResult']['DBInstance'] = @db_instance @db_instance = fresh_instance when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/event_list.rb0000644000004100000410000000165012261242551021472 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS require 'fog/aws/parsers/rds/base' class EventListParser < Base def reset super @response['Events'] = [] end def start_element(name, attrs = []) super case name when 'Event'; then @event = {} end end def end_element(name) case name when 'Date' @event[name] = DateTime.parse(value.strip) when 'Message', 'SourceIdentifier', 'SourceType' @event[name] = value ? value.strip : name when 'Event' @response['Events'] << @event unless @event.empty? when 'IsTruncated', 'Marker', 'NextMarker' @response[name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/rds/db_parser.rb0000644000004100000410000001236512261242551021264 0ustar www-datawww-datamodule Fog module Parsers module AWS module RDS class DbParser < Fog::Parsers::Base def reset @db_instance = fresh_instance end def fresh_instance {'PendingModifiedValues' => [], 'DBSecurityGroups' => [], 'ReadReplicaDBInstanceIdentifiers' => [], 'Endpoint' => {}} end def start_element(name, attrs = []) super case name when 'PendingModifiedValues' @in_pending_modified_values = true @pending_modified_values = {} when 'DBSecurityGroups' @in_db_security_groups = true @db_security_groups = [] when 'DBSecurityGroup' @db_security_group = {} when 'Endpoint' @in_endpoint = true @endpoint = {} when 'DBParameterGroup' @db_parameter_group = {} when 'DBParameterGroups' @in_db_parameter_groups = true @db_parameter_groups = [] when 'VpcSecurityGroupMembership' @vpc_security_group = {} when 'VpcSecurityGroups' @in_vpc_security_groups = true @vpc_security_groups = [] end end def end_element(name) case name when 'LatestRestorableTime', 'InstanceCreateTime' @db_instance[name] = Time.parse value when 'Engine', 'DBInstanceStatus', 'DBInstanceIdentifier', 'EngineVersion', 'PreferredBackupWindow', 'PreferredMaintenanceWindow', 'AvailabilityZone', 'MasterUsername', 'DBName', 'LicenseModel', 'DBSubnetGroupName' @db_instance[name] = value when 'MultiAZ', 'AutoMinorVersionUpgrade', 'PubliclyAccessible' if value == 'false' @db_instance[name] = false else @db_instance[name] = true end when 'DBParameterGroups' @in_db_parameter_groups = false @db_instance['DBParameterGroups'] = @db_parameter_groups when 'DBParameterGroup' @db_parameter_groups << @db_parameter_group @db_parameter_group = {} when 'ParameterApplyStatus', 'DBParameterGroupName' if @in_db_parameter_groups @db_parameter_group[name] = value end when 'BackupRetentionPeriod' if @in_pending_modified_values @pending_modified_values[name] = value.to_i else @db_instance[name] = value.to_i end when 'DBInstanceClass', 'EngineVersion', 'MasterUserPassword', 'MultiAZ' if @in_pending_modified_values @pending_modified_values[name] = value else @db_instance[name] = value end when 'DBSecurityGroups' @in_db_security_groups = false @db_instance['DBSecurityGroups'] = @db_security_groups when 'DBSecurityGroupName' @db_security_group[name]=value when 'DBSecurityGroup' @db_security_groups << @db_security_group @db_security_group = {} when 'VpcSecurityGroups' @in_vpc_security_groups = false @db_instance['VpcSecurityGroups'] = @vpc_security_groups when 'VpcSecurityGroupMembership' @vpc_security_groups << @vpc_security_group @vpc_security_group = {} when 'VpcSecurityGroupId' @vpc_security_group[name] = value when 'AllocatedStorage' if @in_pending_modified_values @pending_modified_values[name] = value.to_i else @db_instance[name] = value.to_i end when 'Status' # Unfortunately, status is used in VpcSecurityGroupMemebership and # DBSecurityGroups if @in_db_security_groups @db_security_group[name]=value end if @in_vpc_security_groups @vpc_security_group[name] = value end when 'Address' @endpoint[name] = value when 'Port' if @in_pending_modified_values @pending_modified_values[name] = value.to_i elsif @in_endpoint @endpoint[name] = value.to_i end when 'PendingModifiedValues' @in_pending_modified_values = false @db_instance['PendingModifiedValues'] = @pending_modified_values when 'Endpoint' @in_endpoint = false @db_instance['Endpoint'] = @endpoint when 'ReadReplicaDBInstanceIdentifier' @db_instance['ReadReplicaDBInstanceIdentifiers'] << value when 'ReadReplicaSourceDBInstanceIdentifier' @db_instance['ReadReplicaSourceDBInstanceIdentifier'] = value when 'DBInstance' @db_instance = fresh_instance end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/0000755000004100000410000000000012261242551017653 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/compute/describe_reserved_instances.rb0000644000004100000410000000202312261242551025723 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeReservedInstances < Fog::Parsers::Base def reset @reserved_instance = {} @response = { 'reservedInstancesSet' => [] } end def end_element(name) case name when 'availabilityZone', 'instanceType', 'productDescription', 'reservedInstancesId', 'state', 'offeringType' @reserved_instance[name] = value when 'duration', 'instanceCount' @reserved_instance[name] = value.to_i when 'fixedPrice', 'amount', 'usagePrice' @reserved_instance[name] = value.to_f when 'item' @response['reservedInstancesSet'] << @reserved_instance @reserved_instance = {} when 'requestId' @response[name] = value when 'start','end' @reserved_instance[name] = Time.parse(value) end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/monitor_unmonitor_instances.rb0000644000004100000410000000150412261242551026050 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class MonitorUnmonitorInstances < Fog::Parsers::Base def reset @response = {} @instance_set = [] @current_instance_set = {} end def end_element(name) case name when 'requestId' @response['requestId'] = value when 'instanceId' @current_instance_set['instanceId'] = value when 'item' @instance_set << @current_instance_set @current_instance_set = {} when 'state' @current_instance_set['monitoring'] = value when 'instancesSet' @response['instancesSet'] = @instance_set end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/create_key_pair.rb0000644000004100000410000000054012261242551023325 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class CreateKeyPair < Fog::Parsers::Base def end_element(name) case name when 'keyFingerprint', 'keyMaterial', 'keyName', 'requestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_security_groups.rb0000644000004100000410000000637612261242551025322 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeSecurityGroups < Fog::Parsers::Base def reset @group = {} @ip_permission = { 'groups' => [], 'ipRanges' => []} @ip_permission_egress = { 'groups' => [], 'ipRanges' => []} @ip_range = {} @security_group = { 'ipPermissions' => [], 'ipPermissionsEgress' => [] } @response = { 'securityGroupInfo' => [] } end def start_element(name, attrs = []) super case name when 'groups' @in_groups = true when 'ipPermissions' @in_ip_permissions = true when 'ipPermissionsEgress' @in_ip_permissions_egress = true when 'ipRanges' @in_ip_ranges = true end end def end_element(name) case name when 'cidrIp' @ip_range[name] = value when 'fromPort', 'toPort' if @in_ip_permissions_egress @ip_permission_egress[name] = value.to_i else @ip_permission[name] = value.to_i end when 'groups' @in_groups = false when 'groupDescription', 'ownerId', 'vpcId' @security_group[name] = value when 'groupId','groupName' if @in_groups @group[name] = value else @security_group[name] = value end when 'ipPermissions' @in_ip_permissions = false when 'ipPermissionsEgress' @in_ip_permissions_egress = false when 'ipProtocol' if @in_ip_permissions_egress @ip_permission_egress[name] = value else @ip_permission[name] = value end when 'ipRanges' @in_ip_ranges = false when 'item' if @in_groups if @in_ip_permissions_egress @ip_permission_egress['groups'] << @group else @ip_permission['groups'] << @group end @group = {} elsif @in_ip_ranges if @in_ip_permissions_egress @ip_permission_egress['ipRanges'] << @ip_range else @ip_permission['ipRanges'] << @ip_range end @ip_range = {} elsif @in_ip_permissions @security_group['ipPermissions'] << @ip_permission @ip_permission = { 'groups' => [], 'ipRanges' => []} elsif @in_ip_permissions_egress @security_group['ipPermissionsEgress'] << @ip_permission_egress @ip_permission_egress = { 'groups' => [], 'ipRanges' => []} else @response['securityGroupInfo'] << @security_group @security_group = { 'ipPermissions' => [], 'ipPermissionsEgress' => [] } end when 'requestId' @response[name] = value when 'userId' @group[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_regions.rb0000644000004100000410000000113112261242551023502 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeRegions < Fog::Parsers::Base def reset @region = {} @response = { 'regionInfo' => [] } end def end_element(name) case name when 'item' @response['regionInfo'] << @region @region = {} when 'regionEndpoint', 'regionName' @region[name] = value when 'requestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/get_console_output.rb0000644000004100000410000000105412261242551024121 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class GetConsoleOutput < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'instanceId', 'requestId' @response[name] = value when 'output' @response[name] = value && Base64.decode64(value) when 'timestamp' @response[name] = Time.parse(value) end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_reserved_instances_offerings.rb0000644000004100000410000000210112261242551027762 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeReservedInstancesOfferings < Fog::Parsers::Base def reset @reserved_instances_offering = {} @response = { 'reservedInstancesOfferingsSet' => [] } end def end_element(name) case name when 'availabilityZone', 'currencyCode', 'instanceType', 'offeringType', 'instanceTenancy', 'productDescription', 'reservedInstancesOfferingId' @reserved_instances_offering[name] = value when 'duration' @reserved_instances_offering[name] = value.to_i when 'fixedPrice', 'usagePrice' @reserved_instances_offering[name] = value.to_f when 'item' @response['reservedInstancesOfferingsSet'] << @reserved_instances_offering unless @reserved_instances_offering.empty? @reserved_instances_offering = {} when 'requestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/create_network_interface.rb0000644000004100000410000000117712261242551025242 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS require 'fog/aws/parsers/compute/network_interface_parser' class CreateNetworkInterface < NetworkInterfaceParser def reset super @response = { 'networkInterface' => {} } end def end_element(name) case name when 'requestId' @response[name] = value when 'networkInterface' @response['networkInterface'] = @nic reset_nic else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/create_image.rb0000644000004100000410000000055612261242551022613 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class CreateImage < Fog::Parsers::Base def end_element(name) case name when 'instanceId', 'requestId', 'name', 'description', 'noReboot', 'imageId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_volumes.rb0000644000004100000410000000413012261242551023530 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeVolumes < Fog::Parsers::Base def reset @attachment = {} @in_attachment_set = false @response = { 'volumeSet' => [] } @tag = {} @volume = { 'attachmentSet' => [], 'tagSet' => {} } end def start_element(name, attrs = []) super case name when 'attachmentSet' @in_attachment_set = true when 'tagSet' @in_tag_set = true end end def end_element(name) if @in_attachment_set case name when 'attachmentSet' @in_attachment_set = false when 'attachTime' @attachment[name] = Time.parse(value) when 'deleteOnTermination' @attachment[name] = value == 'true' when 'device', 'instanceId', 'status', 'volumeId' @attachment[name] = value when 'item' @volume['attachmentSet'] << @attachment @attachment = {} end elsif @in_tag_set case name when 'key', 'value' @tag[name] = value when 'item' @volume['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'tagSet' @in_tag_set = false end else case name when 'availabilityZone', 'snapshotId', 'status', 'volumeId', 'volumeType' @volume[name] = value when 'createTime' @volume[name] = Time.parse(value) when 'item' @response['volumeSet'] << @volume @volume = { 'attachmentSet' => [], 'tagSet' => {} } when 'requestId' @response[name] = value when 'size', 'iops' @volume[name] = value.to_i end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_placement_groups.rb0000644000004100000410000000122512261242551025407 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribePlacementGroups < Fog::Parsers::Base def reset @placement_group = {} @response = { 'placementGroupSet' => [] } end def end_element(name) case name when 'item' @response['placementGroupSet'] << @placement_group @placement_group = {} when 'groupName', 'state', 'strategy' @placement_group[name] = value when 'requestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/get_password_data.rb0000644000004100000410000000074312261242551023676 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class GetPasswordData < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'instanceId', 'requestId', 'passwordData' @response[name] = @value when 'timestamp' @response[name] = Time.parse(@value) end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/cancel_spot_instance_requests.rb0000644000004100000410000000127212261242551026313 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class CancelSpotInstanceRequests < Fog::Parsers::Base def reset @spot_instance_request = {} @response = { 'spotInstanceRequestSet' => [] } end def end_element(name) case name when 'item' @response['spotInstanceRequestSet'] << @spot_instance_request @spot_instance_request = {} when 'requestId' @response[name] = value when 'spotInstanceRequestId', 'state' @spot_instance_request[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_spot_price_history.rb0000644000004100000410000000147112261242551025773 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeSpotPriceHistory < Fog::Parsers::Base def reset @spot_price = {} @response = { 'spotPriceHistorySet' => [] } end def end_element(name) case name when 'availabilityZone', 'instanceType', 'productDescription' @spot_price[name] = value when 'item' @response['spotPriceHistorySet'] << @spot_price @spot_price = {} when 'requestId' @response[name] = value when 'spotPrice' @spot_price[name] = value.to_f when 'timestamp' @spot_price[name] = Time.parse(value) end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/create_security_group.rb0000644000004100000410000000076212261242551024613 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class CreateSecurityGroup < Fog::Parsers::Base def end_element(name) case name when 'return' if value == 'true' @response[name] = true else @response[name] = false end when 'requestId', 'groupId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/create_dhcp_options.rb0000644000004100000410000000433312261242551024217 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class CreateDhcpOptions < Fog::Parsers::Base def reset @dhcp_options = { 'dhcpConfigurationSet' => {}, 'tagSet' => {} } @response = { 'dhcpOptionsSet' => [] } @tag = {} @value_set = [] @dhcp_configuration = {} end def start_element(name, attrs = []) super case name when 'tagSet' @in_tag_set = true when 'dhcpConfigurationSet' @in_dhcp_configuration_set = true when 'valueSet' @in_value_set = true end end def end_element(name) if @in_tag_set case name when 'item' @dhcp_options['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'key', 'value' @tag[name] = value when 'tagSet' @in_tag_set = false end elsif @in_dhcp_configuration_set case name when 'item' unless @in_value_set @dhcp_options['dhcpConfigurationSet'][@dhcp_configuration['key']] = @value_set @value_set=[] @dhcp_configuration = {} end when 'key', 'value' if !@in_value_set @dhcp_configuration[name] = value else @value_set << value end when 'valueSet' @in_value_set = false when 'dhcpConfigurationSet' @in_dhcp_configuration_set = false end else case name when 'dhcpOptionsId' @dhcp_options[name] = value when 'dhcpOptions' @response['dhcpOptionsSet'] << @dhcp_options @dhcp_options = { 'tagSet' => {} } @dhcp_options = { 'dhcpOptionsSet' => {} } when 'requestId' @response[name] = value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/create_subnet.rb0000644000004100000410000000236412261242551023030 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class CreateSubnet < Fog::Parsers::Base def reset @subnet = { 'tagSet' => {} } @response = { 'subnetSet' => [] } @tag = {} end def start_element(name, attrs = []) super case name when 'tagSet' @in_tag_set = true end end def end_element(name) if @in_tag_set case name when 'item' @subnet['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'key', 'value' @tag[name] = value when 'tagSet' @in_tag_set = false end else case name when 'subnetId', 'state', 'vpcId', 'cidrBlock', 'availableIpAddressCount', 'availabilityZone' @subnet[name] = value when 'subnet' @response['subnetSet'] << @subnet @subnet = { 'tagSet' => {} } when 'requestId' @response[name] = value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/purchase_reserved_instances_offering.rb0000644000004100000410000000063512261242551027643 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class PurchaseReservedInstancesOffering < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'reservedInstancesId', 'requestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/copy_snapshot.rb0000644000004100000410000000056712261242551023101 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class CopySnapshot < Fog::Parsers::Base def end_element(name) case name when 'snapshotId' @response[name] = value when 'requestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_route_tables.rb0000755000004100000410000000601612261242551024536 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeRouteTables < Fog::Parsers::Base def reset @association = { 'routeTableAssociationId' => nil, 'routeTableId' => nil, 'subnetId' => nil, 'main' => false } @in_association_set = false @in_route_set = false @route = { 'destinationCidrBlock' => nil, 'gatewayId' => nil, 'instanceId' => nil, 'instanceOwnerId' => nil, 'networkInterfaceId' => nil, 'state' => nil, 'origin' => nil } @response = { 'routeTableSet' => [] } @tag = {} @route_table = { 'associationSet' => [], 'tagSet' => {}, 'routeSet' => [] } end def start_element(name, attrs = []) super case name when 'associationSet' @in_association_set = true when 'tagSet' @in_tag_set = true when 'routeSet' @in_route_set = true end end def end_element(name) if @in_association_set case name when 'associationSet' @in_association_set = false when 'routeTableAssociationId', 'routeTableId', 'subnetId' @association[name] = value when 'main' if value == 'true' @association[name] = true else @association[name] = false end when 'item' @route_table['associationSet'] << @association @association = { 'routeTableAssociationId' => nil, 'routeTableId' => nil, 'subnetId' => nil, 'main' => false } end elsif @in_tag_set case name when 'key', 'value' @tag[name] = value when 'item' @route_table['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'tagSet' @in_tag_set = false end elsif @in_route_set case name when 'destinationCidrBlock', 'gatewayId', 'instanceId', 'instanceOwnerId', 'networkInterfaceId', 'state', 'origin' @route[name] = value when 'item' @route_table['routeSet'] << @route @route = { 'destinationCidrBlock' => nil, 'gatewayId' => nil, 'instanceId' => nil, 'instanceOwnerId' => nil, 'networkInterfaceId' => nil, 'state' => nil, 'origin' => nil } when 'routeSet' @in_route_set = false end else case name when 'routeTableId', 'vpcId' @route_table[name] = value when 'item' @response['routeTableSet'] << @route_table @route_table = { 'associationSet' => [], 'tagSet' => {}, 'routeSet' => [] } when 'requestId' @response[name] = value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/allocate_address.rb0000644000004100000410000000053312261242551023472 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class AllocateAddress < Fog::Parsers::Base def end_element(name) case name when 'publicIp', 'requestId', 'domain', 'allocationId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/spot_datafeed_subscription.rb0000644000004100000410000000130212261242551025602 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class SpotDatafeedSubscription < Fog::Parsers::Base def reset @response = { 'spotDatafeedSubscription' => {} } end def end_element(name) case name when 'bucket', 'ownerId', 'prefix', 'state' @response['spotDatafeedSubscription'][name] = value when 'code', 'message' @response['spotDatafeedSubscription']['fault'] ||= {} @response['spotDatafeedSubscription'][name] = value when 'requestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_network_interfaces.rb0000644000004100000410000000170612261242551025740 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS require 'fog/aws/parsers/compute/network_interface_parser' class DescribeNetworkInterfaces < NetworkInterfaceParser def reset super @response = { 'networkInterfaceSet' => [] } @item_level = 0 end def start_element(name, attrs = []) super case name when 'item' @item_level += 1 end end def end_element(name) case name when 'requestId' @response[name] = value when 'item' @item_level -= 1 if @item_level == 0 @response['networkInterfaceSet'] << @nic reset_nic else super end else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_subnets.rb0000644000004100000410000000236312261242551023527 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeSubnets < Fog::Parsers::Base def reset @subnet = { 'tagSet' => {} } @response = { 'subnetSet' => [] } @tag = {} end def start_element(name, attrs = []) super case name when 'tagSet' @in_tag_set = true end end def end_element(name) if @in_tag_set case name when 'item' @subnet['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'key', 'value' @tag[name] = value when 'tagSet' @in_tag_set = false end else case name when 'subnetId', 'state', 'vpcId', 'cidrBlock', 'availableIpAddressCount', 'availabilityZone' @subnet[name] = value when 'item' @response['subnetSet'] << @subnet @subnet = { 'tagSet' => {} } when 'requestId' @response[name] = value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/create_volume.rb0000644000004100000410000000102412261242551023027 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class CreateVolume < Fog::Parsers::Base def end_element(name) case name when 'availabilityZone', 'requestId', 'snapshotId', 'status', 'volumeId', 'volumeType' @response[name] = value when 'createTime' @response[name] = Time.parse(value) when 'size', 'iops' @response[name] = value.to_i end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_internet_gateways.rb0000644000004100000410000000345312261242551025601 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeInternetGateways < Fog::Parsers::Base def reset @internet_gateway = { 'attachmentSet' => {}, 'tagSet' => {} } @response = { 'internetGatewaySet' => [] } @tag = {} @attachment = {} end def start_element(name, attrs = []) super case name when 'tagSet' @in_tag_set = true when 'attachmentSet' @in_attachment_set = true end end def end_element(name) if @in_tag_set case name when 'item' @internet_gateway['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'key', 'value' @tag[name] = value when 'tagSet' @in_tag_set = false end elsif @in_attachment_set case name when 'item' @internet_gateway['attachmentSet']=@attachment @attachment = {} when 'vpcId', 'state' @attachment[name] = value when 'attachmentSet' @in_attachment_set = false end else case name when 'internetGatewayId' @internet_gateway[name] = value when 'item' @response['internetGatewaySet'] << @internet_gateway @internet_gateway = { 'tagSet' => {} } @internet_gateway = { 'attachmentSet' => {} } when 'requestId' @response[name] = value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/network_interface_parser.rb0000644000004100000410000000540412261242551025270 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class NetworkInterfaceParser < Fog::Parsers::Base def reset_nic @nic = { 'groupSet' => {}, 'attachment' => {}, 'association' => {}, 'tagSet' => {} } @in_tag_set = false @in_group_set = false @in_attachment = false @in_association = false end def reset reset_nic end def start_element(name, attrs = []) super case name when 'tagSet' @in_tag_set = true @tag = {} when 'groupSet' @in_group_set = true @group = {} when 'attachment' @in_attachment = true @attachment = {} when 'association' @in_association = true @association = {} end end def end_element(name) if @in_tag_set case name when 'item' @nic['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'key', 'value' @tag[name] = value when 'tagSet' @in_tag_set = false end elsif @in_group_set case name when 'item' @nic['groupSet'][@group['groupId']] = @group['groupName'] @group = {} when 'groupId', 'groupName' @group[name] = value when 'groupSet' @in_group_set = false end elsif @in_attachment case name when 'attachmentId', 'instanceId', 'instanceOwnerId', 'deviceIndex', 'status', 'attachTime', 'deleteOnTermination' @attachment[name] = value when 'attachment' @nic['attachment'] = @attachment @in_attachment = false end elsif @in_association case name when 'associationId', 'publicIp', 'ipOwnerId' @association[name] = value when 'association' @nic['association'] = @association @in_association = false end else case name when 'networkInterfaceId', 'subnetId', 'vpcId', 'availabilityZone', 'description', 'ownerId', 'requesterId', 'requesterManaged', 'status', 'macAddress', 'privateIpAddress', 'privateDnsName' @nic[name] = value when 'sourceDestCheck' @nic['sourceDestCheck'] = (value == 'true') end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_availability_zones.rb0000644000004100000410000000213312261242551025727 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeAvailabilityZones < Fog::Parsers::Base def start_element(name, attrs = []) case name when 'messageSet' @in_message_set = true end super end def reset @availability_zone = { 'messageSet' => [] } @response = { 'availabilityZoneInfo' => [] } end def end_element(name) case name when 'item' unless @in_message_set @response['availabilityZoneInfo'] << @availability_zone @availability_zone = { 'messageSet' => [] } end when 'message' @availability_zone['messageSet'] << value when 'regionName', 'zoneName', 'zoneState' @availability_zone[name] = value when 'requestId' @response[name] = value when 'messageSet' @in_message_set = false end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/create_snapshot.rb0000644000004100000410000000111512261242551023360 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class CreateSnapshot < Fog::Parsers::Base def end_element(name) case name when 'description', 'ownerId', 'progress', 'snapshotId', 'status', 'volumeId' @response[name] = value when 'requestId' @response[name] = value when 'startTime' @response[name] = Time.parse(value) when 'volumeSize' @response[name] = value.to_i end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_images.rb0000644000004100000410000000610212261242551023304 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeImages < Fog::Parsers::Base def reset @block_device_mapping = {} @image = { 'blockDeviceMapping' => [], 'productCodes' => [], 'stateReason' => {}, 'tagSet' => {} } @response = { 'imagesSet' => [] } @state_reason = {} @tag = {} end def start_element(name, attrs = []) super case name when 'blockDeviceMapping' @in_block_device_mapping = true when 'productCodes' @in_product_codes = true when 'stateReason' @in_state_reason = true when 'tagSet' @in_tag_set = true end end def end_element(name) if @in_block_device_mapping case name when 'blockDeviceMapping' @in_block_device_mapping = false when 'deviceName', 'virtualName', 'snapshotId', 'deleteOnTermination' @block_device_mapping[name] = value when 'volumeSize' @block_device_mapping[name] = value.to_i when 'item' @image['blockDeviceMapping'] << @block_device_mapping @block_device_mapping = {} end elsif @in_product_codes case name when 'productCode' @image['productCodes'] << value when 'productCodes' @in_product_codes = false end elsif @in_tag_set case name when 'item' @image['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'key', 'value' @tag[name] = value when 'tagSet' @in_tag_set = false end elsif @in_state_reason case name when 'code', 'message' @state_reason[name] = value when 'stateReason' @image['stateReason'] = @state_reason @state_reason = {} @in_state_reason = false end else case name when 'architecture', 'description', 'hypervisor', 'imageId', 'imageLocation', 'imageOwnerAlias', 'imageOwnerId', 'imageState', 'imageType', 'kernelId', 'name', 'platform', 'ramdiskId', 'rootDeviceType','rootDeviceName','virtualizationType' @image[name] = value when 'isPublic' if value == 'true' @image[name] = true else @image[name] = false end when 'item' @response['imagesSet'] << @image @image = { 'blockDeviceMapping' => [], 'productCodes' => [], 'stateReason' => {}, 'tagSet' => {} } when 'requestId' @response[name] = value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/spot_instance_requests.rb0000644000004100000410000000543312261242551025011 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class SpotInstanceRequests < Fog::Parsers::Base def reset @block_device_mapping = {} @context = [] @contexts = ['blockDeviceMapping', 'groupSet', 'iamInstanceProfile'] @spot_instance_request = { 'launchSpecification' => { 'iamInstanceProfile' => {}, 'blockDeviceMapping' => [], 'groupSet' => [] } } @response = { 'spotInstanceRequestSet' => [] } end def start_element(name, attrs = []) super if @contexts.include?(name) @context.push(name) end end def end_element(name) case name when 'attachTime' @block_device_mapping[name] = Time.parse(value) when *@contexts @context.pop when 'code', 'message' @spot_instance_request['fault'] ||= {} @spot_instance_request['fault'][name] = value when 'createTime' @spot_instance_request[name] = Time.parse(value) when 'deleteOnTermination' @block_device_mapping[name] = (value == 'true') when 'deviceName', 'status', 'volumeId' @block_device_mapping[name] = value when 'groupId' @spot_instance_request['launchSpecification']['groupSet'] << value when 'arn', 'name' @spot_instance_request['launchSpecification']['iamInstanceProfile'][name] = value when 'instanceId', 'launchedAvailabilityZone', 'productDescription', 'spotInstanceRequestId', 'state', 'type' @spot_instance_request[name] = value when 'item' case @context.last when 'blockDeviceMapping' @spot_instance_request['launchSpecification']['blockDeviceMapping'] << @block_device_mapping @block_device_mapping = {} when nil @response['spotInstanceRequestSet'] << @spot_instance_request @spot_instance_request = { 'launchSpecification' => { 'iamInstanceProfile' => {}, 'blockDeviceMapping' => [], 'groupSet' => [] } } end when 'imageId', 'instanceType', 'keyname', 'subnetId' @spot_instance_request['launchSpecification'][name] = value when 'ebsOptimized' @spot_instance_request['launchSpecification'][name] = value == 'true' when 'enabled' @spot_instance_request['launchSpecification']['monitoring'] = (value == 'true') when 'requestId' @response[name] = value when 'spotPrice' @spot_instance_request[name] = value.to_f end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/create_route_table.rb0000755000004100000410000000422612261242551024037 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class CreateRouteTable < Fog::Parsers::Base def reset @in_route_set = false @in_association_set = false @route = {} @association = {} @route_table = { 'routeSet' => [], 'tagSet' => {}, 'associationSet' => [] } @response = { 'routeTable' => [] } @tag = {} end def start_element(name, attrs = []) super case name when 'tagSet' @in_tag_set = true when 'routeSet' @in_route_set = true when 'associationSet' @in_association_set = true end end def end_element(name) if @in_tag_set case name when 'item' @route_table['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'tagSet' @in_tag_set = false end elsif @in_route_set case name when 'routeSet' @in_route_set = false when 'destinationCidrBlock', 'gatewayId', 'state' @route[name] = value when 'item' @route_table['routeSet'] << @route @route = {} end elsif @in_association_set case name when 'routeTableAssociationId', 'routeTableId', 'main' @association[name] = value when 'associationSet' @route_table['associationSet'] << @association @in_association_set = false end else case name when 'routeTableId', 'vpcId' @route_table[name] = value when 'routeTable' @response['routeTable'] << @route_table @route_table = { 'routeSet' => {}, 'tagSet' => {}, 'associationSet' => {} } when 'requestId' @response[name] = value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_account_attributes.rb0000644000004100000410000000217612261242551025750 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeAccountAttributes < Fog::Parsers::Base def reset @attribute = { 'values' => []} @account_attributes = [] @response = { 'accountAttributeSet' => [] } end def start_element(name, attrs = []) super case name when 'attributeValueSet' @in_attribute_value_set = true end end def end_element(name) case name when 'attributeName' @attribute[name] = value when 'attributeValue' @attribute['values'] << value when['requestId'] @response[name] = value when 'item' @response['accountAttributeSet'] << @attribute @attribute = { 'values' => []} unless @in_attribute_value_set when 'attributeValueSet' @in_attribute_value_set = false else end @response['accountAttributeSet'].uniq! end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/assign_private_ip_addresses.rb0000644000004100000410000000075512261242551025752 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class AssignPrivateIpAddresses < Fog::Parsers::Base def end_element(name) case name when 'requestId' @response[name] = value when 'return' if value == 'true' @response[name] = true else @response[name] = false end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_network_interface_attribute.rb0000644000004100000410000000462512261242551027643 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeNetworkInterfaceAttribute < NetworkInterfaceParser def reset @response = { } @in_description = false @in_group_set = false @in_source_dest_check = false @in_attachment = false end def start_element(name, attrs = []) super case name when 'description' @in_description = true when 'groupSet' @in_group_set = true @group = {} unless @response.key?('groupSet') @response['groupSet'] = {} end when 'sourceDestCheck' @in_source_dest_check = true when 'attachment' @in_attachment = true @attachment = {} end end def end_element(name) if @in_description case name when 'value' @response['description'] = value when 'description' @in_description = false end elsif @in_group_set case name when 'item' @response['groupSet'][@group['groupId']] = @group['groupName'] @group = {} when 'groupId', 'groupName' @group[name] = value when 'groupSet' @in_group_set = false end elsif @in_source_dest_check case name when 'value' @response['sourceDestCheck'] = (value == 'true') when 'sourceDestCheck' @in_source_dest_check = false end elsif @in_attachment case name when 'attachmentId', 'instanceId', 'instanceOwnerId', 'deviceIndex', 'status', 'attachTime', 'deleteOnTermination' @attachment[name] = value when 'attachment' @response['attachment'] = @attachment @in_attachment = false end else case name when 'requestId', 'networkInterfaceId' @response[name] = value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/run_instances.rb0000644000004100000410000000636312261242551023063 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class RunInstances < Fog::Parsers::Base def reset @block_device_mapping = {} @context = [] @contexts = ['blockDeviceMapping', 'groupSet', 'placement', 'productCodes'] @instance = { 'blockDeviceMapping' => [], 'instanceState' => {}, 'monitoring' => {}, 'placement' => {}, 'productCodes' => [] } @response = { 'groupSet' => [], 'instancesSet' => [] } end def start_element(name, attrs = []) super if @contexts.include?(name) @context.push(name) end end def end_element(name) case name when 'amiLaunchIndex' @instance[name] = value.to_i when 'architecture', 'clientToken', 'dnsName', 'hypervisor', 'imageId', 'instanceId', 'instanceType', 'ipAddress', 'kernelId', 'keyName', 'instanceLifecycle', 'privateDnsName', 'privateIpAddress', 'ramdiskId', 'reason', 'requesterId', 'rootDeviceType', 'sourceDestCheck', 'spotInstanceRequestId', 'virtualizationType' @instance[name] = value when 'availabilityZone', 'tenancy' @instance['placement'][name] = value when 'attachTime' @block_device_mapping[name] = Time.parse(value) when *@contexts @context.pop when 'code' @instance['instanceState'][name] = value.to_i when 'deleteOnTermination' @block_device_mapping[name] = (value == 'true') when 'deviceName', 'status', 'volumeId' @block_device_mapping[name] = value when 'groupId' @response['groupSet'] << value when 'groupName' case @context.last when 'groupSet' @response['groupSet'] << value when 'placement' @instance['placement'][name] = value end when 'item' case @context.last when 'blockDeviceMapping' @instance['blockDeviceMapping'] << @block_device_mapping @block_device_mapping = {} when nil @response['instancesSet'] << @instance @instance = { 'blockDeviceMapping' => [], 'instanceState' => {}, 'monitoring' => {}, 'placement' => {}, 'productCodes' => [] } end when 'launchTime' @instance[name] = Time.parse(value) when 'name' @instance['instanceState'][name] = value when 'ownerId', 'requestId', 'reservationId' @response[name] = value when 'product_code' @instance['productCodes'] << value when 'state' @instance['monitoring'][name] = (value == 'true') when 'subnetId' @response[name] = value when 'ebsOptimized' @instance['ebsOptimized'] = (value == 'true') when 'associatePublicIP' @instance['associatePublicIP'] = (value == 'true') end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/start_stop_instances.rb0000644000004100000410000000173112261242551024453 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class StartStopInstances < Fog::Parsers::Base def reset @instance = { 'currentState' => {}, 'previousState' => {} } @response = { 'instancesSet' => [] } @state = nil end def start_element(name, attrs = []) super case name when 'currentState', 'previousState' @state = name end end def end_element(name) case name when 'code' @instance[@state][name] = value.to_s when 'instanceId' @instance[name] = value when 'item' @response['instancesSet'] << @instance @instance = { 'currentState' => {}, 'previousState' => {} } when 'name' @instance[@state][name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_instance_status.rb0000644000004100000410000000425012261242551025250 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeInstanceStatus < Fog::Parsers::Base def new_instance! @instance = { 'instanceState' => {}, 'systemStatus' => { 'details' => [] }, 'instanceStatus' => { 'details' => [] }, 'eventsSet' => [] } end def new_item! @item = {} end def reset @response = { 'instanceStatusSet' => [] } @inside = nil end def start_element(name, attrs=[]) super case name when 'item' if @inside new_item! else new_instance! end when 'systemStatus' @inside = :systemStatus when 'instanceState' @inside = :instanceState when 'instanceStatus' @inside = :instanceStatus when 'eventsSet' @inside = :eventsSet end end def end_element(name) case name #Simple closers when 'instanceId', 'availabilityZone' @instance[name] = value when 'nextToken', 'requestId' @response[name] = value when 'systemStatus', 'instanceState', 'instanceStatus', 'eventsSet' @inside = nil when 'item' case @inside when :eventsSet @instance['eventsSet'] << @item when :systemStatus, :instanceStatus @instance[@inside.to_s]['details'] << @item when nil @response['instanceStatusSet'] << @instance end @item = nil when 'code' case @inside when :eventsSet @item[name] = value when :instanceState @instance[@inside.to_s][name] = value.to_i end when 'description', 'notBefore', 'notAfter', 'name', 'status' @item.nil? ? (@instance[@inside.to_s][name] = value) : (@item[name] = value) end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/deregister_image.rb0000644000004100000410000000051312261242551023476 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DeregisterImage < Fog::Parsers::Base def end_element(name) case name when 'return', 'requestId', 'imageId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/register_image.rb0000644000004100000410000000047712261242551023176 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class RegisterImage < Fog::Parsers::Base def end_element(name) case name when 'requestId', 'imageId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/associate_address.rb0000644000004100000410000000076612261242551023671 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class AssociateAddress < Fog::Parsers::Base def end_element(name) case name when 'requestId', 'associationId' @response[name] = value when 'return' if value == 'true' @response[name] = true else @response[name] = false end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_volume_status.rb0000644000004100000410000000527712261242551024765 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeVolumeStatus < Fog::Parsers::Base def reset @action_set = {} @detail = {} @event_set = {} @volume_status = { 'details' => [] } @volume = { 'actionsSet' => [], 'eventsSet' => [] } @response = { 'volumeStatusSet' => [] } end def start_element(name, attrs=[]) super case name when 'actionsSet' @in_actions_set = true when 'details' @in_details = true when 'eventsSet' @in_events_set = true when 'volumeStatus' @in_volume_status = true end end def end_element(name) if @in_actions_set case name when 'actionsSet' @in_actions_set = false when 'code', 'eventId', 'eventType', 'description' @action_set[name] = value.strip when 'item' @volume['actionsSet'] << @action_set @action_set = {} end elsif @in_details case name when 'details' @in_details = false when 'name', 'status' @detail[name] = value when 'item' @volume_status['details'] << @detail @detail = {} end elsif @in_events_set case name when 'eventsSet' @in_events_set = false when 'code', 'eventId', 'eventType', 'description' @event_set[name] = value.strip when 'notAfter', 'notBefore' @event_set[name] = Time.parse(value) when 'item' @volume['eventsSet'] << @event_set @event_set = {} end elsif @in_volume_status case name when 'volumeStatus' @volume['volumeStatus'] = @volume_status @volume_status = { 'details' => [] } @in_volume_status = false when 'status' @volume_status[name] = value end else case name when 'volumeId', 'availabilityZone' @volume[name] = value when 'nextToken', 'requestId' @response[name] = value when 'item' @response['volumeStatusSet'] << @volume @volume = { 'actionsSet' => [], 'eventsSet' => [] } end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/create_vpc.rb0000644000004100000410000000225712261242551022321 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class CreateVpc < Fog::Parsers::Base def reset @vpc = { 'tagSet' => {} } @response = { 'vpcSet' => [] } @tag = {} end def start_element(name, attrs = []) super case name when 'tagSet' @in_tag_set = true end end def end_element(name) if @in_tag_set case name when 'item' @vpc['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'key', 'value' @tag[name] = value when 'tagSet' @in_tag_set = false end else case name when 'vpcId', 'state', 'cidrBlock', 'dhcpOptionsId' @vpc[name] = value when 'vpc' @response['vpcSet'] << @vpc @vpc = { 'tagSet' => {} } when 'requestId' @response[name] = value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_key_pairs.rb0000644000004100000410000000110312261242551024021 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeKeyPairs < Fog::Parsers::Base def reset @key = {} @response = { 'keySet' => [] } end def end_element(name) case name when 'item' @response['keySet'] << @key @key = {} when 'keyFingerprint', 'keyName' @key[name] = value when 'requestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_dhcp_options.rb0000644000004100000410000000433412261242551024535 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeDhcpOptions < Fog::Parsers::Base def reset @dhcp_options = { 'dhcpConfigurationSet' => {}, 'tagSet' => {} } @response = { 'dhcpOptionsSet' => [] } @tag = {} @value_set = [] @dhcp_configuration = {} end def start_element(name, attrs = []) super case name when 'tagSet' @in_tag_set = true when 'dhcpConfigurationSet' @in_dhcp_configuration_set = true when 'valueSet' @in_value_set = true end end def end_element(name) if @in_tag_set case name when 'item' @dhcp_options['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'key', 'value' @tag[name] = value when 'tagSet' @in_tag_set = false end elsif @in_dhcp_configuration_set case name when 'item' unless @in_value_set @dhcp_options['dhcpConfigurationSet'][@dhcp_configuration['key']] = @value_set @value_set=[] @dhcp_configuration = {} end when 'key', 'value' if !@in_value_set @dhcp_configuration[name] = value else @value_set << value end when 'valueSet' @in_value_set = false when 'dhcpConfigurationSet' @in_dhcp_configuration_set = false end else case name when 'dhcpOptionsId' @dhcp_options[name] = value when 'item' @response['dhcpOptionsSet'] << @dhcp_options @dhcp_options = { 'tagSet' => {} } @dhcp_options = { 'dhcpConfigurationSet' => {} } when 'requestId' @response[name] = value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/import_key_pair.rb0000644000004100000410000000052112261242551023373 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class ImportKeyPair < Fog::Parsers::Base def end_element(name) case name when 'keyFingerprint', 'keyName', 'requestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_vpcs.rb0000644000004100000410000000230412261242551023012 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeVpcs < Fog::Parsers::Base def reset @vpc = { 'tagSet' => {} } @response = { 'vpcSet' => [] } @tag = {} end def start_element(name, attrs = []) super case name when 'tagSet' @in_tag_set = true end end def end_element(name) if @in_tag_set case name when 'item' @vpc['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'key', 'value' @tag[name] = value when 'tagSet' @in_tag_set = false end else case name when 'vpcId', 'state', 'cidrBlock', 'dhcpOptionsId', 'instanceTenancy' @vpc[name] = value when 'item' @response['vpcSet'] << @vpc @vpc = { 'tagSet' => {} } when 'requestId' @response[name] = value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_tags.rb0000644000004100000410000000112012261242551022770 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeTags < Fog::Parsers::Base def reset @tag = {} @response = { 'tagSet' => [] } end def end_element(name) case name when 'resourceId', 'resourceType', 'key', 'value' @tag[name] = value when 'item' @response['tagSet'] << @tag @tag = {} when 'requestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/attach_network_interface.rb0000644000004100000410000000051312261242551025234 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class AttachNetworkInterface < Fog::Parsers::Base def end_element(name) case name when 'requestId', 'attachmentId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/detach_volume.rb0000644000004100000410000000066112261242551023022 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DetachVolume < Fog::Parsers::Base def end_element(name) case name when 'attachTime' @response[name] = Time.parse(value) when 'device', 'instanceId', 'requestId', 'status', 'volumeId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_addresses.rb0000644000004100000410000000127112261242551024016 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeAddresses < Fog::Parsers::Base def reset @address = {} @response = { 'addressesSet' => [] } end def end_element(name) case name when 'instanceId', 'publicIp', 'domain', 'allocationId', 'associationId', 'networkInterfaceId', 'networkInterfaceOwnerId' @address[name] = value when 'item' @response['addressesSet'] << @address @address = {} when 'requestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_snapshots.rb0000644000004100000410000000257112261242551024067 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeSnapshots < Fog::Parsers::Base def reset @response = { 'snapshotSet' => [] } @snapshot = { 'tagSet' => {} } @tag = {} end def start_element(name, attrs = []) super if name == 'tagSet' @in_tag_set = true end end def end_element(name) if @in_tag_set case name when 'item' @snapshot['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'key', 'value' @tag[name] = value when 'tagSet' @in_tag_set = false end else case name when 'item' @response['snapshotSet'] << @snapshot @snapshot = { 'tagSet' => {} } when 'description', 'ownerId', 'progress', 'snapshotId', 'status', 'volumeId' @snapshot[name] ||= value when 'requestId' @response[name] = value when 'startTime' @snapshot[name] = Time.parse(value) when 'volumeSize' @snapshot[name] = value.to_i end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/basic.rb0000644000004100000410000000073212261242551021263 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class Basic < Fog::Parsers::Base def end_element(name) case name when 'requestId' @response[name] = value when 'return' if value == 'true' @response[name] = true else @response[name] = false end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/attach_volume.rb0000644000004100000410000000066112261242551023036 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class AttachVolume < Fog::Parsers::Base def end_element(name) case name when 'attachTime' @response[name] = Time.parse(value) when 'device', 'instanceId', 'requestId', 'status', 'volumeId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/create_internet_gateway.rb0000644000004100000410000000350312261242551025075 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class CreateInternetGateway < Fog::Parsers::Base def reset @internet_gateway = { 'attachmentSet' => {}, 'tagSet' => {} } @response = { 'internetGatewaySet' => [] } @tag = {} @attachment = {} end def start_element(name, attrs = []) super case name when 'tagSet' @in_tag_set = true when 'attachmentSet' @in_attachment_set = true end end def end_element(name) if @in_tag_set case name when 'item' @vpc['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'key', 'value' @tag[name] = value when 'tagSet' @in_tag_set = false end elsif @in_attachment_set case name when 'item' @internet_gateway['attachmentSet'][@attachment['key']] = @attachment['value'] @attachment = {} when 'key', 'value' @attachment[name] = value when 'attachmentSet' @in_attachment_set = false end else case name when 'internetGatewayId' @internet_gateway[name] = value when 'internetGateway' @response['internetGatewaySet'] << @internet_gateway @internet_gateway = { 'tagSet' => {} } @internet_gateway = { 'attachmentSet' => {} } when 'requestId' @response[name] = value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/terminate_instances.rb0000644000004100000410000000302412261242551024236 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class TerminateInstances < Fog::Parsers::Base def reset @instance = { 'previousState' => {}, 'currentState' => {} } @response = { 'instancesSet' => [] } end def start_element(name, attrs = []) super if name == 'previousState' @in_previous_state = true elsif name == 'currentState' @in_current_state = true end end def end_element(name) case name when 'instanceId' @instance[name] = value when 'item' @response['instancesSet'] << @instance @instance = { 'previousState' => {}, 'currentState' => {} } when 'code' if @in_previous_state @instance['previousState'][name] = value.to_i elsif @in_current_state @instance['currentState'][name] = value.to_i end when 'name' if @in_previous_state @instance['previousState'][name] = value elsif @in_current_state @instance['currentState'][name] = value end when 'previousState' @in_previous_state = false when 'requestId' @response[name] = value when 'currentState' @in_current_state = false end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/associate_route_table.rb0000755000004100000410000000051312261242551024542 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class AssociateRouteTable < Fog::Parsers::Base def end_element(name) case name when 'requestId', 'associationId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/describe_instances.rb0000644000004100000410000001241212261242551024027 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class DescribeInstances < Fog::Parsers::Base def reset @block_device_mapping = {} @network_interface = {} @context = [] @contexts = ['blockDevices', 'blockDeviceMapping', 'groupSet', 'iamInstanceProfile', 'instancesSet', 'instanceState', 'networkInterfaceSet', 'placement', 'productCodes', 'stateReason', 'tagSet'] @instance = { 'blockDeviceMapping' => [], 'networkInterfaces' => [], 'iamInstanceProfile' => {}, 'instanceState' => {}, 'monitoring' => {}, 'placement' => {}, 'productCodes' => [], 'stateReason' => {}, 'tagSet' => {} } @reservation = { 'groupIds' => [], 'groupSet' => [], 'instancesSet' => [] } @response = { 'reservationSet' => [] } @tag = {} end def start_element(name, attrs = []) super if @contexts.include?(name) @context.push(name) end end def end_element(name) case name when 'amiLaunchIndex' @instance[name] = value.to_i when 'arn' @instance[@context.last][name] = value when 'availabilityZone', 'tenancy' @instance['placement'][name] = value when 'architecture', 'clientToken', 'dnsName', 'hypervisor', 'imageId', 'instanceId', 'instanceType', 'ipAddress', 'kernelId', 'keyName', 'instanceLifecycle', 'platform', 'privateDnsName', 'privateIpAddress', 'ramdiskId', 'reason', 'requesterId', 'rootDeviceType', 'spotInstanceRequestId', 'virtualizationType' @instance[name] = value when 'attachTime' @block_device_mapping[name] = Time.parse(value) when *@contexts @context.pop when 'code' @instance[@context.last][name] = @context.last == 'stateReason' ? value : value.to_i when 'message' @instance[@context.last][name] = value when 'deleteOnTermination' @block_device_mapping[name] = (value == 'true') when 'deviceName', 'status', 'volumeId' @block_device_mapping[name] = value when 'subnetId', 'vpcId', 'ownerId', 'networkInterfaceId', 'attachmentId' @network_interface[name] = value @instance[name] = value when 'groupId', 'groupName' case @context.last when 'groupSet' (name == 'groupName') ? current_key = 'groupSet' : current_key = 'groupIds' case @context[-2] when 'instancesSet' @reservation[current_key] << value when 'networkInterfaceSet' @network_interface[current_key] ||= [] @network_interface[current_key] << value end when 'placement' @instance['placement'][name] = value end when 'id' @instance[@context.last][name] = value when 'item' case @context.last when 'blockDeviceMapping' @instance['blockDeviceMapping'] << @block_device_mapping @block_device_mapping = {} when 'networkInterfaceSet' @instance['networkInterfaces'] << @network_interface @network_interface = {} when 'instancesSet' @reservation['instancesSet'] << @instance @instance = { 'blockDeviceMapping' => [], 'networkInterfaces' => [], 'iamInstanceProfile' => {}, 'instanceState' => {}, 'monitoring' => {}, 'placement' => {}, 'productCodes' => [], 'stateReason' => {}, 'tagSet' => {} } when 'tagSet' @instance['tagSet'][@tag['key']] = @tag['value'] @tag = {} when 'blockDevices' # Ignore this one (Eucalyptus specific) when nil @response['reservationSet'] << @reservation @reservation = { 'groupIds' => [], 'groupSet' => [], 'instancesSet' => [] } end when 'key', 'value' @tag[name] = value when 'launchTime' @instance[name] = Time.parse(value) when 'name' @instance[@context.last][name] = value when 'ownerId', 'reservationId' @reservation[name] = value when 'requestId' @response[name] = value when 'productCode' @instance['productCodes'] << value when 'state' @instance['monitoring'][name] = (value == 'enabled') when 'ebsOptimized' @instance['ebsOptimized'] = (value == 'true') when 'sourceDestCheck' if value == 'true' @instance[name] = true else @instance[name] = false end # Eucalyptus passes status in schema non conforming way when 'stateCode' @instance['instanceState']['code'] = value when 'stateName' @instance['instanceState']['name'] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/compute/copy_image.rb0000644000004100000410000000056112261242551022316 0ustar www-datawww-datamodule Fog module Parsers module Compute module AWS class CopyImage < Fog::Parsers::Base def end_element(name) case name when 'imageId' @response[name] = value when 'requestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/0000755000004100000410000000000012261242551020444 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/elasticache/describe_security_groups.rb0000644000004100000410000000111512261242551026075 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/security_group_parser' class DescribeSecurityGroups < SecurityGroupParser def reset super @response['CacheSecurityGroups'] = [] end def end_element(name) case name when 'CacheSecurityGroup' @response["#{name}s"] << @security_group reset_security_group else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/describe_reserved_cache_nodes.rb0000644000004100000410000000177512261242551026775 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache class DescribeReservedCacheNodes < Fog::Parsers::Base def reset @reserved_node = {} @response = { 'ReservedCacheNodes' => [] } end def end_element(name) case name when 'ReservedCacheNodeId', 'ReservedCacheNodesOfferingId', 'CacheNodeType', 'ProductDescription', 'State' @reserved_node[name] = @value when 'Duration', 'CacheNodeCount' @reserved_node[name] = @value.to_i when 'FixedPrice', 'UsagePrice' @reserved_node[name] = @value.to_f when 'ReservedCacheNode' @response['ReservedCacheNodes'] << @reserved_node @reserved_node = {} when 'Marker' @response[name] = @value when 'StartTime' @reserved_node[name] = Time.parse(@value) end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/describe_parameter_groups.rb0000644000004100000410000000112412261242551026206 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/parameter_group_parser' class DescribeParameterGroups < ParameterGroupParser def reset super @response['CacheParameterGroups'] = [] end def end_element(name) case name when 'CacheParameterGroup' @response["#{name}s"] << @parameter_group reset_parameter_group else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/describe_engine_default_parameters.rb0000644000004100000410000000075012261242551030027 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/engine_defaults_parser' class DescribeEngineDefaultParameters < EngineDefaultsParser def end_element(name) case name when 'EngineDefaults' @response[name] = @engine_defaults reset_engine_defaults else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/engine_defaults_parser.rb0000644000004100000410000000332712261242551025506 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/base' class EngineDefaultsParser < Base def reset super reset_engine_defaults end def reset_engine_defaults @engine_defaults = { 'CacheNodeTypeSpecificParameters' => [], 'Parameters' => [], } end def start_element(name, attrs = []) case name when 'CacheNodeTypeSpecificParameter', 'Parameter' @parameter = {} when 'CacheNodeTypeSpecificValues' @parameter[name] = [] when 'CacheNodeTypeSpecificValue' @node_specific_value = {} else super end end def end_element(name) case name when 'CacheParameterGroupFamily' @engine_defaults[name] = value when 'CacheNodeTypeSpecificParameter', 'Parameter' if not @parameter.empty? @engine_defaults["#{name}s"] << @parameter end when 'AllowedValues', 'DataType', 'Description', 'IsModifiable', 'MinimumEngineVersion', 'ParameterName', 'ParameterValue', 'Source' @parameter[name] = value when 'CacheNodeType', 'Value' @node_specific_value[name] = value when 'CacheNodeTypeSpecificValue' if not @node_specific_value.empty? @parameter["#{name}s"] << @node_specific_value end else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/single_security_group.rb0000644000004100000410000000135512261242551025421 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/security_group_parser' class SingleSecurityGroup < SecurityGroupParser def reset super @response = { 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) case name when 'CacheSecurityGroup' @response[name] = @security_group reset_security_group when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/single_parameter_group.rb0000644000004100000410000000074212261242551025531 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/parameter_group_parser' class SingleParameterGroup < ParameterGroupParser def end_element(name) case name when 'CacheParameterGroup' @response[name] = @parameter_group reset_parameter_group else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/describe_cache_parameters.rb0000644000004100000410000000075712261242551026130 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/engine_defaults_parser' class DescribeCacheParameters < EngineDefaultsParser def end_element(name) case name when 'DescribeCacheParametersResult' @response[name] = @engine_defaults reset_engine_defaults else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/authorize_cache_security_group_ingress.rb0000644000004100000410000000104412261242551031022 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/security_group_parser' class AuthorizeCacheSecurityGroupIngress < Fog::Parsers::AWS::Elasticache::SecurityGroupParser def end_element(name) case name when 'CacheSecurityGroup' then @response['CacheSecurityGroup'] = @security_group reset_security_group else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/modify_parameter_group.rb0000644000004100000410000000114112261242551025531 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/parameter_group_parser' class ModifyParameterGroup < ParameterGroupParser def reset super @response['ModifyCacheParameterGroupResult'] = [] end def end_element(name) case name when 'ModifyCacheParameterGroupResult' @response[name] = @parameter_group reset_parameter_group else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/cache_cluster_parser.rb0000644000004100000410000000522112261242551025151 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/base' class CacheClusterParser < Base def reset super reset_cache_cluster end def reset_cache_cluster @cache_cluster = { 'CacheSecurityGroups' => [], 'CacheNodes' => [], 'CacheParameterGroup' => {} } end def start_element(name, attrs = []) super case name when 'CacheSecurityGroup'; then @security_group = {} when 'CacheNode'; then @cache_node = {} when 'PendingModifiedValues'; then @pending_values = {} end end def end_element(name) case name when 'AutoMinorVersionUpgrade', 'CacheClusterId', 'CacheClusterStatus', 'CacheNodeType', 'Engine', 'PreferredAvailabilityZone', 'PreferredMaintenanceWindow' @cache_cluster[name] = value when 'EngineVersion', 'CacheNodeIdsToRemoves' if @pending_values @pending_values[name] = value ? value.strip : name else @cache_cluster[name] = value end when 'NumCacheNodes' if @pending_values @pending_values[name] = value.to_i else @cache_cluster[name] = value.to_i end when 'CacheClusterCreateTime' @cache_cluster[name] = DateTime.parse(value) when 'CacheSecurityGroup' @cache_cluster["#{name}s"] << @security_group unless @security_group.empty? when 'CacheSecurityGroupName', 'Status' @security_group[name] = value when 'CacheNode' @cache_cluster["#{name}s"] << @cache_node unless @cache_node.empty? @cache_node = nil when'PendingModifiedValues' @cache_cluster[name] = @pending_values @pending_values = nil when 'CacheNodeCreateTime', 'CacheNodeStatus', 'Address', 'ParameterGroupStatus', 'Port', 'CacheNodeId' if @cache_node @cache_node[name] = value ? value.strip : name elsif @pending_values @pending_values[name] = value ? value.strip : name end when 'CacheNodeIdsToReboots', 'CacheParameterGroupName', 'ParameterApplyStatus' @cache_cluster['CacheParameterGroup'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/reset_parameter_group.rb0000644000004100000410000000113612261242551025370 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/parameter_group_parser' class ResetParameterGroup < ParameterGroupParser def reset super @response['ResetCacheParameterGroupResult'] = [] end def end_element(name) case name when 'ResetCacheParameterGroupResult' @response[name] = @parameter_group reset_parameter_group else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/single_cache_cluster.rb0000644000004100000410000000072112261242551025136 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/cache_cluster_parser' class SingleCacheCluster < CacheClusterParser def end_element(name) case name when 'CacheCluster' @response[name] = @cache_cluster reset_cache_cluster else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/describe_cache_clusters.rb0000644000004100000410000000107412261242551025622 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/cache_cluster_parser' class DescribeCacheClusters < CacheClusterParser def reset super @response['CacheClusters'] = [] end def end_element(name) case name when 'CacheCluster' @response["#{name}s"] << @cache_cluster reset_cache_cluster else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/base.rb0000644000004100000410000000112712261242551021704 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache # Base parser for ResponseMetadata, RequestId class Base < Fog::Parsers::Base def reset super @response = { 'ResponseMetadata' => {} } end def start_element(name, attrs = []) super end def end_element(name) case name when 'RequestId' @response['ResponseMetadata'][name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/security_group_parser.rb0000644000004100000410000000176712261242551025443 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/base' class SecurityGroupParser < Fog::Parsers::Base def reset super reset_security_group end def reset_security_group @security_group = {'EC2SecurityGroups' => []} end def start_element(name, attrs = []) super case name when 'EC2SecurityGroup'; then @ec2_group = {} end end def end_element(name) case name when 'Description', 'CacheSecurityGroupName', 'OwnerId' @security_group[name] = value when 'EC2SecurityGroup' @security_group["#{name}s"] << @ec2_group unless @ec2_group.empty? when 'EC2SecurityGroupName', 'EC2SecurityGroupOwnerId', 'Status' @ec2_group[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/parameter_group_parser.rb0000644000004100000410000000116412261242551025543 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/base' class ParameterGroupParser < Base def reset super reset_parameter_group end def reset_parameter_group @parameter_group = {} end def end_element(name) case name when 'Description', 'CacheParameterGroupName', 'CacheParameterGroupFamily' @parameter_group[name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/elasticache/event_list.rb0000644000004100000410000000166712261242551023157 0ustar www-datawww-datamodule Fog module Parsers module AWS module Elasticache require 'fog/aws/parsers/elasticache/base' class EventListParser < Base def reset super @response['Events'] = [] end def start_element(name, attrs = []) super case name when 'Event'; then @event = {} end end def end_element(name) case name when 'Date' @event[name] = DateTime.parse(value.strip) when 'Message', 'SourceIdentifier', 'SourceType' @event[name] = value ? value.strip : name when 'Event' @response['Events'] << @event unless @event.empty? when 'IsTruncated', 'Marker', 'NextMarker' @response[name] = value else super end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_formation/0000755000004100000410000000000012261242551021363 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/cloud_formation/describe_stacks.rb0000644000004100000410000000452212261242551025043 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudFormation class DescribeStacks < Fog::Parsers::Base def reset @stack = { 'Outputs' => [], 'Parameters' => [], 'Capabilities' => [] } @output = {} @parameter = {} @response = { 'Stacks' => [] } end def start_element(name, attrs = []) super case name when 'Outputs' @in_outputs = true when 'Parameters' @in_parameters = true when 'Capabilities' @in_capabilities = true end end def end_element(name) if @in_outputs case name when 'OutputKey', 'OutputValue', 'Description' @output[name] = value when 'member' @stack['Outputs'] << @output @output = {} when 'Outputs' @in_outputs = false end elsif @in_parameters case name when 'ParameterKey', 'ParameterValue' @parameter[name] = value when 'member' @stack['Parameters'] << @parameter @parameter = {} when 'Parameters' @in_parameters = false end elsif @in_capabilities case name when 'member' @stack['Capabilities'] << value when 'Capabilities' @in_capabilities = false end else case name when 'member' @response['Stacks'] << @stack @stack = { 'Outputs' => [], 'Parameters' => [], 'Capabilities' => []} when 'RequestId' @response[name] = value when 'CreationTime' @stack[name] = Time.parse(value) when 'DisableRollback' case value when 'false' @stack[name] = false when 'true' @stack[name] = true end when 'StackName', 'StackId', 'StackStatus' @stack[name] = value end end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_formation/validate_template.rb0000644000004100000410000000235012261242551025374 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudFormation class ValidateTemplate < Fog::Parsers::Base def reset @parameter = {} @response = { 'Parameters' => [] } end def start_element(name, attrs = []) super case name when 'Parameters' @in_parameters = true end end def end_element(name) case name when 'DefaultValue', 'ParameterKey' @parameter[name] = value when 'Description' if @in_parameters @parameter[name] = value else @response[name] = value end when 'RequestId' @response[name] = value when 'member' @response['Parameters'] << @parameter @parameter = {} when 'NoEcho' case value when 'false' @parameter[name] = false when 'true' @parameter[name] = true end when 'Parameters' @in_parameters = false end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_formation/list_stack_resources.rb0000644000004100000410000000151512261242551026144 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudFormation class ListStackResources < Fog::Parsers::Base def reset @resource = {} @response = { 'StackResourceSummaries' => [] } end def end_element(name) case name when 'ResourceStatus', 'LogicalResourceId', 'PhysicalResourceId', 'ResourceType' @resource[name] = value when 'member' @response['StackResourceSummaries'] << @resource @resource = {} when 'LastUpdatedTimestamp' @resource[name] = Time.parse(value) when 'RequestId' @response[name] = value when 'NextToken' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_formation/list_stacks.rb0000644000004100000410000000153612261242551024240 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudFormation class ListStacks < Fog::Parsers::Base def reset @stack = {} @response = { 'StackSummaries' => [] } end def end_element(name) case name when 'StackId', 'StackStatus', 'StackName', 'TemplateDescription' @stack[name] = value when 'member' @response['StackSummaries'] << @stack @stack = {} when 'RequestId' @response[name] = value when 'CreationTime' @stack[name] = Time.parse(value) when 'DeletionTime' @stack[name] = Time.parse(value) when 'NextToken' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_formation/update_stack.rb0000644000004100000410000000050312261242551024355 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudFormation class UpdateStack < Fog::Parsers::Base def end_element(name) case name when 'RequestId', 'StackId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_formation/describe_stack_events.rb0000644000004100000410000000145512261242551026246 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudFormation class DescribeStackEvents < Fog::Parsers::Base def reset @event = {} @response = { 'StackEvents' => [] } end def end_element(name) case name when 'EventId', 'LogicalResourceId', 'PhysicalResourceId', 'ResourceProperties', 'ResourceStatus', 'ResourceStatusReason', 'ResourceType', 'StackId', 'StackName' @event[name] = value when 'member' @response['StackEvents'] << @event @event = {} when 'RequestId' @response[name] = value when 'Timestamp' @event[name] = Time.parse(value) end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_formation/get_template.rb0000644000004100000410000000051012261242551024356 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudFormation class GetTemplate < Fog::Parsers::Base def end_element(name) case name when 'RequestId', 'TemplateBody' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_formation/create_stack.rb0000644000004100000410000000050312261242551024336 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudFormation class CreateStack < Fog::Parsers::Base def end_element(name) case name when 'RequestId', 'StackId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_formation/basic.rb0000644000004100000410000000023212261242551022766 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudFormation class Basic < Fog::Parsers::Base end end end end end fog-1.19.0/lib/fog/aws/parsers/cloud_formation/describe_stack_resources.rb0000644000004100000410000000141412261242551026747 0ustar www-datawww-datamodule Fog module Parsers module AWS module CloudFormation class DescribeStackResources < Fog::Parsers::Base def reset @resource = {} @response = { 'StackResources' => [] } end def end_element(name) case name when 'StackId', 'StackName', 'LogicalResourceId', 'PhysicalResourceId', 'ResourceType', 'ResourceStatus' @resource[name] = value when 'member' @response['StackResources'] << @resource @resource = {} when 'RequestId' @response[name] = value when 'Timestamp' @resource[name] = Time.parse(value) end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sns/0000755000004100000410000000000012261242551017002 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/sns/list_topics.rb0000644000004100000410000000072612261242551021670 0ustar www-datawww-datamodule Fog module Parsers module AWS module SNS class ListTopics < Fog::Parsers::Base def reset @response = { 'Topics' => [] } end def end_element(name) case name when 'TopicArn' @response['Topics'] << @value.strip when 'NextToken', 'RequestId' response[name] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sns/delete_topic.rb0000644000004100000410000000055512261242551021774 0ustar www-datawww-datamodule Fog module Parsers module AWS module SNS class DeleteTopic < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'RequestId' @response[name] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sns/subscribe.rb0000644000004100000410000000060412261242551021310 0ustar www-datawww-datamodule Fog module Parsers module AWS module SNS class Subscribe < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'SubscriptionArn', 'RequestId' @response[name] = @value.strip end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sns/get_topic_attributes.rb0000644000004100000410000000136412261242551023556 0ustar www-datawww-datamodule Fog module Parsers module AWS module SNS class GetTopicAttributes < Fog::Parsers::Base def reset @response = { 'Attributes' => {} } end def end_element(name) case name when 'key' @key = @value.rstrip when 'value' case @key when 'SubscriptionsConfirmed', 'SubscriptionsDeleted', 'SubscriptionsPending' @response['Attributes'][@key] = @value.rstrip.to_i else @response['Attributes'][@key] = @value.rstrip end when 'RequestId' @response[name] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sns/remove_permission.rb0000644000004100000410000000056212261242551023077 0ustar www-datawww-datamodule Fog module Parsers module AWS module SNS class RemovePermission < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'RequestId' @response[name] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sns/confirm_subscription.rb0000644000004100000410000000061612261242551023573 0ustar www-datawww-datamodule Fog module Parsers module AWS module SNS class ConfirmSubscription < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'SubscriptionArn', 'RequestId' @response[name] = @value.strip end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sns/set_topic_attributes.rb0000644000004100000410000000056412261242551023573 0ustar www-datawww-datamodule Fog module Parsers module AWS module SNS class SetTopicAttributes < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'RequestId' @response[name] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sns/publish.rb0000644000004100000410000000057512261242551021004 0ustar www-datawww-datamodule Fog module Parsers module AWS module SNS class Publish < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'MessageId', 'RequestId' @response[name] = @value.rstrip end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sns/create_topic.rb0000644000004100000410000000057712261242551022001 0ustar www-datawww-datamodule Fog module Parsers module AWS module SNS class CreateTopic < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'TopicArn', 'RequestId' @response[name] = @value.strip end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sns/add_permission.rb0000644000004100000410000000055712261242551022336 0ustar www-datawww-datamodule Fog module Parsers module AWS module SNS class AddPermission < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'RequestId' @response[name] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sns/unsubscribe.rb0000644000004100000410000000055512261242551021660 0ustar www-datawww-datamodule Fog module Parsers module AWS module SNS class Unsubscribe < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'RequestId' @response[name] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/sns/list_subscriptions.rb0000644000004100000410000000126112261242551023271 0ustar www-datawww-datamodule Fog module Parsers module AWS module SNS class ListSubscriptions < Fog::Parsers::Base def reset @response = { 'Subscriptions' => [] } @subscription = {} end def end_element(name) case name when "TopicArn", "Protocol", "SubscriptionArn", "Owner", "Endpoint" @subscription[name] = @value.strip when "member" @response['Subscriptions'] << @subscription @subscription = {} when 'RequestId', 'NextToken' @response[name] = @value.strip end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/0000755000004100000410000000000012261242551016745 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/iam/list_account_aliases.rb0000644000004100000410000000106412261242551023463 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class ListAccountAliases < Fog::Parsers::Base def reset @response = { 'AccountAliases' => [] } end def end_element(name) case name when 'member' @response['AccountAliases'] << @value when 'IsTruncated' response[name] = (@value == 'true') when 'Marker', 'RequestId' response[name] = @value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/single_role.rb0000644000004100000410000000106212261242551021573 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM require 'fog/aws/parsers/iam/role_parser' class SingleRole < Fog::Parsers::AWS::IAM::RoleParser def reset super @response = { 'Role' => {} } end def finished_role(role) @response['Role'] = role end def end_element(name) case name when 'RequestId' @response[name] = value end super end end end end end endfog-1.19.0/lib/fog/aws/parsers/iam/create_group.rb0000644000004100000410000000074112261242551021753 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class CreateGroup < Fog::Parsers::Base def reset @response = { 'Group' => {} } end def end_element(name) case name when 'Arn', 'GroupId', 'GroupName', 'Path' @response['Group'][name] = value when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/list_access_keys.rb0000644000004100000410000000130412261242551022617 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class ListAccessKeys < Fog::Parsers::Base def reset @access_key = {} @response = { 'AccessKeys' => [] } end def end_element(name) case name when 'AccessKeyId', 'Status', 'Username' @access_key[name] = value when 'member' @response['AccessKeys'] << @access_key @access_key = {} when 'IsTruncated' response[name] = (value == 'true') when 'Marker', 'RequestId' response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/get_user.rb0000644000004100000410000000120612261242551021106 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class GetUser < Fog::Parsers::Base # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_GetUser.html def reset @response = { 'User' => {} } end def end_element(name) case name when 'Arn', 'UserId', 'UserName', 'Path' @response['User'][name] = value when 'CreateDate' @response['User'][name] = Time.parse(value) when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/login_profile.rb0000644000004100000410000000110212261242551022114 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class LoginProfile < Fog::Parsers::Base def reset @response = { 'LoginProfile' => {} } end def end_element(name) case name when 'UserName' @response['LoginProfile']['UserName'] = value when 'CreateDate' @response['LoginProfile']['CreateDate'] = Time.parse(value) when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/list_server_certificates.rb0000644000004100000410000000157212261242551024365 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class ListServerCertificates < Fog::Parsers::Base def reset @response = { 'Certificates' => [] } reset_certificate end def reset_certificate @certificate = {} end def end_element(name) case name when 'Arn', 'Path', 'ServerCertificateId', 'ServerCertificateName' @certificate[name] = value when 'UploadDate' @certificate[name] = Time.parse(value) when 'member' @response['Certificates'] << @certificate reset_certificate when 'IsTrunctated' @response[name] = !!value when 'Marker' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/get_role_policy.rb0000644000004100000410000000141112261242551022446 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class GetRolePolicy < Fog::Parsers::Base def reset @response = {'Policy' => {}} end def end_element(name) case name when 'RoleName', 'PolicyName' @response['Policy'][name] = value when 'PolicyDocument' @response['Policy'][name] = if decoded_string = URI.decode(value) Fog::JSON.decode(decoded_string) rescue value else value end when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/get_group_policy.rb0000644000004100000410000000153712261242551022652 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class GetGroupPolicy < Fog::Parsers::Base # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_GetGroupPolicy.html def reset @response = { 'Policy' => {} } end def end_element(name) case name when 'GroupName', 'PolicyName' @response[name] = value when 'PolicyDocument' @response['Policy'][name] = if decoded_string = URI.decode(value) Fog::JSON.decode(decoded_string) rescue value else value end when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/upload_signing_certificate.rb0000644000004100000410000000101512261242551024633 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class UploadSigningCertificate < Fog::Parsers::Base def reset @response = { 'Certificate' => {} } end def end_element(name) case name when 'CertificateId', 'UserName', 'CertificateBody', 'Status' @response['Certificate'][name] = value when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/list_policies.rb0000644000004100000410000000104512261242551022134 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class ListPolicies < Fog::Parsers::Base def reset @response = { 'PolicyNames' => [] } end def end_element(name) case name when 'member' @response['PolicyNames'] << value when 'IsTruncated' response[name] = (value == 'true') when 'Marker', 'RequestId' response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/update_group.rb0000644000004100000410000000110412261242551021764 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class UpdateGroup < Fog::Parsers::Base # http://docs.amazonwebservices.com/IAM/latest/APIReference/index.html?API_UpdateGroup.html def reset @response = { 'Group' => {} } end def end_element(name) case name when 'Arn', 'GroupId', 'GroupName', 'Path' @response['Group'][name] = value when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/create_user.rb0000644000004100000410000000073412261242551021577 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class CreateUser < Fog::Parsers::Base def reset @response = { 'User' => {} } end def end_element(name) case name when 'Arn', 'UserId', 'UserName', 'Path' @response['User'][name] = value when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/create_access_key.rb0000644000004100000410000000077512261242551022737 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class CreateAccessKey < Fog::Parsers::Base def reset @response = { 'AccessKey' => {} } end def end_element(name) case name when 'AccessKeyId', 'UserName', 'SecretAccessKey', 'Status' @response['AccessKey'][name] = value when 'RequestId' @response[name] = value end end end end end end endfog-1.19.0/lib/fog/aws/parsers/iam/list_instance_profiles.rb0000644000004100000410000000132612261242551024036 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM require 'fog/aws/parsers/iam/base_instance_profile' class ListInstanceProfiles < Fog::Parsers::AWS::IAM::BaseInstanceProfile def reset super @response = {'InstanceProfiles' => []} end def finished_instance_profile(profile) @response['InstanceProfiles'] << profile end def end_element(name) case name when 'RequestId', 'Marker' @response[name] = value when 'IsTruncated' @response[name] = (value == 'true') end super end end end end end endfog-1.19.0/lib/fog/aws/parsers/iam/instance_profile.rb0000644000004100000410000000115212261242551022615 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM require 'fog/aws/parsers/iam/base_instance_profile' class InstanceProfile < Fog::Parsers::AWS::IAM::BaseInstanceProfile def reset super @response = {} end def finished_instance_profile(profile) @response['InstanceProfile'] = profile end def end_element(name) case name when 'RequestId' @response[name] = value end super end end end end end endfog-1.19.0/lib/fog/aws/parsers/iam/role_parser.rb0000644000004100000410000000225512261242551021613 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class RoleParser < Fog::Parsers::Base def reset @role = {} @stack = [] end def start_element(name,attrs = []) case name when 'Roles' @stack << name when 'Role' @role = {} when 'member' if @stack.last == 'Roles' @role = {} end end super end def end_element(name) case name when 'Arn', 'AssumeRolePolicyDocument', 'Path', 'RoleId','RoleName' @role[name] = value if @role when 'CreateDate' @role[name] = Time.parse(value) if @role when 'Role' finished_role(@role) @role = nil when 'Roles' if @stack.last == 'Roles' @stack.pop end when 'member' if @stack.last == 'Roles' finished_role(@role) @role = nil end end end end end end end endfog-1.19.0/lib/fog/aws/parsers/iam/list_signing_certificates.rb0000644000004100000410000000144212261242551024511 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class ListSigningCertificates < Fog::Parsers::Base def reset @signing_certificate = {} @response = { 'SigningCertificates' => [] } end def end_element(name) case name when 'UserName', 'CertificateId', 'CertificateBody', 'Status' @signing_certificate[name] = value when 'member' @response['SigningCertificates'] << @signing_certificate @signing_certificate = {} when 'IsTruncated' response[name] = (value == 'true') when 'Marker', 'RequestId' response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/list_users.rb0000644000004100000410000000135112261242551021466 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class ListUsers < Fog::Parsers::Base def reset @user = {} @response = { 'Users' => [] } end def end_element(name) case name when 'Arn', 'UserId', 'UserName', 'Path' @user[name] = value when 'CreateDate' @user[name] = Time.parse(value) when 'member' @response['Users'] << @user @user = {} when 'IsTruncated' response[name] = (value == 'true') when 'Marker', 'RequestId' response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/upload_server_certificate.rb0000644000004100000410000000116012261242551024504 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class UploadServerCertificate < Fog::Parsers::Base def reset @response = { 'Certificate' => {} } end def end_element(name) case name when 'Arn', 'Path', 'ServerCertificateId', 'ServerCertificateName' @response['Certificate'][name] = value when 'UploadDate' @response['Certificate'][name] = Time.parse(value) when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/get_user_policy.rb0000644000004100000410000000154612261242551022474 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class GetUserPolicy < Fog::Parsers::Base # http://docs.amazonwebservices.com/IAM/latest/APIReference/API_GetUserPolicy.html def reset @response = { 'Policy' => {} } end def end_element(name) case name when 'UserName', 'PolicyName' @response['Policy'][name] = value when 'PolicyDocument' @response['Policy'][name] = if decoded_string = URI.decode(value) Fog::JSON.decode(decoded_string) rescue value else value end when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/list_groups.rb0000644000004100000410000000124612261242551021647 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class ListGroups < Fog::Parsers::Base def reset @group = {} @response = { 'Groups' => [] } end def end_element(name) case name when 'Arn', 'GroupId', 'GroupName', 'Path' @group[name] = value when 'member' @response['Groups'] << @group @group = {} when 'IsTruncated' response[name] = (value == 'true') when 'Marker', 'RequestId' response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/list_roles.rb0000644000004100000410000000123112261242551021446 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM require 'fog/aws/parsers/iam/role_parser' class ListRoles < Fog::Parsers::AWS::IAM::RoleParser def reset super @response = { 'Roles' => [] } end def finished_role(role) @response['Roles'] << role end def end_element(name) case name when 'RequestId', 'Marker' @response[name] = value when 'IsTruncated' @response[name] = (value == 'true') end super end end end end end endfog-1.19.0/lib/fog/aws/parsers/iam/list_groups_for_user.rb0000644000004100000410000000133712261242551023554 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class ListGroupsForUser < Fog::Parsers::Base def reset @group_for_user = {} @response = { 'GroupsForUser' => [] } end def end_element(name) case name when 'Path', 'GroupName', 'GroupId', 'Arn' @group_for_user[name] = value when 'member' @response['GroupsForUser'] << @group_for_user @group_for_user = {} when 'IsTruncated' response[name] = (value == 'true') when 'Marker', 'RequestId' response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/base_instance_profile.rb0000644000004100000410000000425512261242551023616 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class BaseInstanceProfile < Fog::Parsers::Base def reset super @stack = [] end def start_element(name,attrs = []) super case name when 'InstanceProfile' @instance_profile = {'Roles' =>[]} when 'InstanceProfiles' @stack << 'InstanceProfiles' when 'Roles' @stack << 'Role' when 'member' case @stack.last when 'InstanceProfiles' @instance_profile = {'Roles' =>[]} when 'Roles' if @instance_profile @role = {} end end end end def end_element(name) if @instance_profile case name when 'Arn', 'Path' if @role @role[name] = value else @instance_profile[name] = value end when 'AssumeRolePolicyDocument', 'RoleId','RoleName' @role[name] = value if @role when 'CreateDate' if @role @role[name] = Time.parse(value) else @instance_profile[name] = Time.parse(value) end when 'member' case @stack.last when 'InstanceProfiles' finished_instance_profile(@instance_profile) @instance_profile = nil when 'Roles' if @instance_profile @instance_profile['Roles'] << @role @role = nil end end when 'InstanceProfiles', 'Roles' @stack.pop when 'InstanceProfile' finished_instance_profile(@instance_profile) @instance_profile = nil when 'InstanceProfileName', 'InstanceProfileId' @instance_profile[name] = value end end end end end end end endfog-1.19.0/lib/fog/aws/parsers/iam/get_group.rb0000644000004100000410000000261012261242551021264 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class GetGroup < Fog::Parsers::Base # http://docs.amazonwebservices.com/IAM/latest/APIReference/index.html?API_GetGroup.html def reset @user = {} @response = { 'Group' => {}, 'Users' => [] } end def start_element(name, attrs = []) super case name when 'Group' @in_group = true when 'Users' @in_users = true end end def end_element(name) case name when 'Arn', 'Path' if @in_group @response['Group'][name] = value elsif @in_users @user[name] = value end when 'Group' @in_group = false when 'GroupName', 'GroupId' @response['Group'][name] = value when 'Users' @in_users = false when 'UserId', 'UserName' @user[name] = value when 'member' @response['Users'] << @user @user = {} when 'IsTruncated' response[name] = (value == 'true') when 'Marker', 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/update_user.rb0000644000004100000410000000110712261242551021611 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class UpdateUser < Fog::Parsers::Base # http://docs.amazonwebservices.com/IAM/latest/APIReference/index.html?API_UpdateUser.html def reset @response = { 'User' => {} } end def end_element(name) case name when 'Arn', 'UserId', 'UserName', 'Path' @response['User'][name] = value when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/iam/basic.rb0000644000004100000410000000044712261242551020360 0ustar www-datawww-datamodule Fog module Parsers module AWS module IAM class Basic < Fog::Parsers::Base def end_element(name) case name when 'RequestId' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/aws/parsers/simpledb/0000755000004100000410000000000012261242551017776 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/parsers/simpledb/domain_metadata.rb0000644000004100000410000000141312261242551023431 0ustar www-datawww-datarequire 'fog/aws/parsers/simpledb/basic' module Fog module Parsers module AWS module SimpleDB class DomainMetadata < Fog::Parsers::AWS::SimpleDB::Basic def reset @response = {} end def end_element(name) case name when 'AttributeNameCount', 'AttributeNamesSizeBytes', 'AttributeValueCount', 'AttributeValuesSizeBytes', 'ItemCount', 'ItemNamesSizeBytes' response[name] = value.to_i when 'BoxUsage' response[name] = value.to_f when 'RequestId' response[name] = value when 'Timestamp' response[name] = Time.at(value.to_i) end end end end end end endfog-1.19.0/lib/fog/aws/parsers/simpledb/select.rb0000644000004100000410000000201512261242551021600 0ustar www-datawww-datarequire 'fog/aws/parsers/simpledb/basic' module Fog module Parsers module AWS module SimpleDB class Select < Fog::Parsers::AWS::SimpleDB::Basic def reset @item_name = @attribute_name = nil @response = { 'Items' => {} } end def end_element(name) case name when 'BoxUsage' response[name] = value.to_f when 'Item' @item_name = @attribute_name = nil when 'Name' if @item_name.nil? @item_name = value response['Items'][@item_name] = {} else @attribute_name = value response['Items'][@item_name][@attribute_name] ||= [] end when 'NextToken', 'RequestId' response[name] = value when 'Value' response['Items'][@item_name][@attribute_name] << sdb_decode(value) end end end end end end end fog-1.19.0/lib/fog/aws/parsers/simpledb/list_domains.rb0000644000004100000410000000112712261242551023011 0ustar www-datawww-datarequire 'fog/aws/parsers/simpledb/basic' module Fog module Parsers module AWS module SimpleDB class ListDomains < Fog::Parsers::AWS::SimpleDB::Basic def reset @response = { 'Domains' => [] } end def end_element(name) case(name) when 'BoxUsage' response[name] = value.to_f when 'DomainName' response['Domains'] << value when 'NextToken', 'RequestId' response[name] = value end end end end end end endfog-1.19.0/lib/fog/aws/parsers/simpledb/get_attributes.rb0000644000004100000410000000145712261242551023357 0ustar www-datawww-datarequire 'fog/aws/parsers/simpledb/basic' module Fog module Parsers module AWS module SimpleDB class GetAttributes < Fog::Parsers::AWS::SimpleDB::Basic def reset @attribute = nil @response = { 'Attributes' => {} } end def end_element(name) case name when 'Attribute' @attribute = nil when 'BoxUsage' response[name] = value.to_f when 'Name' @attribute = value response['Attributes'][@attribute] ||= [] when 'RequestId' response[name] = value when 'Value' response['Attributes'][@attribute] << sdb_decode(value) end end end end end end end fog-1.19.0/lib/fog/aws/parsers/simpledb/basic.rb0000644000004100000410000000107612261242551021410 0ustar www-datawww-datamodule Fog module Parsers module AWS module SimpleDB class Basic < Fog::Parsers::Base def initialize(nil_string) @nil_string = nil_string reset end def end_element(name) case(name) when 'BoxUsage' response[name] = value.to_f when 'RequestId' response[name] = value end end def sdb_decode(value) value.eql?(@nil_string) ? nil : value end end end end end endfog-1.19.0/lib/fog/aws/elb/0000755000004100000410000000000012261242551015262 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/elb/policy_types.rb0000644000004100000410000003013112261242551020330 0ustar www-datawww-dataclass Fog::AWS::ELB::Mock POLICY_TYPES = [{ "Description" => "", "PolicyAttributeTypeDescriptions" => [{ "AttributeName"=>"CookieName", "AttributeType"=>"String", "Cardinality"=>"ONE", "DefaultValue"=>"", "Description"=>"" }], "PolicyTypeName"=>"AppCookieStickinessPolicyType" }, { "Description" => "", "PolicyAttributeTypeDescriptions" => [{ "AttributeName"=>"CookieExpirationPeriod", "AttributeType"=>"String", "Cardinality"=>"ONE", "DefaultValue"=>"", "Description"=>"" }], "PolicyTypeName"=>"LBCookieStickinessPolicyType" }, { "Description" => "Policy containing a list of public keys to accept when authenticating the back-end server(s). This policy cannot be applied directly to back-end servers or listeners but must be part of a BackendServerAuthenticationPolicyType.", "PolicyAttributeTypeDescriptions" => [{ "AttributeName"=>"PublicKey", "AttributeType"=>"String", "Cardinality"=>"ONE", "DefaultValue"=>"", "Description"=>"" }], "PolicyTypeName"=>"PublicKeyPolicyType" }, { "Description" => "Listener policy that defines the ciphers and protocols that will be accepted by the load balancer. This policy can be associated only with HTTPS/SSL listeners.", "PolicyAttributeTypeDescriptions" => [{ "AttributeName"=>"Protocol-SSLv2", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EDH-DSS-DES-CBC3-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"DHE-RSA-CAMELLIA128-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"DES-CBC-MD5", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"KRB5-RC4-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"ADH-CAMELLIA128-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EXP-KRB5-RC4-MD5", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"ADH-RC4-MD5", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"PSK-RC4-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"PSK-AES128-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EXP-EDH-RSA-DES-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"CAMELLIA128-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"DHE-DSS-AES128-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EDH-RSA-DES-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"DHE-RSA-SEED-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"KRB5-DES-CBC-MD5", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"DHE-RSA-CAMELLIA256-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"ADH-DES-CBC3-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"DES-CBC3-MD5", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EXP-KRB5-RC2-CBC-MD5", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EDH-DSS-DES-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"KRB5-DES-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"PSK-AES256-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"ADH-AES256-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"KRB5-DES-CBC3-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"AES128-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"TRUE", "Description"=>"" }, { "AttributeName"=>"DHE-DSS-SEED-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"ADH-CAMELLIA256-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EXP-KRB5-RC4-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EDH-RSA-DES-CBC3-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EXP-KRB5-DES-CBC-MD5", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"Protocol-TLSv1", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"TRUE", "Description"=>"" }, { "AttributeName"=>"PSK-3DES-EDE-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"SEED-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"DHE-DSS-CAMELLIA256-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"IDEA-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"RC2-CBC-MD5", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"KRB5-RC4-MD5", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"ADH-AES128-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"RC4-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"TRUE", "Description"=>"" }, { "AttributeName"=>"AES256-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"TRUE", "Description"=>"" }, { "AttributeName"=>"Protocol-SSLv3", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"TRUE", "Description"=>"" }, { "AttributeName"=>"EXP-DES-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"DES-CBC3-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"TRUE", "Description"=>"" }, { "AttributeName"=>"DHE-RSA-AES128-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EXP-EDH-DSS-DES-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EXP-KRB5-RC2-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"DHE-RSA-AES256-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"KRB5-DES-CBC3-MD5", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"RC4-MD5", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"TRUE", "Description"=>"" }, { "AttributeName"=>"EXP-RC2-CBC-MD5", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"DES-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EXP-ADH-RC4-MD5", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EXP-RC4-MD5", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"ADH-DES-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"CAMELLIA256-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"DHE-DSS-CAMELLIA128-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EXP-KRB5-DES-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"EXP-ADH-DES-CBC-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"DHE-DSS-AES256-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }, { "AttributeName"=>"ADH-SEED-SHA", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"FALSE", "Description"=>"" }], "PolicyTypeName"=>"SSLNegotiationPolicyType" }, { "Description"=>"Policy that controls whether to include the IP address and port of the originating request for TCP messages. This policy operates on TCP/SSL listeners only", "PolicyAttributeTypeDescriptions"=>[{ "AttributeName"=>"ProxyProtocol", "AttributeType"=>"Boolean", "Cardinality"=>"ONE", "DefaultValue"=>"", "Description"=>"" }], "PolicyTypeName"=>"ProxyProtocolPolicyType" }] end fog-1.19.0/lib/fog/aws/elb.rb0000644000004100000410000002141112261242551015606 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class ELB < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods class DuplicatePolicyName < Fog::Errors::Error; end class IdentifierTaken < Fog::Errors::Error; end class InvalidInstance < Fog::Errors::Error; end class InvalidConfigurationRequest < Fog::Errors::Error; end class PolicyNotFound < Fog::Errors::Error; end class PolicyTypeNotFound < Fog::Errors::Error; end class Throttled < Fog::Errors::Error; end class TooManyPolicies < Fog::Errors::Error; end class ValidationError < Fog::Errors::Error; end requires :aws_access_key_id, :aws_secret_access_key recognizes :region, :host, :path, :port, :scheme, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at, :instrumentor, :instrumentor_name request_path 'fog/aws/requests/elb' request :configure_health_check request :create_app_cookie_stickiness_policy request :create_lb_cookie_stickiness_policy request :create_load_balancer request :create_load_balancer_listeners request :create_load_balancer_policy request :delete_load_balancer request :delete_load_balancer_listeners request :delete_load_balancer_policy request :deregister_instances_from_load_balancer request :describe_instance_health request :describe_load_balancers request :describe_load_balancer_attributes request :describe_load_balancer_policies request :describe_load_balancer_policy_types request :disable_availability_zones_for_load_balancer request :enable_availability_zones_for_load_balancer request :modify_load_balancer_attributes request :register_instances_with_load_balancer request :set_load_balancer_listener_ssl_certificate request :set_load_balancer_policies_of_listener request :attach_load_balancer_to_subnets request :detach_load_balancer_from_subnets request :apply_security_groups_to_load_balancer request :set_load_balancer_policies_for_backend_server model_path 'fog/aws/models/elb' model :load_balancer collection :load_balancers model :policy collection :policies model :listener collection :listeners model :backend_server_description collection :backend_server_descriptions class Mock require 'fog/aws/elb/policy_types' def self.data @data ||= Hash.new do |hash, region| owner_id = Fog::AWS::Mock.owner_id hash[region] = Hash.new do |region_hash, key| region_hash[key] = { :owner_id => owner_id, :load_balancers => {}, :policy_types => Fog::AWS::ELB::Mock::POLICY_TYPES } end end end def self.dns_name(name, region) "#{name}-#{Fog::Mock.random_hex(8)}.#{region}.elb.amazonaws.com" end def self.reset @data = nil end def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @region = options[:region] || 'us-east-1' unless ['ap-northeast-1', 'ap-southeast-1', 'ap-southeast-2', 'eu-west-1', 'us-east-1', 'us-west-1', 'us-west-2'].include?(@region) raise ArgumentError, "Unknown region: #{@region.inspect}" end end def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] end def data self.class.data[@region][@aws_access_key_id] end def reset_data self.class.data[@region].delete(@aws_access_key_id) end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to ELB # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # elb = ELB.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # * region<~String> - optional region to use. For instance, 'eu-west-1', 'us-east-1', etc. # # ==== Returns # * ELB object with connection to AWS. def initialize(options={}) require 'fog/core/parser' @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} @instrumentor = options[:instrumentor] @instrumentor_name = options[:instrumentor_name] || 'fog.aws.elb' options[:region] ||= 'us-east-1' @host = options[:host] || "elasticloadbalancing.#{options[:region]}.amazonaws.com" @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end def reload @connection.reset end private def setup_credentials(options={}) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) end def request(params) refresh_credentials_if_expired idempotent = params.delete(:idempotent) parser = params.delete(:parser) body = Fog::AWS.signed_params( params, { :aws_access_key_id => @aws_access_key_id, :aws_session_token => @aws_session_token, :hmac => @hmac, :host => @host, :path => @path, :port => @port, :version => '2012-06-01' } ) if @instrumentor @instrumentor.instrument("#{@instrumentor_name}.request", params) do _request(body, idempotent, parser) end else _request(body, idempotent, parser) end end def _request(body, idempotent, parser) @connection.request({ :body => body, :expects => 200, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded' }, :idempotent => idempotent, :method => 'POST', :parser => parser }) rescue Excon::Errors::HTTPStatusError => error match = Fog::AWS::Errors.match_error(error) raise if match.empty? raise case match[:code] when 'CertificateNotFound' Fog::AWS::IAM::NotFound.slurp(error, match[:message]) when 'DuplicateLoadBalancerName' Fog::AWS::ELB::IdentifierTaken.slurp(error, match[:message]) when 'DuplicatePolicyName' Fog::AWS::ELB::DuplicatePolicyName.slurp(error, match[:message]) when 'InvalidInstance' Fog::AWS::ELB::InvalidInstance.slurp(error, match[:message]) when 'InvalidConfigurationRequest' # when do they fucking use this shit? Fog::AWS::ELB::InvalidConfigurationRequest.slurp(error, match[:message]) when 'LoadBalancerNotFound' Fog::AWS::ELB::NotFound.slurp(error, match[:message]) when 'PolicyNotFound' Fog::AWS::ELB::PolicyNotFound.slurp(error, match[:message]) when 'PolicyTypeNotFound' Fog::AWS::ELB::PolicyTypeNotFound.slurp(error, match[:message]) when 'Throttling' Fog::AWS::ELB::Throttled.slurp(error, match[:message]) when 'TooManyPolicies' Fog::AWS::ELB::TooManyPolicies.slurp(error, match[:message]) when 'ValidationError' Fog::AWS::ELB::ValidationError.slurp(error, match[:message]) else Fog::AWS::ELB::Error.slurp(error, "#{match[:code]} => #{match[:message]}") end end end end end end fog-1.19.0/lib/fog/aws/data_pipeline.rb0000644000004100000410000000760612261242551017654 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class DataPipeline < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods requires :aws_access_key_id, :aws_secret_access_key recognizes :region, :host, :path, :port, :scheme, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at request_path 'fog/aws/requests/data_pipeline' request :activate_pipeline request :create_pipeline request :delete_pipeline request :describe_pipelines request :list_pipelines request :put_pipeline_definition request :get_pipeline_definition request :query_objects request :describe_objects model_path 'fog/aws/models/data_pipeline' model :pipeline collection :pipelines class Mock def initialize(options={}) Fog::Mock.not_implemented end end class Real attr_reader :region include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to DataPipeline # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # datapipeline = DataPipeline.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # * region<~String> - optional region to use. For instance, 'eu-west-1', 'us-east-1' and etc. # # ==== Returns # * DataPipeline object with connection to AWS. def initialize(options={}) @use_iam_profile = options[:use_iam_profile] @connection_options = options[:connection_options] || {} @version = '2012-10-29' @region = options[:region] || 'us-east-1' @host = options[:host] || "datapipeline.#{@region}.amazonaws.com" @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) setup_credentials(options) end def owner_id @owner_id ||= security_groups.get('default').owner_id end def reload @connection.reset end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @signer = Fog::AWS::SignatureV4.new(@aws_access_key_id, @aws_secret_access_key, @region, 'datapipeline') end def request(params) refresh_credentials_if_expired # Params for all DataPipeline requests params.merge!({ :expects => 200, :method => :post, :path => '/', }) date = Fog::Time.now params[:headers] = { 'Date' => date.to_date_header, 'Host' => @host, 'X-Amz-Date' => date.to_iso8601_basic, 'Content-Type' => 'application/x-amz-json-1.1', 'Content-Length' => params[:body].bytesize.to_s, }.merge!(params[:headers] || {}) params[:headers]['x-amz-security-token'] = @aws_session_token if @aws_session_token params[:headers]['Authorization'] = @signer.sign(params, date) response = @connection.request(params) response end end end end end fog-1.19.0/lib/fog/aws/dns.rb0000644000004100000410000001057212261242551015636 0ustar www-datawww-datarequire 'fog/aws' require 'fog/dns' module Fog module DNS class AWS < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods requires :aws_access_key_id, :aws_secret_access_key recognizes :host, :path, :port, :scheme, :version, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at model_path 'fog/aws/models/dns' model :record collection :records model :zone collection :zones request_path 'fog/aws/requests/dns' request :create_hosted_zone request :get_hosted_zone request :delete_hosted_zone request :list_hosted_zones request :change_resource_record_sets request :list_resource_record_sets request :get_change class Mock def self.data @data ||= Hash.new do |hash, region| hash[region] = Hash.new do |region_hash, key| region_hash[key] = { :buckets => {}, :limits => { :duplicate_domains => 5 }, :zones => {}, :changes => {} } end end end def self.reset @data = nil end def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @region = options[:region] end def data self.class.data[@region][@aws_access_key_id] end def reset_data self.class.data[@region].delete(@aws_access_key_id) end def signature(params) "foo" end def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to Route 53 DNS service # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # dns = Fog::AWS::DNS.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # # ==== Returns # * dns object with connection to aws. def initialize(options={}) require 'fog/core/parser' @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} @host = options[:host] || 'route53.amazonaws.com' @path = options[:path] || '/' @persistent = options.fetch(:persistent, true) @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @version = options[:version] || '2012-02-29' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end def reload @connection.reset end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha1', @aws_secret_access_key) end def request(params, &block) refresh_credentials_if_expired params[:headers] ||= {} params[:headers]['Date'] = Fog::Time.now.to_date_header params[:headers]['x-amz-security-token'] = @aws_session_token if @aws_session_token params[:headers]['X-Amzn-Authorization'] = "AWS3-HTTPS AWSAccessKeyId=#{@aws_access_key_id},Algorithm=HmacSHA1,Signature=#{signature(params)}" params[:path] = "/#{@version}/#{params[:path]}" @connection.request(params, &block) end def signature(params) string_to_sign = params[:headers]['Date'] signed_string = @hmac.sign(string_to_sign) Base64.encode64(signed_string).chomp! end end end end end fog-1.19.0/lib/fog/aws/rds.rb0000644000004100000410000002060612261242551015641 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class RDS < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods class IdentifierTaken < Fog::Errors::Error; end class AuthorizationAlreadyExists < Fog::Errors::Error; end requires :aws_access_key_id, :aws_secret_access_key recognizes :region, :host, :path, :port, :scheme, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at, :version request_path 'fog/aws/requests/rds' request :describe_events request :create_db_instance request :modify_db_instance request :describe_db_instances request :delete_db_instance request :reboot_db_instance request :create_db_instance_read_replica request :describe_db_engine_versions request :describe_db_reserved_instances request :add_tags_to_resource request :list_tags_for_resource request :remove_tags_from_resource request :describe_db_snapshots request :create_db_snapshot request :delete_db_snapshot request :create_db_parameter_group request :delete_db_parameter_group request :modify_db_parameter_group request :describe_db_parameter_groups request :describe_db_security_groups request :create_db_security_group request :delete_db_security_group request :authorize_db_security_group_ingress request :revoke_db_security_group_ingress request :describe_db_parameters request :restore_db_instance_from_db_snapshot request :restore_db_instance_to_point_in_time request :create_db_subnet_group request :describe_db_subnet_groups request :delete_db_subnet_group # TODO: :modify_db_subnet_group request :describe_orderable_db_instance_options request :describe_db_log_files request :download_db_logfile_portion model_path 'fog/aws/models/rds' model :server collection :servers model :snapshot collection :snapshots model :parameter_group collection :parameter_groups model :parameter collection :parameters model :security_group collection :security_groups model :subnet_group collection :subnet_groups model :instance_option collection :instance_options model :log_file collection :log_files class Mock def self.data @data ||= Hash.new do |hash, region| hash[region] = Hash.new do |region_hash, key| region_hash[key] = { :servers => {}, :security_groups => {}, :subnet_groups => {}, :snapshots => {}, :parameter_groups => {"default.mysql5.1" => { "DBParameterGroupFamily"=>"mysql5.1", "Description"=>"Default parameter group for mysql5.1", "DBParameterGroupName"=>"default.mysql5.1" }, "default.mysql5.5" => {"DBParameterGroupFamily"=>"mysql5.5", "Description"=>"Default parameter group for mysql5.5", "DBParameterGroupName"=>"default.mysql5.5" } } } end end end def self.reset @data = nil end def initialize(options={}) @use_iam_profile = options[:use_iam_profile] @region = options[:region] || 'us-east-1' unless ['ap-northeast-1', 'ap-southeast-1', 'ap-southeast-2', 'eu-west-1', 'us-east-1', 'us-west-1', 'us-west-2', 'sa-east-1'].include?(@region) raise ArgumentError, "Unknown region: #{@region.inspect}" end end def data self.class.data[@region][@aws_access_key_id] end def reset_data self.class.data[@region].delete(@aws_access_key_id) end def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] end end class Real attr_reader :region include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to ELB # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # elb = ELB.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # * region<~String> - optional region to use. For instance, 'eu-west-1', 'us-east-1' and etc. # # ==== Returns # * ELB object with connection to AWS. def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} @region = options[:region] || 'us-east-1' @host = options[:host] || "rds.#{@region}.amazonaws.com" @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) @version = options[:version] || '2013-05-15' end def owner_id @owner_id ||= security_groups.get('default').owner_id end def reload @connection.reset end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) end def request(params) refresh_credentials_if_expired idempotent = params.delete(:idempotent) parser = params.delete(:parser) body = Fog::AWS.signed_params( params, { :aws_access_key_id => @aws_access_key_id, :aws_session_token => @aws_session_token, :hmac => @hmac, :host => @host, :path => @path, :port => @port, :version => @version } ) begin @connection.request({ :body => body, :expects => 200, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded' }, :idempotent => idempotent, :method => 'POST', :parser => parser }) rescue Excon::Errors::HTTPStatusError => error match = Fog::AWS::Errors.match_error(error) if match.empty? case error.message when 'Not Found' raise Fog::AWS::RDS::NotFound.slurp(error, 'RDS Instance not found') else raise end else raise case match[:code] when 'DBInstanceNotFound', 'DBParameterGroupNotFound', 'DBSnapshotNotFound', 'DBSecurityGroupNotFound' Fog::AWS::RDS::NotFound.slurp(error, match[:message]) when 'DBParameterGroupAlreadyExists' Fog::AWS::RDS::IdentifierTaken.slurp(error, match[:message]) when 'AuthorizationAlreadyExists' Fog::AWS::RDS::AuthorizationAlreadyExists.slurp(error, match[:message]) else Fog::AWS::RDS::Error.slurp(error, "#{match[:code]} => #{match[:message]}") end end end end end end end end fog-1.19.0/lib/fog/aws/simpledb.rb0000644000004100000410000001511012261242551016642 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class SimpleDB < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods requires :aws_access_key_id, :aws_secret_access_key recognizes :host, :nil_string, :path, :port, :scheme, :persistent, :region, :aws_session_token, :use_iam_profile, :aws_credentials_expire_at request_path 'fog/aws/requests/simpledb' request :batch_put_attributes request :create_domain request :delete_attributes request :delete_domain request :domain_metadata request :get_attributes request :list_domains request :put_attributes request :select class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = { :domains => {} } end end def self.reset @data = nil end def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) end def data self.class.data[@aws_access_key_id] end def reset_data self.class.data.delete(@aws_access_key_id) end def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to SimpleDB # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # sdb = SimpleDB.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # # ==== Returns # * SimpleDB object with connection to aws. def initialize(options={}) require 'fog/core/parser' @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} @nil_string = options[:nil_string]|| 'nil' options[:region] ||= 'us-east-1' @host = options[:host] || case options[:region] when 'us-east-1' 'sdb.amazonaws.com' else "sdb.#{options[:region]}.amazonaws.com" end @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) end def encode_attributes(attributes, replace_attributes = [], expected_attributes = {}) encoded_attributes = {} if attributes expected_attributes.keys.each_with_index do |exkey, index| for value in Array(expected_attributes[exkey]) encoded_attributes["Expected.#{index}.Name"] = exkey.to_s encoded_attributes["Expected.#{index}.Value"] = sdb_encode(value) end end index = 0 for key in attributes.keys for value in Array(attributes[key]) encoded_attributes["Attribute.#{index}.Name"] = key.to_s if replace_attributes.include?(key) encoded_attributes["Attribute.#{index}.Replace"] = 'true' end encoded_attributes["Attribute.#{index}.Value"] = sdb_encode(value) index += 1 end end end encoded_attributes end def encode_attribute_names(attributes) Fog::AWS.indexed_param('AttributeName', attributes.map {|attribute| attributes.to_s}) end def encode_batch_attributes(items, replace_attributes = Hash.new([])) encoded_attributes = {} if items item_index = 0 for item_key in items.keys encoded_attributes["Item.#{item_index}.ItemName"] = item_key.to_s attribute_index = 0 for attribute_key in items[item_key].keys for value in Array(items[item_key][attribute_key]) encoded_attributes["Item.#{item_index}.Attribute.#{attribute_index}.Name"] = attribute_key.to_s if replace_attributes[item_key].include?(attribute_key) encoded_attributes["Item.#{item_index}.Attribute.#{attribute_index}.Replace"] = 'true' end encoded_attributes["Item.#{item_index}.Attribute.#{attribute_index}.Value"] = sdb_encode(value) attribute_index += 1 end end item_index += 1 end end encoded_attributes end def reload @connection.reset end def request(params) refresh_credentials_if_expired idempotent = params.delete(:idempotent) parser = params.delete(:parser) body = Fog::AWS.signed_params( params, { :aws_access_key_id => @aws_access_key_id, :aws_session_token => @aws_session_token, :hmac => @hmac, :host => @host, :path => @path, :port => @port, :version => '2009-04-15' } ) response = @connection.request({ :body => body, :expects => 200, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8' }, :idempotent => idempotent, :method => 'POST', :parser => parser }) response end def sdb_encode(value) if value.nil? @nil_string else value.to_s end end end end end end fog-1.19.0/lib/fog/aws/cloud_watch.rb0000644000004100000410000001246012261242551017344 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class CloudWatch < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods requires :aws_access_key_id, :aws_secret_access_key recognizes :region, :host, :path, :port, :scheme, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at, :instrumentor, :instrumentor_name request_path 'fog/aws/requests/cloud_watch' request :list_metrics request :get_metric_statistics request :put_metric_data request :describe_alarms request :put_metric_alarm request :delete_alarms request :describe_alarm_history request :enable_alarm_actions request :disable_alarm_actions request :describe_alarms_for_metric request :set_alarm_state model_path 'fog/aws/models/cloud_watch' model :metric collection :metrics model :metric_statistic collection :metric_statistics model :alarm_datum collection :alarm_data model :alarm_history collection :alarm_histories model :alarm collection :alarms class Mock def self.data @data ||= Hash.new do |hash, region| hash[region] = Hash.new do |region_hash, key| region_hash[key] = { :metric_alarms => {} } end end end def self.reset @data = nil end def initialize(options={}) @aws_access_key_id = options[:aws_access_key_id] @region = options[:region] || 'us-east-1' unless ['ap-northeast-1', 'ap-southeast-1', 'ap-southeast-2', 'eu-west-1', 'sa-east-1', 'us-east-1', 'us-west-1', 'us-west-2'].include?(@region) raise ArgumentError, "Unknown region: #{@region.inspect}" end end def data self.class.data[@region][@aws_access_key_id] end def reset_data self.class.data[@region].delete(@aws_access_key_id) end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to Cloudwatch # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # elb = CloudWatch.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # * region<~String> - optional region to use. For instance, 'eu-west-1', 'us-east-1', etc. # # ==== Returns # * CloudWatch object with connection to AWS. def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} @instrumentor = options[:instrumentor] @instrumentor_name = options[:instrumentor_name] || 'fog.aws.cloud_watch' options[:region] ||= 'us-east-1' @host = options[:host] || "monitoring.#{options[:region]}.amazonaws.com" @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end def reload @connection.reset end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) end def request(params) refresh_credentials_if_expired idempotent = params.delete(:idempotent) parser = params.delete(:parser) body = AWS.signed_params( params, { :aws_access_key_id => @aws_access_key_id, :aws_session_token => @aws_session_token, :hmac => @hmac, :host => @host, :path => @path, :port => @port, :version => '2010-08-01' } ) if @instrumentor @instrumentor.instrument("#{@instrumentor_name}.request", params) do _request(body, idempotent, parser) end else _request(body, idempotent, parser) end end def _request(body, idempotent, parser) @connection.request({ :body => body, :expects => 200, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded' }, :idempotent => idempotent, :method => 'POST', :parser => parser }) end end end end end fog-1.19.0/lib/fog/aws/sts.rb0000644000004100000410000001116312261242551015660 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class STS < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods class EntityAlreadyExists < Fog::AWS::STS::Error; end class ValidationError < Fog::AWS::STS::Error; end requires :aws_access_key_id, :aws_secret_access_key recognizes :host, :path, :port, :scheme, :persistent, :aws_session_token, :use_iam_profile, :aws_credentials_expire_at request_path 'fog/aws/requests/sts' request :get_federation_token request :get_session_token request :assume_role class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = { :owner_id => Fog::AWS::Mock.owner_id, :server_certificates => {} } end end def self.reset @data = nil end def self.server_certificate_id Fog::Mock.random_hex(16) end def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) end def data self.class.data[@aws_access_key_id] end def reset_data self.class.data.delete(@aws_access_key_id) end def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to STS # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # iam = STS.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # # ==== Returns # * STS object with connection to AWS. def initialize(options={}) require 'fog/core/parser' @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} @host = options[:host] || 'sts.amazonaws.com' @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end def reload @connection.reset end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) end def request(params) idempotent = params.delete(:idempotent) parser = params.delete(:parser) body = Fog::AWS.signed_params( params, { :aws_access_key_id => @aws_access_key_id, :aws_session_token => @aws_session_token, :hmac => @hmac, :host => @host, :path => @path, :port => @port, :version => '2011-06-15' } ) begin @connection.request({ :body => body, :expects => 200, :idempotent => idempotent, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded' }, :host => @host, :method => 'POST', :parser => parser }) rescue Excon::Errors::HTTPStatusError => error match = Fog::AWS::Errors.match_error(error) raise if match.empty? raise case match[:code] when 'EntityAlreadyExists', 'KeyPairMismatch', 'LimitExceeded', 'MalformedCertificate', 'ValidationError' Fog::AWS::STS.const_get(match[:code]).slurp(error, match[:message]) else Fog::AWS::STS::Error.slurp(error, "#{match[:code]} => #{match[:message]}") end end end end end end end fog-1.19.0/lib/fog/aws/models/0000755000004100000410000000000012261242551016003 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/models/storage/0000755000004100000410000000000012261242551017447 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/models/storage/directory.rb0000644000004100000410000000670212261242551022005 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/aws/models/storage/files' require 'fog/aws/models/storage/versions' module Fog module Storage class AWS class Directory < Fog::Model VALID_ACLS = ['private', 'public-read', 'public-read-write', 'authenticated-read'] attr_reader :acl identity :key, :aliases => ['Name', 'name'] attribute :creation_date, :aliases => 'CreationDate', :type => 'time' attribute :location, :aliases => 'LocationConstraint', :type => 'string' def acl=(new_acl) unless VALID_ACLS.include?(new_acl) raise ArgumentError.new("acl must be one of [#{VALID_ACLS.join(', ')}]") else @acl = new_acl end end def destroy requires :key service.delete_bucket(key) true rescue Excon::Errors::NotFound false end def location @location ||= (bucket_location || self.service.region) end # NOTE: you can't change the region once the bucket is created def location=(new_location) @location = new_location end def files @files ||= Fog::Storage::AWS::Files.new(:directory => self, :service => service) end def payer requires :key data = service.get_request_payment(key) data.body['Payer'] end def payer=(new_payer) requires :key service.put_request_payment(key, new_payer) @payer = new_payer end def versioning? requires :key data = service.get_bucket_versioning(key) data.body['VersioningConfiguration']['Status'] == 'Enabled' end def versioning=(new_versioning) requires :key service.put_bucket_versioning(key, new_versioning ? 'Enabled' : 'Suspended') end def versions @versions ||= Fog::Storage::AWS::Versions.new(:directory => self, :service => service) end def public=(new_public) self.acl = new_public ? 'public-read' : 'private' new_public end def public_url requires :key if service.get_bucket_acl(key).body['AccessControlList'].detect {|grant| grant['Grantee']['URI'] == 'http://acs.amazonaws.com/groups/global/AllUsers' && grant['Permission'] == 'READ'} service.request_url( :bucket_name => key ) else nil end end def save requires :key options = {} options['x-amz-acl'] = acl if acl # http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUT.html # Ignore the default region us-east-1 if !persisted? && location != DEFAULT_REGION options['LocationConstraint'] = location end service.put_bucket(key, options) attributes[:is_persisted] = true true end def persisted? # is_persisted is true in case of directories.get or after #save # creation_date is set in case of directories.all attributes[:is_persisted] || !!attributes[:creation_date] end private def bucket_location requires :key return nil unless persisted? data = service.get_bucket_location(key) data.body['LocationConstraint'] end end end end end fog-1.19.0/lib/fog/aws/models/storage/files.rb0000644000004100000410000000710012261242551021074 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/storage/file' module Fog module Storage class AWS class Files < Fog::Collection extend Fog::Deprecation deprecate :get_url, :get_https_url attribute :common_prefixes, :aliases => 'CommonPrefixes' attribute :delimiter, :aliases => 'Delimiter' attribute :directory attribute :is_truncated, :aliases => 'IsTruncated' attribute :marker, :aliases => 'Marker' attribute :max_keys, :aliases => ['MaxKeys', 'max-keys'] attribute :prefix, :aliases => 'Prefix' model Fog::Storage::AWS::File def all(options = {}) requires :directory options = { 'delimiter' => delimiter, 'marker' => marker, 'max-keys' => max_keys, 'prefix' => prefix }.merge!(options) options = options.reject {|key,value| value.nil? || value.to_s.empty?} merge_attributes(options) parent = directory.collection.get( directory.key, options ) if parent merge_attributes(parent.files.attributes) load(parent.files.map {|file| file.attributes}) else nil end end alias :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.is_truncated subset = subset.all(:marker => subset.last.key) subset.each_file_this_page {|f| yield f} end self end end def get(key, options = {}, &block) requires :directory data = service.get_object(directory.key, key, options, &block) normalize_headers(data) file_data = data.headers.merge({ :body => data.body, :key => key }) new(file_data) rescue Excon::Errors::NotFound => error case error.response.body when /NoSuchKey<\/Code>/ nil when /NoSuchBucket<\/Code>/ raise(Fog::Storage::AWS::NotFound.new("Directory #{directory.identity} does not exist.")) else raise(error) end end def get_url(key, expires, options = {}) requires :directory service.get_object_url(directory.key, key, expires, options) end def get_http_url(key, expires, options = {}) requires :directory service.get_object_http_url(directory.key, key, expires, options) end def get_https_url(key, expires, options = {}) requires :directory service.get_object_https_url(directory.key, key, expires, options) end def head(key, options = {}) requires :directory data = service.head_object(directory.key, key, options) normalize_headers(data) file_data = data.headers.merge({ :key => key }) new(file_data) rescue Excon::Errors::NotFound nil end def new(attributes = {}) requires :directory super({ :directory => directory }.merge!(attributes)) end def normalize_headers(data) data.headers['Last-Modified'] = Time.parse(data.get_header('Last-Modified')) data.headers['ETag'] = data.get_header('ETag').gsub('"','') end end end end end fog-1.19.0/lib/fog/aws/models/storage/directories.rb0000644000004100000410000000211512261242551022307 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/storage/directory' module Fog module Storage class AWS class Directories < Fog::Collection model Fog::Storage::AWS::Directory def all data = service.get_service.body['Buckets'] load(data) end def get(key, options = {}) remap_attributes(options, { :delimiter => 'delimiter', :marker => 'marker', :max_keys => 'max-keys', :prefix => 'prefix' }) data = service.get_bucket(key, options).body directory = new(:key => data['Name'], :is_persisted => true) options = {} for k, v in data if ['CommonPrefixes', 'Delimiter', 'IsTruncated', 'Marker', 'MaxKeys', 'Prefix'].include?(k) options[k] = v end end directory.files.merge_attributes(options) directory.files.load(data['Contents']) directory rescue Excon::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/aws/models/storage/file.rb0000644000004100000410000002435312261242551020722 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/aws/models/storage/versions' module Fog module Storage class AWS class File < Fog::Model # @see AWS Object docs http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectOps.html identity :key, :aliases => 'Key' attr_writer :body attribute :cache_control, :aliases => 'Cache-Control' attribute :content_disposition, :aliases => 'Content-Disposition' attribute :content_encoding, :aliases => 'Content-Encoding' attribute :content_length, :aliases => ['Content-Length', 'Size'], :type => :integer attribute :content_md5, :aliases => 'Content-MD5' attribute :content_type, :aliases => 'Content-Type' attribute :etag, :aliases => ['Etag', 'ETag'] attribute :expires, :aliases => 'Expires' attribute :last_modified, :aliases => ['Last-Modified', 'LastModified'] attribute :metadata attribute :owner, :aliases => 'Owner' attribute :storage_class, :aliases => ['x-amz-storage-class', 'StorageClass'] attribute :encryption, :aliases => 'x-amz-server-side-encryption' attribute :version, :aliases => 'x-amz-version-id' # @note Chunk size to use for multipart uploads. # Use small chunk sizes to minimize memory. E.g. 5242880 = 5mb attr_accessor :multipart_chunk_size # Set file's access control list (ACL). # # valid acls: private, public-read, public-read-write, authenticated-read, bucket-owner-read, bucket-owner-full-control # # @param [String] new_acl one of valid options # @return [String] @acl # def acl=(new_acl) valid_acls = ['private', 'public-read', 'public-read-write', 'authenticated-read', 'bucket-owner-read', 'bucket-owner-full-control'] unless valid_acls.include?(new_acl) raise ArgumentError.new("acl must be one of [#{valid_acls.join(', ')}]") end @acl = new_acl end # Get file's body if exists, else ' '. # # @return [File] # def body attributes[:body] ||= if last_modified && (file = collection.get(identity)) file.body else '' end end # Set body attribute. # # @param [File] new_body # @return [File] attributes[:body] # def body=(new_body) attributes[:body] = new_body end # Get the file instance's directory. # # @return [Fog::AWS::Storage::Directory] # def directory @directory end # Copy object from one bucket to other bucket. # # required attributes: directory, key # # @param target_directory_key [String] # @param target_file_key [String] # @param options [Hash] options for copy_object method # @return [String] Fog::AWS::Files#head status of directory contents # def copy(target_directory_key, target_file_key, options = {}) requires :directory, :key 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.head(target_file_key) end # Destroy file via http DELETE. # # required attributes: directory, key # # @param options [Hash] # @option options versionId [] # @return [Boolean] true if successful # def destroy(options = {}) requires :directory, :key attributes[:body] = nil if options['versionId'] == version service.delete_object(directory.key, key, options) true end remove_method :metadata def metadata attributes.reject {|key, value| !(key.to_s =~ /^x-amz-/)} end remove_method :metadata= def metadata=(new_metadata) merge_attributes(new_metadata) end remove_method :owner= def owner=(new_owner) if new_owner attributes[:owner] = { :display_name => new_owner['DisplayName'], :id => new_owner['ID'] } end end # Set Access-Control-List permissions. # # valid new_publics: public_read, private # # @param [String] new_public # @return [String] new_puplic # def public=(new_public) if new_public @acl = 'public-read' else @acl = 'private' end new_public end # Get pubically acessible url via http GET. # Checks persmissions before creating. # Defaults to s3 subdomain or compliant bucket name # # required attributes: directory, key # # @return [String] public url # def public_url requires :directory, :key if service.get_object_acl(directory.key, key).body['AccessControlList'].detect {|grant| grant['Grantee']['URI'] == 'http://acs.amazonaws.com/groups/global/AllUsers' && grant['Permission'] == 'READ'} service.request_url( :bucket_name => directory.key, :object_name => key ) else nil end end # Save file with body as contents to directory.key with name key via http PUT # # required attributes: body, directory, key # # @param [Hash] options # @option options [String] acl sets x-amz-acl HTTP header. Valid values include, private | public-read | public-read-write | authenticated-read | bucket-owner-read | bucket-owner-full-control # @option options [String] cache_control sets Cache-Control header. For example, 'No-cache' # @option options [String] content_disposition sets Content-Disposition HTTP header. For exampple, 'attachment; filename=testing.txt' # @option options [String] content_encoding sets Content-Encoding HTTP header. For example, 'x-gzip' # @option options [String] content_md5 sets Content-MD5. For example, '79054025255fb1a26e4bc422aef54eb4' # @option options [String] content_type Content-Type. For example, 'text/plain' # @option options [String] expires sets number of seconds before AWS Object expires. # @option options [String] storage_class sets x-amz-storage-class HTTP header. Defaults to 'STANDARD'. Or, 'REDUCED_REDUNDANCY' # @option options [String] encryption sets HTTP encryption header. Set to 'AES256' to encrypt files at rest on S3 # @return [Boolean] true if no errors # def save(options = {}) requires :body, :directory, :key if options != {} Fog::Logger.deprecation("options param is deprecated, use acl= instead [light_black](#{caller.first})[/]") end options['x-amz-acl'] ||= @acl if @acl options['Cache-Control'] = cache_control if cache_control options['Content-Disposition'] = content_disposition if content_disposition options['Content-Encoding'] = content_encoding if content_encoding options['Content-MD5'] = content_md5 if content_md5 options['Content-Type'] = content_type if content_type options['Expires'] = expires if expires options.merge!(metadata) options['x-amz-storage-class'] = storage_class if storage_class options['x-amz-server-side-encryption'] = encryption if encryption if multipart_chunk_size && body.respond_to?(:read) data = multipart_save(options) merge_attributes(data.body) else data = service.put_object(directory.key, key, body, options) merge_attributes(data.headers.reject {|key, value| ['Content-Length', 'Content-Type'].include?(key)}) end self.etag.gsub!('"','') self.content_length = Fog::Storage.get_body_size(body) self.content_type ||= Fog::Storage.get_content_type(body) true 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 # def url(expires, options = {}) requires :key collection.get_url(key, expires, options) end # File version if exists or creates new version. # @return [Fog::Storage::AWS::Version] # def versions @versions ||= begin Fog::Storage::AWS::Versions.new( :file => self, :service => service ) end end private def directory=(new_directory) @directory = new_directory end def multipart_save(options) # Initiate the upload res = service.initiate_multipart_upload(directory.key, key, options) upload_id = res.body["UploadId"] # Store ETags of upload parts part_tags = [] # Upload each part # TODO: optionally upload chunks in parallel using threads # (may cause network performance problems with many small chunks) # TODO: Support large chunk sizes without reading the chunk into memory body.rewind if body.respond_to?(:rewind) while (chunk = body.read(multipart_chunk_size)) do md5 = Base64.encode64(Digest::MD5.digest(chunk)).strip part_upload = service.upload_part(directory.key, key, upload_id, part_tags.size + 1, chunk, 'Content-MD5' => md5 ) part_tags << part_upload.headers["ETag"] end rescue # Abort the upload & reraise service.abort_multipart_upload(directory.key, key, upload_id) if upload_id raise else # Complete the upload service.complete_multipart_upload(directory.key, key, upload_id, part_tags) end end end end end fog-1.19.0/lib/fog/aws/models/storage/version.rb0000644000004100000410000000214212261242551021460 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Storage class AWS class Version < Fog::Model identity :version, :aliases => 'VersionId' attribute :key, :aliases => 'Key' attribute :last_modified, :aliases => ['Last-Modified', 'LastModified'] attribute :latest, :aliases => 'IsLatest', :type => :boolean attribute :content_length, :aliases => ['Content-Length', 'Size'], :type => :integer attribute :delete_marker, :type => :boolean def file @file ||= if collection.file collection.file.directory.files.get(key, 'versionId' => version) else collection.directory.files.get(key, 'versionId' => version) end end def destroy if collection.file collection.service.delete_object(collection.file.directory.key, key, 'versionId' => version) else collection.service.delete_object(collection.directory.key, key, 'versionId' => version) end end end end end end fog-1.19.0/lib/fog/aws/models/storage/versions.rb0000644000004100000410000000150012261242551021640 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/storage/version' module Fog module Storage class AWS class Versions < Fog::Collection attribute :file attribute :directory model Fog::Storage::AWS::Version def all(options = {}) data = if file service.get_bucket_object_versions(file.directory.key, options.merge('prefix' => file.key)).body['Versions'] else service.get_bucket_object_versions(directory.key, options).body['Versions'] end load(data) end def new(attributes = {}) version_type = attributes.keys.first model = super(attributes[version_type]) model.delete_marker = version_type == 'DeleteMarker' model end end end end end fog-1.19.0/lib/fog/aws/models/auto_scaling/0000755000004100000410000000000012261242551020453 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/models/auto_scaling/configuration.rb0000644000004100000410000000511012261242551023644 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class AutoScaling class Configuration < Fog::Model identity :id, :aliases => 'LaunchConfigurationName' attribute :arn, :aliases => 'LaunchConfigurationARN' attribute :associate_public_ip, :aliases => 'AssociatePublicIpAddress' attribute :block_device_mappings, :aliases => 'BlockDeviceMappings' attribute :created_at, :aliases => 'CreatedTime' attribute :iam_instance_profile, :aliases => 'IamInstanceProfile' attribute :image_id, :aliases => 'ImageId' #attribute :instance_monitoring, :aliases => 'InstanceMonitoring' attribute :instance_monitoring, :aliases => 'InstanceMonitoring', :squash => 'Enabled' attribute :instance_type, :aliases => 'InstanceType' attribute :kernel_id, :aliases => 'KernelId' attribute :key_name, :aliases => 'KeyName' attribute :ramdisk_id, :aliases => 'RamdiskId' attribute :security_groups, :aliases => 'SecurityGroups' attribute :user_data, :aliases => 'UserData' attribute :spot_price, :aliases => 'SpotPrice' def initialize(attributes={}) #attributes[:availability_zones] ||= %w(us-east-1a us-east-1b us-east-1c us-east-1d) #attributes['ListenerDescriptions'] ||= [{ # 'Listener' => {'LoadBalancerPort' => 80, 'InstancePort' => 80, 'Protocol' => 'http'}, # 'PolicyNames' => [] #}] #attributes['Policies'] ||= {'AppCookieStickinessPolicies' => [], 'LBCookieStickinessPolicies' => []} super end def ready? # AutoScaling requests are synchronous true end def save requires :id requires :image_id requires :instance_type options = Hash[self.class.aliases.map { |key, value| [key, send(value)] }] options.delete_if { |key, value| value.nil? } service.create_launch_configuration(image_id, instance_type, id, options) #, listeners.map{|l| l.to_params}) # reload instead of merge attributes b/c some attrs (like HealthCheck) # may be set, but only the DNS name is returned in the create_load_balance # API call reload end def reload super self end def destroy requires :id service.delete_launch_configuration(id) end end end end end fog-1.19.0/lib/fog/aws/models/auto_scaling/activities.rb0000644000004100000410000000203312261242551023142 0ustar www-datawww-datarequire 'fog/aws/models/auto_scaling/activity' module Fog module AWS class AutoScaling class Activities < Fog::Collection model Fog::AWS::AutoScaling::Activity attribute :filters # Creates a new scaling policy. def initialize(attributes={}) self.filters = attributes super(attributes) end def all(filters = filters) data = [] next_token = nil self.filters = filters loop do result = service.describe_scaling_activities(filters.merge('NextToken' => next_token)).body['DescribeScalingActivitiesResult'] data += result['Activities'] next_token = result['NextToken'] break if next_token.nil? end load(data) end def get(identity) data = service.describe_scaling_activities('ActivityId' => identity).body['DescribeScalingActivitiesResult']['Activities'].first new(data) unless data.nil? end end end end end fog-1.19.0/lib/fog/aws/models/auto_scaling/activity.rb0000644000004100000410000000164012261242551022635 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class AutoScaling class Activity < Fog::Model identity :id, :aliases => 'ActivityId' attribute :auto_scaling_group_name, :aliases => 'AutoScalingGroupName' attribute :cause, :aliases => 'Cause' attribute :description, :aliases => 'Description' attribute :end_time, :aliases => 'EndTime' attribute :progress, :aliases => 'Progress' attribute :start_time, :aliases => 'StartTime' attribute :status_code, :aliases => 'StatusCode' attribute :status_message, :aliases => 'StatusMessage' def group service.groups.get(attributes['AutoScalingGroupName']) end def save raise "Operation not supported" end end end end end fog-1.19.0/lib/fog/aws/models/auto_scaling/policy.rb0000644000004100000410000000304012261242551022274 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class AutoScaling class Policy < Fog::Model identity :id, :aliases => 'PolicyName' attribute :arn, :aliases => 'PolicyARN' attribute :adjustment_type, :aliases => 'AdjustmentType' attribute :alarms, :aliases => 'Alarms' attribute :auto_scaling_group_name, :aliases => 'AutoScalingGroupName' attribute :cooldown, :aliases => 'Cooldown' attribute :min_adjustment_step, :aliases => 'MinAdjustmentStep' attribute :scaling_adjustment, :aliases => 'ScalingAdjustment' def initialize(attributes) attributes['AdjustmentType'] ||= 'ChangeInCapacity' attributes['ScalingAdjustment'] ||= 1 super end # TODO: implement #alarms # TODO: implement #auto_scaling_group def save requires :id requires :adjustment_type requires :auto_scaling_group_name requires :scaling_adjustment options = Hash[self.class.aliases.map { |key, value| [key, send(value)] }] options.delete_if { |key, value| value.nil? } service.put_scaling_policy(adjustment_type, auto_scaling_group_name, id, scaling_adjustment, options) reload end def destroy requires :id requires :auto_scaling_group_name service.delete_policy(auto_scaling_group_name, id) end end end end end fog-1.19.0/lib/fog/aws/models/auto_scaling/instances.rb0000644000004100000410000000150412261242551022767 0ustar www-datawww-datarequire 'fog/aws/models/auto_scaling/instance' module Fog module AWS class AutoScaling class Instances < Fog::Collection model Fog::AWS::AutoScaling::Instance def all data = [] next_token = nil loop do result = service.describe_auto_scaling_instances('NextToken' => next_token).body['DescribeAutoScalingInstancesResult'] data += result['AutoScalingInstances'] next_token = result['NextToken'] break if next_token.nil? end load(data) end def get(identity) data = service.describe_auto_scaling_instances('InstanceIds' => identity).body['DescribeAutoScalingInstancesResult']['AutoScalingInstances'].first new(data) unless data.nil? end end end end end fog-1.19.0/lib/fog/aws/models/auto_scaling/group.rb0000644000004100000410000001231412261242551022135 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class AutoScaling class Group < Fog::Model identity :id, :aliases => 'AutoScalingGroupName' attribute :arn, :aliases => 'AutoScalingGroupARN' attribute :availability_zones, :aliases => 'AvailabilityZones' attribute :created_at, :aliases => 'CreatedTime' attribute :default_cooldown, :aliases => 'DefaultCooldown' attribute :desired_capacity, :aliases => 'DesiredCapacity' attribute :enabled_metrics, :aliases => 'EnabledMetrics' attribute :health_check_grace_period, :aliases => 'HealthCheckGracePeriod' attribute :health_check_type, :aliases => 'HealthCheckType' attribute :instances, :aliases => 'Instances' attribute :launch_configuration_name, :aliases => 'LaunchConfigurationName' attribute :load_balancer_names, :aliases => 'LoadBalancerNames' attribute :max_size, :aliases => 'MaxSize' attribute :min_size, :aliases => 'MinSize' attribute :placement_group, :aliases => 'PlacementGroup' attribute :suspended_processes, :aliases => 'SuspendedProcesses' attribute :tags, :aliases => 'Tags' attribute :termination_policies, :aliases => 'TerminationPolicies' attribute :vpc_zone_identifier, :aliases => 'VPCZoneIdentifier' def initialize(attributes={}) self.instances = [] self.default_cooldown = 300 self.desired_capacity = 0 self.enabled_metrics = [] self.health_check_grace_period = 0 self.health_check_type = 'EC2' self.load_balancer_names = [] self.max_size = 0 self.min_size = 0 self.suspended_processes = [] self.tags = {} self.termination_policies = ['Default'] super end def activities requires :id data = [] next_token = nil loop do result = service.describe_scaling_activities('AutoScalingGroupName' => id, 'NextToken' => next_token).body['DescribeScalingActivitiesResult'] data += result['Activities'] next_token = result['NextToken'] break if next_token.nil? end Fog::AWS::AutoScaling::Activities.new({ :data => data, :service => service, #:load_balancer => self }) end def configuration requires :launch_configuration_name service.configurations.get(launch_configuration_name) end def disable_metrics_collection(metrics = {}) requires :id service.disable_metrics_collection(id, 'Metrics' => metrics) reload end def enable_metrics_collection(granularity = '1Minute', metrics = {}) requires :id service.enable_metrics_collection(id, granularity, 'Metrics' => metrics) reload end def instances Fog::AWS::AutoScaling::Instances.new(:service => service).load(attributes[:instances]) end def instances_in_service attributes[:instances].select {|hash| hash['LifecycleState'] == 'InService'}.map {|hash| hash['InstanceId']} end def instances_out_service attributes[:instances].select {|hash| hash['LifecycleState'] == 'OutOfService'}.map {|hash| hash['InstanceId']} end def resume_processes(processes = []) requires :id service.resume_processes(id, 'ScalingProcesses' => processes) reload end def suspend_processes(processes = []) requires :id service.suspend_processes(id, 'ScalingProcesses' => processes) reload end def ready? # Is this useful? #instances_in_service.length == desired_capacity #instances_in_service.length >= min_size true end def save requires :id requires :availability_zones requires :launch_configuration_name requires :max_size requires :min_size service.create_auto_scaling_group(id, availability_zones, launch_configuration_name, max_size, min_size, filtered_options(:create_auto_scaling_group)) reload end #def reload # super # self #end def destroy(options = { :force => false }) requires :id opts = {} opts.merge!({'ForceDelete' => true}) if options[:force] service.delete_auto_scaling_group(id, opts) end def update requires :id service.update_auto_scaling_group(id, filtered_options(:update_auto_scaling_group) ) reload end def filtered_options(method) Hash[options.select{|k,_| ExpectedOptions[method].include?(k)}] end def options ret = Hash[self.class.aliases.map { |key, value| [key, send(value)] }] ret.delete_if { |key, value| value.nil? } ret end end end end end fog-1.19.0/lib/fog/aws/models/auto_scaling/configurations.rb0000644000004100000410000000170712261242551024037 0ustar www-datawww-datarequire 'fog/aws/models/auto_scaling/configuration' module Fog module AWS class AutoScaling class Configurations < Fog::Collection model Fog::AWS::AutoScaling::Configuration # Creates a new launch configuration def initialize(attributes={}) super end def all data = [] next_token = nil loop do result = service.describe_launch_configurations('NextToken' => next_token).body['DescribeLaunchConfigurationsResult'] data += result['LaunchConfigurations'] next_token = result['NextToken'] break if next_token.nil? end load(data) end def get(identity) data = service.describe_launch_configurations('LaunchConfigurationNames' => identity).body['DescribeLaunchConfigurationsResult']['LaunchConfigurations'].first new(data) unless data.nil? end end end end end fog-1.19.0/lib/fog/aws/models/auto_scaling/groups.rb0000644000004100000410000000204412261242551022317 0ustar www-datawww-datarequire 'fog/aws/models/auto_scaling/group' module Fog module AWS class AutoScaling class Groups < Fog::Collection model Fog::AWS::AutoScaling::Group attribute :filters # Creates a new auto scaling group. def initialize(attributes={}) self.filters = attributes super end def all(filters = filters) data = [] next_token = nil self.filters = filters loop do result = service.describe_auto_scaling_groups(filters.merge('NextToken' => next_token)).body['DescribeAutoScalingGroupsResult'] data += result['AutoScalingGroups'] next_token = result['NextToken'] break if next_token.nil? end load(data) end def get(identity) data = service.describe_auto_scaling_groups('AutoScalingGroupNames' => identity).body['DescribeAutoScalingGroupsResult']['AutoScalingGroups'].first new(data) unless data.nil? end end end end end fog-1.19.0/lib/fog/aws/models/auto_scaling/policies.rb0000644000004100000410000000210112261242551022601 0ustar www-datawww-datarequire 'fog/aws/models/auto_scaling/policy' module Fog module AWS class AutoScaling class Policies < Fog::Collection model Fog::AWS::AutoScaling::Policy attribute :filters # Creates a new scaling policy. def initialize(attributes={}) self.filters = attributes super(attributes) end def all(filters = filters) data = [] next_token = nil self.filters = filters loop do result = service.describe_policies(filters.merge('NextToken' => next_token)).body['DescribePoliciesResult'] data += result['ScalingPolicies'] next_token = result['NextToken'] break if next_token.nil? end load(data) end def get(identity, auto_scaling_group = nil) data = service.describe_policies('PolicyNames' => identity, 'AutoScalingGroupName' => auto_scaling_group).body['DescribePoliciesResult']['ScalingPolicies'].first new(data) unless data.nil? end end end end end fog-1.19.0/lib/fog/aws/models/auto_scaling/instance.rb0000644000004100000410000000303512261242551022605 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class AutoScaling class Instance < Fog::Model identity :id, :aliases => 'InstanceId' attribute :auto_scaling_group_name, :aliases => 'AutoScalingGroupName' attribute :availability_zone, :aliases => 'AvailabilityZone' attribute :health_status, :aliases => 'HealthStatus' attribute :launch_configuration_name, :aliases => 'LaunchConfigurationName' attribute :life_cycle_state, :aliases => 'LifecycleState' def initialize(attributes={}) super end def group service.groups.get(attributes['AutoScalingGroupName']) end def configuration service.configurations.get(attributes['LaunchConfigurationName']) end def set_health(health_status, options) requires :id service.set_instance_health(health_status, id, options) reload end def terminate(should_decrement_desired_capacity) requires :id service.terminate_instance_in_auto_scaling_group(id, should_decrement_desired_capacity) reload end def healthy? health_status == 'HEALTHY' end def ready? life_cycle_state == 'InService' end def reload super self end #def destroy # requires :id # service.delete_auto_scaling_group(id) #end end end end end fog-1.19.0/lib/fog/aws/models/beanstalk/0000755000004100000410000000000012261242551017747 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/models/beanstalk/application.rb0000644000004100000410000000275312261242551022606 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class ElasticBeanstalk class Application < Fog::Model identity :name, :aliases => 'ApplicationName' attribute :template_names, :aliases => 'ConfigurationTemplates' attribute :created_at, :aliases => 'DateCreated' attribute :updated_at, :aliases => 'DateUpdated' attribute :description, :aliases => 'Description' attribute :version_names, :aliases => 'Versions' def initialize(attributes={}) super end def environments requires :name service.environments.all({'ApplicationName' => name}) end def events requires :name service.events.all({'ApplicationName' => name}) end def templates requires :name service.templates.all({'ApplicationName' => name}) end def versions requires :name service.versions.all({'ApplicationName' => name}) end def destroy requires :name service.delete_application(name) true end def save requires :name options = { 'ApplicationName' => name } options['Description'] = description unless description.nil? data = service.create_application(options).body['CreateApplicationResult']['Application'] merge_attributes(data) true end end end end end fog-1.19.0/lib/fog/aws/models/beanstalk/environments.rb0000644000004100000410000000141712261242551023026 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/beanstalk/environment' module Fog module AWS class ElasticBeanstalk class Environments < Fog::Collection model Fog::AWS::ElasticBeanstalk::Environment def all(options={}) data = service.describe_environments(options).body['DescribeEnvironmentsResult']['Environments'] load(data) # data is an array of attribute hashes end # Gets an environment given a name. # def get(environment_name) options = { 'EnvironmentNames' => [environment_name] } if data = service.describe_environments(options).body['DescribeEnvironmentsResult']['Environments'].first new(data) end end end end end end fog-1.19.0/lib/fog/aws/models/beanstalk/event.rb0000644000004100000410000000112712261242551021416 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class ElasticBeanstalk class Event < Fog::Model attribute :application_name, :aliases => 'ApplicationName' attribute :environment_name, :aliases => 'EnvironmentName' attribute :date, :aliases => 'EventDate' attribute :message, :aliases => 'Message' attribute :request_id, :aliases => 'RequestId' attribute :severity, :aliases => 'Severity' attribute :template_name, :aliases => 'TemplateName' attribute :version_label, :aliases => 'VersionLabel' end end end endfog-1.19.0/lib/fog/aws/models/beanstalk/version.rb0000644000004100000410000000514512261242551021766 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class ElasticBeanstalk class Version < Fog::Model attribute :label, :aliases => 'VersionLabel' attribute :application_name, :aliases => 'ApplicationName' attribute :created_at, :aliases => 'DateCreated' attribute :updated_at, :aliases => 'DateUpdated' attribute :description, :aliases => 'Description' attribute :source_bundle, :aliases => 'SourceBundle' attribute :auto_create_application # FIXME - should be write only def initialize(attributes={}) super end # Return events related to this version def events requires :label, :application_name service.events.all({ 'ApplicationName' => application_name, 'VersionLabel' => label }) end # Returns environments running this version def environments requires :label, :application_name service.environments.all({ 'ApplicationName' => application_name, 'VersionLabel' => label }) end def destroy(delete_source_bundle = nil) requires :label, :application_name service.delete_application_version(application_name, label, delete_source_bundle) true end def save requires :label, :application_name options = { 'ApplicationName' => application_name, 'AutoCreateApplication' => auto_create_application, 'Description' => description, 'SourceBundle' => source_bundle, 'VersionLabel' => label } options.delete_if {|key, value| value.nil?} data = service.create_application_version(options).body['CreateApplicationVersionResult']['ApplicationVersion'] merge_attributes(data) true end # Updates the version label with the current property values. Currently only updates description def update requires :label, :application_name options = { 'ApplicationName' => application_name, 'Description' => description, 'VersionLabel' => label } options.delete_if {|key, value| value.nil?} data = service.update_application_version(options).body['UpdateApplicationVersionResult']['ApplicationVersion'] merge_attributes(data) end end end end end fog-1.19.0/lib/fog/aws/models/beanstalk/environment.rb0000644000004100000410000001154512261242551022646 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class ElasticBeanstalk class Environment < Fog::Model identity :name, :aliases => 'EnvironmentName' attribute :id, :aliases => 'EnvironmentId' attribute :application_name, :aliases => 'ApplicationName' attribute :cname, :aliases => 'CNAME' attribute :cname_prefix, :aliases => 'CNAMEPrefix' attribute :created_at, :aliases => 'DateCreated' attribute :updated_at, :aliases => 'DateUpdated' attribute :updated_at, :aliases => 'DateUpdated' attribute :description, :aliases => 'Description' attribute :endpoint_url, :aliases => 'EndpointURL' attribute :health, :aliases => 'Health' attribute :resources, :aliases => 'Resources' attribute :solution_stack_name, :aliases => 'SolutionStackName' attribute :status, :aliases => 'Status' attribute :template_name, :aliases => 'TemplateName' attribute :version_label, :aliases => 'VersionLabel' attribute :option_settings, :aliases => 'OptionSettings' attribute :options_to_remove, :aliases => 'OptionsToRemove' def healthy? health == 'Green' end def ready? status == 'Ready' end def terminated? status == 'Terminated' end # Returns the current live resources for this environment def live_resources requires :id data = service.describe_environment_resources({'EnvironmentId' => id}).body['DescribeEnvironmentResourcesResult']['EnvironmentResources'] data.delete('EnvironmentName') # Delete the environment name from the result, only return actual resources data end # Returns the load balancer object associated with the environment. def load_balancer(elb_connection = Fog::AWS[:elb]) if resources.nil? elb_connection.load_balancers.get(live_resources['LoadBalancers'].first['Name']) else elb_connection.load_balancers.get(resources['LoadBalancer']['LoadBalancerName']) end end # Return events related to this version def events requires :id service.events.all({'EnvironmentId' => id}) end # Restarts the app servers in this environment def restart_app_server requires :id service.restart_app_server({'EnvironmentId' => id}) reload end # Rebuilds the environment def rebuild requires :id service.rebuild_environment({'EnvironmentId' => id}) reload end def swap_cnames(source) requires :name service.swap_environment_cnames({ 'SourceEnvironmentName' => source.name, 'DestinationEnvironmentName' => name }) source.reload reload end # Return the version object for this environment def version requires :application_name, :version_label service.versions.get(application_name, version_label) end # Update the running version of this environment def version=(new_version) requires :id if new_version.is_a?(String) new_version_label = new_version elsif new_version.is_a?(Fog::AWS::ElasticBeanstalk::Version) new_version_label = new_version.label else raise "Unknown type for new_version, must be either String or Fog::AWS::ElasticBeanstalk::Version" end if new_version.nil? raise "Version label not specified." end data = service.update_environment({ 'EnvironmentId' => id, 'VersionLabel' => new_version_label }).body['UpdateEnvironmentResult'] merge_attributes(data) end def destroy requires :id service.terminate_environment({'EnvironmentId' => id}) true end def save requires :name, :application_name requires_one :template_name, :solution_stack_name options = { 'ApplicationName' => application_name, 'CNAMEPrefix' => cname_prefix, 'Description' => description, 'EnvironmentName' => name, 'OptionSettings' => option_settings, 'OptionsToRemove' => options_to_remove, 'SolutionStackName' => solution_stack_name, 'TemplateName' => template_name, 'VersionLabel' => version_label } options.delete_if {|key, value| value.nil?} data = service.create_environment(options).body['CreateEnvironmentResult'] merge_attributes(data) true end end end end end fog-1.19.0/lib/fog/aws/models/beanstalk/events.rb0000644000004100000410000000065412261242551021605 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/beanstalk/event' module Fog module AWS class ElasticBeanstalk class Events < Fog::Collection model Fog::AWS::ElasticBeanstalk::Event def all(options={}) data = service.describe_events(options).body['DescribeEventsResult']['Events'] load(data) # data is an array of attribute hashes end end end end end fog-1.19.0/lib/fog/aws/models/beanstalk/applications.rb0000644000004100000410000000126612261242551022767 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/beanstalk/application' module Fog module AWS class ElasticBeanstalk class Applications < Fog::Collection model Fog::AWS::ElasticBeanstalk::Application def all(application_names=[]) data = service.describe_applications(application_names).body['DescribeApplicationsResult']['Applications'] load(data) # data is an array of attribute hashes end def get(application_name) if data = service.describe_applications([application_name]).body['DescribeApplicationsResult']['Applications'].first new(data) end end end end end end fog-1.19.0/lib/fog/aws/models/beanstalk/templates.rb0000644000004100000410000000466412261242551022304 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/beanstalk/template' module Fog module AWS class ElasticBeanstalk class Templates < Fog::Collection model Fog::AWS::ElasticBeanstalk::Template # Describes all configuration templates, may optionally pass an ApplicationName filter # # Note: This is currently an expensive operation requiring multiple API calls due to a lack of # a describe configuration templates call in the AWS API. def all(options={}) application_filter = [] if options.has_key?('ApplicationName') application_filter << options['ApplicationName'] end # Initialize with empty array data = [] applications = service.describe_applications(application_filter).body['DescribeApplicationsResult']['Applications'] applications.each { |application| application['ConfigurationTemplates'].each { |template_name| begin options = { 'ApplicationName' => application['ApplicationName'], 'TemplateName' => template_name } settings = service.describe_configuration_settings(options).body['DescribeConfigurationSettingsResult']['ConfigurationSettings'] if settings.length == 1 # Add to data data << settings.first end rescue Fog::AWS::ElasticBeanstalk::InvalidParameterError # Ignore end } } load(data) # data is an array of attribute hashes end def get(application_name, template_name) options = { 'ApplicationName' => application_name, 'TemplateName' => template_name } result = nil # There is no describe call for templates, so we must use describe_configuration_settings. Unfortunately, # it throws an exception if template name doesn't exist, which is inconsistent, catch and return nil begin data = service.describe_configuration_settings(options).body['DescribeConfigurationSettingsResult']['ConfigurationSettings'] if data.length == 1 result = new(data.first) end rescue Fog::AWS::ElasticBeanstalk::InvalidParameterError end result end end end end end fog-1.19.0/lib/fog/aws/models/beanstalk/versions.rb0000644000004100000410000000177612261242551022157 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/beanstalk/version' module Fog module AWS class ElasticBeanstalk class Versions < Fog::Collection model Fog::AWS::ElasticBeanstalk::Version def all(options={}) data = service.describe_application_versions(options).body['DescribeApplicationVersionsResult']['ApplicationVersions'] load(data) # data is an array of attribute hashes end def get(application_name, version_label) if data = service.describe_application_versions({ 'ApplicationName' => application_name, 'VersionLabels' => [version_label] }).body['DescribeApplicationVersionsResult']['ApplicationVersions'] if data.length == 1 new(data.first) end end end end end end end fog-1.19.0/lib/fog/aws/models/beanstalk/template.rb0000644000004100000410000000514012261242551022107 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class ElasticBeanstalk class Template < Fog::Model attribute :name, :aliases => 'TemplateName' attribute :application_name, :aliases => 'ApplicationName' attribute :created_at, :aliases => 'DateCreated' attribute :updated_at, :aliases => 'DateUpdated' attribute :deployment_status, :aliases => 'DeploymentStatus' attribute :description, :aliases => 'Description' attribute :environment_id attribute :environment_name, :aliases => 'EnvironmentName' attribute :solution_stack_name, :aliases => 'SolutionStackName' attribute :source_configuration attribute :option_settings, :aliases => 'OptionSettings' def initialize(attributes={}) super end # Returns an array of options that may be set on this template def options requires :name, :application_name data = service.describe_configuration_options({ 'ApplicationName' => application_name, 'TemplateName' => name }) data.body['DescribeConfigurationOptionsResult']['Options'] end def destroy requires :name, :application_name service.delete_configuration_template(application_name, name) true end def save requires :name, :application_name options = { 'ApplicationName' => application_name, 'Description' => description, 'EnvironmentId' => environment_id, 'OptionSettings' => option_settings, 'SolutionStackName' => solution_stack_name, 'SourceConfiguration' => source_configuration, 'TemplateName' => name } options.delete_if {|key, value| value.nil?} data = service.create_configuration_template(options).body['CreateConfigurationTemplateResult'] merge_attributes(data) true end def modify(new_attributes) requires :name, :application_name options = { 'ApplicationName' => application_name, 'Description' => new_attributes[:description], 'OptionSettings' => new_attributes[:option_settings], 'TemplateName' => name } options.delete_if {|key, value| value.nil?} data = service.update_configuration_template(options).body['UpdateConfigurationTemplateResult'] merge_attributes(data) true end end end end end fog-1.19.0/lib/fog/aws/models/cloud_watch/0000755000004100000410000000000012261242551020277 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/models/cloud_watch/metric_statistics.rb0000644000004100000410000000155612261242551024370 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/cloud_watch/metric_statistic' module Fog module AWS class CloudWatch class MetricStatistics < Fog::Collection model Fog::AWS::CloudWatch::MetricStatistic def all(conditions) metricName = conditions['MetricName'] namespace = conditions['Namespace'] dimensions = conditions['Dimensions'] get_metric_opts = {"StartTime" => (Time.now-3600).iso8601, "EndTime" => Time.now.iso8601, "Period" => 300}.merge(conditions) data = service.get_metric_statistics(get_metric_opts).body['GetMetricStatisticsResult']['Datapoints'] data.collect! { |datum| datum.merge('MetricName' => metricName, 'Namespace' => namespace, 'Dimensions' => dimensions) } load(data) # data is an array of attribute hashes end end end end end fog-1.19.0/lib/fog/aws/models/cloud_watch/alarms.rb0000644000004100000410000000222212261242551022101 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/cloud_watch/alarm' module Fog module AWS class CloudWatch class Alarms < Fog::Collection model Fog::AWS::CloudWatch::Alarm def all data = [] next_token = nil loop do body = service.describe_alarms('NextToken' => next_token).body data += body['DescribeAlarmsResult']['MetricAlarms'] next_token = body['ResponseMetadata']['NextToken'] break if next_token.nil? end load(data) end def get(identity) data = service.describe_alarms('AlarmNames' => identity).body['DescribeAlarmsResult']['MetricAlarms'].first new(data) unless data.nil? end #alarm_names is an array of alarm names def delete(alarm_names) service.delete_alarms(alarm_names) true end def disable(alarm_names) service.disable_alarm_actions(alarm_names) true end def enable(alarm_names) service.enable_alarm_actions(alarm_names) true end end end end end fog-1.19.0/lib/fog/aws/models/cloud_watch/alarm_datum.rb0000644000004100000410000000546712261242551023126 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class CloudWatch class AlarmDatum < Fog::Model attribute :alarm_name, :aliases => 'AlarmName' attribute :metric_name, :aliases => 'MetricName' attribute :namespace, :aliases => 'Namespace' attribute :dimensions, :aliases => 'Dimensions' attribute :alarm_description, :aliases => 'AlarmDescription' attribute :alarm_arn, :aliases => 'AlarmArn' attribute :state_value, :aliases => 'StateValue' attribute :statistic, :aliases => 'Statistic' attribute :comparison_operator, :aliases => 'ComparisonOperator' attribute :state_reason, :aliases => 'StateReason' attribute :action_enabled, :aliases => 'ActionsEnabled' attribute :period, :aliases => 'Period' attribute :evaluation_periods, :aliases => 'EvaluationPeriods' attribute :threshold, :aliases => 'Threshold' attribute :alarm_actions, :aliases => 'AlarmActions' attribute :ok_actions, :aliases => 'OKActions' attribute :insufficient_actions, :aliases => 'InsufficientDataActions' attribute :unit, :aliases => 'Unit' attribute :state_updated_timestamp, :aliases => 'StateUpdatedTimestamp' attribute :alarm_configuration_updated_timestamp, :aliases => 'AlarmConfigurationUpdatedTimestamp' def save requires :alarm_name requires :comparison_operator requires :evaluation_periods requires :metric_name requires :namespace requires :period requires :statistic requires :threshold alarm_definition = { 'AlarmName' => alarm_name, 'ComparisonOperator' => comparison_operator, 'EvaluationPeriods' => evaluation_periods, 'MetricName' => metric_name, 'Namespace' => namespace, 'Period' => period, 'Statistic' => statistic, 'Threshold' => threshold } alarm_definition.merge!('ActionsEnabled' => action_enabled) if action_enabled alarm_definition.merge!('AlarmActions' => alarm_actions) if alarm_actions alarm_definition.merge!('AlarmDescription' => alarm_description) if alarm_description #dimension is an array of Name/Value pairs, ex. [{'Name'=>'host', 'Value'=>'localhost'},{'Name'=>'version', 'Value'=>'0.11.0'}] alarm_definition.merge!('Dimensions' => dimensions) if dimensions alarm_definition.merge!('InsufficientDataActions' => insufficient_actions) if insufficient_actions alarm_definition.merge!('OKActions' => ok_actions) if ok_actions alarm_definition.merge!('Unit' => unit) if unit service.put_metric_alarm(alarm_definition) true end end end end end fog-1.19.0/lib/fog/aws/models/cloud_watch/alarm_history.rb0000644000004100000410000000065012261242551023502 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class CloudWatch class AlarmHistory < Fog::Model attribute :alarm_name, :aliases => 'AlarmName' attribute :end_date, :aliases => 'EndDate' attribute :history_item_type, :aliases => 'HistoryItemType' attribute :max_records, :aliases => 'MaxRecords' attribute :start_date, :aliases => 'StartDate' end end end end fog-1.19.0/lib/fog/aws/models/cloud_watch/metric.rb0000644000004100000410000000044312261242551022110 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class CloudWatch class Metric < Fog::Model attribute :name, :aliases => 'MetricName' attribute :namespace, :aliases => 'Namespace' attribute :dimensions, :aliases => 'Dimensions' end end end endfog-1.19.0/lib/fog/aws/models/cloud_watch/metric_statistic.rb0000644000004100000410000000256112261242551024202 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class CloudWatch class MetricStatistic < Fog::Model attribute :label, :aliases => 'Label' attribute :minimum, :aliases => 'Minimum' attribute :maximum, :aliases => 'Maximum' attribute :sum, :aliases => 'Sum' attribute :average, :aliases => 'Average' attribute :sample_count, :aliases => 'SampleCount' attribute :timestamp, :aliases => 'Timestamp' attribute :unit, :aliases => 'Unit' attribute :metric_name, :aliases => 'MetricName' attribute :namespace, :aliases => 'Namespace' attribute :dimensions, :aliases => 'Dimensions' attribute :value def save requires :metric_name requires :namespace requires :unit put_opts = {'MetricName' => metric_name, 'Unit' => unit} put_opts.merge!('Dimensions' => dimensions) if dimensions if value put_opts.merge!('Value' => value) else put_opts.merge!('StatisticValues' => { 'Minimum' => minimum, 'Maximum' => maximum, 'Sum' => sum, 'Average' => average, 'SampleCount' => sample_count }) end service.put_metric_data(namespace, [put_opts]) true end end end end end fog-1.19.0/lib/fog/aws/models/cloud_watch/metrics.rb0000644000004100000410000000271412261242551022276 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/cloud_watch/metric' module Fog module AWS class CloudWatch class Metrics < Fog::Collection attribute :next_token, :aliases => 'NextToken' model Fog::AWS::CloudWatch::Metric def all(conditions={}) result = service.list_metrics(conditions).body['ListMetricsResult'] merge_attributes("NextToken" => result["NextToken"]) load(result['Metrics']) # an array of attribute hashes end alias :each_metric_this_page :each def each if !block_given? self else subset = dup.all subset.each_metric_this_page {|m| yield m } while next_token = subset.next_token subset = subset.all("NextToken" => next_token) subset.each_metric_this_page {|m| yield m } end self end end def get(namespace, metric_name, dimensions=nil) list_opts = {'Namespace' => namespace, 'MetricName' => metric_name} if dimensions dimensions_array = dimensions.collect do |name, value| {'Name' => name, 'Value' => value} end # list_opts.merge!('Dimensions' => dimensions_array) end if data = service.list_metrics(list_opts).body['ListMetricsResult']['Metrics'].first new(data) end end end end end end fog-1.19.0/lib/fog/aws/models/cloud_watch/alarm_data.rb0000644000004100000410000000234012261242551022710 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/cloud_watch/alarm_datum' module Fog module AWS class CloudWatch class AlarmData < Fog::Collection model Fog::AWS::CloudWatch::AlarmDatum def all(conditions={}) data = service.describe_alarms(conditions).body['DescribeAlarmsResult']['MetricAlarms'] load(data) # data is an array of attribute hashes end def get(namespace, metric_name, dimensions=nil, period=nil, statistic=nil, unit=nil) list_opts = {'Namespace' => namespace, 'MetricName' => metric_name} if dimensions dimensions_array = dimensions.collect do |name, value| {'Name' => name, 'Value' => value} end list_opts.merge!('Dimensions' => dimensions_array) end if period list_opts.merge!('Period' => period) end if statistic list_opts.merge!('Statistic' => statistic) end if unit list_opts.merge!('Unit' => unit) end data = service.describe_alarms_for_metric(list_opts).body['DescribeAlarmsForMetricResult']['MetricAlarms'] load(data) end end end end end fog-1.19.0/lib/fog/aws/models/cloud_watch/alarm_histories.rb0000644000004100000410000000072612261242551024016 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/cloud_watch/alarm_history' module Fog module AWS class CloudWatch class AlarmHistories < Fog::Collection model Fog::AWS::CloudWatch::AlarmHistory def all(conditions={}) data = service.describe_alarm_history(conditions).body['DescribeAlarmHistoryResult']['AlarmHistoryItems'] load(data) # data is an array of attribute hashes end end end end end fog-1.19.0/lib/fog/aws/models/cloud_watch/alarm.rb0000644000004100000410000000421112261242551021716 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class CloudWatch class Alarm < Fog::Model identity :id, :aliases => 'AlarmName' attribute :actions_enabled, :aliases => 'ActionsEnabled' attribute :alarm_actions, :aliases => 'AlarmActions' attribute :arn, :aliases => 'AlarmArn' attribute :alarm_configuration_updated_timestamp, :aliases => 'AlarmConfigurationUpdatedTimestamp' attribute :alarm_description, :aliases => 'AlarmDescription' attribute :comparison_operator, :aliases => 'ComparisonOperator' attribute :dimensions, :aliases => 'Dimensions' attribute :evaluation_periods, :aliases => 'EvaluationPeriods' attribute :insufficient_data_actions, :aliases => 'InsufficientDataActions' attribute :metric_name, :aliases => 'MetricName' attribute :namespace, :aliases => 'Namespace' attribute :ok_actions, :aliases => 'OKActions' attribute :period, :aliases => 'Period' attribute :state_reason, :aliases => 'StateReason' attribute :state_reason_data, :aliases => 'StateReasonData' attribute :state_updated_timestamp, :aliases => 'StateUpdatedTimestamp' attribute :state_value, :aliases => 'StateValue' attribute :statistic, :aliases => 'Statistic' attribute :threshold, :aliases => 'Threshold' attribute :unit, :aliases => 'Unit' def initialize(attributes) attributes['EvaluationPeriods'] ||= 1 attributes['Namespace'] ||= 'AWS/EC2' super end def save requires :id requires :comparison_operator requires :evaluation_periods requires :metric_name requires :namespace requires :period requires :statistic requires :threshold options = Hash[self.class.aliases.map { |key, value| [key, send(value)] }] options.delete_if { |key, value| value.nil? } service.put_metric_alarm(options) reload end def destroy requires :id service.delete_alarms(id) end end end end end fog-1.19.0/lib/fog/aws/models/glacier/0000755000004100000410000000000012261242551017411 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/models/glacier/job.rb0000644000004100000410000000424012261242551020510 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class Glacier class Job < Fog::Model ARCHIVE = 'archive-retrieval' INVENTORY = 'inventory-retrieval' identity :id, :aliases => "JobId" attribute :action, :aliases => "Action" attribute :archive_id, :aliases => "ArchiveId" attribute :archive_size, :aliases => "ArchiveSizeInBytes", :type => :integer attribute :completed, :aliases => "Completed", :type => :boolean attribute :completed_at, :aliases => "CompletionDate", :type => :time attribute :created_at, :aliases => "CreationDate", :type => :time attribute :inventory_size, :aliases => "InventorySizeInBytes", :type => :integer attribute :description, :aliases=> "JobDescription" attribute :tree_hash, :aliases=> "SHA256TreeHash" attribute :sns_topic, :aliases => "SNSTopic" attribute :status_code, :aliases=> "StatusCode" attribute :status_message, :aliases=> "StatusMessage" attribute :vault_arn, :aliases=> "VaultARN" attribute :format attribute :type def ready? completed end def save requires :vault, :type specification = {'Type' => type, 'ArchiveId' => archive_id, 'Format' => format, 'Description' => description, 'SNSTopic' => sns_topic}.reject{|k,v| v.nil?} data = service.initiate_job(vault.id, specification) self.id = data.headers['x-amz-job-id'] reload end def vault @vault end #pass :range => 1..1234 to only retrieve those bytes #pass :io => f to stream the response to that tio def get_output(options={}) if io = options.delete(:io) options = options.merge :response_block => lambda {|chunk, remaining_bytes, total_bytes| io.write chunk} end options['Range'] = options.delete :range service.get_job_output(vault.id, id, options) end private def vault=(new_vault) @vault = new_vault end end end end end fog-1.19.0/lib/fog/aws/models/glacier/vaults.rb0000644000004100000410000000074212261242551021257 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/glacier/vault' module Fog module AWS class Glacier class Vaults < Fog::Collection model Fog::AWS::Glacier::Vault def all data = service.list_vaults.body['VaultList'] load(data) end def get(key) data = service.describe_vault(key).body new(data) rescue Excon::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/aws/models/glacier/archives.rb0000644000004100000410000000101412261242551021536 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/glacier/archive' module Fog module AWS class Glacier class Archives < Fog::Collection model Fog::AWS::Glacier::Archive attribute :vault #you can't list a vault's archives def all nil end def get(key) new(:id => key) end def new(attributes = {}) requires :vault super({ :vault => vault }.merge!(attributes)) end end end end end fog-1.19.0/lib/fog/aws/models/glacier/archive.rb0000644000004100000410000000342212261242551021360 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class Glacier class Archive < Fog::Model identity :id attribute :description attribute :body attr_accessor :multipart_chunk_size #must be a power of 2 multiple of 1MB def vault @vault end def save requires :body, :vault if multipart_chunk_size && body.respond_to?(:read) self.id = multipart_save else data = service.create_archive(vault.id, body, 'description' => description) self.id = data.headers['x-amz-archive-id'] end true end def destroy requires :id service.delete_archive(vault.id,id) end private def vault=(new_vault) @vault = new_vault end def multipart_save # Initiate the upload res = service.initiate_multipart_upload vault.id, multipart_chunk_size, 'description' => description upload_id = res.headers["x-amz-multipart-upload-id"] hash = Fog::AWS::Glacier::TreeHash.new body.rewind if body.respond_to?(:rewind) offset = 0 while (chunk = body.read(multipart_chunk_size)) do part_hash = hash.add_part(chunk) part_upload = service.upload_part(vault.id, upload_id, chunk, offset, part_hash ) offset += chunk.bytesize end rescue # Abort the upload & reraise service.abort_multipart_upload(vault.id, upload_id) if upload_id raise else # Complete the upload service.complete_multipart_upload(vault.id, upload_id, offset, hash.hexdigest).headers['x-amz-archive-id'] end end end end end fog-1.19.0/lib/fog/aws/models/glacier/jobs.rb0000644000004100000410000000166612261242551020704 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/glacier/job' module Fog module AWS class Glacier class Jobs < Fog::Collection model Fog::AWS::Glacier::Job attribute :vault attribute :filters def initialize(attributes) self.filters = {} super end # acceptable filters are: # statuscode InProgress/Failed/Succeeded # completed (true/false) def all(filters = self.filters) self.filters = filters data = service.list_jobs(vault.id, self.filters).body['JobList'] load(data) end def get(key) data = service.describe_job(vault.id, key).body new(data) rescue Excon::Errors::NotFound nil end def new(attributes = {}) requires :vault super({ :vault => vault }.merge!(attributes)) end end end end end fog-1.19.0/lib/fog/aws/models/glacier/vault.rb0000644000004100000410000000275212261242551021077 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/aws/models/glacier/archives' require 'fog/aws/models/glacier/jobs' module Fog module AWS class Glacier class Vault < Fog::Model identity :id, :aliases => 'VaultName' attribute :created_at, :aliases => 'CreationDate', :type => :time attribute :last_inventory_at, :aliases => 'LastInventoryDate', :type => :time attribute :number_of_archives, :aliases => 'NumberOfArchives', :type => :integer attribute :size_in_bytes, :aliases => 'SizeInBytes', :type => :integer attribute :arn, :aliases => 'VaultARN' def ready? # Glacier requests are synchronous true end def archives @archives ||= Fog::AWS::Glacier::Archives.new(:vault => self, :service => service) end def jobs(filters={}) Fog::AWS::Glacier::Jobs.new(:vault => self, :service => service, :filters => filters) end def set_notification_configuration(topic, events) service.set_vault_notification_configuration(id, topic, events) end def delete_notification_configuration service.delete_vault_notification_configuration(id) end def save requires :id service.create_vault(id) reload end def destroy requires :id service.delete_vault(id) end end end end end fog-1.19.0/lib/fog/aws/models/dns/0000755000004100000410000000000012261242551016567 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/models/dns/zones.rb0000644000004100000410000000127112261242551020253 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/dns/zone' module Fog module DNS class AWS class Zones < Fog::Collection attribute :marker, :aliases => 'Marker' attribute :max_items, :aliases => 'MaxItems' model Fog::DNS::AWS::Zone def all(options = {}) options['marker'] ||= marker options['maxitems'] ||= max_items data = service.list_hosted_zones(options).body['HostedZones'] load(data) end def get(zone_id) data = service.get_hosted_zone(zone_id).body new(data) rescue Excon::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/aws/models/dns/record.rb0000644000004100000410000000574612261242551020406 0ustar www-datawww-datarequire 'fog/core/model' module Fog module DNS class AWS class Record < Fog::Model extend Fog::Deprecation deprecate :ip, :value deprecate :ip=, :value= identity :name, :aliases => ['Name'] attribute :value, :aliases => ['ResourceRecords'] attribute :ttl, :aliases => ['TTL'] attribute :type, :aliases => ['Type'] attribute :status, :aliases => ['Status'] attribute :created_at, :aliases => ['SubmittedAt'] attribute :alias_target, :aliases => ['AliasTarget'] attribute :change_id, :aliases => ['Id'] attribute :region, :aliases => ['Region'] attribute :weight, :aliases => ['Weight'] attribute :set_identifier,:aliases => ['SetIdentifier'] def initialize(attributes={}) super end def destroy options = attributes_to_options('DELETE') service.change_resource_record_sets(zone.id, [options]) true end def zone @zone end def save self.ttl ||= 3600 options = attributes_to_options('CREATE') data = service.change_resource_record_sets(zone.id, [options]).body merge_attributes(data) true end def modify(new_attributes) options = [] # Delete the current attributes options << attributes_to_options('DELETE') # Create the new attributes merge_attributes(new_attributes) options << attributes_to_options('CREATE') data = service.change_resource_record_sets(zone.id, options).body merge_attributes(data) true end # Returns true if record is insync. May only be called for newly created or modified records that # have a change_id and status set. def ready? requires :change_id, :status status == 'INSYNC' end def reload # If we have a change_id (newly created or modified), then reload performs a get_change to update status. if change_id data = service.get_change(change_id).body merge_attributes(data) self else super end end private def zone=(new_zone) @zone = new_zone end def attributes_to_options(action) requires :name, :ttl, :type, :zone requires_one :value, :alias_target { :action => action, :name => name, :resource_records => [*value], :alias_target => symbolize_keys(alias_target), :ttl => ttl, :type => type, :weight => weight, :set_identifier => set_identifier, :region => region } end end end end end fog-1.19.0/lib/fog/aws/models/dns/zone.rb0000644000004100000410000000244112261242551020070 0ustar www-datawww-datarequire 'fog/core/model' # require 'fog/aws/models/dns/records' module Fog module DNS class AWS class Zone < Fog::Model identity :id, :aliases => 'Id' attribute :caller_reference, :aliases => 'CallerReference' attribute :change_info, :aliases => 'ChangeInfo' attribute :description, :aliases => 'Comment' attribute :domain, :aliases => 'Name' attribute :nameservers, :aliases => 'NameServers' def destroy requires :identity service.delete_hosted_zone(identity) true end def records @records ||= begin Fog::DNS::AWS::Records.new( :zone => self, :service => service ) end end def save requires :domain options = {} options[:caller_ref] = caller_reference if caller_reference options[:comment] = description if description data = service.create_hosted_zone(domain, options).body merge_attributes(data) true end private define_method(:HostedZone=) do |new_hosted_zone| merge_attributes(new_hosted_zone) end end end end end fog-1.19.0/lib/fog/aws/models/dns/records.rb0000644000004100000410000001057312261242551020563 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/dns/record' module Fog module DNS class AWS class Records < Fog::Collection attribute :is_truncated, :aliases => ['IsTruncated'] attribute :max_items, :aliases => ['MaxItems'] attribute :name attribute :next_record_name, :aliases => ['NextRecordName'] attribute :next_record_type, :aliases => ['NextRecordType'] attribute :next_record_identifier, :aliases => ['NextRecordIdentifier'] attribute :type attribute :identifier attribute :zone model Fog::DNS::AWS::Record def all(options = {}) requires :zone options[:max_items] ||= max_items options[:name] ||= zone.domain options[:type] ||= type options[:identifier] ||= identifier options.delete_if {|key, value| value.nil?} data = service.list_resource_record_sets(zone.id, options).body # NextRecordIdentifier is completely absent instead of nil, so set to nil, or iteration breaks. data['NextRecordIdentifier'] = nil unless data.has_key?('NextRecordIdentifier') merge_attributes(data.reject {|key, value| !['IsTruncated', 'MaxItems', 'NextRecordName', 'NextRecordType', 'NextRecordIdentifier'].include?(key)}) load(data['ResourceRecordSets']) end # # Load all zone records into the collection. # def all! data = [] merge_attributes({'NextRecordName' => nil, 'NextRecordType' => nil, 'NextRecordIdentifier' => nil, 'IsTruncated' => nil}) begin options = { :name => next_record_name, :type => next_record_type, :identifier => next_record_identifier } options.delete_if {|key, value| value.nil?} batch = service.list_resource_record_sets(zone.id, options).body # NextRecordIdentifier is completely absent instead of nil, so set to nil, or iteration breaks. batch['NextRecordIdentifier'] = nil unless batch.has_key?('NextRecordIdentifier') merge_attributes(batch.reject {|key, value| !['IsTruncated', 'MaxItems', 'NextRecordName', 'NextRecordType', 'NextRecordIdentifier'].include?(key)}) data.concat(batch['ResourceRecordSets']) end while is_truncated load(data) end # # AWS Route 53 records are uniquely identified by a compound key of name, type, and identifier. # #get allows one to retrieve a record using one or more of those key components. # # ==== Parameters # * record_name - The name of the record to retrieve. # * record_type - The type of record to retrieve, if nil, then the first matching record is returned. # * record_identifier - The record set identifier to retrieve, if nil, then the first matching record is returned. # def get(record_name, record_type = nil, record_identifier = nil) requires :zone # Append a trailing period to the record_name if absent. record_name = record_name + "." unless record_name.end_with?(".") record_type = record_type.upcase unless record_type.nil? options = { :max_items => 1, :name => record_name, :type => record_type, :identifier => record_identifier } options.delete_if {|key, value| value.nil?} data = service.list_resource_record_sets(zone.id, options).body # Get first record data = data['ResourceRecordSets'].shift if data record = new(data) # make sure everything matches if record.name == record_name if (!record_type.nil? && record.type != record_type) || (!record_identifier.nil? && record.set_identifier != record_identifier) nil else record end end else nil end rescue Excon::Errors::NotFound nil end def new(attributes = {}) requires :zone super({ :zone => zone }.merge!(attributes)) end end end end end fog-1.19.0/lib/fog/aws/models/elb/0000755000004100000410000000000012261242551016545 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/models/elb/listeners.rb0000644000004100000410000000135212261242551021103 0ustar www-datawww-datarequire 'fog/aws/models/elb/listener' module Fog module AWS class ELB class Listeners < Fog::Collection model Fog::AWS::ELB::Listener attr_accessor :data, :load_balancer def all load(munged_data) end def get(lb_port) all.detect{|listener| listener.lb_port == lb_port} end private # Munge an array of ListenerDescription hashes like: # {'Listener' => listener, 'PolicyNames' => []} # to an array of listeners with a PolicyNames key def munged_data data.map {|description| description['Listener'].merge('PolicyNames' => description['PolicyNames']) } end end end end end fog-1.19.0/lib/fog/aws/models/elb/listener.rb0000644000004100000410000000333412261242551020722 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class ELB class Listener < Fog::Model attribute :policy_names, :aliases => 'PolicyNames' attribute :instance_port, :aliases => 'InstancePort' attribute :instance_protocol, :aliases => 'InstanceProtocol' attribute :lb_port, :aliases => 'LoadBalancerPort' attribute :protocol, :aliases => 'Protocol' attribute :ssl_id, :aliases => 'SSLCertificateId' def initialize(attributes={}) # set defaults, which may be overridden in super merge_attributes(:policy_names => [], :instance_port => 80, :instance_protocol => 'HTTP', :lb_port => 80, :protocol => 'HTTP') super end def save requires :load_balancer, :instance_port, :lb_port, :protocol, :instance_protocol service.create_load_balancer_listeners(load_balancer.id, [to_params]) reload end def destroy requires :load_balancer, :lb_port service.delete_load_balancer_listeners(load_balancer.id, [lb_port]) reload end # Return the policy associated with this load balancer def policy load_balancer.policies.get(policy_names.first) end def reload load_balancer.reload end def load_balancer collection.load_balancer end def to_params { 'InstancePort' => instance_port, 'InstanceProtocol' => instance_protocol, 'LoadBalancerPort' => lb_port, 'Protocol' => protocol, 'SSLCertificateId' => ssl_id } end end end end end fog-1.19.0/lib/fog/aws/models/elb/load_balancer.rb0000644000004100000410000001631412261242551021645 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class ELB class LoadBalancer < Fog::Model identity :id, :aliases => 'LoadBalancerName' attribute :availability_zones, :aliases => 'AvailabilityZones' attribute :created_at, :aliases => 'CreatedTime' attribute :dns_name, :aliases => 'DNSName' attribute :health_check, :aliases => 'HealthCheck' attribute :instances, :aliases => 'Instances' attribute :source_group, :aliases => 'SourceSecurityGroup' attribute :hosted_zone_name, :aliases => 'CanonicalHostedZoneName' attribute :hosted_zone_name_id, :aliases => 'CanonicalHostedZoneNameID' attribute :subnet_ids, :aliases => 'Subnets' attribute :security_groups, :aliases => 'SecurityGroups' attribute :scheme, :aliases => 'Scheme' attribute :vpc_id, :aliases => 'VPCId' def initialize(attributes={}) if attributes[:subnet_ids] ||= attributes['Subnets'] attributes[:availability_zones] ||= attributes['AvailabilityZones'] else attributes[:availability_zones] ||= attributes['AvailabilityZones'] || %w(us-east-1a us-east-1b us-east-1c us-east-1d) end unless attributes['ListenerDescriptions'] new_listener = Fog::AWS::ELB::Listener.new attributes['ListenerDescriptions'] = [{ 'Listener' => new_listener.to_params, 'PolicyNames' => new_listener.policy_names }] end super end def cross_zone_load_balancing? requires :id service.describe_load_balancer_attributes(id).body['DescribeLoadBalancerAttributesResult']['LoadBalancerAttributes']['CrossZoneLoadBalancing']['Enabled'] end def cross_zone_load_balancing= value requires :id service.modify_load_balancer_attributes(id, 'CrossZoneLoadBalancing' => {'Enabled' => value}) end def register_instances(instances) requires :id data = service.register_instances_with_load_balancer(instances, id).body['RegisterInstancesWithLoadBalancerResult'] data['Instances'].map!{|h| h['InstanceId']} merge_attributes(data) end def deregister_instances(instances) requires :id data = service.deregister_instances_from_load_balancer(instances, id).body['DeregisterInstancesFromLoadBalancerResult'] data['Instances'].map!{|h| h['InstanceId']} merge_attributes(data) end def enable_availability_zones(zones) requires :id data = service.enable_availability_zones_for_load_balancer(zones, id).body['EnableAvailabilityZonesForLoadBalancerResult'] merge_attributes(data) end def disable_availability_zones(zones) requires :id data = service.disable_availability_zones_for_load_balancer(zones, id).body['DisableAvailabilityZonesForLoadBalancerResult'] merge_attributes(data) end def attach_subnets(subnet_ids) requires :id data = service.attach_load_balancer_to_subnets(subnet_ids, id).body['AttachLoadBalancerToSubnetsResult'] merge_attributes(data) end def detach_subnets(subnet_ids) requires :id data = service.detach_load_balancer_from_subnets(subnet_ids, id).body['DetachLoadBalancerFromSubnetsResult'] merge_attributes(data) end def apply_security_groups(security_groups) requires :id data = service.apply_security_groups_to_load_balancer(security_groups, id).body['ApplySecurityGroupsToLoadBalancerResult'] merge_attributes(data) end def instance_health requires :id @instance_health ||= service.describe_instance_health(id).body['DescribeInstanceHealthResult']['InstanceStates'] end def instances_in_service instance_health.select{|hash| hash['State'] == 'InService'}.map{|hash| hash['InstanceId']} end def instances_out_of_service instance_health.select{|hash| hash['State'] == 'OutOfService'}.map{|hash| hash['InstanceId']} end def configure_health_check(health_check) requires :id data = service.configure_health_check(id, health_check).body['ConfigureHealthCheckResult']['HealthCheck'] merge_attributes(:health_check => data) end def backend_server_descriptions Fog::AWS::ELB::BackendServerDescriptions.new({ :data => attributes['BackendServerDescriptions'], :service => service, :load_balancer => self }) end def listeners Fog::AWS::ELB::Listeners.new({ :data => attributes['ListenerDescriptions'], :service => service, :load_balancer => self }) end def policies Fog::AWS::ELB::Policies.new({ :data => policy_descriptions, :service => service, :load_balancer => self }) end def policy_descriptions requires :id @policy_descriptions ||= service.describe_load_balancer_policies(id).body["DescribeLoadBalancerPoliciesResult"]["PolicyDescriptions"] end def set_listener_policy(port, policy_name) requires :id policy_name = [policy_name].flatten service.set_load_balancer_policies_of_listener(id, port, policy_name) reload end def set_listener_ssl_certificate(port, ssl_certificate_id) requires :id service.set_load_balancer_listener_ssl_certificate(id, port, ssl_certificate_id) reload end def unset_listener_policy(port) set_listener_policy(port, []) end def ready? # ELB requests are synchronous true end def save requires :id requires :listeners # with the VPC release, the ELB can have either availability zones or subnets # if both are specified, the availability zones have preference #requires :availability_zones if (availability_zones || subnet_ids) service.create_load_balancer(availability_zones, id, listeners.map{|l| l.to_params}) if availability_zones service.create_load_balancer(nil, id, listeners.map{|l| l.to_params}, {:subnet_ids => subnet_ids, :security_groups => security_groups, :scheme => scheme}) if subnet_ids && !availability_zones else throw Fog::Errors::Error.new("No availability zones or subnet ids specified") end # reload instead of merge attributes b/c some attrs (like HealthCheck) # may be set, but only the DNS name is returned in the create_load_balance # API call reload end def reload super @instance_health = nil @policy_descriptions = nil self end def destroy requires :id service.delete_load_balancer(id) end end end end end fog-1.19.0/lib/fog/aws/models/elb/policy.rb0000644000004100000410000000303412261242551020371 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class ELB class Policy < Fog::Model identity :id, :aliases => 'PolicyName' attribute :cookie, :aliases => 'CookieName' attribute :expiration, :aliases => 'CookieExpirationPeriod' attribute :type_name attribute :policy_attributes attr_accessor :cookie_stickiness # Either :app or :lb def save requires :id, :load_balancer service_method = nil args = [load_balancer.id, id] if cookie_stickiness case cookie_stickiness when :app requires :cookie method = :create_app_cookie_stickiness_policy args << cookie when :lb method = :create_lb_cookie_stickiness_policy args << expiration if expiration else raise ArgumentError.new('cookie_stickiness must be :app or :lb') end else requires :type_name, :policy_attributes method = :create_load_balancer_policy args << type_name args << policy_attributes end service.send(method, *args) reload end def destroy requires :id, :load_balancer service.delete_load_balancer_policy(load_balancer.id, id) reload end def reload load_balancer.reload end def load_balancer collection.load_balancer end end end end end fog-1.19.0/lib/fog/aws/models/elb/load_balancers.rb0000644000004100000410000000207112261242551022023 0ustar www-datawww-datarequire 'fog/aws/models/elb/load_balancer' module Fog module AWS class ELB class LoadBalancers < Fog::Collection model Fog::AWS::ELB::LoadBalancer # Creates a new load balancer def initialize(attributes={}) super end def all result = [] marker = nil finished = false while !finished data = service.describe_load_balancers('Marker' => marker).body result.concat(data['DescribeLoadBalancersResult']['LoadBalancerDescriptions']) marker = data['DescribeLoadBalancersResult']['NextMarker'] finished = marker.nil? end load(result) # data is an array of attribute hashes end def get(identity) if identity data = service.describe_load_balancers('LoadBalancerNames' => identity).body['DescribeLoadBalancersResult']['LoadBalancerDescriptions'].first new(data) end rescue Fog::AWS::ELB::NotFound nil end end end end end fog-1.19.0/lib/fog/aws/models/elb/backend_server_description.rb0000644000004100000410000000041612261242551024453 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class ELB class BackendServerDescription < Fog::Model attribute :policy_names, :aliases => 'PolicyNames' attribute :instance_port, :aliases => 'InstancePort' end end end end fog-1.19.0/lib/fog/aws/models/elb/backend_server_descriptions.rb0000644000004100000410000000066012261242551024637 0ustar www-datawww-datarequire 'fog/aws/models/elb/backend_server_description' module Fog module AWS class ELB class BackendServerDescriptions < Fog::Collection model Fog::AWS::ELB::BackendServerDescription attr_accessor :data, :load_balancer def all load(data) end def get(instance_port) all.detect{|e| e.instance_port == instance_port} end end end end end fog-1.19.0/lib/fog/aws/models/elb/policies.rb0000644000004100000410000000307312261242551020704 0ustar www-datawww-datarequire 'fog/aws/models/elb/policy' module Fog module AWS class ELB class Policies < Fog::Collection model Fog::AWS::ELB::Policy attr_accessor :data, :load_balancer def all load(munged_data) end def get(id) all.detect{|policy| id == policy.id} end private def munged_data data.inject([]){|m,e| policy_attribute_descriptions = e["PolicyAttributeDescriptions"] policy = { :id => e["PolicyName"], :type_name => e["PolicyTypeName"], :policy_attributes => policy_attributes(policy_attribute_descriptions) } case e["PolicyTypeName"] when 'AppCookieStickinessPolicyType' cookie_name = policy_attribute_descriptions.detect{|h| h['AttributeName'] == 'CookieName'}['AttributeValue'] policy['CookieName'] = cookie_name if cookie_name when 'LBCookieStickinessPolicyType' cookie_expiration_period = policy_attribute_descriptions.detect{|h| h['AttributeName'] == 'CookieExpirationPeriod'}['AttributeValue'].to_i policy['CookieExpirationPeriod'] = cookie_expiration_period if cookie_expiration_period > 0 end m << policy m } end def policy_attributes(policy_attribute_descriptions) policy_attribute_descriptions.inject({}){|m,e| m[e["AttributeName"]] = e["AttributeValue"] m } end end end end end fog-1.19.0/lib/fog/aws/models/data_pipeline/0000755000004100000410000000000012261242551020601 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/models/data_pipeline/pipeline.rb0000644000004100000410000000264212261242551022737 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class DataPipeline class Pipeline < Fog::Model identity :id, :aliases => 'pipelineId' attribute :name attribute :description attribute :user_id, :aliases => 'userId' attribute :account_id, :aliases => 'accountId' attribute :state, :aliases => 'pipelineState' attribute :unique_id, :aliases => 'uniqueId' def initialize(attributes={}) # Extract the 'fields' portion of a response to attributes if attributes.include?('fields') string_fields = attributes['fields'].select { |f| f.include?('stringValue') } field_attributes = Hash[string_fields.map { |f| [f['key'][/^@(.+)$/, 1], f['stringValue']] }] merge_attributes(field_attributes) end super end def save requires :name requires :unique_id data = service.create_pipeline(unique_id, name) merge_attributes(data) true end def activate requires :id service.activate_pipeline(id) true end def put(objects) requires :id service.put_pipeline_definition(id, objects) true end def destroy requires :id service.delete_pipeline(id) true end end end end end fog-1.19.0/lib/fog/aws/models/data_pipeline/pipelines.rb0000644000004100000410000000165712261242551023127 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/data_pipeline/pipeline' module Fog module AWS class DataPipeline class Pipelines < Fog::Collection model Fog::AWS::DataPipeline::Pipeline def all ids = [] begin result = service.list_pipelines ids << result['pipelineIdList'].map { |id| id['id'] } end while (result['hasMoreResults'] && result['marker']) load(service.describe_pipelines(ids.flatten)['pipelineDescriptionList']) end def get(id) data = service.describe_pipelines([id])['pipelineDescriptionList'].first new(data) rescue Excon::Errors::BadRequest => error data = Fog::JSON.decode(error.response.body) raise unless data['__type'] == 'PipelineDeletedException' || data['__type'] == 'PipelineNotFoundException' nil end end end end end fog-1.19.0/lib/fog/aws/models/cdn/0000755000004100000410000000000012261242551016547 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/models/cdn/distribution.rb0000644000004100000410000000624112261242551021616 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/aws/models/cdn/invalidations' require 'fog/aws/models/cdn/distribution_helper' module Fog module CDN class AWS class Distribution < Fog::Model include Fog::CDN::AWS::DistributionHelper identity :id, :aliases => 'Id' attribute :caller_reference, :aliases => 'CallerReference' attribute :last_modified_time, :aliases => 'LastModifiedTime' attribute :status, :aliases => 'Status' attribute :s3_origin, :aliases => 'S3Origin' attribute :custom_origin, :aliases => 'CustomOrigin' attribute :cname, :aliases => 'CNAME' attribute :comment, :aliases => 'Comment' attribute :enabled, :aliases => 'Enabled' attribute :in_progress_invalidation_batches, :aliases => 'InProgressInvalidationBatches' attribute :logging, :aliases => 'Logging' attribute :trusted_signers, :aliases => 'TrustedSigners' attribute :default_root_object,:aliases => 'DefaultRootObject' attribute :domain, :aliases => 'DomainName' attribute :etag, :aliases => ['Etag', 'ETag'] # items part of DistributionConfig CONFIG = [ :caller_reference, :origin, :cname, :comment, :enabled, :logging, :trusted_signers, :default_root_object ] def initialize(new_attributes = {}) super(distribution_config_to_attributes(new_attributes)) end def invalidations @invalidations ||= begin Fog::CDN::AWS::Invalidations.new( :distribution => self, :service => service ) end end def save requires_one :s3_origin, :custom_origin options = attributes_to_options response = identity ? put_distribution_config(identity, etag, options) : post_distribution(options) etag = response.headers['ETag'] merge_attributes(response.body) true end private def delete_distribution(identity, etag) service.delete_distribution(identity, etag) end def put_distribution_config(identity, etag, options) service.put_distribution_config(identity, etag, options) end def post_distribution(options = {}) service.post_distribution(options) end def attributes_to_options options = { 'CallerReference' => caller_reference, 'S3Origin' => s3_origin, 'CustomOrigin' => custom_origin, 'CNAME' => cname, 'Comment' => comment, 'Enabled' => enabled, 'Logging' => logging, 'TrustedSigners' => trusted_signers, 'DefaultRootObject' => default_root_object } options.reject! { |k,v| v.nil? } options.reject! { |k,v| v.respond_to?(:empty?) && v.empty? } options end def distribution_config_to_attributes(new_attributes = {}) new_attributes.merge(new_attributes.delete('DistributionConfig') || {}) end end end end end fog-1.19.0/lib/fog/aws/models/cdn/streaming_distributions.rb0000644000004100000410000000152412261242551024051 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/cdn/streaming_distribution' require 'fog/aws/models/cdn/distributions_helper' module Fog module CDN class AWS class StreamingDistributions < Fog::Collection include Fog::CDN::AWS::DistributionsHelper model Fog::CDN::AWS::StreamingDistribution attribute :marker, :aliases => 'Marker' attribute :max_items, :aliases => 'MaxItems' attribute :is_truncated, :aliases => 'IsTruncated' def get_distribution(dist_id) service.get_streaming_distribution(dist_id) end def list_distributions(options = {}) service.get_streaming_distribution_list(options) end alias_method :each_distribution_this_page, :each alias_method :each, :each_distribution end end end end fog-1.19.0/lib/fog/aws/models/cdn/streaming_distribution.rb0000644000004100000410000000476112261242551023674 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/aws/models/cdn/invalidations' require 'fog/aws/models/cdn/distribution_helper' module Fog module CDN class AWS class StreamingDistribution < Fog::Model include Fog::CDN::AWS::DistributionHelper identity :id, :aliases => 'Id' attribute :caller_reference, :aliases => 'CallerReference' attribute :last_modified_time, :aliases => 'LastModifiedTime' attribute :status, :aliases => 'Status' attribute :s3_origin, :aliases => 'S3Origin' attribute :cname, :aliases => 'CNAME' attribute :comment, :aliases => 'Comment' attribute :enabled, :aliases => 'Enabled' attribute :logging, :aliases => 'Logging' attribute :domain, :aliases => 'DomainName' attribute :etag, :aliases => ['Etag', 'ETag'] # items part of DistributionConfig CONFIG = [ :caller_reference, :cname, :comment, :enabled, :logging ] def initialize(new_attributes = {}) super(distribution_config_to_attributes(new_attributes)) end def save requires_one :s3_origin options = attributes_to_options response = identity ? put_distribution_config(identity, etag, options) : post_distribution(options) etag = response.headers['ETag'] merge_attributes(response.body) true end private def delete_distribution(identity, etag) service.delete_streaming_distribution(identity, etag) end def put_distribution_config(identity, etag, options) service.put_streaming_distribution_config(identity, etag, options) end def post_distribution(options = {}) service.post_streaming_distribution(options) end def attributes_to_options options = { 'CallerReference' => caller_reference, 'S3Origin' => s3_origin, 'CNAME' => cname, 'Comment' => comment, 'Enabled' => enabled, 'Logging' => logging, } options.reject! { |k,v| v.nil? } options.reject! { |k,v| v.respond_to?(:empty?) && v.empty? } options end def distribution_config_to_attributes(new_attributes = {}) new_attributes.merge(new_attributes.delete('StreamingDistributionConfig') || {}) end end end end end fog-1.19.0/lib/fog/aws/models/cdn/invalidations.rb0000644000004100000410000000264012261242551021742 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/cdn/invalidation' module Fog module CDN class AWS class Invalidations < Fog::Collection attribute :is_truncated, :aliases => ['IsTruncated'] attribute :max_items, :aliases => ['MaxItems'] attribute :next_marker, :aliases => ['NextMarker'] attribute :marker, :aliases => ['Marker'] attribute :distribution model Fog::CDN::AWS::Invalidation def all(options = {}) requires :distribution options[:max_items] ||= max_items options.delete_if {|key, value| value.nil?} data = service.get_invalidation_list(distribution.identity, options).body merge_attributes(data.reject {|key, value| !['IsTruncated', 'MaxItems', 'NextMarker', 'Marker'].include?(key)}) load(data['InvalidationSummary']) end def get(invalidation_id) requires :distribution data = service.get_invalidation(distribution.identity, invalidation_id).body if data invalidation = new(data) else nil end rescue Excon::Errors::NotFound nil end def new(attributes = {}) requires :distribution super({ :distribution => distribution }.merge!(attributes)) end end end end end fog-1.19.0/lib/fog/aws/models/cdn/invalidation.rb0000644000004100000410000000336212261242551021561 0ustar www-datawww-datarequire 'fog/core/model' module Fog module CDN class AWS class Invalidation < Fog::Model identity :id, :aliases => 'Id' attribute :status, :aliases => 'Status' attribute :create_time, :aliases => 'CreateTime' attribute :caller_reference, :aliases => 'CallerReference' attribute :paths, :aliases => 'Paths' def initialize(new_attributes={}) new_attributes[:caller_reference] ||= Time.now.utc.to_i.to_s super(invalidation_to_attributes(new_attributes)) end def distribution @distribution end def ready? requires :id, :status status == 'Completed' end def save requires :paths, :caller_reference raise "Submitted invalidation cannot be submitted again" if persisted? response = service.post_invalidation(distribution.identity, paths, caller_reference) merge_attributes(invalidation_to_attributes(response.body)) true end def destroy # invalidations can't be removed, but tests are requiring they do :) true end private def distribution=(dist) @distribution = dist end def invalidation_to_attributes(new_attributes={}) invalidation_batch = new_attributes.delete('InvalidationBatch') || {} if invalidation_batch['Path'] new_attributes[:paths] = invalidation_batch['Path'] end if invalidation_batch['CallerReference'] new_attributes[:caller_reference] = invalidation_batch['CallerReference'] end new_attributes end end end end end fog-1.19.0/lib/fog/aws/models/cdn/distribution_helper.rb0000644000004100000410000000273112261242551023155 0ustar www-datawww-datarequire 'fog/core/collection' module Fog module CDN class AWS module DistributionHelper def destroy requires :identity, :etag, :caller_reference raise "Distribution must be disabled to be deleted" unless disabled? delete_distribution(identity, etag) true end def enabled? requires :identity !!enabled and ready? end def disabled? requires :identity not enabled? and ready? end def custom_origin? requires :identity not custom_origin.nil? end def ready? requires :identity status == 'Deployed' end def enable requires :identity reload if etag.nil? or caller_reference.nil? unless enabled? self.enabled = true response = put_distribution_config(identity, etag, attributes_to_options) etag = response.headers['ETag'] merge_attributes(response.body) end true end def disable requires :identity reload if etag.nil? or caller_reference.nil? if enabled? self.enabled = false response = put_distribution_config(identity, etag, attributes_to_options) etag = response.headers['ETag'] merge_attributes(response.body) end true end end end end endfog-1.19.0/lib/fog/aws/models/cdn/distributions.rb0000644000004100000410000000144412261242551022001 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/cdn/distribution' require 'fog/aws/models/cdn/distributions_helper' module Fog module CDN class AWS class Distributions < Fog::Collection include Fog::CDN::AWS::DistributionsHelper model Fog::CDN::AWS::Distribution attribute :marker, :aliases => 'Marker' attribute :max_items, :aliases => 'MaxItems' attribute :is_truncated, :aliases => 'IsTruncated' def get_distribution(dist_id) service.get_distribution(dist_id) end def list_distributions(options = {}) service.get_distribution_list(options) end alias_method :each_distribution_this_page, :each alias_method :each, :each_distribution end end end end fog-1.19.0/lib/fog/aws/models/cdn/distributions_helper.rb0000644000004100000410000000243712261242551023343 0ustar www-datawww-datarequire 'fog/core/collection' module Fog module CDN class AWS module DistributionsHelper def all(options = {}) merge_attributes(options) data = list_distributions(options).body merge_attributes('IsTruncated' => data['IsTruncated'], 'Marker' => data['Marker'], 'MaxItems' => data['MaxItems']) if summary = data['DistributionSummary'] load(summary.map { |a| { 'DistributionConfig' => a } }) else load((data['StreamingDistributionSummary'] || {}).map { |a| { 'StreamingDistributionConfig' => a }}) end end def get(dist_id) response = get_distribution(dist_id) data = response.body.merge({'ETag' => response.headers['ETag']}) new(data) rescue Excon::Errors::NotFound nil end def each_distribution if !block_given? self else subset = dup.all subset.each_distribution_this_page {|f| yield f} while subset.is_truncated subset = subset.all('Marker' => subset.marker, 'MaxItems' => 1000) subset.each_distribution_this_page {|f| yield f} end self end end end end end endfog-1.19.0/lib/fog/aws/models/rds/0000755000004100000410000000000012261242551016573 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/models/rds/security_group.rb0000644000004100000410000000474612261242551022216 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/core/current_machine' module Fog module AWS class RDS class SecurityGroup < Fog::Model identity :id, :aliases => ['DBSecurityGroupName'] attribute :description, :aliases => 'DBSecurityGroupDescription' attribute :ec2_security_groups, :aliases => 'EC2SecurityGroups', :type => :array attribute :ip_ranges, :aliases => 'IPRanges', :type => :array attribute :owner_id, :aliases => 'OwnerId' def ready? (ec2_security_groups + ip_ranges).all?{|ingress| ingress['Status'] == 'authorized'} end def destroy requires :id service.delete_db_security_group(id) true end def save requires :id requires :description data = service.create_db_security_group(id, description).body['CreateDBSecurityGroupResult']['DBSecurityGroup'] merge_attributes(data) true end # group_owner_id defaults to the current owner_id def authorize_ec2_security_group(group_name, group_owner_id=owner_id) authorize_ingress({ 'EC2SecurityGroupName' => group_name, 'EC2SecurityGroupOwnerId' => group_owner_id }) end def authorize_cidrip(cidrip) authorize_ingress({'CIDRIP' => cidrip}) end # Add the current machine to the RDS security group. def authorize_me authorize_ip_address(Fog::CurrentMachine.ip_address) end # Add the ip address to the RDS security group. def authorize_ip_address(ip) authorize_cidrip("#{ip}/32") end def authorize_ingress(opts) data = service.authorize_db_security_group_ingress(id, opts).body['AuthorizeDBSecurityGroupIngressResult']['DBSecurityGroup'] merge_attributes(data) end # group_owner_id defaults to the current owner_id def revoke_ec2_security_group(group_name, group_owner_id=owner_id) revoke_ingress({ 'EC2SecurityGroupName' => group_name, 'EC2SecurityGroupOwnerId' => group_owner_id }) end def revoke_cidrip(cidrip) revoke_ingress({'CIDRIP' => cidrip}) end def revoke_ingress(opts) data = service.revoke_db_security_group_ingress(id, opts).body['RevokeDBSecurityGroupIngressResult']['DBSecurityGroup'] merge_attributes(data) end end end end end fog-1.19.0/lib/fog/aws/models/rds/subnet_groups.rb0000644000004100000410000000125312261242551022020 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/rds/subnet_group' module Fog module AWS class RDS class SubnetGroups < Fog::Collection model Fog::AWS::RDS::SubnetGroup def all data = service.describe_db_subnet_groups.body['DescribeDBSubnetGroupsResult']['DBSubnetGroups'] load(data) # data is an array of attribute hashes end def get(identity) data = service.describe_db_subnet_groups(identity).body['DescribeDBSubnetGroupsResult']['DBSubnetGroups'].first new(data) # data is an attribute hash rescue Fog::AWS::RDS::NotFound nil end end end end end fog-1.19.0/lib/fog/aws/models/rds/parameter_group.rb0000644000004100000410000000165612261242551022324 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class RDS class ParameterGroup < Fog::Model identity :id, :aliases => ['DBParameterGroupName', :name] attribute :family, :aliases => 'DBParameterGroupFamily' attribute :description, :aliases => 'Description' def save requires :family requires :description requires :id service.create_db_parameter_group(id, family, description) end def modify(changes) service.modify_db_parameter_group id, changes.collect {|c| {'ParameterName' => c[:name], 'ParameterValue' => c[:value], 'ApplyMethod' => c[:apply_method]}} end def destroy requires :id service.delete_db_parameter_group(id) true end def parameters(filters={}) service.parameters({:group => self}.merge(filters)) end end end end end fog-1.19.0/lib/fog/aws/models/rds/servers.rb0000644000004100000410000000120712261242551020611 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/rds/server' module Fog module AWS class RDS class Servers < Fog::Collection model Fog::AWS::RDS::Server def all data = service.describe_db_instances.body['DescribeDBInstancesResult']['DBInstances'] load(data) # data is an array of attribute hashes end def get(identity) data = service.describe_db_instances(identity).body['DescribeDBInstancesResult']['DBInstances'].first new(data) # data is an attribute hash rescue Fog::AWS::RDS::NotFound nil end end end end end fog-1.19.0/lib/fog/aws/models/rds/security_groups.rb0000644000004100000410000000222312261242551022365 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/rds/security_group' module Fog module AWS class RDS class SecurityGroups < Fog::Collection attribute :server attribute :filters model Fog::AWS::RDS::SecurityGroup def initialize(attributes={}) self.filters ||= {} if attributes[:server] filters[:identifier] = attributes[:server].id end super end def all(filters = filters) self.filters = filters data = service.describe_db_security_groups(filters).body['DescribeDBSecurityGroupsResult']['DBSecurityGroups'] load(data) # data is an array of attribute hashes end # Example: # get('my_db_security_group') # => model for my_db_security_group def get(identity) data = service.describe_db_security_groups(identity).body['DescribeDBSecurityGroupsResult']['DBSecurityGroups'].first new(data) # data is an attribute hash rescue Fog::AWS::RDS::NotFound nil end def new(attributes = {}) super end end end end end fog-1.19.0/lib/fog/aws/models/rds/log_file.rb0000644000004100000410000000144712261242551020706 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class RDS class LogFile < Fog::Model attribute :rds_id, :aliases => 'DBInstanceIdentifier' attribute :name, :aliases => 'LogFileName' attribute :size, :aliases => 'Size', :type => :integer attribute :last_written, :aliases => 'LastWritten', :type => :time attribute :content, :aliases => 'LogFileData' attribute :marker, :aliases => 'Marker' attribute :more_content_available, :aliases => 'AdditionalDataPending', :type => :boolean def content_excerpt(marker=nil) result = service.download_db_logfile_portion(self.rds_id, self.name, {:marker => marker}) merge_attributes(result.body['DownloadDBLogFilePortionResult']) end end end end end fog-1.19.0/lib/fog/aws/models/rds/instance_option.rb0000644000004100000410000000127612261242551022322 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class RDS class InstanceOption < Fog::Model attribute :multi_az_capable, :aliases => 'MultiAZCapable', :type => :boolean attribute :engine, :aliases => 'Engine' attribute :license_model, :aliases => 'LicenseModel' attribute :read_replica_capable, :aliases => 'ReadReplicaCapable', :type => :boolean attribute :engine_version, :aliases => 'EngineVersion' attribute :availability_zones, :aliases => 'AvailabilityZones', :type => :array attribute :db_instance_class, :aliases => 'DBInstanceClass' attribute :vpc, :aliases => 'Vpc', :type => :boolean end end end end fog-1.19.0/lib/fog/aws/models/rds/snapshot.rb0000644000004100000410000000277712261242551020774 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class RDS class Snapshot < Fog::Model identity :id, :aliases => ['DBSnapshotIdentifier', :name] attribute :instance_id, :aliases => 'DBInstanceIdentifier' attribute :created_at, :aliases => 'SnapshotCreateTime', :type => :time attribute :instance_created_at, :aliases => 'InstanceCreateTime', :type => :time attribute :engine, :aliases => 'Engine' attribute :engine_version, :aliases => 'EngineVersion' attribute :master_username, :aliases => 'MasterUsername' attribute :state, :aliases => 'Status' attribute :port, :aliases => 'Port', :type => :integer attribute :allocated_storage, :aliases => 'AllocatedStorage', :type => :integer attribute :availability_zone, :aliases => 'AvailabilityZone' attribute :type, :aliases => 'SnapshotType' attribute :publicly_accessible, :aliases => 'PubliclyAccessible' def ready? state == 'available' end def destroy requires :id service.delete_db_snapshot(id) true end def save requires :instance_id requires :id data = service.create_db_snapshot(instance_id, id).body['CreateDBSnapshotResult']['DBSnapshot'] merge_attributes(data) true end def server requires :instance_id service.servers.get(instance_id) end end end end end fog-1.19.0/lib/fog/aws/models/rds/subnet_group.rb0000644000004100000410000000142512261242551021636 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class RDS class SubnetGroup < Fog::Model identity :id, :aliases => ['DBSubnetGroupName', :name] attribute :description, :aliases => 'DBSubnetGroupDescription' attribute :status, :aliases => 'SubnetGroupStatus' attribute :vpc_id, :aliases => 'VpcId' attribute :subnet_ids, :aliases => 'Subnets' def ready? requires :status status == 'Complete' end def save requires :description, :id, :subnet_ids service.create_db_subnet_group(id, subnet_ids, description) reload end def destroy requires :id service.delete_db_subnet_group(id) end end end end end fog-1.19.0/lib/fog/aws/models/rds/parameters.rb0000644000004100000410000000174012261242551021265 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/rds/parameter' module Fog module AWS class RDS class Parameters < Fog::Collection attribute :group attribute :filters model Fog::AWS::RDS::Parameter def initialize(attributes) self.filters ||= {} if attributes[:source] filters[:source] = attributes[:source] end super end def all(filters = filters) self.filters = filters result = [] marker = nil finished = false while !finished data = service.describe_db_parameters(group.id, filters.merge(:marker => marker)).body result.concat(data['DescribeDBParametersResult']['Parameters']) marker = data['DescribeDBParametersResult']['Marker'] finished = marker.nil? end load(result) # data is an array of attribute hashes end end end end end fog-1.19.0/lib/fog/aws/models/rds/parameter.rb0000644000004100000410000000110712261242551021077 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class RDS class Parameter < Fog::Model attribute :name, :aliases => ['ParameterName'] attribute :data_type, :aliases => 'DataType' attribute :description, :aliases => 'Description' attribute :allowed_values, :aliases => 'AllowedValues' attribute :source, :aliases => 'Source' attribute :modifiable, :aliases => 'IsModifiable' attribute :apply_type, :aliases => 'ApplyType' attribute :value, :aliases => 'ParameterValue' end end end end fog-1.19.0/lib/fog/aws/models/rds/parameter_groups.rb0000644000004100000410000000130612261242551022477 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/rds/parameter_group' module Fog module AWS class RDS class ParameterGroups < Fog::Collection model Fog::AWS::RDS::ParameterGroup def all data = service.describe_db_parameter_groups.body['DescribeDBParameterGroupsResult']['DBParameterGroups'] load(data) # data is an array of attribute hashes end def get(identity) data = service.describe_db_parameter_groups(identity).body['DescribeDBParameterGroupsResult']['DBParameterGroups'].first new(data) # data is an attribute hash rescue Fog::AWS::RDS::NotFound nil end end end end end fog-1.19.0/lib/fog/aws/models/rds/log_files.rb0000644000004100000410000000262712261242551021072 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/rds/log_file' module Fog module AWS class RDS class LogFiles < Fog::Collection attribute :filters attribute :rds_id model Fog::AWS::RDS::LogFile def initialize(attributes) self.filters ||= {} super end # This method deliberately returns only a single page of results def all(filters=filters) self.filters.merge!(filters) result = service.describe_db_log_files(rds_id, self.filters).body['DescribeDBLogFilesResult'] self.filters[:marker] = result['Marker'] load(result['DBLogFiles']) end def each(filters=filters) if block_given? begin page = self.all(filters) # We need to explicitly use the base 'each' method here on the page, otherwise we get infinite recursion base_each = Fog::Collection.instance_method(:each) base_each.bind(page).call { |log_file| yield log_file } end while self.filters[:marker] end self end def get(file_name=nil) if file_name matches = self.select {|log_file| log_file.name.upcase == file_name.upcase} return matches.first unless matches.empty? end rescue Fog::AWS::RDS::NotFound end end end end end fog-1.19.0/lib/fog/aws/models/rds/snapshots.rb0000644000004100000410000000475312261242551021153 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/rds/snapshot' module Fog module AWS class RDS class Snapshots < Fog::Collection attribute :server attribute :filters model Fog::AWS::RDS::Snapshot def initialize(attributes) self.filters ||= {} if attributes[:server] filters[:identifier] = attributes[:server].id end if attributes[:type] filters[:type] = attributes[:type] end super end # This method does NOT return all snapshots. Its implementation deliberately returns a single page # of results for any one call. It will return a single page based on the current or provided filters, # updating the filters with the marker for the next page. Calling this repeatedly will iterate # through pages. See the implementation of each for an example of such iteration. # # It is arguably incorrect for the method not to return all snapshots, particularly considering the # implementation in the corresponding 'elb' files. But this implementation has been released, and # backwards-compatibility requires leaving it as implemented. def all(filters = filters) self.filters.merge!(filters) page = service.describe_db_snapshots(self.filters).body['DescribeDBSnapshotsResult'] self.filters[:marker] = page['Marker'] load(page['DBSnapshots']) end # This will execute a block for each snapshot, fetching new pages of snapshots as required. def each(filters = filters) if block_given? begin page = self.all(filters) # We need to explicitly use the base 'each' method here on the page, otherwise we get infinite recursion base_each = Fog::Collection.instance_method(:each) base_each.bind(page).call { |snapshot| yield snapshot } end while self.filters[:marker] end self end def get(identity) data = service.describe_db_snapshots(:snapshot_id => identity).body['DescribeDBSnapshotsResult']['DBSnapshots'].first new(data) # data is an attribute hash rescue Fog::AWS::RDS::NotFound nil end def new(attributes = {}) if server super({ :instance_id => server.id }.merge!(attributes)) else super end end end end end end fog-1.19.0/lib/fog/aws/models/rds/server.rb0000644000004100000410000001324512261242551020433 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class RDS class Server < Fog::Model identity :id, :aliases => 'DBInstanceIdentifier' attribute :engine, :aliases => 'Engine' attribute :engine_version, :aliases => 'EngineVersion' attribute :state, :aliases => 'DBInstanceStatus' attribute :allocated_storage, :aliases => 'AllocatedStorage', :type => :integer attribute :iops, :aliases => 'Iops' attribute :availability_zone , :aliases => 'AvailabilityZone' attribute :flavor_id, :aliases => 'DBInstanceClass' attribute :endpoint, :aliases => 'Endpoint' attribute :read_replica_source, :aliases => 'ReadReplicaSourceDBInstanceIdentifier' attribute :read_replica_identifiers, :aliases => 'ReadReplicaDBInstanceIdentifiers', :type => :array attribute :master_username, :aliases => 'MasterUsername' attribute :multi_az, :aliases => 'MultiAZ' attribute :created_at, :aliases => 'InstanceCreateTime', :type => :time attribute :last_restorable_time, :aliases => 'LatestRestorableTime', :type => :time attribute :auto_minor_version_upgrade, :aliases => 'AutoMinorVersionUpgrade' attribute :pending_modified_values, :aliases => 'PendingModifiedValues' attribute :preferred_backup_window, :aliases => 'PreferredBackupWindow' attribute :preferred_maintenance_window, :aliases => 'PreferredMaintenanceWindow' attribute :db_name, :aliases => 'DBName' attribute :db_security_groups, :aliases => 'DBSecurityGroups', :type => :array attribute :db_parameter_groups, :aliases => 'DBParameterGroups' attribute :backup_retention_period, :aliases => 'BackupRetentionPeriod', :type => :integer attribute :license_model, :aliases => 'LicenseModel' attribute :db_subnet_group_name, :aliases => 'DBSubnetGroupName' attribute :publicly_accessible, :aliases => 'PubliclyAccessible' attribute :vpc_security_groups, :aliases => 'VpcSecurityGroups', :type => :array attr_accessor :password, :parameter_group_name, :security_group_names, :port def create_read_replica(replica_id, options={}) options[:security_group_names] ||= options['DBSecurityGroups'] params = self.class.new(options).attributes_to_params service.create_db_instance_read_replica(replica_id, id, params) service.servers.get(replica_id) end def ready? state == 'available' end def destroy(snapshot_identifier=nil) requires :id service.delete_db_instance(id, snapshot_identifier, snapshot_identifier.nil?) true end def reboot service.reboot_db_instance(id) true end def snapshots requires :id service.snapshots(:server => self) end def tags requires :id service.list_tags_for_resource(id). body['ListTagsForResourceResult']['TagList'] end def add_tags(new_tags) requires :id service.add_tags_to_resource(id, new_tags) tags end def remove_tags(tag_keys) requires :id service.remove_tags_from_resource(id, tag_keys) tags end def modify(immediately, options) options[:security_group_names] ||= options['DBSecurityGroups'] params = self.class.new(options).attributes_to_params data = service.modify_db_instance(id, immediately, params) merge_attributes(data.body['ModifyDBInstanceResult']['DBInstance']) true end def save requires :engine requires :allocated_storage requires :master_username requires :password self.flavor_id ||= 'db.m1.small' data = service.create_db_instance(id, attributes_to_params) merge_attributes(data.body['CreateDBInstanceResult']['DBInstance']) true end # Converts attributes to a parameter hash suitable for requests def attributes_to_params options = { 'AllocatedStorage' => allocated_storage, 'AutoMinorVersionUpgrade' => auto_minor_version_upgrade, 'BackupRetentionPeriod' => backup_retention_period, 'DBName' => db_name, 'DBParameterGroupName' => parameter_group_name || attributes['DBParameterGroupName'], 'DBSecurityGroups' => security_group_names, 'DBInstanceIdentifier' => id, 'AvailabilityZone' => availability_zone, 'DBInstanceClass' => flavor_id, 'Port' => port || attributes['Port'], 'Engine' => engine, 'EngineVersion' => engine_version, 'Iops' => iops, 'MasterUsername' => master_username, 'MasterUserPassword' => password || attributes['MasterUserPassword'], 'PreferredMaintenanceWindow' => preferred_maintenance_window, 'PreferredBackupWindow' => preferred_backup_window, 'MultiAZ' => multi_az, 'LicenseModel' => license_model, 'DBSubnetGroupName' => db_subnet_group_name, 'PubliclyAccessible' => publicly_accessible, 'VpcSecurityGroups' => vpc_security_groups, } options.delete_if {|key, value| value.nil?} end end end end end fog-1.19.0/lib/fog/aws/models/rds/instance_options.rb0000644000004100000410000000142212261242551022476 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/rds/instance_option' module Fog module AWS class RDS class InstanceOptions < Fog::PagedCollection attribute :filters attribute :engine model Fog::AWS::RDS::InstanceOption def initialize(attributes) self.filters ||= {} super end # This method deliberately returns only a single page of results def all(filters=filters) self.filters.merge!(filters) result = service.describe_orderable_db_instance_options(engine, self.filters).body['DescribeOrderableDBInstanceOptionsResult'] self.filters[:marker] = result['Marker'] load(result['OrderableDBInstanceOptions']) end end end end end fog-1.19.0/lib/fog/aws/models/compute/0000755000004100000410000000000012261242551017457 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/models/compute/address.rb0000644000004100000410000000403312261242551021431 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class AWS class Address < Fog::Model identity :public_ip, :aliases => 'publicIp' attribute :allocation_id, :aliases => 'allocationId' attribute :association_id, :aliases => 'associationId' attribute :server_id, :aliases => 'instanceId' attribute :network_interface_id, :aliases => 'networkInterfaceId' attribute :network_interface_owner_id, :aliases => 'networkInterfaceOwnerId' attribute :domain def initialize(attributes = {}) # assign server first to prevent race condition with persisted? self.server = attributes.delete(:server) super end def destroy requires :public_ip service.release_address(allocation_id || public_ip) true end def server=(new_server) if new_server associate(new_server) else disassociate end end def server service.servers.get(server_id) end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? data = service.allocate_address(domain).body new_attributes = data.reject {|key,value| key == 'requestId'} merge_attributes(new_attributes) if @server self.server = @server end true end private def associate(new_server) unless persisted? @server = new_server else @server = nil self.server_id = new_server.id service.associate_address(server_id, public_ip, network_interface_id, allocation_id) end end def disassociate @server = nil self.server_id = nil if persisted? service.disassociate_address(public_ip) end end end end end end fog-1.19.0/lib/fog/aws/models/compute/addresses.rb0000644000004100000410000000504712261242551021767 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/address' module Fog module Compute class AWS class Addresses < Fog::Collection attribute :filters attribute :server model Fog::Compute::AWS::Address # Used to create an IP address # # ==== Returns # #>> AWS.addresses.create # # # The IP address can be retrieved by running AWS.addresses.get("test"). See get method below. # def initialize(attributes) self.filters ||= {} super end # AWS.addresses.all # # ==== Returns # # Returns an array of all IP addresses # #>> AWS.addresses.all # , # ....... # # ] # > #>> def all(filters = filters) unless filters.is_a?(Hash) Fog::Logger.deprecation("all with #{filters.class} param is deprecated, use all('public-ip' => []) instead [light_black](#{caller.first})[/]") filters = {'public-ip' => [*filters]} end self.filters = filters data = service.describe_addresses(filters).body load( data['addressesSet'].map do |address| address.reject {|key, value| value.nil? || value.empty? } end ) if server self.replace(self.select {|address| address.server_id == server.id}) end self end # Used to retrieve an IP address # # public_ip is required to get the associated IP information. # # You can run the following command to get the details: # AWS.addresses.get("76.7.46.54") def get(public_ip) if public_ip self.class.new(:service => service).all('public-ip' => public_ip).first end end def new(attributes = {}) if server super({ :server => server }.merge!(attributes)) else super(attributes) end end end end end end fog-1.19.0/lib/fog/aws/models/compute/volume.rb0000644000004100000410000000674012261242551021322 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class AWS class Volume < Fog::Model identity :id, :aliases => 'volumeId' attribute :attached_at, :aliases => 'attachTime' attribute :availability_zone, :aliases => 'availabilityZone' attribute :created_at, :aliases => 'createTime' attribute :delete_on_termination, :aliases => 'deleteOnTermination' attribute :device attribute :iops attribute :server_id, :aliases => 'instanceId' attribute :size attribute :snapshot_id, :aliases => 'snapshotId' attribute :state, :aliases => 'status' attribute :tags, :aliases => 'tagSet' attribute :type, :aliases => 'volumeType' def initialize(attributes = {}) # assign server first to prevent race condition with persisted? self.server = attributes.delete(:server) super end def destroy requires :id service.delete_volume(id) true end def ready? state == 'available' end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :availability_zone requires_one :size, :snapshot_id if type == 'io1' requires :iops end data = service.create_volume(availability_zone, size, 'SnapshotId' => snapshot_id, 'VolumeType' => type, 'Iops' => iops).body new_attributes = data.reject {|key,value| key == 'requestId'} merge_attributes(new_attributes) if tags = self.tags # expect eventual consistency Fog.wait_for { self.reload rescue nil } for key, value in (self.tags = tags) service.tags.create( :key => key, :resource_id => self.identity, :value => value ) end end if @server self.server = @server end true end def server requires :server_id service.servers.get(server_id) end def server=(new_server) if new_server attach(new_server) else detach end end def snapshots requires :id service.snapshots(:volume => self) end def snapshot(description) requires :id service.create_snapshot(id, description) end def force_detach detach(true) end private def attachmentSet=(new_attachment_set) merge_attributes(new_attachment_set.first || {}) end def attach(new_server) if !persisted? @server = new_server self.availability_zone = new_server.availability_zone elsif new_server requires :device wait_for { ready? } @server = nil self.server_id = new_server.id service.attach_volume(server_id, id, device) reload end end def detach(force = false) @server = nil self.server_id = nil if persisted? service.detach_volume(id, 'Force' => force) reload end end end end end end fog-1.19.0/lib/fog/aws/models/compute/images.rb0000644000004100000410000000252412261242551021254 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/image' module Fog module Compute class AWS class Images < Fog::Collection attribute :filters model Fog::Compute::AWS::Image # Creates a new Amazon machine image # # AWS.images.new # # ==== Returns # # Returns the details of the new image # #>> AWS.images.new # # def initialize(attributes) self.filters ||= {} super end def all(filters = filters) self.filters = filters data = service.describe_images(filters).body load(data['imagesSet']) end def get(image_id) if image_id self.class.new(:service => service).all('image-id' => image_id).first end end end end end end fog-1.19.0/lib/fog/aws/models/compute/vpc.rb0000644000004100000410000000310612261242551020574 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class AWS class VPC < Fog::Model identity :id, :aliases => 'vpcId' attribute :state attribute :cidr_block, :aliases => 'cidrBlock' attribute :dhcp_options_id, :aliases => 'dhcpOptionsId' attribute :tags, :aliases => 'tagSet' attribute :tenancy, :aliases => 'instanceTenancy' def initialize(attributes={}) self.dhcp_options_id ||= "default" self.tenancy ||= "default" super end def ready? requires :state state == 'available' end # Removes an existing vpc # # vpc.destroy # # ==== Returns # # True or false depending on the result # def destroy requires :id service.delete_vpc(id) true end # Create a vpc # # >> g = AWS.vpcs.new(:cidr_block => "10.1.2.0/24") # >> g.save # # == Returns: # # True or an exception depending on the result. Keep in mind that this *creates* a new vpc. # As such, it yields an InvalidGroup.Duplicate exception if you attempt to save an existing vpc. # def save requires :cidr_block data = service.create_vpc(cidr_block).body['vpcSet'].first new_attributes = data.reject {|key,value| key == 'requestId'} merge_attributes(new_attributes) true end end end end end fog-1.19.0/lib/fog/aws/models/compute/internet_gateways.rb0000644000004100000410000000456312261242551023550 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/internet_gateway' module Fog module Compute class AWS class InternetGateways < Fog::Collection attribute :filters model Fog::Compute::AWS::InternetGateway # Creates a new internet gateway # # AWS.internet_gateways.new # # ==== Returns # # Returns the details of the new InternetGateway # #>> AWS.internet_gateways.new #=> # def initialize(attributes) self.filters ||= {} super end # Returns an array of all InternetGateways that have been created # # AWS.internet_gateways.all # # ==== Returns # # Returns an array of all InternetGateways # #>> AWS.internet_gateways.all #"vpc-some-id", "state"=>"available"}, #tag_set={} #> #] #> # def all(filters = filters) unless filters.is_a?(Hash) Fog::Logger.warning("all with #{filters.class} param is deprecated, use all('internet-gateway-id' => []) instead [light_black](#{caller.first})[/]") filters = {'internet-gateway-id' => [*filters]} end self.filters = filters data = service.describe_internet_gateways(filters).body load(data['internetGatewaySet']) end # Used to retrieve an InternetGateway # # You can run the following command to get the details: # AWS.internet_gateways.get("igw-12345678") # # ==== Returns # #>> AWS.internet_gateways.get("igw-12345678") #=> "vpc-12345678", "state"=>"available"}, #tag_set={} #> # def get(internet_gateway_id) if internet_gateway_id self.class.new(:service => service).all('internet-gateway-id' => internet_gateway_id).first end end end end end end fog-1.19.0/lib/fog/aws/models/compute/security_group.rb0000644000004100000410000002232612261242551023074 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class AWS class SecurityGroup < Fog::Model identity :name, :aliases => 'groupName' attribute :description, :aliases => 'groupDescription' attribute :group_id, :aliases => 'groupId' attribute :ip_permissions, :aliases => 'ipPermissions' attribute :ip_permissions_egress, :aliases => 'ipPermissionsEgress' attribute :owner_id, :aliases => 'ownerId' attribute :vpc_id, :aliases => 'vpcId' # Authorize access by another security group # # >> g = AWS.security_groups.all(:description => "something").first # >> g.authorize_group_and_owner("some_group_name", "1234567890") # # == Parameters: # group:: # The name of the security group you're granting access to. # # owner:: # The owner id for security group you're granting access to. # # == Returns: # # An excon response object representing the result # # "some-id-string", # "return"=>true}, # headers{"Transfer-Encoding"=>"chunked", # "Date"=>"Mon, 27 Dec 2010 22:12:57 GMT", # "Content-Type"=>"text/xml;charset=UTF-8", # "Server"=>"AmazonEC2"} # def authorize_group_and_owner(group, owner = nil) Fog::Logger.deprecation("authorize_group_and_owner is deprecated, use authorize_port_range with :group option instead") requires_one :name, :group_id service.authorize_security_group_ingress( name, 'GroupId' => group_id, 'SourceSecurityGroupName' => group, 'SourceSecurityGroupOwnerId' => owner ) end # Authorize a new port range for a security group # # >> g = AWS.security_groups.all(:description => "something").first # >> g.authorize_port_range(20..21) # # == Parameters: # range:: # A Range object representing the port range you want to open up. E.g., 20..21 # # options:: # A hash that can contain any of the following keys: # :cidr_ip (defaults to "0.0.0.0/0") # :group - ("account:group_name" or "account:group_id"), cannot be used with :cidr_ip # :ip_protocol (defaults to "tcp") # # == Returns: # # An excon response object representing the result # # "some-id-string", # "return"=>true}, # headers{"Transfer-Encoding"=>"chunked", # "Date"=>"Mon, 27 Dec 2010 22:12:57 GMT", # "Content-Type"=>"text/xml;charset=UTF-8", # "Server"=>"AmazonEC2"} # def authorize_port_range(range, options = {}) requires_one :name, :group_id ip_permission = { 'FromPort' => range.min, 'ToPort' => range.max, 'IpProtocol' => options[:ip_protocol] || 'tcp' } if options[:group].nil? ip_permission['IpRanges'] = [ { 'CidrIp' => options[:cidr_ip] || '0.0.0.0/0' } ] else ip_permission['Groups'] = [ group_info(options[:group]) ] end service.authorize_security_group_ingress( name, 'GroupId' => group_id, 'IpPermissions' => [ ip_permission ] ) end # Removes an existing security group # # security_group.destroy # # ==== Returns # # True or false depending on the result # def destroy requires_one :name, :group_id if group_id.nil? service.delete_security_group(name) else service.delete_security_group(nil, group_id) end true end # Revoke access by another security group # # >> g = AWS.security_groups.all(:description => "something").first # >> g.revoke_group_and_owner("some_group_name", "1234567890") # # == Parameters: # group:: # The name of the security group you're revoking access to. # # owner:: # The owner id for security group you're revoking access access to. # # == Returns: # # An excon response object representing the result # # "some-id-string", # "return"=>true}, # headers{"Transfer-Encoding"=>"chunked", # "Date"=>"Mon, 27 Dec 2010 22:12:57 GMT", # "Content-Type"=>"text/xml;charset=UTF-8", # "Server"=>"AmazonEC2"} # def revoke_group_and_owner(group, owner = nil) Fog::Logger.deprecation("revoke_group_and_owner is deprecated, use revoke_port_range with :group option instead") requires_one :name, :group_id service.revoke_security_group_ingress( name, 'GroupId' => group_id, 'SourceSecurityGroupName' => group, 'SourceSecurityGroupOwnerId' => owner ) end # Revoke an existing port range for a security group # # >> g = AWS.security_groups.all(:description => "something").first # >> g.revoke_port_range(20..21) # # == Parameters: # range:: # A Range object representing the port range you want to open up. E.g., 20..21 # # options:: # A hash that can contain any of the following keys: # :cidr_ip (defaults to "0.0.0.0/0") # :group - ("account:group_name" or "account:group_id"), cannot be used with :cidr_ip # :ip_protocol (defaults to "tcp") # # == Returns: # # An excon response object representing the result # # "some-id-string", # "return"=>true}, # headers{"Transfer-Encoding"=>"chunked", # "Date"=>"Mon, 27 Dec 2010 22:12:57 GMT", # "Content-Type"=>"text/xml;charset=UTF-8", # "Server"=>"AmazonEC2"} # def revoke_port_range(range, options = {}) requires_one :name, :group_id ip_permission = { 'FromPort' => range.min, 'ToPort' => range.max, 'IpProtocol' => options[:ip_protocol] || 'tcp' } if options[:group].nil? ip_permission['IpRanges'] = [ { 'CidrIp' => options[:cidr_ip] || '0.0.0.0/0' } ] else ip_permission['Groups'] = [ group_info(options[:group]) ] end service.revoke_security_group_ingress( name, 'GroupId' => group_id, 'IpPermissions' => [ ip_permission ] ) end # Create a security group # # >> g = AWS.security_groups.new(:name => "some_name", :description => "something") # >> g.save # # == Returns: # # True or an exception depending on the result. Keep in mind that this *creates* a new security group. # As such, it yields an InvalidGroup.Duplicate exception if you attempt to save an existing group. # def save requires :description, :name data = service.create_security_group(name, description, vpc_id).body new_attributes = data.reject {|key,value| key == 'requestId'} merge_attributes(new_attributes) true end private # # +group_arg+ may be a string or a hash with one key & value. # # If group_arg is a string, it is assumed to be the group name, # and the UserId is assumed to be self.owner_id. # # The "account:group" form is deprecated. # # If group_arg is a hash, the key is the UserId and value is the group. def group_info(group_arg) if Hash === group_arg account = group_arg.keys.first group = group_arg.values.first elsif group_arg.match(/:/) account, group = group_arg.split(':') Fog::Logger.deprecation("'account:group' argument is deprecated. Use {account => group} or just group instead") else requires :owner_id account = owner_id group = group_arg end info = { 'UserId' => account } if group.start_with?("sg-") # we're dealing with a security group id info['GroupId'] = group else # this has to be a security group name info['GroupName'] = group end info end end end end end fog-1.19.0/lib/fog/aws/models/compute/servers.rb0000644000004100000410000001147112261242551021501 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/server' module Fog module Compute class AWS class Servers < Fog::Collection attribute :filters model Fog::Compute::AWS::Server # Creates a new server # # AWS.servers.new # # ==== Returns # # Returns the details of the new server # #>> AWS.servers.new # # def initialize(attributes) self.filters ||= {} super end def all(filters = self.filters) unless filters.is_a?(Hash) Fog::Logger.deprecation("all with #{filters.class} param is deprecated, use all('instance-id' => []) instead [light_black](#{caller.first})[/]") filters = {'instance-id' => [*filters]} end self.filters = filters data = service.describe_instances(filters).body load( data['reservationSet'].map do |reservation| reservation['instancesSet'].map do |instance| instance.merge(:groups => reservation['groupSet'], :security_group_ids => reservation['groupIds']) end end.flatten ) end def bootstrap(new_attributes = {}) server = service.servers.new(new_attributes) unless new_attributes[:key_name] # first or create fog_#{credential} keypair name = Fog.respond_to?(:credential) && Fog.credential || :default unless server.key_pair = service.key_pairs.get("fog_#{name}") server.key_pair = service.key_pairs.create( :name => "fog_#{name}", :public_key => server.public_key ) end end # make sure port 22 is open in the first security group security_group = service.security_groups.get(server.groups.first) authorized = security_group.ip_permissions.detect do |ip_permission| ip_permission['ipRanges'].first && ip_permission['ipRanges'].first['cidrIp'] == '0.0.0.0/0' && ip_permission['fromPort'] == 22 && ip_permission['ipProtocol'] == 'tcp' && ip_permission['toPort'] == 22 end unless authorized security_group.authorize_port_range(22..22) end server.save server.wait_for { ready? } server.setup(:key_data => [server.private_key]) server end # Used to retrieve a server # # server_id is required to get the associated server information. # # You can run the following command to get the details: # AWS.servers.get("i-5c973972") # # ==== Returns # #>> AWS.servers.get("i-5c973972") # # def get(server_id) if server_id self.class.new(:service => service).all('instance-id' => server_id).first end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/aws/models/compute/subnets.rb0000644000004100000410000000466412261242551021501 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/subnet' module Fog module Compute class AWS class Subnets < Fog::Collection attribute :filters model Fog::Compute::AWS::Subnet # Creates a new subnet # # AWS.subnets.new # # ==== Returns # # Returns the details of the new Subnet # #>> AWS.subnets.new # # def initialize(attributes) self.filters ||= {} super end # Returns an array of all Subnets that have been created # # AWS.subnets.all # # ==== Returns # # Returns an array of all VPCs # #>> AWS.subnets.all # # def all(filters = filters) unless filters.is_a?(Hash) Fog::Logger.warning("all with #{filters.class} param is deprecated, use all('subnet-id' => []) instead [light_black](#{caller.first})[/]") filters = {'subnet-id' => [*filters]} end self.filters = filters data = service.describe_subnets(filters).body load(data['subnetSet']) end # Used to retrieve a Subnet # subnet-id is required to get the associated VPC information. # # You can run the following command to get the details: # AWS.subnets.get("subnet-12345678") # # ==== Returns # #>> AWS.subnets.get("subnet-12345678") # # def get(subnet_id) if subnet_id self.class.new(:service => service).all('subnet-id' => subnet_id).first end end end end end end fog-1.19.0/lib/fog/aws/models/compute/key_pairs.rb0000644000004100000410000001024112261242551021770 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/key_pair' module Fog module Compute class AWS class KeyPairs < Fog::Collection attribute :filters attribute :key_name model Fog::Compute::AWS::KeyPair # Used to create a key pair. There are 3 arguments and only name is required. You can generate a new key_pair as follows: # AWS.key_pairs.create(:name => "test", :fingerprint => "123", :private_key => '234234') # # ==== Returns # # # # The key_pair can be retrieved by running AWS.key_pairs.get("test"). See get method below. # def initialize(attributes) self.filters ||= {} super end # Returns an array of all key pairs that have been created # # AWS.key_pairs.all # # ==== Returns # # # ] #> # def all(filters = filters) unless filters.is_a?(Hash) Fog::Logger.deprecation("all with #{filters.class} param is deprecated, use all('key-name' => []) instead [light_black](#{caller.first})[/]") filters = {'key-name' => [*filters]} end self.filters = filters data = service.describe_key_pairs(filters).body load(data['keySet']) end # Used to retrieve a key pair that was created with the AWS.key_pairs.create method. # The name is required to get the associated key_pair information. # # You can run the following command to get the details: # AWS.key_pairs.get("test") # # ==== Returns # #>> AWS.key_pairs.get("test") # # def get(key_name) if key_name self.class.new(:service => service).all('key-name' => key_name).first end end end end end end fog-1.19.0/lib/fog/aws/models/compute/dhcp_options.rb0000644000004100000410000000443212261242551022500 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/dhcp_option' module Fog module Compute class AWS class DhcpOptions < Fog::Collection attribute :filters model Fog::Compute::AWS::DhcpOption # Creates a new dhcp option # # AWS.dhcp_options.new # # ==== Returns # # Returns the details of the new DHCP options # #>> AWS.dhcp_options.new #=> # def initialize(attributes) self.filters ||= {} super end # Returns an array of all DhcpOptions that have been created # # AWS.dhcp_options.all # # ==== Returns # # Returns an array of all DhcpOptions # #>> AWS.dhcp_options.all #"vpc-some-id", "state"=>"available"}, #tag_set={} #> #] #> # def all(filters = filters) unless filters.is_a?(Hash) Fog::Logger.warning("all with #{filters.class} param is deprecated, use all('internet-gateway-id' => []) instead [light_black](#{caller.first})[/]") filters = {'dhcp-options-id' => [*filters]} end self.filters = filters data = service.describe_dhcp_options(filters).body load(data['dhcpOptionsSet']) end # Used to retrieve an DhcpOption # # You can run the following command to get the details: # AWS.dhcp_options.get("dopt-12345678") # # ==== Returns # #>> AWS.dhcp_options.get("dopt-12345678") #=> "vpc-12345678", "state"=>"available"}, #tag_set={} #> # def get(dhcp_options_id) if dhcp_options_id self.class.new(:service => service).all('dhcp-options-id' => dhcp_options_id).first end end end end end end fog-1.19.0/lib/fog/aws/models/compute/security_groups.rb0000644000004100000410000001063612261242551023260 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/security_group' module Fog module Compute class AWS class SecurityGroups < Fog::Collection attribute :filters model Fog::Compute::AWS::SecurityGroup # Creates a new security group # # AWS.security_groups.new # # ==== Returns # # Returns the details of the new image # #>> AWS.security_groups.new # # def initialize(attributes) self.filters ||= {} super end # Returns an array of all security groups that have been created # # AWS.security_groups.all # # ==== Returns # # Returns an array of all security groups # #>> AWS.security_groups.all # [{"groupName"=>"default", "userId"=>"312571045469"}], "fromPort"=>-1, "toPort"=>-1, "ipRanges"=>[], "ipProtocol"=>"icmp"}, {"groups"=>[{"groupName"=>"default", "userId"=>"312571045469"}], "fromPort"=>0, "toPort"=>65535, "ipRanges"=>[], "ipProtocol"=>"tcp"}, {"groups"=>[{"groupName"=>"default", "userId"=>"312571045469"}], "fromPort"=>0, "toPort"=>65535, "ipRanges"=>[], "ipProtocol"=>"udp"}], # owner_id="312571045469" # vpc_id=nill # > # ] # > # def all(filters = filters) unless filters.is_a?(Hash) Fog::Logger.deprecation("all with #{filters.class} param is deprecated, use all('group-name' => []) instead [light_black](#{caller.first})[/]") filters = {'group-name' => [*filters]} end self.filters = filters data = service.describe_security_groups(filters).body load(data['securityGroupInfo']) end # Used to retrieve a security group # group name is required to get the associated flavor information. # # You can run the following command to get the details: # AWS.security_groups.get("default") # # ==== Returns # #>> AWS.security_groups.get("default") # [{"groupName"=>"default", "userId"=>"312571045469"}], "fromPort"=>-1, "toPort"=>-1, "ipRanges"=>[], "ipProtocol"=>"icmp"}, {"groups"=>[{"groupName"=>"default", "userId"=>"312571045469"}], "fromPort"=>0, "toPort"=>65535, "ipRanges"=>[], "ipProtocol"=>"tcp"}, {"groups"=>[{"groupName"=>"default", "userId"=>"312571045469"}], "fromPort"=>0, "toPort"=>65535, "ipRanges"=>[], "ipProtocol"=>"udp"}], # owner_id="312571045469" # vpc_id=nil # > # def get(group_name) if group_name self.class.new(:service => service).all('group-name' => group_name).first end end # Used to retrieve a security group # group id is required to get the associated flavor information. # # You can run the following command to get the details: # AWS.security_groups.get_by_id("default") # # ==== Returns # #>> AWS.security_groups.get_by_id("sg-123456") # [{"groupName"=>"default", "userId"=>"312571045469"}], "fromPort"=>-1, "toPort"=>-1, "ipRanges"=>[], "ipProtocol"=>"icmp"}, {"groups"=>[{"groupName"=>"default", "userId"=>"312571045469"}], "fromPort"=>0, "toPort"=>65535, "ipRanges"=>[], "ipProtocol"=>"tcp"}, {"groups"=>[{"groupName"=>"default", "userId"=>"312571045469"}], "fromPort"=>0, "toPort"=>65535, "ipRanges"=>[], "ipProtocol"=>"udp"}], # owner_id="312571045469" # > # def get_by_id(group_id) if group_id self.class.new(:service => service).all('group-id' => group_id).first end end end end end end fog-1.19.0/lib/fog/aws/models/compute/internet_gateway.rb0000644000004100000410000000355612261242551023366 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class AWS class InternetGateway < Fog::Model identity :id, :aliases => 'internetGatewayId' attribute :attachment_set, :aliases => 'attachmentSet' attribute :tag_set, :aliases => 'tagSet' def initialize(attributes={}) super end # Attaches an existing internet gateway # # internet_gateway.attach(igw-id, vpc-id) # # ==== Returns # # True or false depending on the result # def attach(vpc_id) requires :id service.attach_internet_gateway(id, vpc_id) reload end # Detaches an existing internet gateway # # internet_gateway.detach(igw-id, vpc-id) # # ==== Returns # # True or false depending on the result # def detach(vpc_id) requires :id service.detach_internet_gateway(id, vpc_id) reload end # Removes an existing internet gateway # # internet_gateway.destroy # # ==== Returns # # True or false depending on the result # def destroy requires :id service.delete_internet_gateway(id) true end # Create an internet gateway # # >> g = AWS.internet_gateways.new() # >> g.save # # == Returns: # # requestId and a internetGateway object # def save data = service.create_internet_gateway.body['internetGatewaySet'].first new_attributes = data.reject {|key,value| key == 'requestId'} merge_attributes(new_attributes) true true end end end end end fog-1.19.0/lib/fog/aws/models/compute/route_tables.rb0000755000004100000410000000433312261242551022502 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/route_table' module Fog module Compute class AWS class RouteTables < Fog::Collection attribute :filters model Fog::Compute::AWS::RouteTable # Creates a new route table # # AWS.route_tables.new # # ==== Returns # # Returns the details of the new route table # #>> AWS.route_tables.new # # def initialize(attributes) self.filters ||= {} super end # Returns an array of all route tables that have been created # # AWS.route_tables.all # # ==== Returns # # Returns an array of all route tables # #>> AWS.route_tables.all # # ] # > # def all(filters = filters) unless filters.is_a?(Hash) Fog::Logger.warning("all with #{filters.class} param is deprecated, use all('route-table-id' => []) instead [light_black](#{caller.first})[/]") filters = {'route-table-id' => [*filters]} end self.filters = filters data = service.describe_route_tables(filters).body load(data['routeTableSet']) end # Used to retrieve a route table # route_table_id is required to get the associated route table information. # # You can run the following command to get the details: # AWS.route_tables.get("rtb-41e8552f") # # ==== Returns # #>> AWS.route_tables.get("rtb-41e8552f") # # def get(route_table_id) if route_table_id self.class.new(:service => service).all('route-table-id' => route_table_id).first end end end end end end fog-1.19.0/lib/fog/aws/models/compute/dhcp_option.rb0000644000004100000410000000312612261242551022314 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class AWS class DhcpOption < Fog::Model identity :id, :aliases => 'dhcpOptionsId' attribute :dhcp_configuration_set, :aliases => 'dhcpConfigurationSet' attribute :tag_set, :aliases => 'tagSet' def initialize(attributes={}) super end # Associates an existing dhcp configration set with a VPC # # dhcp_option.attach(dopt-id, vpc-id) # # ==== Returns # # True or false depending on the result # def associate(vpc_id) requires :id service.attach_dhcp_option(id, vpc_id) #reload end # Removes an existing dhcp configuration set # # dhcp_option.destroy # # ==== Returns # # True or false depending on the result # def destroy requires :id service.delete_dhcp_options(id) true end # Create a dhcp configuration set # # >> g = AWS.dhcp_options.new() # >> g.save # # == Returns: # # requestId and a dhcpOptions object # def save requires :dhcp_configuration_set data = service.create_dhcp_options(dhcp_configuration_set).body['dhcpOptionsSet'].first new_attributes = data.reject {|key,value| key == 'requestId'} merge_attributes(new_attributes) true true end end end end end fog-1.19.0/lib/fog/aws/models/compute/snapshot.rb0000644000004100000410000000246312261242551021650 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class AWS class Snapshot < Fog::Model identity :id, :aliases => 'snapshotId' attribute :description attribute :progress attribute :created_at, :aliases => 'startTime' attribute :owner_id, :aliases => 'ownerId' attribute :state, :aliases => 'status' attribute :tags, :aliases => 'tagSet' attribute :volume_id, :aliases => 'volumeId' attribute :volume_size, :aliases => 'volumeSize' def destroy requires :id service.delete_snapshot(id) true end def ready? state == 'completed' end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :volume_id data = service.create_snapshot(volume_id, description).body new_attributes = data.reject {|key,value| key == 'requestId'} merge_attributes(new_attributes) true end def volume requires :id service.describe_volumes(volume_id) end private def volume=(new_volume) self.volume_id = new_volume.volume_id end end end end end fog-1.19.0/lib/fog/aws/models/compute/network_interfaces.rb0000644000004100000410000000754412261242551023712 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/network_interface' module Fog module Compute class AWS class NetworkInterfaces < Fog::Collection attribute :filters model Fog::Compute::AWS::NetworkInterface # Creates a new network interface # # AWS.network_interfaces.new # # ==== Returns # # Returns the details of the new network interface # #>> AWS.network_interfaces.new # # def initialize(attributes) self.filters ||= {} super end # Returns an array of all network interfaces that have been created # # AWS.network_interfaces.all # # ==== Returns # # Returns an array of all network interfaces # #>> AWS.network_interfaves.all # # ] # > # def all(filters = filters) self.filters = filters data = service.describe_network_interfaces(filters).body load(data['networkInterfaceSet']) end # Used to retrieve a network interface # network interface id is required to get any information # # You can run the following command to get the details: # AWS.network_interfaces.get("eni-11223344") # # ==== Returns # #>> AWS.NetworkInterface.get("eni-11223344") # # def get(nic_id) if nic_id self.class.new(:service => service).all('network-interface-id' => nic_id).first end end end end end end fog-1.19.0/lib/fog/aws/models/compute/spot_requests.rb0000644000004100000410000000651312261242551022731 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/spot_request' module Fog module Compute class AWS class SpotRequests < Fog::Collection attribute :filters model Fog::Compute::AWS::SpotRequest def initialize(attributes) self.filters ||= {} super end def all(filters = self.filters) unless filters.is_a?(Hash) Fog::Logger.deprecation("all with #{filters.class} param is deprecated, use all('spot-instance-request-id' => []) instead [light_black](#{caller.first})[/]") filters = {'spot-instance-request-id' => [*filters]} end self.filters = filters data = service.describe_spot_instance_requests(filters).body load( data['spotInstanceRequestSet'].map do |spot_instance_request| spot_instance_request['LaunchSpecification.Placement.AvailabilityZone'] = spot_instance_request['launchedAvailabilityZone'] spot_instance_request['launchSpecification'].each do |name,value| spot_instance_request['LaunchSpecification.' + name[0,1].upcase + name[1..-1]] = value end spot_instance_request.merge(:groups => spot_instance_request['LaunchSpecification.GroupSet']) spot_instance_request end.flatten ) end def bootstrap(new_attributes = {}) spot_request = service.spot_requests.new(new_attributes) unless new_attributes[:key_name] # first or create fog_#{credential} keypair name = Fog.respond_to?(:credential) && Fog.credential || :default unless spot_request.key_pair = service.key_pairs.get("fog_#{name}") spot_request.key_pair = service.key_pairs.create( :name => "fog_#{name}", :public_key => spot_request.public_key ) end end # make sure port 22 is open in the first security group security_group = service.security_groups.get(spot_request.groups.first) authorized = security_group.ip_permissions.detect do |ip_permission| ip_permission['ipRanges'].first && ip_permission['ipRanges'].first['cidrIp'] == '0.0.0.0/0' && ip_permission['fromPort'] == 22 && ip_permission['ipProtocol'] == 'tcp' && ip_permission['toPort'] == 22 end unless authorized security_group.authorize_port_range(22..22) end spot_request.save Fog.wait_for { spot_request.reload.ready? rescue nil } server = service.servers.get(spot_request.instance_id) if spot_request.tags for key, value in spot_request.tags service.tags.create( :key => key, :resource_id => spot_request.instance_id, :value => value ) end end server.wait_for { ready? } server.setup(:key_data => [spot_request.private_key]) server end def get(spot_request_id) if spot_request_id self.class.new(:service => service).all('spot-instance-request-id' => spot_request_id).first end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/aws/models/compute/subnet.rb0000644000004100000410000000314612261242551021310 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class AWS class Subnet < Fog::Model identity :subnet_id, :aliases => 'subnetId' attribute :state attribute :vpc_id, :aliases => 'vpcId' attribute :cidr_block, :aliases => 'cidrBlock' attribute :available_ip_address_count, :aliases => 'availableIpAddressCount' attribute :availability_zone, :aliases => 'availabilityZone' attribute :tag_set, :aliases => 'tagSet' def ready? requires :state state == 'available' end # Removes an existing subnet # # subnet.destroy # # ==== Returns # # True or false depending on the result # def destroy requires :subnet_id service.delete_subnet(subnet_id) true end # Create a subnet # # >> g = AWS.subnets.new(:vpc_id => "vpc-someId", :cidr_block => "10.0.0.0/24") # >> g.save # # == Returns: # # requestId and a subnetSet object # def save requires :vpc_id, :cidr_block options = {} options['AvailabilityZone'] = availability_zone if availability_zone data = service.create_subnet(vpc_id, cidr_block, options).body['subnetSet'].first new_attributes = data.reject {|key,value| key == 'requestId'} merge_attributes(new_attributes) true true end end end end end fog-1.19.0/lib/fog/aws/models/compute/vpcs.rb0000644000004100000410000000402112261242551020754 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/vpc' module Fog module Compute class AWS class Vpcs < Fog::Collection attribute :filters model Fog::Compute::AWS::VPC # Creates a new VPC # # AWS.vpcs.new # # ==== Returns # # Returns the details of the new VPC # #>> AWS.vpcs.new # # def initialize(attributes) self.filters ||= {} super end # Returns an array of all VPCs that have been created # # AWS.vpcs.all # # ==== Returns # # Returns an array of all VPCs # #>> AWS.vpcs.all # # ] # > # def all(filters = filters) unless filters.is_a?(Hash) Fog::Logger.warning("all with #{filters.class} param is deprecated, use all('vpc-id' => []) instead [light_black](#{caller.first})[/]") filters = {'vpc-id' => [*filters]} end self.filters = filters data = service.describe_vpcs(filters).body load(data['vpcSet']) end # Used to retrieve a VPC # vpc_id is required to get the associated VPC information. # # You can run the following command to get the details: # AWS.vpcs.get("vpc-12345678") # # ==== Returns # #>> AWS.vpcs.get("vpc-12345678") # # def get(vpc_id) if vpc_id self.class.new(:service => service).all('vpc-id' => vpc_id).first end end end end end end fog-1.19.0/lib/fog/aws/models/compute/flavors.rb0000644000004100000410000002010612261242551021457 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/flavor' module Fog module Compute class AWS FLAVORS = [ { :bits => 0, :cores => 2, :disk => 0, :id => 't1.micro', :name => 'Micro Instance', :ram => 613}, { :bits => 32, :cores => 1, :disk => 160, :id => 'm1.small', :name => 'Small Instance', :ram => 1740.8}, { :bits => 32, :cores => 2, :disk => 400, :id => 'm1.medium', :name => 'Medium Instance', :ram => 3750}, { :bits => 64, :cores => 4, :disk => 850, :id => 'm1.large', :name => 'Large Instance', :ram => 7680}, { :bits => 64, :cores => 8, :disk => 1690, :id => 'm1.xlarge', :name => 'Extra Large Instance', :ram => 15360}, { :bits => 32, :cores => 5, :disk => 350, :id => 'c1.medium', :name => 'High-CPU Medium', :ram => 1740.8}, { :bits => 64, :cores => 20, :disk => 1690, :id => 'c1.xlarge', :name => 'High-CPU Extra Large', :ram => 7168}, { :bits => 64, :cores => 7, :disk => 32, :id => 'c3.large', :name => 'C3 Large', :ram => 3750}, { :bits => 64, :cores => 14, :disk => 80, :id => 'c3.xlarge', :name => 'C3 Extra Large', :ram => 7168}, { :bits => 64, :cores => 28, :disk => 160, :id => 'c3.2xlarge', :name => 'C3 Double Extra Large', :ram => 15360}, { :bits => 64, :cores => 55, :disk => 320, :id => 'c3.4xlarge', :name => 'C3 Quadruple Extra Large', :ram => 30720}, { :bits => 64, :cores => 108, :disk => 640, :id => 'c3.8xlarge', :name => 'C3 Eight Extra Large', :ram => 61440}, { :bits => 64, :cores => 26, :disk => 60, :id => 'g2.2xlarge', :name => 'GPU Double Extra Large', :ram => 15360}, { :bits => 64, :cores => 35, :disk => 50331648, :id => 'hs1.8xlarge', :name => 'High Storage Eight Extra Large', :ram => 119808}, { :bits => 64, :cores => 6.5, :disk => 420, :id => 'm2.xlarge', :name => 'High-Memory Extra Large', :ram => 17510.4}, { :bits => 64, :cores => 13, :disk => 850, :id => 'm2.2xlarge', :name => 'High Memory Double Extra Large', :ram => 35020.8}, { :bits => 64, :cores => 26, :disk => 1690, :id => 'm2.4xlarge', :name => 'High Memory Quadruple Extra Large', :ram => 70041.6}, { :bits => 64, :cores => 13, :disk => 0, :id => 'm3.xlarge', :name => 'M3 Extra Large', :ram => 15360}, { :bits => 64, :cores => 26, :disk => 0, :id => 'm3.2xlarge', :name => 'M3 Double Extra Large', :ram => 30720}, { :bits => 64, :cores => 35, :disk => 2048, :id => "hi1.4xlarge", :name => "High I/O Quadruple Extra Large Instance", :ram => 61952}, { :bits => 64, :cores => 33.5, :disk => 1690, :id => 'cc1.4xlarge', :name => 'Cluster Compute Quadruple Extra Large', :ram => 23552}, { :bits => 64, :cores => 88, :disk => 3370, :id => 'cc2.8xlarge', :name => 'Cluster Compute Eight Extra Large', :ram => 61952}, { :bits => 64, :cores => 33.5, :disk => 1690, :id => 'cg1.4xlarge', :name => 'Cluster GPU Quadruple Extra Large', :ram => 22528} ] class Flavors < Fog::Collection model Fog::Compute::AWS::Flavor # Returns an array of all flavors that have been created # # AWS.flavors.all # # ==== Returns # # Returns an array of all available instance sizes # #>> AWS.flavors.all # , # , # , # , # , # , # , # , # , # , # , # , # , # , # # ] # > # def all load(Fog::Compute::AWS::FLAVORS) self end # Used to retrieve a flavor # flavor_id is required to get the associated flavor information. # flavors available currently: # 't1.micro', 'm1.small', 'm1.large', 'm1.xlarge', 'c1.medium', 'c1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'cc1.4xlarge', 'cc2.8xlarge', 'cg1.4xlarge' # # You can run the following command to get the details: # AWS.flavors.get("t1.micro") # # ==== Returns # #>> AWS.flavors.get("t1.micro") # # def get(flavor_id) self.class.new(:service => service).all.detect {|flavor| flavor.id == flavor_id} end end end end end fog-1.19.0/lib/fog/aws/models/compute/key_pair.rb0000644000004100000410000000251312261242551021610 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class AWS class KeyPair < Fog::Model identity :name, :aliases => 'keyName' attribute :fingerprint, :aliases => 'keyFingerprint' attribute :private_key, :aliases => 'keyMaterial' attr_accessor :public_key def destroy requires :name service.delete_key_pair(name) true end def save requires :name data = if public_key service.import_key_pair(name, public_key).body else service.create_key_pair(name).body end new_attributes = data.reject {|key,value| !['keyFingerprint', 'keyMaterial', 'keyName'].include?(key)} merge_attributes(new_attributes) true end def write(path="#{ENV['HOME']}/.ssh/fog_#{Fog.credential.to_s}_#{name}.pem") if writable? split_private_key = private_key.split(/\n/) File.open(path, "w") do |f| split_private_key.each {|line| f.puts line} f.chmod 0600 end "Key file built: #{path}" else "Invalid private key" end end def writable? !!(private_key && ENV.has_key?('HOME')) end end end end end fog-1.19.0/lib/fog/aws/models/compute/tag.rb0000644000004100000410000000123112261242551020554 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class AWS class Tag < Fog::Model identity :key attribute :value attribute :resource_id, :aliases => 'resourceId' attribute :resource_type, :aliases => 'resourceType' def initialize(attributes = {}) super end def destroy requires :key, :resource_id service.delete_tags(resource_id, key => value) true end def save requires :key, :resource_id service.create_tags(resource_id, key => value) true end end end end end fog-1.19.0/lib/fog/aws/models/compute/spot_request.rb0000644000004100000410000001235712261242551022551 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class AWS class SpotRequest < Fog::Compute::Server identity :id, :aliases => 'spotInstanceRequestId' attribute :price, :aliases => 'spotPrice' attribute :request_type, :aliases => 'type' attribute :created_at, :aliases => 'createTime' attribute :instance_count, :aliases => 'instanceCount' attribute :instance_id, :aliases => 'instanceId' attribute :state attribute :valid_from, :aliases => 'validFrom' attribute :valid_until, :aliases => 'validUntil' attribute :launch_group, :aliases => 'launchGroup' attribute :availability_zone_group, :aliases => 'availabilityZoneGroup' attribute :product_description, :aliases => 'productDescription' attribute :ebs_optimized, :aliases => 'LaunchSpecification.EbsOptimized' attribute :groups, :aliases => 'LaunchSpecification.SecurityGroup' attribute :key_name, :aliases => 'LaunchSpecification.KeyName' attribute :availability_zone, :aliases => 'LaunchSpecification.Placement.AvailabilityZone' attribute :flavor_id, :aliases => 'LaunchSpecification.InstanceType' attribute :image_id, :aliases => 'LaunchSpecification.ImageId' attribute :monitoring, :aliases => 'LaunchSpecification.Monitoring' attribute :block_device_mapping, :aliases => 'LaunchSpecification.BlockDeviceMapping' attribute :subnet_id, :aliases => 'LaunchSpecification.SubnetId' attribute :iam_instance_profile, :aliases => 'LaunchSpecification.IamInstanceProfile' attribute :tags, :aliases => 'tagSet' attribute :fault, :squash => 'message' attribute :user_data attr_writer :iam_instance_profile_name, :iam_instance_profile_arn def initialize(attributes={}) self.groups ||= ["default"] self.flavor_id ||= 't1.micro' self.image_id ||= begin self.username ||= 'ubuntu' # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) case @service.instance_variable_get(:@region) # Ubuntu 10.04 LTS 64bit (EBS) when 'ap-northeast-1' 'ami-5e0fa45f' when 'ap-southeast-1' 'ami-f092eca2' when 'eu-west-1' 'ami-3d1f2b49' when 'us-east-1' 'ami-3202f25b' when 'us-west-1' 'ami-f5bfefb0' end end super end def destroy requires :id service.cancel_spot_instance_requests(id) true end def key_pair requires :key_name service.key_pairs.all(key_name).first end def key_pair=(new_keypair) self.key_name = new_keypair && new_keypair.name end def ready? state == 'active' end def save requires :image_id, :flavor_id, :price options = { 'AvailabilityZoneGroup' => availability_zone_group, 'InstanceCount' => instance_count, 'LaunchGroup' => launch_group, 'LaunchSpecification.BlockDeviceMapping' => block_device_mapping, 'LaunchSpecification.KeyName' => key_name, 'LaunchSpecification.Monitoring.Enabled' => monitoring, 'LaunchSpecification.Placement.AvailabilityZone' => availability_zone, 'LaunchSpecification.SecurityGroupId' => groups, 'LaunchSpecification.EbsOptimized' => ebs_optimized, 'LaunchSpecification.UserData' => user_data, 'LaunchSpecification.SubnetId' => subnet_id, 'LaunchSpecification.IamInstanceProfile.Arn' => @iam_instance_profile_arn, 'LaunchSpecification.IamInstanceProfile.Name' => @iam_instance_profile_name, 'Type' => request_type, 'ValidFrom' => valid_from, 'ValidUntil' => valid_until } options.delete_if {|key, value| value.nil?} data = service.request_spot_instances(image_id, flavor_id, price, options).body spot_instance_request = data['spotInstanceRequestSet'].first spot_instance_request['launchSpecification'].each do |name,value| spot_instance_request['LaunchSpecification.' + name[0,1].upcase + name[1..-1]] = value end spot_instance_request.merge(:groups => spot_instance_request['LaunchSpecification.GroupSet']) spot_instance_request.merge(options) merge_attributes( spot_instance_request ) end end end end end fog-1.19.0/lib/fog/aws/models/compute/tags.rb0000644000004100000410000000116712261242551020747 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/tag' module Fog module Compute class AWS class Tags < Fog::Collection attribute :filters model Fog::Compute::AWS::Tag def initialize(attributes) self.filters ||= {} super end def all(filters = filters) self.filters = filters data = service.describe_tags(filters).body load(data['tagSet']) end def get(key) if key self.class.new(:service => service).all('key' => key) end end end end end end fog-1.19.0/lib/fog/aws/models/compute/network_interface.rb0000644000004100000410000000501612261242551023517 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class AWS class NetworkInterface < Fog::Model identity :network_interface_id, :aliases => 'networkInterfaceId' attribute :state attribute :request_id, :aliases => 'requestId' attribute :network_interface_id, :aliases => 'networkInterfaceId' attribute :subnet_id, :aliases => 'subnetId' attribute :vpc_id, :aliases => 'vpcId' attribute :availability_zone, :aliases => 'availabilityZone' attribute :description, :aliases => 'description' attribute :owner_id, :aliases => 'ownerId' attribute :requester_id, :aliases => 'requesterId' attribute :requester_managed, :aliases => 'requesterManaged' attribute :status, :aliases => 'status' attribute :mac_address, :aliases => 'macAddress' attribute :private_ip_address, :aliases => 'privateIpAddress' attribute :private_dns_name, :aliases => 'privateDnsName' attribute :source_dest_check, :aliases => 'sourceDestCheck' attribute :group_set, :aliases => 'groupSet' attribute :attachment, :aliases => 'attachment' attribute :association, :aliases => 'association' attribute :tag_set, :aliases => 'tagSet' # Removes an existing network interface # # network_interface.destroy # # ==== Returns # # True or false depending on the result # def destroy requires :network_interface_id service.delete_network_interface(network_interface_id) true end # Create a network_interface # # >> g = AWS.network_interfaces.new(:subnet_id => "subnet-someId", options) # >> g.save # # options is an optional hash which may contain 'PrivateIpAddress', 'Description', 'groupSet' # # == Returns: # # requestId and a networkInterface object # def save requires :subnet_id data = service.create_network_interface(subnet_id).body['networkInterface'] new_attributes = data.reject {|key,value| key == 'requestId'} merge_attributes(new_attributes) true end end end end end fog-1.19.0/lib/fog/aws/models/compute/volumes.rb0000644000004100000410000000653612261242551021510 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/volume' module Fog module Compute class AWS class Volumes < Fog::Collection attribute :filters attribute :server model Fog::Compute::AWS::Volume # Used to create a volume. There are 3 arguments and availability_zone and size are required. You can generate a new key_pair as follows: # AWS.volumes.create(:availability_zone => 'us-east-1a', :size => 10) # # ==== Returns # # # # The volume can be retrieved by running AWS.volumes.get("vol-1e2028b9"). See get method below. # def initialize(attributes) self.filters ||= {} super end # Used to return all volumes. # AWS.volumes.all # # ==== Returns # #>>AWS.volumes.all # # # The volume can be retrieved by running AWS.volumes.get("vol-1e2028b9"). See get method below. # def all(filters = filters) unless filters.is_a?(Hash) Fog::Logger.deprecation("all with #{filters.class} param is deprecated, use all('volume-id' => []) instead [light_black](#{caller.first})[/]") filters = {'volume-id' => [*filters]} end self.filters = filters data = service.describe_volumes(filters).body load(data['volumeSet']) if server self.replace(self.select {|volume| volume.server_id == server.id}) end self end # Used to retrieve a volume # volume_id is required to get the associated volume information. # # You can run the following command to get the details: # AWS.volumes.get("vol-1e2028b9") # # ==== Returns # #>> AWS.volumes.get("vol-1e2028b9") # # def get(volume_id) if volume_id self.class.new(:service => service).all('volume-id' => volume_id).first end end def new(attributes = {}) if server super({ :server => server }.merge!(attributes)) else super end end end end end end fog-1.19.0/lib/fog/aws/models/compute/flavor.rb0000644000004100000410000000042212261242551021273 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class AWS class Flavor < Fog::Model identity :id attribute :bits attribute :cores attribute :disk attribute :name attribute :ram end end end end fog-1.19.0/lib/fog/aws/models/compute/snapshots.rb0000644000004100000410000000250412261242551022027 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/compute/snapshot' module Fog module Compute class AWS class Snapshots < Fog::Collection attribute :filters attribute :volume model Fog::Compute::AWS::Snapshot def initialize(attributes) self.filters ||= { 'RestorableBy' => 'self' } super end def all(filters = filters, options = {}) unless filters.is_a?(Hash) Fog::Logger.deprecation("all with #{filters.class} param is deprecated, use all('snapshot-id' => []) instead [light_black](#{caller.first})[/]") filters = {'snapshot-id' => [*filters]} end self.filters = filters data = service.describe_snapshots(filters.merge!(options)).body load(data['snapshotSet']) if volume self.replace(self.select {|snapshot| snapshot.volume_id == volume.id}) end self end def get(snapshot_id) if snapshot_id self.class.new(:service => service).all('snapshot-id' => snapshot_id).first end end def new(attributes = {}) if volume super({ 'volumeId' => volume.id }.merge!(attributes)) else super end end end end end end fog-1.19.0/lib/fog/aws/models/compute/server.rb0000644000004100000410000002403312261242551021314 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class AWS class Server < Fog::Compute::Server extend Fog::Deprecation deprecate :ip_address, :public_ip_address identity :id, :aliases => 'instanceId' attr_accessor :architecture attribute :ami_launch_index, :aliases => 'amiLaunchIndex' attribute :associate_public_ip, :aliases => 'associatePublicIP' attribute :availability_zone, :aliases => 'availabilityZone' attribute :block_device_mapping, :aliases => 'blockDeviceMapping' attribute :network_interfaces, :aliases => 'networkInterfaces' attribute :client_token, :aliases => 'clientToken' attribute :dns_name, :aliases => 'dnsName' attribute :ebs_optimized, :aliases => 'ebsOptimized' attribute :groups attribute :flavor_id, :aliases => 'instanceType' attribute :hypervisor attribute :iam_instance_profile, :aliases => 'iamInstanceProfile' attribute :image_id, :aliases => 'imageId' attr_accessor :instance_initiated_shutdown_behavior attribute :kernel_id, :aliases => 'kernelId' attribute :key_name, :aliases => 'keyName' attribute :created_at, :aliases => 'launchTime' attribute :lifecycle, :aliases => 'instanceLifecycle' attribute :monitoring, :squash => 'state' attribute :placement_group, :aliases => 'groupName' attribute :platform, :aliases => 'platform' attribute :product_codes, :aliases => 'productCodes' attribute :private_dns_name, :aliases => 'privateDnsName' attribute :private_ip_address, :aliases => 'privateIpAddress' attribute :public_ip_address, :aliases => 'ipAddress' attribute :ramdisk_id, :aliases => 'ramdiskId' attribute :reason attribute :requester_id, :aliases => 'requesterId' attribute :root_device_name, :aliases => 'rootDeviceName' attribute :root_device_type, :aliases => 'rootDeviceType' attribute :security_group_ids, :aliases => 'securityGroupIds' attribute :source_dest_check, :aliases => 'sourceDestCheck' attribute :spot_instance_request_id, :aliases => 'spotInstanceRequestId' attribute :state, :aliases => 'instanceState', :squash => 'name' attribute :state_reason, :aliases => 'stateReason' attribute :subnet_id, :aliases => 'subnetId' attribute :tenancy attribute :tags, :aliases => 'tagSet' attribute :user_data attribute :virtualization_type, :aliases => 'virtualizationType' attribute :vpc_id, :aliases => 'vpcId' attr_accessor :password attr_writer :iam_instance_profile_name, :iam_instance_profile_arn def initialize(attributes={}) self.groups ||= ["default"] unless (attributes[:subnet_id] || attributes[:security_group_ids]) self.flavor_id ||= 't1.micro' # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) self.image_id ||= begin self.username ||= 'ubuntu' case @service.instance_variable_get(:@region) # Ubuntu 10.04 LTS 64bit (EBS) when 'ap-northeast-1' 'ami-5e0fa45f' when 'ap-southeast-1' 'ami-f092eca2' when 'ap-southeast-2' 'ami-fb8611c1' # Ubuntu 12.04 LTS 64bit (EBS) when 'eu-west-1' 'ami-3d1f2b49' when 'sa-east-1' 'ami-d0429ccd' when 'us-east-1' 'ami-3202f25b' when 'us-west-1' 'ami-f5bfefb0' when 'us-west-2' 'ami-e0ec60d0' end end super end def addresses requires :id service.addresses(:server => self) end def console_output requires :id service.get_console_output(id) end def destroy requires :id service.terminate_instances(id) true end remove_method :flavor_id def flavor_id @flavor && @flavor.id || attributes[:flavor_id] end def flavor=(new_flavor) @flavor = new_flavor end def flavor @flavor ||= service.flavors.all.detect {|flavor| flavor.id == flavor_id} end def key_pair requires :key_name service.key_pairs.all(key_name).first end def key_pair=(new_keypair) self.key_name = new_keypair && new_keypair.name end def ready? state == 'running' end def reboot requires :id service.reboot_instances(id) true end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :image_id options = { 'BlockDeviceMapping' => block_device_mapping, 'ClientToken' => client_token, 'EbsOptimized' => ebs_optimized, 'IamInstanceProfile.Arn' => @iam_instance_profile_arn, 'IamInstanceProfile.Name' => @iam_instance_profile_name, 'InstanceInitiatedShutdownBehavior' => instance_initiated_shutdown_behavior, 'InstanceType' => flavor_id, 'KernelId' => kernel_id, 'KeyName' => key_name, 'Monitoring.Enabled' => monitoring, 'Placement.AvailabilityZone' => availability_zone, 'Placement.GroupName' => placement_group, 'Placement.Tenancy' => tenancy, 'PrivateIpAddress' => private_ip_address, 'RamdiskId' => ramdisk_id, 'SecurityGroup' => groups, 'SecurityGroupId' => security_group_ids, 'SubnetId' => subnet_id, 'UserData' => user_data, } options.delete_if {|key, value| value.nil?} # If subnet is defined then this is a Virtual Private Cloud. # subnet & security group cannot co-exist. Attempting to specify # both subnet and groups will cause an error. Instead please make # use of Security Group Ids when working in a VPC. if subnet_id options.delete('SecurityGroup') if associate_public_ip options['NetworkInterface.0.DeviceIndex'] = 0 options['NetworkInterface.0.AssociatePublicIpAddress'] = associate_public_ip options['NetworkInterface.0.SubnetId'] = options['SubnetId'] options.delete('SubnetId') if options['SecurityGroupId'].kind_of?(Array) options['SecurityGroupId'].each {|id| options["NetworkInterface.0.SecurityGroupId.#{options['SecurityGroupId'].index(id)}"] = id } else options["NetworkInterface.0.SecurityGroupId.0"] = options['SecurityGroupId'] end options.delete('SecurityGroupId') end else options.delete('SubnetId') end data = service.run_instances(image_id, 1, 1, options) merge_attributes(data.body['instancesSet'].first) if tags = self.tags # expect eventual consistency Fog.wait_for { self.reload rescue nil } for key, value in (self.tags = tags) service.tags.create( :key => key, :resource_id => self.identity, :value => value ) end end true end def setup(credentials = {}) requires :public_ip_address, :username require 'net/ssh' commands = [ %{mkdir .ssh}, %{passwd -l #{username}}, %{echo "#{Fog::JSON.encode(Fog::JSON.sanitize(attributes))}" >> ~/attributes.json} ] if public_key commands << %{echo "#{public_key}" >> ~/.ssh/authorized_keys} end # wait for aws to be ready wait_for { sshable?(credentials) } Fog::SSH.new(public_ip_address, username, credentials).run(commands) end def start requires :id service.start_instances(id) true end def stop(force = false) requires :id service.stop_instances(id, force) true end def volumes requires :id service.volumes(:server => self) end #I tried to call it monitoring= and be smart with attributes[] #but in #save a merge_attribute is called after run_instance #thus making an un-necessary request. Use this until finding a clever solution def monitor=(new_monitor) if persisted? case new_monitor when true response = service.monitor_instances(identity) when false response = service.unmonitor_instances(identity) else raise ArgumentError.new("only Boolean allowed here") end end self.monitoring = new_monitor end private def placement=(new_placement) if new_placement.is_a?(Hash) merge_attributes(new_placement) else self.attributes[:placement] = new_placement end end end end end end fog-1.19.0/lib/fog/aws/models/compute/image.rb0000644000004100000410000000320112261242551021062 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class AWS class Image < Fog::Model identity :id, :aliases => 'imageId' attribute :architecture attribute :block_device_mapping, :aliases => 'blockDeviceMapping' attribute :description attribute :location, :aliases => 'imageLocation' attribute :owner_id, :aliases => 'imageOwnerId' attribute :owner_alias, :aliases => 'imageOwnerAlias' attribute :state, :aliases => 'imageState' attribute :type, :aliases => 'imageType' attribute :is_public, :aliases => 'isPublic' attribute :kernel_id, :aliases => 'kernelId' attribute :platform attribute :product_codes, :aliases => 'productCodes' attribute :ramdisk_id, :aliases => 'ramdiskId' attribute :root_device_type, :aliases => 'rootDeviceType' attribute :root_device_name, :aliases => 'rootDeviceName' attribute :tags, :aliases => 'tagSet' attribute :name def deregister(delete_snapshot = false) service.deregister_image(id) if(delete_snapshot && root_device_type == "ebs") block_device = block_device_mapping.detect {|block_device| block_device['deviceName'] == root_device_name} service.snapshots.new(:id => block_device['snapshotId']).destroy else true end end def ready? state == 'available' end end end end end fog-1.19.0/lib/fog/aws/models/compute/route_table.rb0000755000004100000410000000311112261242551022310 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class AWS class RouteTable < Fog::Model identity :id, :aliases => 'routeTableId' attribute :vpc_id, :aliases => 'vpcId' attribute :routes, :aliases => 'routeSet' attribute :associations, :aliases => 'associationSet' attribute :tags, :aliases => 'tagSet' def initialize(attributes={}) super end # Remove an existing route table # # route_tables.destroy # # ==== Returns # # True or false depending on the result # def destroy requires :id service.delete_route_table(id) true end # Create a route table # # >> routetable = connection.route_tables.new # >> routetable.save # # == Returns: # # True or an exception depending on the result. Keep in mind that this *creates* a new route table. # def save requires :vpc_id data = service.create_route_table(vpc_id).body['routeTable'].first new_attributes = data.reject {|key,value| key == 'requestId'} merge_attributes(new_attributes) true end private def associationSet=(new_association_set) merge_attributes(new_association_set.first || {}) end def routeSet=(new_route_set) merge_attributes(new_route_set || {}) end end end end end fog-1.19.0/lib/fog/aws/models/elasticache/0000755000004100000410000000000012261242551020250 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/models/elasticache/security_group.rb0000644000004100000410000000262712261242551023667 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class Elasticache class SecurityGroup < Fog::Model identity :id, :aliases => 'CacheSecurityGroupName' attribute :description, :aliases => 'Description' attribute :ec2_groups, :aliases => 'EC2SecurityGroups', :type => :array attribute :owner_id, :aliases => 'OwnerId' def ready? ec2_groups.all?{|ingress| ingress['Status'] == 'authorized'} end def destroy requires :id service.delete_cache_security_group(id) true end def save requires :id requires :description service.create_cache_security_group(id, description) end def authorize_ec2_group(group_name, group_owner_id=owner_id) requires :id requires :owner_id if group_owner_id.nil? data = service.authorize_cache_security_group_ingress( id, group_name, group_owner_id ) merge_attributes(data.body['CacheSecurityGroup']) end def revoke_ec2_group(group_name, group_owner_id=owner_id) requires :id requires :owner_id if group_owner_id.nil? data = service.revoke_cache_security_group_ingress( id, group_name, group_owner_id ) merge_attributes(data.body['CacheSecurityGroup']) end end end end end fog-1.19.0/lib/fog/aws/models/elasticache/cluster.rb0000644000004100000410000000474212261242551022265 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class Elasticache class Cluster < Fog::Model # simple attributes identity :id, :aliases => 'CacheClusterId' attribute :auto_upgrade, :aliases => 'AutoMinorVersionUpgrade' attribute :status, :aliases => 'CacheClusterStatus' attribute :node_type, :aliases => 'CacheNodeType' attribute :engine, :aliases => 'Engine' attribute :engine_version, :aliases => 'EngineVersion' attribute :num_nodes, :aliases => 'NumCacheNodes' attribute :zone, :aliases => 'PreferredAvailabilityZone' attribute :port, :aliases => 'Port' attribute :maintenance_window, :aliases => 'PreferredMaintenanceWindow' # complex attributes attribute :nodes, :aliases => 'CacheNodes', :type => :array attribute :parameter_group, :aliases => 'CacheParameterGroup', :type => :hash attribute :pending_values, :aliases => 'PendingModifiedValues', :type => :hash attribute :create_time, :aliases => 'CacheClusterCreateTime', :type => :date_time attribute :security_groups, :aliases => 'CacheSecurityGroups', :type => :array attribute :notification_config, :aliases => 'NotificationConfiguration', :type => :hash attr_accessor :parameter_group_name def ready? status == 'available' end def destroy requires :id service.delete_cache_cluster(id) true end def save requires :id parameter_group ||= Hash.new notification_config ||= Hash.new service.create_cache_cluster( id, { :node_type => node_type, :security_group_names => security_groups, :num_nodes => num_nodes, :auto_minor_version_upgrade => auto_upgrade, :engine => engine, :engine_version => engine_version, :notification_topic_arn => notification_config['TopicArn'], :port => port, :preferred_availablility_zone => zone, :preferred_maintenance_window => maintenance_window, :parameter_group_name => parameter_group_name || parameter_group['CacheParameterGroupName'], } ) end end end end end fog-1.19.0/lib/fog/aws/models/elasticache/parameter_group.rb0000644000004100000410000000121312261242551023766 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class Elasticache class ParameterGroup < Fog::Model identity :id, :aliases => 'CacheParameterGroupName' attribute :description, :aliases => 'Description' attribute :family, :aliases => 'CacheParameterGroupFamily' def destroy requires :id service.delete_cache_parameter_group(id) true end def save requires :id service.create_cache_parameter_group( id, description = id, family = 'memcached1.4' ) end end end end end fog-1.19.0/lib/fog/aws/models/elasticache/security_groups.rb0000644000004100000410000000120112261242551024035 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/elasticache/security_group' module Fog module AWS class Elasticache class SecurityGroups < Fog::Collection model Fog::AWS::Elasticache::SecurityGroup def all load( service.describe_cache_security_groups.body['CacheSecurityGroups'] ) end def get(identity) new( service.describe_cache_security_groups( identity ).body['CacheSecurityGroups'].first ) rescue Fog::AWS::Elasticache::NotFound nil end end end end end fog-1.19.0/lib/fog/aws/models/elasticache/parameter_groups.rb0000644000004100000410000000121012261242551024146 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/elasticache/parameter_group' module Fog module AWS class Elasticache class ParameterGroups < Fog::Collection model Fog::AWS::Elasticache::ParameterGroup def all load( service.describe_cache_parameter_groups.body['CacheParameterGroups'] ) end def get(identity) new( service.describe_cache_parameter_groups( identity ).body['CacheParameterGroups'].first ) rescue Fog::AWS::Elasticache::NotFound nil end end end end end fog-1.19.0/lib/fog/aws/models/elasticache/clusters.rb0000644000004100000410000000127212261242551022443 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/elasticache/cluster' module Fog module AWS class Elasticache class Clusters < Fog::Collection model Fog::AWS::Elasticache::Cluster def all load( service.describe_cache_clusters( nil, :show_node_info => true ).body['CacheClusters'] ) end def get(identity, show_node_info = true) new( service.describe_cache_clusters( identity, :show_node_info => show_node_info ).body['CacheClusters'].first ) rescue Fog::AWS::Elasticache::NotFound end end end end end fog-1.19.0/lib/fog/aws/models/iam/0000755000004100000410000000000012261242551016551 5ustar www-datawww-datafog-1.19.0/lib/fog/aws/models/iam/roles.rb0000644000004100000410000000155212261242551020225 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/iam/role' module Fog module AWS class IAM class Roles < Fog::Collection model Fog::AWS::IAM::Role def initialize(attributes = {}) super end def all data = service.list_roles.body['Roles'] load(data) end def get(identity) role = nil begin role = service.roles.new( service.get_role( identity ).data[:body]["Role"] ) rescue Excon::Errors::NotFound # ignore not found error end role end def new(attributes = {}) if not attributes.has_key?(:assume_role_policy_document) attributes[:assume_role_policy_document] = Fog::AWS::IAM::EC2_ASSUME_ROLE_POLICY.to_s end super end end end end end fog-1.19.0/lib/fog/aws/models/iam/access_keys.rb0000644000004100000410000000147712261242551021403 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/iam/access_key' module Fog module AWS class IAM class AccessKeys < Fog::Collection model Fog::AWS::IAM::AccessKey def initialize(attributes = {}) @username = attributes[:username] super end def all data = service.list_access_keys('UserName'=> @username).body['AccessKeys'] # AWS response doesn't contain the UserName, this injects it data.each {|access_key| access_key['UserName'] = @username } load(data) end def get(identity) self.all.select {|access_key| access_key.id == identity}.first end def new(attributes = {}) super({ :username => @username }.merge!(attributes)) end end end end end fog-1.19.0/lib/fog/aws/models/iam/role.rb0000644000004100000410000000171412261242551020042 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class IAM class Role < Fog::Model identity :id, :aliases => 'RoleId' attribute :rolename, :aliases => 'RoleName' attribute :create_date, :aliases => 'CreateDate', :type => :time attribute :assume_role_policy_document, :aliases => 'AssumeRolePolicyDocument' attribute :arn, :aliases => 'Arn' attribute :path, :aliases => 'Path' def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :rolename requires :assume_role_policy_document data = service.create_role(rolename, assume_role_policy_document).body["Role"] merge_attributes(data) true end def destroy requires :rolename service.delete_role(rolename) true end end end end endfog-1.19.0/lib/fog/aws/models/iam/policy.rb0000644000004100000410000000137412261242551020402 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class IAM class Policy < Fog::Model identity :id, :aliases => 'PolicyName' attribute :username, :aliases => 'UserName' attribute :document, :aliases => 'PolicyDocument' def save requires :id requires :username requires :document data = service.put_user_policy(username, id, document).body merge_attributes(data) true end def destroy requires :id requires :username service.delete_user_policy(username, id) true end def user requires :username service.users.get(username) end end end end end fog-1.19.0/lib/fog/aws/models/iam/user.rb0000644000004100000410000000153312261242551020056 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class IAM class User < Fog::Model identity :id, :aliases => 'UserName' attribute :path, :aliases => 'Path' attribute :arn, :aliases => 'Arn' attribute :user_id, :aliases => 'UserId' attribute :created_at, :aliases => 'CreateDate', :type => :time def save requires :id data = service.create_user(id, path || '/').body['User'] merge_attributes(data) true end def destroy requires :id service.delete_user(id) true end def policies requires :id service.policies(:username => id) end def access_keys requires :id service.access_keys(:username => id) end end end end end fog-1.19.0/lib/fog/aws/models/iam/policies.rb0000644000004100000410000000252012261242551020704 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/iam/policy' module Fog module AWS class IAM class Policies < Fog::Collection model Fog::AWS::IAM::Policy def initialize(attributes = {}) @username = attributes[:username] raise ArgumentError.new("Can't get a policy's user without a username") unless @username super end def all # AWS method get_user_policy only returns an array of policy names, this is kind of useless, # that's why it has to loop through the list to get the details of each element. I don't like it because it makes this method slow policy_names = service.list_user_policies(@username).body['PolicyNames'] # it returns an array policies = [] policy_names.each do |policy_name| policies << service.get_user_policy(policy_name,@username).body['Policy'] end load(policies) # data is an array of attribute hashes end def get(identity) data = service.get_user_policy(identity,@username).body['Policy'] new(data) # data is an attribute hash rescue Fog::AWS::IAM::NotFound nil end def new(attributes = {}) super({ :username => @username }.merge!(attributes)) end end end end end fog-1.19.0/lib/fog/aws/models/iam/users.rb0000644000004100000410000000233712261242551020244 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/aws/models/iam/user' module Fog module AWS class IAM class Users < Fog::Collection attribute :is_truncated, :aliases => 'IsTruncated' attribute :marker, :aliases => 'Marker' model Fog::AWS::IAM::User def all(options = {}) merge_attributes(options) data = service.list_users(options).body merge_attributes('IsTruncated' => data['IsTruncated'], 'Marker' => data['Marker']) load(data['Users']) # data is an array of attribute hashes end def get(identity) data = service.get_user(identity).body['User'] new(data) # data is an attribute hash rescue Fog::AWS::IAM::NotFound nil end alias :each_user_this_page :each def each if !block_given? self else subset = dup.all subset.each_user_this_page {|f| yield f} while subset.is_truncated subset = subset.all('Marker' => subset.marker, 'MaxItems' => 1000) subset.each_user_this_page {|f| yield f} end self end end end end end end fog-1.19.0/lib/fog/aws/models/iam/access_key.rb0000644000004100000410000000167212261242551021215 0ustar www-datawww-datarequire 'fog/core/model' module Fog module AWS class IAM class AccessKey < Fog::Model identity :id, :aliases => 'AccessKeyId' attribute :username, :aliases => 'UserName' attribute :secret_access_key, :aliases => 'SecretAccessKey' attribute :status, :aliases => 'Status' def save requires :username if !persisted? data = service.create_access_key('UserName'=> username).body["AccessKey"] else data = service.update_access_key(id, status, "UserName" => username).body["AccessKey"] end merge_attributes(data) true end def destroy requires :id requires :username service.delete_access_key(id,'UserName'=> username) true end def user requires :username service.users.get(username) end end end end end fog-1.19.0/lib/fog/aws/credential_fetcher.rb0000644000004100000410000000424412261242551020663 0ustar www-datawww-datarequire "fog/json" module Fog module AWS module CredentialFetcher INSTANCE_METADATA_HOST = "http://169.254.169.254" INSTANCE_METADATA_PATH = "/latest/meta-data/iam/security-credentials/" module ServiceMethods def fetch_credentials(options) if options[:use_iam_profile] begin connection = options[:connection] || Excon.new(INSTANCE_METADATA_HOST) role_name = connection.get(:path => INSTANCE_METADATA_PATH, :expects => 200).body role_data = connection.get(:path => INSTANCE_METADATA_PATH+role_name, :expects => 200).body session = Fog::JSON.decode(role_data) credentials = {} credentials[:aws_access_key_id] = session['AccessKeyId'] credentials[:aws_secret_access_key] = session['SecretAccessKey'] credentials[:aws_session_token] = session['Token'] credentials[:aws_credentials_expire_at] = Time.xmlschema session['Expiration'] #these indicate the metadata service is unavailable or has no profile setup credentials rescue Excon::Errors::Error => e Fog::Logger.warning("Unable to fetch credentials: #{e.message}") super end else super end end end module ConnectionMethods def refresh_credentials_if_expired refresh_credentials if credentials_expired? end private def credentials_expired? @use_iam_profile && (!@aws_credentials_expire_at || (@aws_credentials_expire_at && Fog::Time.now > @aws_credentials_expire_at - 15)) #new credentials become available from around 5 minutes before expiration time end def refresh_credentials if @use_iam_profile new_credentials = service.fetch_credentials :use_iam_profile => @use_iam_profile if new_credentials.any? setup_credentials new_credentials return true else false end else false end end end end end end fog-1.19.0/lib/fog/aws/signaturev4.rb0000644000004100000410000000440412261242551017322 0ustar www-datawww-data# See http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html # module Fog module AWS class SignatureV4 def initialize(aws_access_key_id, secret_key, region,service) @region = region @service = service @aws_access_key_id = aws_access_key_id @hmac = Fog::HMAC.new('sha256', 'AWS4' + secret_key) end def sign(params, date) canonical_request = <<-DATA #{params[:method].to_s.upcase} #{params[:path]} #{canonical_query_string(params[:query])} #{canonical_headers(params[:headers])} #{signed_headers(params[:headers])} #{Digest::SHA256.hexdigest(params[:body] || '')} DATA canonical_request.chop! credential_scope = "#{date.utc.strftime('%Y%m%d')}/#{@region}/#{@service}/aws4_request" string_to_sign = <<-DATA AWS4-HMAC-SHA256 #{date.to_iso8601_basic} #{credential_scope} #{Digest::SHA256.hexdigest(canonical_request)} DATA string_to_sign.chop! signature = derived_hmac(date).sign(string_to_sign) "AWS4-HMAC-SHA256 Credential=#{@aws_access_key_id}/#{credential_scope}, SignedHeaders=#{signed_headers(params[:headers])}, Signature=#{signature.unpack('H*').first}" end protected def canonical_query_string(query) canonical_query_string = [] for key in (query || {}).keys.sort_by {|k| k.to_s} component = "#{Fog::AWS.escape(key.to_s)}=#{Fog::AWS.escape(query[key].to_s)}" canonical_query_string << component end canonical_query_string.join("&") end def canonical_headers(headers) canonical_headers = '' for key in headers.keys.sort_by {|k| k.to_s} canonical_headers << "#{key.to_s.downcase}:#{headers[key].to_s.strip}\n" end canonical_headers end def signed_headers(headers) headers.keys.collect {|key| key.to_s}.sort.collect {|key| key.downcase}.join(';') end def derived_hmac(date) kDate = @hmac.sign(date.utc.strftime('%Y%m%d')) kRegion = Fog::HMAC.new('sha256', kDate).sign(@region) kService = Fog::HMAC.new('sha256', kRegion).sign(@service) kSigning = Fog::HMAC.new('sha256', kService).sign('aws4_request') Fog::HMAC.new('sha256', kSigning) end end end end fog-1.19.0/lib/fog/aws/glacier.rb0000644000004100000410000001303012261242551016450 0ustar www-datawww-datarequire 'fog/aws' module Fog module AWS class Glacier < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods requires :aws_access_key_id, :aws_secret_access_key recognizes :region, :host, :path, :port, :scheme, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at request_path 'fog/aws/requests/glacier' request :abort_multipart_upload request :complete_multipart_upload request :create_archive request :create_vault request :delete_archive request :delete_vault request :delete_vault_notification_configuration request :describe_job request :describe_vault request :get_job_output request :get_vault_notification_configuration request :initiate_job request :initiate_multipart_upload request :list_jobs request :list_multipart_uploads request :list_parts request :list_vaults request :set_vault_notification_configuration request :upload_part model_path 'fog/aws/models/glacier' model :vault collection :vaults MEGABYTE = 1024*1024 class TreeHash def self.digest(body) new.add_part(body) end def reduce_digests(digests) while digests.length > 1 digests = digests.each_slice(2).collect do |pair| if pair.length == 2 Digest::SHA256.digest(pair[0]+pair[1]) else pair.first end end end digests.first end def initialize @digests = [] end def add_part(bytes) part = self.digest_for_part(bytes) @digests << part part.unpack('H*').first end def digest_for_part(body) chunk_count = [body.bytesize / MEGABYTE + (body.bytesize % MEGABYTE > 0 ? 1 : 0), 1].max if body.respond_to? :byteslice digests_for_part = chunk_count.times.collect {|chunk_index| Digest::SHA256.digest(body.byteslice(chunk_index * MEGABYTE, MEGABYTE))} else if body.respond_to? :encoding old_encoding = body.encoding body.force_encoding('BINARY') end digests_for_part = chunk_count.times.collect {|chunk_index| Digest::SHA256.digest(body.slice(chunk_index * MEGABYTE, MEGABYTE))} if body.respond_to? :encoding body.force_encoding(old_encoding) end end reduce_digests(digests_for_part) end def hexdigest digest.unpack('H*').first end def digest reduce_digests(@digests) end end class Mock def initialize(options={}) Fog::Mock.not_implemented end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to Glacier # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # ses = SES.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # * region<~String> - optional region to use. For instance, 'us-east-1' and etc. # # ==== Returns # * Glacier object with connection to AWS. def initialize(options={}) @use_iam_profile = options[:use_iam_profile] @region = options[:region] || 'us-east-1' setup_credentials(options) @connection_options = options[:connection_options] || {} @host = options[:host] || "glacier.#{@region}.amazonaws.com" @version = '2012-06-01' @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @signer = Fog::AWS::SignatureV4.new( @aws_access_key_id, @aws_secret_access_key,@region,'glacier') end def request(params, &block) refresh_credentials_if_expired date = Fog::Time.now params[:headers]['Date'] = date.to_date_header params[:headers]['x-amz-date'] = date.to_iso8601_basic params[:headers]['Host'] = @host params[:headers]['x-amz-glacier-version'] = @version params[:headers]['x-amz-security-token'] = @aws_session_token if @aws_session_token params[:headers]['Authorization'] = @signer.sign params, date response = @connection.request(params, &block) if response.headers['Content-Type'] == 'application/json' && response.body.size > 0 #body will be empty if the streaming form has been used response.body = Fog::JSON.decode(response.body) end response end end end end end fog-1.19.0/lib/fog/aws/compute.rb0000644000004100000410000004051612261242551016527 0ustar www-datawww-datarequire 'fog/aws' require 'fog/compute' module Fog module Compute class AWS < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods requires :aws_access_key_id, :aws_secret_access_key recognizes :endpoint, :region, :host, :path, :port, :scheme, :persistent, :aws_session_token, :use_iam_profile, :aws_credentials_expire_at, :instrumentor, :instrumentor_name, :version secrets :aws_secret_access_key, :hmac, :aws_session_token model_path 'fog/aws/models/compute' model :address collection :addresses model :dhcp_options collection :dhcp_options model :flavor collection :flavors model :image collection :images model :internet_gateway collection :internet_gateways model :key_pair collection :key_pairs model :network_interface collection :network_interfaces model :route_table collection :route_tables model :security_group collection :security_groups model :server collection :servers model :snapshot collection :snapshots model :tag collection :tags model :volume collection :volumes model :spot_request collection :spot_requests model :subnet collection :subnets model :vpc collection :vpcs request_path 'fog/aws/requests/compute' request :allocate_address request :assign_private_ip_addresses request :associate_address request :associate_dhcp_options request :attach_network_interface request :associate_route_table request :attach_internet_gateway request :attach_volume request :authorize_security_group_ingress request :cancel_spot_instance_requests request :create_dhcp_options request :create_internet_gateway request :create_image request :create_key_pair request :create_network_interface request :create_placement_group request :create_route request :create_route_table request :create_security_group request :create_snapshot request :create_spot_datafeed_subscription request :create_subnet request :create_tags request :create_volume request :create_vpc request :copy_image request :copy_snapshot request :delete_dhcp_options request :delete_internet_gateway request :delete_key_pair request :delete_network_interface request :delete_security_group request :delete_placement_group request :delete_route request :delete_route_table request :delete_snapshot request :delete_spot_datafeed_subscription request :delete_subnet request :delete_tags request :delete_volume request :delete_vpc request :deregister_image request :describe_account_attributes request :describe_addresses request :describe_availability_zones request :describe_dhcp_options request :describe_images request :describe_instances request :describe_internet_gateways request :describe_reserved_instances request :describe_instance_status request :describe_key_pairs request :describe_network_interface_attribute request :describe_network_interfaces request :describe_route_tables request :describe_placement_groups request :describe_regions request :describe_reserved_instances_offerings request :describe_security_groups request :describe_snapshots request :describe_spot_datafeed_subscription request :describe_spot_instance_requests request :describe_spot_price_history request :describe_subnets request :describe_tags request :describe_volumes request :describe_volume_status request :describe_vpcs request :detach_network_interface request :detach_internet_gateway request :detach_volume request :disassociate_address request :disassociate_route_table request :get_console_output request :get_password_data request :import_key_pair request :modify_image_attribute request :modify_instance_attribute request :modify_network_interface_attribute request :modify_snapshot_attribute request :modify_volume_attribute request :modify_vpc_attribute request :purchase_reserved_instances_offering request :reboot_instances request :release_address request :register_image request :request_spot_instances request :reset_network_interface_attribute request :revoke_security_group_ingress request :run_instances request :terminate_instances request :start_instances request :stop_instances request :monitor_instances request :unmonitor_instances # deprecation class Real def modify_image_attributes(*params) Fog::Logger.deprecation("modify_image_attributes is deprecated, use modify_image_attribute instead [light_black](#{caller.first})[/]") modify_image_attribute(*params) end end class Mock include Fog::AWS::CredentialFetcher::ConnectionMethods def self.data @data ||= Hash.new do |hash, region| hash[region] = Hash.new do |region_hash, key| owner_id = Fog::AWS::Mock.owner_id security_group_id = Fog::AWS::Mock.security_group_id region_hash[key] = { :deleted_at => {}, :addresses => {}, :images => {}, :image_launch_permissions => Hash.new do |permissions_hash, image_key| permissions_hash[image_key] = { :users => [] } end, :instances => {}, :reserved_instances => {}, :key_pairs => {}, :limits => { :addresses => 5 }, :owner_id => owner_id, :security_groups => { 'default' => { 'groupDescription' => 'default group', 'groupName' => 'default', 'groupId' => security_group_id, 'ipPermissionsEgress' => [], 'ipPermissions' => [ { 'groups' => [{'groupName' => 'default', 'userId' => owner_id, 'groupId' => security_group_id }], 'fromPort' => -1, 'toPort' => -1, 'ipProtocol' => 'icmp', 'ipRanges' => [] }, { 'groups' => [{'groupName' => 'default', 'userId' => owner_id, 'groupId' => security_group_id}], 'fromPort' => 0, 'toPort' => 65535, 'ipProtocol' => 'tcp', 'ipRanges' => [] }, { 'groups' => [{'groupName' => 'default', 'userId' => owner_id, 'groupId' => security_group_id}], 'fromPort' => 0, 'toPort' => 65535, 'ipProtocol' => 'udp', 'ipRanges' => [] } ], 'ownerId' => owner_id }, 'amazon-elb-sg' => { 'groupDescription' => 'amazon-elb-sg', 'groupName' => 'amazon-elb-sg', 'groupId' => 'amazon-elb', 'ownerId' => 'amazon-elb', 'ipPermissionsEgree' => [], 'ipPermissions' => [], }, }, :network_interfaces => {}, :snapshots => {}, :volumes => {}, :internet_gateways => {}, :tags => {}, :tag_sets => Hash.new do |tag_set_hash, resource_id| tag_set_hash[resource_id] = {} end, :subnets => [], :vpcs => [], :dhcp_options => [], :route_tables => [], :account_attributes => [ { "values" => ["5"], "attributeName" => "vpc-max-security-groups-per-interface" }, { "values" => ["20"], "attributeName" => "max-instances" }, { "values" => ["EC2", "VPC"], "attributeName" => "supported-platforms" }, { "values" => ["none"], "attributeName" => "default-vpc" }, { "values" => ["5"], "attributeName" => "max-elastic-ips" }, { "values" => ["5"], "attributeName" => "vpc-max-elastic-ips" } ] } end end end def self.reset @data = nil end attr_accessor :region def initialize(options={}) @use_iam_profile = options[:use_iam_profile] @aws_credentials_expire_at = Time::now + 20 setup_credentials(options) @region = options[:region] || 'us-east-1' unless ['ap-northeast-1', 'ap-southeast-1', 'ap-southeast-2', 'eu-west-1', 'us-east-1', 'us-west-1', 'us-west-2', 'sa-east-1'].include?(@region) raise ArgumentError, "Unknown region: #{@region.inspect}" end end def region_data self.class.data[@region] end def data self.region_data[@aws_access_key_id] end def reset_data self.region_data.delete(@aws_access_key_id) end def visible_images images = self.data[:images].values.inject({}) do |h, image| h.update(image['imageId'] => image) end self.region_data.each do |aws_access_key_id, data| data[:image_launch_permissions].each do |image_id, list| if list[:users].include?(self.data[:owner_id]) images.update(image_id => data[:images][image_id]) end end end images end def ec2_compatibility_mode(enabled=true) values = enabled ? ["EC2", "VPC"] : ["VPC"] self.data[:account_attributes].detect { |h| h["attributeName"] == "supported-platforms" }["values"] = values end def apply_tag_filters(resources, filters, resource_id_key) tag_set_fetcher = lambda {|resource| self.data[:tag_sets][resource[resource_id_key]] } # tag-key: match resources tagged with this key (any value) if filters.has_key?('tag-key') value = filters.delete('tag-key') resources = resources.select{|r| tag_set_fetcher[r].has_key?(value)} end # tag-value: match resources tagged with this value (any key) if filters.has_key?('tag-value') value = filters.delete('tag-value') resources = resources.select{|r| tag_set_fetcher[r].values.include?(value)} end # tag:key: match resources tagged with a key-value pair. Value may be an array, which is OR'd. tag_filters = {} filters.keys.each do |key| tag_filters[key.gsub('tag:', '')] = filters.delete(key) if /^tag:/ =~ key end for tag_key, tag_value in tag_filters resources = resources.select{|r| tag_value.include?(tag_set_fetcher[r][tag_key])} end resources end def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] end end class Real include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to EC2 # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # sdb = SimpleDB.new( # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # * region<~String> - optional region to use. For instance, # 'eu-west-1', 'us-east-1', and etc. # * aws_session_token<~String> - when using Session Tokens or Federated Users, a session_token must be presented # # ==== Returns # * EC2 object with connection to aws. attr_accessor :region def initialize(options={}) require 'fog/core/parser' @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} @region = options[:region] ||= 'us-east-1' @instrumentor = options[:instrumentor] @instrumentor_name = options[:instrumentor_name] || 'fog.aws.compute' @version = options[:version] || '2013-10-01' if @endpoint = options[:endpoint] endpoint = URI.parse(@endpoint) @host = endpoint.host @path = endpoint.path @port = endpoint.port @scheme = endpoint.scheme else @host = options[:host] || "ec2.#{options[:region]}.amazonaws.com" @path = options[:path] || '/' @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' end @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options) end def reload @connection.reset end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha256', @aws_secret_access_key) end def request(params) refresh_credentials_if_expired idempotent = params.delete(:idempotent) parser = params.delete(:parser) body = Fog::AWS.signed_params( params, { :aws_access_key_id => @aws_access_key_id, :aws_session_token => @aws_session_token, :hmac => @hmac, :host => @host, :path => @path, :port => @port, :version => @version } ) if @instrumentor @instrumentor.instrument("#{@instrumentor_name}.request", params) do _request(body, idempotent, parser) end else _request(body, idempotent, parser) end end def _request(body, idempotent, parser) @connection.request({ :body => body, :expects => 200, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded' }, :idempotent => idempotent, :method => 'POST', :parser => parser }) rescue Excon::Errors::HTTPStatusError => error match = Fog::AWS::Errors.match_error(error) raise if match.empty? raise case match[:code] when 'NotFound', 'Unknown' Fog::Compute::AWS::NotFound.slurp(error, match[:message]) else Fog::Compute::AWS::Error.slurp(error, "#{match[:code]} => #{match[:message]}") end end end end end end fog-1.19.0/lib/fog/aws/storage.rb0000644000004100000410000004302412261242551016514 0ustar www-datawww-datarequire 'fog/aws' require 'fog/storage' module Fog module Storage class AWS < Fog::Service extend Fog::AWS::CredentialFetcher::ServiceMethods COMPLIANT_BUCKET_NAMES = /^(?:[a-z]|\d(?!\d{0,2}(?:\.\d{1,3}){3}$))(?:[a-z0-9]|\.(?![\.\-])|\-(?![\.])){1,61}[a-z0-9]$/ DEFAULT_REGION = 'us-east-1' DEFAULT_SCHEME = 'https' DEFAULT_SCHEME_PORT = { 'http' => 80, 'https' => 443 } VALID_QUERY_KEYS = %w[ acl cors delete lifecycle location logging notification partNumber policy requestPayment response-cache-control response-content-disposition response-content-encoding response-content-language response-content-type response-expires restore tagging torrent uploadId uploads versionId versioning versions website ] requires :aws_access_key_id, :aws_secret_access_key recognizes :endpoint, :region, :host, :port, :scheme, :persistent, :use_iam_profile, :aws_session_token, :aws_credentials_expire_at, :path_style secrets :aws_secret_access_key, :hmac model_path 'fog/aws/models/storage' collection :directories model :directory collection :files model :file request_path 'fog/aws/requests/storage' request :abort_multipart_upload request :complete_multipart_upload request :copy_object request :delete_bucket request :delete_bucket_cors request :delete_bucket_lifecycle request :delete_bucket_policy request :delete_bucket_website request :delete_object request :delete_multiple_objects request :delete_bucket_tagging request :get_bucket request :get_bucket_acl request :get_bucket_cors request :get_bucket_lifecycle request :get_bucket_location request :get_bucket_logging request :get_bucket_object_versions request :get_bucket_policy request :get_bucket_tagging request :get_bucket_versioning request :get_bucket_website request :get_object request :get_object_acl request :get_object_torrent request :get_object_http_url request :get_object_https_url request :get_object_url request :get_request_payment request :get_service request :head_object request :initiate_multipart_upload request :list_multipart_uploads request :list_parts request :post_object_hidden_fields request :post_object_restore request :put_bucket request :put_bucket_acl request :put_bucket_cors request :put_bucket_lifecycle request :put_bucket_logging request :put_bucket_policy request :put_bucket_tagging request :put_bucket_versioning request :put_bucket_website request :put_object request :put_object_acl request :put_object_url request :put_request_payment request :sync_clock request :upload_part module Utils attr_accessor :region def cdn @cdn ||= Fog::AWS::CDN.new( :aws_access_key_id => @aws_access_key_id, :aws_secret_access_key => @aws_secret_access_key, :use_iam_profile => @use_iam_profile ) end def http_url(params, expires) signed_url(params.merge(:scheme => 'http'), expires) end def https_url(params, expires) signed_url(params.merge(:scheme => 'https'), expires) end def url(params, expires) Fog::Logger.deprecation("Fog::Storage::AWS => #url is deprecated, use #https_url instead [light_black](#{caller.first})[/]") https_url(params, expires) end def request_url(params) params = request_params(params) params_to_url(params) end def signed_url(params, expires) expires = expires.to_i if @aws_session_token params[:headers]||= {} params[:headers]['x-amz-security-token'] = @aws_session_token end signature = signature(params, expires) params = request_params(params) params[:query] = (params[:query] || {}).merge({ 'AWSAccessKeyId' => @aws_access_key_id, 'Signature' => signature, 'Expires' => expires, }) params[:query]['x-amz-security-token'] = @aws_session_token if @aws_session_token params_to_url(params) end private def region_to_host(region=nil) case region.to_s when DEFAULT_REGION, '' 's3.amazonaws.com' else "s3-#{region}.amazonaws.com" end end def object_to_path(object_name=nil) '/' + escape(object_name.to_s).gsub('%2F','/') end def bucket_to_path(bucket_name, path=nil) "/#{escape(bucket_name.to_s)}#{path}" end # NOTE: differs from Fog::AWS.escape by NOT escaping `/` def escape(string) unless @unf_loaded_or_warned begin require('unf/normalizer') rescue LoadError Fog::Logger.warning("Unable to load the 'unf' gem. Your AWS strings may not be properly encoded.") end @unf_loaded_or_warned = true end string = defined?(::UNF::Normalizer) ? ::UNF::Normalizer.normalize(string, :nfc) : string string.gsub(/([^a-zA-Z0-9_.\-~\/]+)/) { "%" + $1.unpack("H2" * $1.bytesize).join("%").upcase } end # Transforms things like bucket_name, object_name, region # # Should yield the same result when called f*f def request_params(params) headers = params[:headers] || {} if params[:scheme] scheme = params[:scheme] port = params[:port] || DEFAULT_SCHEME_PORT[scheme] else scheme = @scheme port = @port end if DEFAULT_SCHEME_PORT[scheme] == port port = nil end if params[:region] region = params[:region] host = params[:host] || region_to_host(region) else region = @region || DEFAULT_REGION host = params[:host] || @host || region_to_host(region) end path = params[:path] || object_to_path(params[:object_name]) path = '/' + path if path[0..0] != '/' if params[:bucket_name] bucket_name = params[:bucket_name] path_style = params.fetch(:path_style, @path_style) if !path_style && COMPLIANT_BUCKET_NAMES !~ bucket_name Fog::Logger.warning("fog: the specified s3 bucket name(#{bucket_name}) is not a valid dns name, which will negatively impact performance. For details see: http://docs.amazonwebservices.com/AmazonS3/latest/dev/BucketRestrictions.html") path_style = true end if path_style path = bucket_to_path bucket_name, path else host = [bucket_name, host].join('.') end end ret = params.merge({ :scheme => scheme, :host => host, :port => port, :path => path, :headers => headers }) # ret.delete(:path_style) ret.delete(:bucket_name) ret.delete(:object_name) ret.delete(:region) ret end def params_to_url(params) query = params[:query] && params[:query].map do |key, value| if value [key, escape(value.to_s)].join('=') else key end end.join('&') URI::Generic.build({ :scheme => params[:scheme], :host => params[:host], :port => params[:port], :path => params[:path], :query => query, }).to_s end end class Mock include Utils def self.acls(type) case type when 'private' { "AccessControlList" => [ { "Permission" => "FULL_CONTROL", "Grantee" => {"DisplayName" => "me", "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0"} } ], "Owner" => {"DisplayName" => "me", "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0"} } when 'public-read' { "AccessControlList" => [ { "Permission" => "FULL_CONTROL", "Grantee" => {"DisplayName" => "me", "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0"} }, { "Permission" => "READ", "Grantee" => {"URI" => "http://acs.amazonaws.com/groups/global/AllUsers"} } ], "Owner" => {"DisplayName" => "me", "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0"} } when 'public-read-write' { "AccessControlList" => [ { "Permission" => "FULL_CONTROL", "Grantee" => {"DisplayName" => "me", "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0"} }, { "Permission" => "READ", "Grantee" => {"URI" => "http://acs.amazonaws.com/groups/global/AllUsers"} }, { "Permission" => "WRITE", "Grantee" => {"URI" => "http://acs.amazonaws.com/groups/global/AllUsers"} } ], "Owner" => {"DisplayName" => "me", "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0"} } when 'authenticated-read' { "AccessControlList" => [ { "Permission" => "FULL_CONTROL", "Grantee" => {"DisplayName" => "me", "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0"} }, { "Permission" => "READ", "Grantee" => {"URI" => "http://acs.amazonaws.com/groups/global/AuthenticatedUsers"} } ], "Owner" => {"DisplayName" => "me", "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0"} } end end def self.data @data ||= Hash.new do |hash, region| hash[region] = Hash.new do |region_hash, key| region_hash[key] = { :acls => { :bucket => {}, :object => {} }, :buckets => {}, :cors => { :bucket => {} }, :bucket_tagging => {} } end end end def self.reset @data = nil end def initialize(options={}) @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @region = options[:region] || DEFAULT_REGION @host = options[:host] || region_to_host(@region) @scheme = options[:scheme] || DEFAULT_SCHEME end def data self.class.data[@region][@aws_access_key_id] end def reset_data self.class.data[@region].delete(@aws_access_key_id) end def signature(params, expires) "foo" end def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] end end class Real include Utils include Fog::AWS::CredentialFetcher::ConnectionMethods # Initialize connection to S3 # # ==== Notes # options parameter must include values for :aws_access_key_id and # :aws_secret_access_key in order to create a connection # # ==== Examples # s3 = Fog::Storage.new( # :provider => "AWS", # :aws_access_key_id => your_aws_access_key_id, # :aws_secret_access_key => your_aws_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # # ==== Returns # * S3 object with connection to aws. def initialize(options={}) require 'fog/core/parser' @use_iam_profile = options[:use_iam_profile] setup_credentials(options) @connection_options = options[:connection_options] || {} @persistent = options.fetch(:persistent, false) @path_style = options[:path_style] || false if @endpoint = options[:endpoint] endpoint = URI.parse(@endpoint) @host = endpoint.host @scheme = endpoint.scheme @port = endpoint.port else @region = options[:region] || DEFAULT_REGION @host = options[:host] || region_to_host(@region) @scheme = options[:scheme] || DEFAULT_SCHEME @port = options[:port] || DEFAULT_SCHEME_PORT[@scheme] end end def reload @connection.reset if @connection end def signature(params, expires) headers = params[:headers] || {} string_to_sign = <<-DATA #{params[:method].to_s.upcase} #{headers['Content-MD5']} #{headers['Content-Type']} #{expires} DATA amz_headers, canonical_amz_headers = {}, '' for key, value in headers if key[0..5] == 'x-amz-' amz_headers[key] = value end end amz_headers = amz_headers.sort {|x, y| x[0] <=> y[0]} for key, value in amz_headers canonical_amz_headers << "#{key}:#{value}\n" end string_to_sign << canonical_amz_headers query_string = '' if params[:query] query_args = [] for key in params[:query].keys.sort if VALID_QUERY_KEYS.include?(key) value = params[:query][key] if value query_args << "#{key}=#{value}" else query_args << key end end end if query_args.any? query_string = '?' + query_args.join('&') end end canonical_path = (params[:path] || object_to_path(params[:object_name])).to_s canonical_path = '/' + canonical_path if canonical_path[0..0] != '/' if params[:bucket_name] canonical_resource = "/#{params[:bucket_name]}#{canonical_path}" else canonical_resource = canonical_path end canonical_resource << query_string string_to_sign << canonical_resource signed_string = @hmac.sign(string_to_sign) Base64.encode64(signed_string).chomp! end private def setup_credentials(options) @aws_access_key_id = options[:aws_access_key_id] @aws_secret_access_key = options[:aws_secret_access_key] @aws_session_token = options[:aws_session_token] @aws_credentials_expire_at = options[:aws_credentials_expire_at] @hmac = Fog::HMAC.new('sha1', @aws_secret_access_key) end def connection(scheme, host, port) uri = "#{scheme}://#{host}:#{port}" if @persistent unless uri == @connection_uri @connection_uri = uri reload @connection = nil end else @connection = nil end @connection ||= Fog::Connection.new(uri, @persistent, @connection_options) end def request(params, &block) refresh_credentials_if_expired expires = Fog::Time.now.to_date_header params[:headers]['x-amz-security-token'] = @aws_session_token if @aws_session_token signature = signature(params, expires) params = request_params(params) scheme = params.delete(:scheme) host = params.delete(:host) port = params.delete(:port) || DEFAULT_SCHEME_PORT[scheme] params[:headers]['Date'] = expires params[:headers]['Authorization'] = "AWS #{@aws_access_key_id}:#{signature}" # FIXME: ToHashParser should make this not needed original_params = params.dup begin response = connection(scheme, host, port).request(params, &block) rescue Excon::Errors::TemporaryRedirect => error headers = (error.response.is_a?(Hash) ? error.response[:headers] : error.response.headers) uri = URI.parse(headers['Location']) Fog::Logger.warning("fog: followed redirect to #{uri.host}, connecting to the matching region will be more performant") response = Fog::Connection.new("#{uri.scheme}://#{uri.host}:#{uri.port}", false, @connection_options).request(original_params, &block) end response end end end end end fog-1.19.0/lib/fog/voxel.rb0000644000004100000410000000054712261242552015417 0ustar www-datawww-datarequire 'fog/core' require 'digest/md5' module Fog module Voxel extend Fog::Provider service(:compute, 'voxel/compute', 'Compute') def self.create_signature(secret, options) to_sign = options.keys.map { |k| k.to_s }.sort.map { |k| "#{k}#{options[k.to_sym]}" }.join("") Digest::MD7.hexdigest( secret + to_sign ) end end end fog-1.19.0/lib/fog/bin.rb0000644000004100000410000000466012261242551015031 0ustar www-datawww-datarequire 'fog/core/credentials' module Fog class << self def available_providers @available_providers ||= Fog.providers.values.select {|provider| Kernel.const_get(provider).available?}.sort end def registered_providers @registered_providers ||= Fog.providers.values.sort end end class Bin class << self def available? availability = true for service in services begin service = self.class_for(service) availability &&= service.requirements.all? { |requirement| Fog.credentials.include?(requirement) } rescue ArgumentError => e Fog::Logger.warning(e.message) availability = false rescue => e availability = false end end if availability for service in services for collection in self.class_for(service).collections unless self.respond_to?(collection) self.class_eval <<-EOS, __FILE__, __LINE__ def self.#{collection} self[:#{service}].#{collection} end EOS end end end end availability end def collections services.map {|service| self[service].collections}.flatten.sort_by {|service| service.to_s} end end end end require 'fog/bin/atmos' require 'fog/bin/aws' require 'fog/bin/bluebox' require 'fog/bin/brightbox' require 'fog/bin/cloudstack' require 'fog/bin/clodo' require 'fog/bin/digitalocean' require 'fog/bin/dnsimple' require 'fog/bin/dnsmadeeasy' require 'fog/bin/dreamhost' require 'fog/bin/dynect' require 'fog/bin/ecloud' require 'fog/bin/glesys' require 'fog/bin/go_grid' require 'fog/bin/google' require 'fog/bin/hp' require 'fog/bin/ibm' require 'fog/bin/internet_archive' require 'fog/bin/joyent' require 'fog/bin/libvirt' require 'fog/bin/linode' require 'fog/bin/local' require 'fog/bin/bare_metal_cloud' require 'fog/bin/ninefold' require 'fog/bin/rackspace' require 'fog/bin/riakcs' require 'fog/bin/openstack' require 'fog/bin/ovirt' require 'fog/bin/serverlove' require 'fog/bin/stormondemand' require 'fog/bin/terremark' require 'fog/bin/vcloud' require 'fog/bin/vcloud_director' require 'fog/bin/vmfusion' require 'fog/bin/vsphere' require 'fog/bin/voxel' require 'fog/bin/xenserver' require 'fog/bin/zerigo' require 'fog/bin/cloudsigma' require 'fog/bin/openvz' fog-1.19.0/lib/fog/volume.rb0000644000004100000410000000112312261242552015560 0ustar www-datawww-datamodule Fog module Volume def self.[](provider) self.new(:provider => provider) end def self.new(attributes) attributes = attributes.dup # Prevent delete from having side effects provider = attributes.delete(:provider).to_s.downcase.to_sym if self.providers.include?(provider) require "fog/#{provider}/volume" return Fog::Volume.const_get(Fog.providers[provider]).new(attributes) end raise ArgumentError.new("#{provider} has no identity service") end def self.providers Fog.services[:volume] end end end fog-1.19.0/lib/fog/riakcs.rb0000644000004100000410000000664112261242552015537 0ustar www-datawww-datarequire(File.expand_path(File.join(File.dirname(__FILE__), 'core'))) module Fog module RiakCS module MultipartUtils require 'net/http' class Headers include Net::HTTPHeader def initialize initialize_http_header({}) end # Parse a single header line into its key and value # @param [String] chunk a single header line def self.parse(chunk) line = chunk.strip # thanks Net::HTTPResponse return [nil,nil] if chunk =~ /\AHTTP(?:\/(\d+\.\d+))?\s+(\d\d\d)\s*(.*)\z/in m = /\A([^:]+):\s*/.match(line) [m[1], m.post_match] rescue [nil, nil] end # Parses a header line and adds it to the header collection # @param [String] chunk a single header line def parse(chunk) key, value = self.class.parse(chunk) add_field(key, value) if key && value end end def parse(data, boundary) contents = data.match(end_boundary_regex(boundary)).pre_match rescue "" contents.split(inner_boundary_regex(boundary)).reject(&:empty?).map do |part| parse_multipart_section(part) end.compact end def extract_boundary(header_string) $1 if header_string =~ /boundary=([A-Za-z0-9\'()+_,-.\/:=?]+)/ end private def end_boundary_regex(boundary) /\r?\n--#{Regexp.escape(boundary)}--\r?\n?/ end def inner_boundary_regex(boundary) /\r?\n--#{Regexp.escape(boundary)}\r?\n/ end def parse_multipart_section(part) headers = Headers.new if md = part.match(/\r?\n\r?\n/) body = md.post_match md.pre_match.split(/\r?\n/).each do |line| headers.parse(line) end if headers["content-type"] =~ /multipart\/mixed/ boundary = extract_boundary(headers.to_hash["content-type"].first) parse(body, boundary) else {:headers => headers.to_hash, :body => body} end end end end module UserUtils def update_riakcs_user(key_id, user) response = @s3_connection.put_object('riak-cs', "user/#{key_id}", Fog::JSON.encode(user), { 'Content-Type' => 'application/json' }) if !response.body.empty? response.body = Fog::JSON.decode(response.body) end response end def update_mock_user(key_id, user) if data[key_id] if status = user[:status] data[key_id][:status] = status end if user[:new_key_secret] data[key_id][:key_secret] = rand(100).to_s end Excon::Response.new.tap do |response| response.status = 200 response.body = data[key_id] end else Excon::Response.new.tap do |response| response.status = 403 end end end end module Utils def configure_uri_options(options = {}) @host = options[:host] || 'localhost' @persistent = options[:persistent] || true @port = options[:port] || 8080 @scheme = options[:scheme] || 'http' end def riakcs_uri "#{@scheme}://#{@host}:#{@port}" end end extend Fog::Provider service(:provisioning, 'riakcs/provisioning', 'Provisioning') service(:usage, 'riakcs/usage', 'Usage') end end fog-1.19.0/lib/fog/zerigo/0000755000004100000410000000000012261242552015226 5ustar www-datawww-datafog-1.19.0/lib/fog/zerigo/requests/0000755000004100000410000000000012261242552017101 5ustar www-datawww-datafog-1.19.0/lib/fog/zerigo/requests/dns/0000755000004100000410000000000012261242552017665 5ustar www-datawww-datafog-1.19.0/lib/fog/zerigo/requests/dns/create_host.rb0000644000004100000410000000754212261242552022522 0ustar www-datawww-datamodule Fog module DNS class Zerigo class Real require 'fog/zerigo/parsers/dns/create_host' # Create a new host in the specified zone # # ==== Parameters # * zone_id<~Integer> # * host_type<~String> # * data<~String> # * options<~Hash> - optional parameters # * hostname<~String> - Note: normally this is set/required!! # * notes<~String> # * priority<~Integer> - Note: required for MX or SRV records # * ttl<~Integer> # ==== Returns # * response<~Excon::Response>: # * body<~Hash> # * 'created-at'<~String> # * 'data'<~String> # * 'fqdn'<~String> # * 'host-type'<~String> # * 'hostname'<~String> # * 'id'<~Integer> # * 'notes'<~String> # * 'priority'<~Integer> # * 'ttl'<~Integer> # * 'updated-at'<~String> # * 'zone-id'<~String> # * 'status'<~Integer> - 201 if successful def create_host(zone_id, host_type, data, options = {}) optional_tags= '' options.each { |option, value| case option when :hostname optional_tags+= "#{value}" when :notes optional_tags+= "#{value}" when :priority optional_tags+= "#{value}" when :ttl optional_tags+= "#{value}" end } request( :body => %Q{#{host_type}#{data}#{optional_tags}}, :expects => 201, :method => 'POST', :parser => Fog::Parsers::DNS::Zerigo::CreateHost.new, :path => "/api/1.1/zones/#{zone_id}/hosts.xml" ) end end class Mock # :nodoc:all def valid_host_types %w[A AAAA CNAME GEO MX NS SPF SRV TXT URL PTR CNAME NS] end def create_host(zone_id, host_type, data, options = {}) zone = find_by_zone_id(zone_id) response = Excon::Response.new # Handle error cases. # Zone doesn't exist. unless zone response.status = 404 return response end # Bad host type. unless valid_host_types.include?(host_type) response.status = 422 response.body = { 'errors' => [ 'error' => 'Host type is not included in the list' ] } return response end # Missing or bad priority value for MX or SRV records. if %w[MX SRV].include?(host_type) && options['priority'].to_s !~ /\d+/ response.status = 422 response.body = { 'errors' => [ 'error' => 'Priority is not a number' ] } return response end # Successful case. now = Time.now host = { 'id' => rand(10000000), 'fqdn' => options[:hostname] ? "#{options[:hostname]}.#{zone['domain']}" : zone['domain'], 'data' => data, 'hostname' => options[:hostname], 'ttl' => options[:ttl].to_i, 'host-type' => host_type, 'created-at' => now, 'updated-at' => now, 'notes' => options[:notes], 'priority' => options[:priority].to_i, 'zone-id' => zone_id } zone['hosts'] << host response.status = 201 response.body = host response end end end end end fog-1.19.0/lib/fog/zerigo/requests/dns/get_zone.rb0000644000004100000410000000367712261242552022041 0ustar www-datawww-datamodule Fog module DNS class Zerigo class Real require 'fog/zerigo/parsers/dns/get_zone' # Get details of a DNS zone. The response is similar to list_zones, with the # addition of hosts-count and possibly hosts. # # ==== Parameters # * zone<~String> - Either the zone ID or the zone name (ie sample-domain.com) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'default-ttl'<~Integer> # * 'id'<~Integer> # * 'nx-ttl'<~Integer> # * 'hosts-count'<~Integer> # * 'created-at'<~String> # * 'custom-nameservers'<~String> # * 'custom-ns'<~String> # * 'domain'<~String> # * 'hostmaster'<~String> # * 'notes'<~String> # * 'ns1'<~String> # * 'ns-type'<~String> # * 'slave-nameservers'<~String> # * 'tag-list'<~String> # * 'updated-at'<~String> # * 'hosts'<~Array> - a list of all host records. For the format of host info, see get_host() # * 'axfr-ips'<~String> # * 'restrict-axfr'<~String> # * 'status'<~Integer> - 200 indicates success def get_zone(zone_id_or_domain) request( :expects => 200, :method => 'GET', :parser => Fog::Parsers::DNS::Zerigo::GetZone.new, :path => "/api/1.1/zones/#{zone_id_or_domain}.xml" ) end end class Mock # :nodoc:all def get_zone(zone_id_or_domain) zone = find_by_zone_id(zone_id_or_domain) || find_by_domain(zone_id_or_domain) response = Excon::Response.new if zone response.status = 200 response.body = zone else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/zerigo/requests/dns/get_zone_stats.rb0000644000004100000410000000326312261242552023246 0ustar www-datawww-datamodule Fog module DNS class Zerigo class Real require 'fog/zerigo/parsers/dns/get_zone_stats' # returns current traffic statistics about this zone. Queries is measured from the # beginning of the current period through the time of the API call. # # ==== Parameters # * zone_id<~Integer> - the zone ID # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'domain'<~String> - domain name (ie example.com) # * 'id'<~Integer> - Id of the zone # * 'period-being'<~String> - date in following format 2010-07-01 # * 'period-end'<~String> - date # * 'queries'<~Integer> - # of queries for the zone during period # * 'status'<~Integer> - 200 indicates success def get_zone_stats(zone_id) request( :expects => 200, :method => 'GET', :parser => Fog::Parsers::DNS::Zerigo::GetZoneStats.new, :path => "/api/1.1/zones/#{zone_id}/stats.xml" ) end end class Mock # :nodoc:all def get_zone_stats(zone_id) zone = find_by_zone_id(zone_id) response = Excon::Response.new if zone response.status = 200 response.body = { 'id' => zone, 'domain' => zone['domain'], 'period-begin' => zone['created-at'].strftime("%F"), 'period-end' => Date.today.to_s, 'queries' => 0 } else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/zerigo/requests/dns/create_zone.rb0000644000004100000410000001230312261242552022507 0ustar www-datawww-datamodule Fog module DNS class Zerigo class Real require 'fog/zerigo/parsers/dns/create_zone' # Create a new zone for Zerigo's DNS servers to serve/host # ==== Parameters # # * domain<~String> # * default_ttl<~Integer> # * ns_type<~String> # * options<~Hash> - optional paramaters # * ns1<~String> - required if ns_type == sec # * nx_ttl<~Integer> - # * slave_nameservers<~String> - required if ns_type == pri # * axfr_ips<~String> - comma-separated list of IPs or IP blocks allowed to perform AXFRs # * custom_nameservers<~String> - comma-separated list of custom nameservers # * custom_ns<~String> - indicates if vanity (custom) nameservers are enabled for this domain # * hostmaster<~String> - email of the DNS administrator or hostmaster # * notes<~String> - notes about the domain # * restrict_axfr<~String> - indicates if AXFR transfers should be restricted to IPs in axfr-ips # * tag_list<~String> - List of all tags associated with this domain # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'id'<~Integer> - zone ID to use for future calls # * 'default-ttl'<~Integer> # * 'nx-ttl'<~Integer> # * 'hosts-count'<~Integer> # * 'created-at'<~String> # * 'custom-nameservers'<~String> # * 'custom-ns'<~String> # * 'domain'<~String> # * 'hostmaster'<~String> # * 'notes'<~String> # * 'ns1'<~String> # * 'ns-type'<~String> # * 'slave-nameservers'<~String> # * 'tag-list'<~String> # * 'updated-at'<~String> # * 'hosts'<~String> # * 'axfr-ips'<~String> # * 'restrict-axfr'<~String> # * 'status'<~Integer> - 201 if successful def create_zone(domain, default_ttl, ns_type, options = {}) optional_tags= '' options.each { |option, value| case option when :ns1 optional_tags+= "#{value}" when :nx_ttl optional_tags+= "#{value}" when :slave_nameservers optional_tags+= "#{value}" when :axfr_ips optional_tags+= "#{value}" when :custom_nameservers optional_tags+= "#{value}" when :custom_ns optional_tags+= "#{value}" when :hostmaster optional_tags+= "#{value}" when :notes optional_tags+= "#{value}" when :restrict_axfr optional_tags+= "#{value}" when :tag_list optional_tags+= "#{value}" end } request( :body => %Q{#{domain}#{default_ttl}#{ns_type}#{optional_tags}}, :expects => 201, :method => 'POST', :parser => Fog::Parsers::DNS::Zerigo::CreateZone.new, :path => '/api/1.1/zones.xml' ) end end class Mock # :nodoc:all def create_zone(domain, default_ttl, ns_type, options = {}) now = Time.now zone = { 'id' => rand(10000000), 'domain' => domain, 'created-at' => now, 'updated-at' => now, 'ns1' => options[:ns1], 'nx-ttl' => options[:nx_ttl].to_i, 'default-ttl' => default_ttl.to_i, 'ns-type' => ns_type, 'hosts' => options[:hosts] || [], 'hosts-count' => (options[:hosts] || []).size, 'notes' => options[:notes], 'slave-nameservers' => options[:slave_nameservers], 'tag-list' => options[:tag_list] } response = Excon::Response.new if self.data[:zones].any? {|z| z['domain'] == zone['domain'] } response.status = 422 response.body = { 'errors' => [ 'error' => 'Domain is already associated to another account', 'error' => 'Domain already exists. If it was just deleted, wait a minute and try again' ] } else self.data[:zones] << zone response.status = 201 response.headers = { 'Location' => "http://ns.zerigo.com/api/1.1/zones/#{zone['id']}" } response.body = zone['hosts'].empty? ? zone.merge(:hosts => nil) : zone # Zerigo returns nil, not an empty list only on the create command. end response end end end end end fog-1.19.0/lib/fog/zerigo/requests/dns/delete_zone.rb0000644000004100000410000000157112261242552022513 0ustar www-datawww-datamodule Fog module DNS class Zerigo class Real # Delete a zone from Zerigo # # ==== Parameters # * zone_id<~Integer> - Id of zone to delete # ==== Returns # * response<~Excon::Response>: # * 'status'<~Integer> - 200 indicates success def delete_zone(zone_id) request( :expects => 200, :method => 'DELETE', :path => "/api/1.1/zones/#{zone_id}.xml" ) end end class Mock # :nodoc:all def delete_zone(zone_id) zone = find_by_zone_id(zone_id) response = Excon::Response.new if zone self.data[:zones].delete(zone) response.status = 200 else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/zerigo/requests/dns/count_zones.rb0000644000004100000410000000172712261242552022567 0ustar www-datawww-datamodule Fog module DNS class Zerigo class Real require 'fog/zerigo/parsers/dns/count_zones' # Total number of zones hosted Zerigo for this account. It is the same value as provided # in the X-Query-Count header in the list_zones API method # # ==== Returns # * response<~Excon::Response>: # * body<~Hash> # * 'count'<~Integer> # * 'status'<~Integer> - 200 indicates success def count_zones request( :expects => 200, :method => 'GET', :parser => Fog::Parsers::DNS::Zerigo::CountZones.new, :path => "/api/1.1/zones/count.xml" ) end end class Mock # :nodoc:all def count_zones response = Excon::Response.new response.status = 200 response.body = { 'count' => self.data[:zones].size } response end end end end end fog-1.19.0/lib/fog/zerigo/requests/dns/list_zones.rb0000644000004100000410000000354412261242552022411 0ustar www-datawww-datamodule Fog module DNS class Zerigo class Real require 'fog/zerigo/parsers/dns/list_zones' # Get list of all DNS zones hosted on Slicehost (for this account) # # ==== Parameters # * options<~Hash> # * page<~Integer> - Indicates where to begin in your list of zones. # * per_page<~Integer> - The maximum number of zones to be included in the response body # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'zones'<~Array> # * 'default-ttl'<~Integer> # * 'id'<~Integer> # * 'nx-ttl'<~Integer> # * 'hosts-count'<~Integer> # * 'created-at'<~String> # * 'custom-nameservers'<~String> # * 'custom-ns'<~String> # * 'domain'<~String> # * 'hostmaster'<~String> # * 'notes'<~String> # * 'ns1'<~String> # * 'ns-type'<~String> # * 'slave-nameservers'<~String> # * 'tag-list'<~String> # * 'updated-at'<~String> # * 'hosts'<~String> # * 'axfr-ips'<~String> # * 'restrict-axfr'<~String> # * 'status'<~Integer> - 200 indicates success def list_zones(options = {}) request( :query => options, :expects => 200, :method => 'GET', :parser => Fog::Parsers::DNS::Zerigo::ListZones.new, :path => '/api/1.1/zones.xml' ) end end class Mock # :nodoc:all def list_zones response = Excon::Response.new response.status = 200 response.body = { 'zones' => self.data[:zones] } response end end end end end fog-1.19.0/lib/fog/zerigo/requests/dns/update_host.rb0000644000004100000410000000400612261242552022531 0ustar www-datawww-datamodule Fog module DNS class Zerigo class Real # Update a host record # # ==== Parameters # * host_id<~Integer> - host ID of the record to update # * options<~Hash> - optional paramaters # * host_type<~String> # * data<~String> # * hostname<~String> - Note: normally this is set/required!! # * notes<~String> # * priority<~Integer> - Note: required for MX or SRV records # * ttl<~Integer> # ==== Returns # * response<~Excon::Response>: # * 'status'<~Integer> - 200 for success # def update_host(host_id, options = {}) optional_tags= '' options.each { |option, value| case option when :host_type optional_tags+= "#{value}" when :data optional_tags+= "#{value}" when :hostname optional_tags+= "#{value}" when :notes optional_tags+= "#{value}" when :priority optional_tags+= "#{value}" when :ttl optional_tags+= "#{value}" end } request( :body => %Q{#{optional_tags}}, :expects => 200, :method => 'PUT', :path => "/api/1.1/hosts/#{host_id}.xml" ) end end class Mock # :nodoc:all def update_host(host_id, options = {}) host = find_host(host_id) response = Excon::Response.new if host options.each { |k, v| host[k.to_s] = v } # Deal with symbols in requests but strings in responses. host['updated-at'] = Time.now response.status = 200 else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/zerigo/requests/dns/get_host.rb0000644000004100000410000000257512261242552022037 0ustar www-datawww-datamodule Fog module DNS class Zerigo class Real require 'fog/zerigo/parsers/dns/get_host' # get details about a given host record # # ==== Parameters # * host_id<~Integer> - ID of the host record to retrieve # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'created-at'<~String> # * 'data'<~String> # * 'fqdn'<~String> # * 'host-type'<~String> # * 'hostname'<~String> # * 'id'<~Integer> # * 'notes'<~String> # * 'priority'<~Integer> # * 'ttl'<~Integer> # * 'updated-at'<~String> # * 'zone-id'<~String> # * 'status'<~Integer> - 200 indicates success def get_host(host_id) request( :expects => 200, :method => 'GET', :parser => Fog::Parsers::DNS::Zerigo::GetHost.new, :path => "/api/1.1/hosts/#{host_id}.xml" ) end end class Mock # :nodoc:all def get_host(host_id) host = find_host(host_id) response = Excon::Response.new if host response.status = 200 response.body = host else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/zerigo/requests/dns/update_zone.rb0000644000004100000410000000627612261242552022542 0ustar www-datawww-datamodule Fog module DNS class Zerigo class Real # Update the parameters of a zone # ==== Parameters # # * zone_id<~Integer> # * options<~Hash> - optional paramaters # * default_ttl<~Integer> # * ns_type<~String> # * ns1<~String> - required if ns_type == sec # * nx_ttl<~Integer> - # * slave_nameservers<~String> - required if ns_type == pri # * axfr_ips<~String> - comma-separated list of IPs or IP blocks allowed to perform AXFRs # * custom_nameservers<~String> - comma-separated list of custom nameservers # * custom_ns<~String> - indicates if vanity (custom) nameservers are enabled for this domain # * hostmaster<~String> - email of the DNS administrator or hostmaster # * notes<~String> - notes about the domain # * restrict_axfr<~String> - indicates if AXFR transfers should be restricted to IPs in axfr-ips # * tag_list<~String> - List of all tags associated with this domain # # ==== Returns # * response<~Excon::Response>: # * 'status'<~Integer> - 200 for success def update_zone(zone_id, options = {}) optional_tags= '' options.each { |option, value| case option when :default_ttl optional_tags+= "#{value}" when :ns_type optional_tags+= "#{value}" when :ns1 optional_tags+= "#{value}" when :nx_ttl optional_tags+= "#{value}" when :slave_nameservers optional_tags+= "#{value}" when :axfr_ips optional_tags+= "#{value}" when :custom_nameservers optional_tags+= "#{value}" when :custom_ns optional_tags+= "#{value}" when :hostmaster optional_tags+= "#{value}" when :notes optional_tags+= "#{value}" when :restrict_axfr optional_tags+= "#{value}" when :tag_list optional_tags+= "#{value}" end } request( :body => %Q{#{optional_tags}}, :expects => 200, :method => 'PUT', :path => "/api/1.1/zones/#{zone_id}.xml" ) end end class Mock # :nodoc:all def update_zone(zone_id, options = {}) zone = find_by_zone_id(zone_id) response = Excon::Response.new if zone options.each { |k, v| zone[k.to_s] = v } # Deal with symbols in requests but strings in responses. zone['updated-at'] = Time.now response.status = 200 else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/zerigo/requests/dns/list_hosts.rb0000644000004100000410000000305612261242552022411 0ustar www-datawww-datamodule Fog module DNS class Zerigo class Real require 'fog/zerigo/parsers/dns/list_hosts' # Get list of all DNS zones hosted on Slicehost (for this account) # # ==== Parameters # * zone_id<~Integer> - the zone ID of the zone from which to get the host records for # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'hosts'<~Array> # * 'created-at'<~String> # * 'data'<~String> # * 'fqdn'<~String> # * 'host-type'<~String> # * 'hostname'<~String> # * 'id'<~Integer> # * 'notes'<~String> # * 'priority'<~Integer> # * 'ttl'<~Integer> # * 'updated-at'<~String> # * 'zone-id'<~String> # * 'status'<~Integer> - 200 indicates success def list_hosts(zone_id) request( :expects => 200, :method => 'GET', :parser => Fog::Parsers::DNS::Zerigo::ListHosts.new, :path => "/api/1.1/zones/#{zone_id}/hosts.xml" ) end end class Mock # :nodoc:all def list_hosts(zone_id) zone = find_by_zone_id(zone_id) response = Excon::Response.new if zone response.status = 200 response.body = { 'hosts' => zone['hosts'] } else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/zerigo/requests/dns/count_hosts.rb0000644000004100000410000000222212261242552022560 0ustar www-datawww-datamodule Fog module DNS class Zerigo class Real require 'fog/zerigo/parsers/dns/count_hosts' # total number of hosts available for the specified zone. It is the same value as provided # in the X-Query-Count header in the list_hosts API method # # ==== Returns # * response<~Excon::Response>: # * body<~Hash> # * 'count'<~Integer> # * 'status'<~Integer> - 200 indicates success def count_hosts(zone_id) request( :expects => 200, :method => 'GET', :parser => Fog::Parsers::DNS::Zerigo::CountHosts.new, :path => "/api/1.1/zones/#{zone_id}/hosts/count.xml" ) end end class Mock # :nodoc:all def count_hosts(zone_id) zone = find_by_zone_id(zone_id) response = Excon::Response.new if zone response.status = 200 response.body = { 'count' => zone['hosts'].size } else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/zerigo/requests/dns/find_hosts.rb0000644000004100000410000000437612261242552022364 0ustar www-datawww-datamodule Fog module DNS class Zerigo class Real require 'fog/zerigo/parsers/dns/find_hosts' # Get list of all the host records that match the FQDN. If desired, can limit # search to a specific zone # # # ==== Parameters # * fqdn<~String> - domain to look for # * zone_id<~Integer> - if want to limit search to specific zone # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'hosts'<~Hash> # * 'created-at'<~String> # * 'data'<~String> # * 'fqdn'<~String> # * 'host-type'<~String> # * 'hostname'<~String> # * 'id'<~Integer> # * 'notes'<~String> # * 'priority'<~Integer> # * 'ttl'<~Integer> # * 'updated-at'<~String> # * 'zone-id'<~String> # * 'status'<~Integer> - 200 indicated success # def find_hosts(fqdn, zone_id = nil) if zone_id.nil? #look for matching host across all zones request( :expects => 200, :method => 'GET', :parser => Fog::Parsers::DNS::Zerigo::FindHosts.new, :path => "/api/1.1/hosts.xml?fqdn=#{fqdn}" ) else #look for hosts in a specific zone request( :expects => 200, :method => 'GET', :parser => Fog::Parsers::DNS::Zerigo::FindHosts.new, :path => "/api/1.1/zones/#{zone_id}/hosts.xml?fqdn=#{fqdn}" ) end end end class Mock # :nodoc:all def find_hosts(fqdn, zone_id = nil) response = Excon::Response.new zone = find_by_zone_id(zone_id) if zone_id && !zone response.status = 404 else hosts = zone ? zone['hosts'].select { |z| z['fqdn'] == fqdn } : self.data[:zones].collect { |z| z['hosts'].find { |h| h['fqdn'] == fqdn } }.compact response.status = 200 response.body = { 'hosts' => hosts } end response end end end end end fog-1.19.0/lib/fog/zerigo/requests/dns/delete_host.rb0000644000004100000410000000163712261242552022520 0ustar www-datawww-datamodule Fog module DNS class Zerigo class Real # Delete a host record # # ==== Parameters # * host_id<~Integer> - Id of host record to delete # ==== Returns # * response<~Excon::Response>: # * 'status'<~Integer> - 200 indicates success def delete_host(host_id) request( :expects => 200, :method => 'DELETE', :path => "/api/1.1/hosts/#{host_id}.xml" ) end end class Mock # :nodoc:all def delete_host(host_id) host = find_host(host_id) response = Excon::Response.new if host zone = find_by_zone_id(host['zone-id']) zone['hosts'].delete(host) response.status = 200 else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/zerigo/parsers/0000755000004100000410000000000012261242552016705 5ustar www-datawww-datafog-1.19.0/lib/fog/zerigo/parsers/dns/0000755000004100000410000000000012261242552017471 5ustar www-datawww-datafog-1.19.0/lib/fog/zerigo/parsers/dns/create_host.rb0000644000004100000410000000113512261242552022316 0ustar www-datawww-datamodule Fog module Parsers module DNS module Zerigo class CreateHost < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'id', 'zone-id' @response[name] = value.to_i when 'priority', 'ttl' @response[name] = value.to_i if value when 'data', 'fqdn', 'host-type', 'hostname', 'notes', 'zone-id', 'created-at', 'updated-at' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/zerigo/parsers/dns/get_zone.rb0000644000004100000410000000330412261242552021630 0ustar www-datawww-datamodule Fog module Parsers module DNS module Zerigo class GetZone < Fog::Parsers::Base def reset @host = {} @hosts = [] @response = {} @in_hosts = false end def start_element(name, attrs = []) super(name, attrs) #look out for start of section #needed as some of the tags have the same name as the parent section if name == 'hosts' @in_hosts= true end end def end_element(name) if (@in_hosts) #in hosts part of response case name when 'id', 'zone-id' @host[name] = value.to_i when 'priority', 'ttl' @host[name] = value.to_i if value when 'data', 'fqdn', 'host-type', 'hostname', 'notes', 'zone-id', 'created-at', 'updated-at' @host[name] = value when 'host' @hosts << @host @host = {} when 'hosts' @response[name] = @hosts @in_hosts = false end else #in zone part of data case name when 'default-ttl', 'id', 'nx-ttl', 'hosts-count' @response[name] = value.to_i when 'created-at', 'custom-nameservers', 'custom-ns', 'domain', 'hostmaster', 'notes', 'ns1', 'ns-type', 'slave-nameservers', 'tag-list', 'updated-at', 'hosts', 'axfr-ips', 'restrict-axfr' @response[name] = value end end end end end end end end fog-1.19.0/lib/fog/zerigo/parsers/dns/get_zone_stats.rb0000644000004100000410000000074312261242552023052 0ustar www-datawww-datamodule Fog module Parsers module DNS module Zerigo class GetZoneStats < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'id', 'queries' @response[name] = value.to_i when 'domain', 'period-begin', 'period-end' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/zerigo/parsers/dns/create_zone.rb0000644000004100000410000000120312261242552022310 0ustar www-datawww-datamodule Fog module Parsers module DNS module Zerigo class CreateZone < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'default-ttl', 'id', 'nx-ttl', 'hosts-count' @response[name] = value.to_i when 'created-at', 'custom-nameservers', 'custom-ns', 'domain', 'hostmaster', 'notes', 'ns1', 'ns-type', 'slave-nameservers', 'tag-list', 'updated-at', 'hosts', 'axfr-ips', 'restrict-axfr' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/zerigo/parsers/dns/count_zones.rb0000644000004100000410000000055712261242552022373 0ustar www-datawww-datamodule Fog module Parsers module DNS module Zerigo class CountZones < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'count' @response[name] = value.to_i end end end end end end end fog-1.19.0/lib/fog/zerigo/parsers/dns/list_zones.rb0000644000004100000410000000137312261242552022213 0ustar www-datawww-datamodule Fog module Parsers module DNS module Zerigo class ListZones < Fog::Parsers::Base def reset @zone = {} @response = { 'zones' => [] } end def end_element(name) case name when 'default-ttl', 'id', 'nx-ttl', 'hosts-count' @zone[name] = value.to_i when 'created-at', 'custom-nameservers', 'custom-ns', 'domain', 'hostmaster', 'notes', 'ns1', 'ns-type', 'slave-nameservers', 'tag-list', 'updated-at', 'hosts', 'axfr-ips', 'restrict-axfr' @zone[name] = value when 'zone' @response['zones'] << @zone @zone = {} end end end end end end end fog-1.19.0/lib/fog/zerigo/parsers/dns/get_host.rb0000644000004100000410000000113212261242552021627 0ustar www-datawww-datamodule Fog module Parsers module DNS module Zerigo class GetHost < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'id', 'zone-id' @response[name] = value.to_i when 'priority', 'ttl' @response[name] = value.to_i if value when 'data', 'fqdn', 'host-type', 'hostname', 'notes', 'zone-id', 'created-at', 'updated-at' @response[name] = value end end end end end end end fog-1.19.0/lib/fog/zerigo/parsers/dns/list_hosts.rb0000644000004100000410000000132112261242552022206 0ustar www-datawww-datamodule Fog module Parsers module DNS module Zerigo class ListHosts < Fog::Parsers::Base def reset @host = {} @response = { 'hosts' => [] } end def end_element(name) case name when 'id', 'zone-id' @host[name] = value.to_i when 'priority', 'ttl' @host[name] = value.to_i if value when 'data', 'fqdn', 'host-type', 'hostname', 'notes', 'zone-id', 'created-at', 'updated-at' @host[name] = value when 'host' @response['hosts'] << @host @host = {} end end end end end end end fog-1.19.0/lib/fog/zerigo/parsers/dns/count_hosts.rb0000644000004100000410000000055712261242552022375 0ustar www-datawww-datamodule Fog module Parsers module DNS module Zerigo class CountHosts < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'count' @response[name] = value.to_i end end end end end end end fog-1.19.0/lib/fog/zerigo/parsers/dns/find_hosts.rb0000644000004100000410000000132112261242552022153 0ustar www-datawww-datamodule Fog module Parsers module DNS module Zerigo class FindHosts < Fog::Parsers::Base def reset @host = {} @response = { 'hosts' => [] } end def end_element(name) case name when 'id', 'zone-id' @host[name] = value.to_i when 'priority', 'ttl' @host[name] = value.to_i if value when 'data', 'fqdn', 'host-type', 'hostname', 'notes', 'zone-id', 'created-at', 'updated-at' @host[name] = value when 'host' @response['hosts'] << @host @host = {} end end end end end end end fog-1.19.0/lib/fog/zerigo/dns.rb0000644000004100000410000000614512261242552016345 0ustar www-datawww-datarequire 'fog/zerigo' require 'fog/dns' module Fog module DNS class Zerigo < Fog::Service requires :zerigo_email, :zerigo_token recognizes :host, :persistent, :port, :scheme, :timeout model_path 'fog/zerigo/models/dns' model :record collection :records model :zone collection :zones request_path 'fog/zerigo/requests/dns' request :count_hosts request :count_zones request :create_host request :create_zone request :delete_host request :delete_zone request :find_hosts request :get_host request :get_zone request :get_zone_stats request :list_zones request :list_hosts request :update_host request :update_zone class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = key == :zones ? [] : {} end end def self.reset @data = nil end def initialize(options={}) @zerigo_email = options[:zerigo_email] @zerigo_token = options[:zerigo_token] end def data self.class.data end def reset_data self.class.reset end def find_by_zone_id(zone_id) self.data[:zones].find { |z| z['id'] == zone_id } end def find_by_domain(domain) self.data[:zones].find { |z| z['domain'] == domain } end def find_host(host_id) self.data[:zones].collect { |z| z['hosts'].find { |h| h['id'] == host_id } }.compact.first end end class Real def initialize(options={}) require 'fog/core/parser' @zerigo_email = options[:zerigo_email] @zerigo_token = options[:zerigo_token] @connection_options = options[:connection_options] || {} @host = options[:host] || "ns.zerigo.com" @persistent = options[:persistent] || false @port = options[:port] || 80 @scheme = options[:scheme] || 'http' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def reload @connection.reset end def request(params) params[:headers] ||= {} key= "#{@zerigo_email}:#{@zerigo_token}" params[:headers].merge!({ 'Authorization' => "Basic #{Base64.encode64(key).delete("\r\n")}" }) case params[:method] when 'DELETE', 'GET', 'HEAD' params[:headers]['Accept'] = 'application/xml' when 'POST', 'PUT' params[:headers]['Content-Type'] = 'application/xml' end begin response = @connection.request(params.merge!({:host => @host})) rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::DNS::Zerigo::NotFound.slurp(error) else error end end response end end end end end fog-1.19.0/lib/fog/zerigo/models/0000755000004100000410000000000012261242552016511 5ustar www-datawww-datafog-1.19.0/lib/fog/zerigo/models/dns/0000755000004100000410000000000012261242552017275 5ustar www-datawww-datafog-1.19.0/lib/fog/zerigo/models/dns/zones.rb0000644000004100000410000000110412261242552020754 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/zerigo/models/dns/zone' module Fog module DNS class Zerigo class Zones < Fog::Collection model Fog::DNS::Zerigo::Zone def all(options = {}) data = service.list_zones(options).body['zones'] load(data) end def get(zone_id_or_domain) data = service.get_zone(zone_id_or_domain).body zone = new(data) zone.records.load(data['hosts']) zone rescue Fog::Service::NotFound nil end end end end end fog-1.19.0/lib/fog/zerigo/models/dns/record.rb0000644000004100000410000000316212261242552021102 0ustar www-datawww-datarequire 'fog/core/model' module Fog module DNS class Zerigo class Record < Fog::Model extend Fog::Deprecation deprecate :ip, :value deprecate :ip=, :value= identity :id attribute :created_at, :aliases => 'created-at' attribute :value, :aliases => 'data' attribute :domain, :aliases => 'fqdn' attribute :name, :aliases => 'hostname' attribute :description, :aliases => 'notes' attribute :priority attribute :ttl attribute :type, :aliases => 'host-type' attribute :updated_at, :aliases => 'updated-at' attribute :zone_id, :aliases => 'zone-id' def initialize(attributes={}) super end def destroy requires :identity service.delete_host(identity) true end def zone @zone end def save requires :zone, :type, :value options = {} options[:hostname] = name if name options[:notes] = description if description options[:priority] = priority if priority options[:ttl] = ttl if ttl if persisted? options[:host_type] = type options[:data] = value service.update_host(identity, options) else data = service.create_host(@zone.id, type, value, options) merge_attributes(data.body) end true end private def zone=(new_zone) @zone = new_zone end end end end end fog-1.19.0/lib/fog/zerigo/models/dns/zone.rb0000644000004100000410000000530612261242552020601 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/zerigo/models/dns/records' module Fog module DNS class Zerigo class Zone < Fog::Model identity :id attribute :created_at, :aliases => 'created-at' attribute :domain attribute :ttl, :aliases => 'default-ttl' attribute :type, :aliases => 'ns-type' attribute :updated_at, :aliases => 'updated-at' # ns1.example.com,ns2.example.com # true # dnsadmin@example.com # # # # # one two # 1 def initialize(attributes={}) self.type ||= 'pri_sec' super end def destroy requires :identity service.delete_zone(identity) true end def records @records ||= begin Fog::DNS::Zerigo::Records.new( :zone => self, :service => service ) end end def nameservers [ 'a.ns.zerigo.net', 'b.ns.zerigo.net', 'c.ns.zerigo.net', 'd.ns.zerigo.net', 'e.ns.zerigo.net' ] end def save self.ttl ||= 3600 requires :domain, :type, :ttl options = {} # * options<~Hash> - optional paramaters # * ns1<~String> - required if ns_type == sec # * nx_ttl<~Integer> - # * slave_nameservers<~String> - required if ns_type == pri # * axfr_ips<~String> - comma-separated list of IPs or IP blocks allowed to perform AXFRs # * custom_nameservers<~String> - comma-separated list of custom nameservers # * custom_ns<~String> - indicates if vanity (custom) nameservers are enabled for this domain # * hostmaster<~String> - email of the DNS administrator or hostmaster # * notes<~String> - notes about the domain # * restrict_axfr<~String> - indicates if AXFR transfers should be restricted to IPs in axfr-ips # * tag_list<~String> - List of all tags associated with this domain data = unless identity service.create_zone(domain, ttl, type, options) else options[:default_ttl] = ttl options[:ns_type] = type service.update_zone(identity, options) end merge_attributes(data.body) true end end end end end fog-1.19.0/lib/fog/zerigo/models/dns/records.rb0000644000004100000410000000225012261242552021262 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/zerigo/models/dns/record' module Fog module DNS class Zerigo class Records < Fog::Collection attribute :zone model Fog::DNS::Zerigo::Record # List all domains # @param [Hash] options Options to pass to the underlying API call # @option options [String] :fqdn search for the given fqdn def all(options = {}) requires :zone if options[:fqdn] hosts = service.find_hosts(options[:fqdn], zone.id).body['hosts'] load(hosts) else parent = zone.collection.get(zone.identity) if parent merge_attributes(parent.records.attributes) load(parent.records.map {|record| record.attributes}) else nil end end end def get(record_id) data = service.get_host(record_id).body new(data) rescue Fog::Service::NotFound nil end def new(attributes = {}) requires :zone super({ :zone => zone }.merge!(attributes)) end end end end end fog-1.19.0/lib/fog/libvirt.rb0000644000004100000410000000021212261242552015722 0ustar www-datawww-datarequire 'fog/core' module Fog module Libvirt extend Fog::Provider service(:compute, 'libvirt/compute', 'Compute') end end fog-1.19.0/lib/fog/openstack/0000755000004100000410000000000012261242552015716 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/examples/0000755000004100000410000000000012261242552017534 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/examples/network/0000755000004100000410000000000012261242552021225 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/examples/network/network_subnets_routers.rb0000644000004100000410000000436312261242552026577 0ustar www-datawww-datarequire 'fog/openstack' # # Quantum demo # # Create some routers, networks and subnets for # a couple of tenants. # # Needs Fog >= 1.11.0 # Needs OpenStack credentials in ~/.fog # def create_tenant_network( tenant_name, external_net, router_name = 'router1', subnet_range = '10.0.0.0/21', subnet_gateway = '10.0.0.1', private_network_name = 'private' ) network = Fog::Network[:openstack] id = Fog::Identity[:openstack] tenant = id.tenants.find { |t| t.name == tenant_name } # Create a router for the tenant router = network.routers.create :name => router_name, :tenant_id => tenant.id, :external_gateway_info => { 'network_id' => external_net.id } # Create a private network for the tenant net = network.networks.create :name => private_network_name, :tenant_id => tenant.id # Create a subnet for the previous network and associate it # with the tenant subnet = network.subnets.create :name => 'net_10', :network_id => net.id, :ip_version => 4, :gateway_ip => subnet_gateway, :cidr => subnet_range, :tenant_id => tenant.id, :enable_dhcp => true network.add_router_interface router.id, subnet.id end # Create a public shared network public_net = network.networks.create :name => 'nova', :router_external => true # Create the public subnet public_subnet = network.subnets.create :name => 'floating_ips_net', :network_id => public_net.id, :ip_version => 4, :cidr => '1.2.3.0/24', :enable_dhcp => false # Create tenant networks create_tenant_network, 'admin@example.net', public_net create_tenant_network, 'demo@example.net', public_net fog-1.19.0/lib/fog/openstack/examples/storage/0000755000004100000410000000000012261242552021200 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/examples/storage/set-account-quota.rb0000644000004100000410000000425312261242552025105 0ustar www-datawww-datarequire 'fog' require 'pp' # # This example sets the account quota (in bytes) for the tenant demo@test.lan # using an admin account (admin has the reseller user role). # # Uses the account impersonation feature recently added to the # OpenStack Storage service in Fog (See https://github.com/fog/fog/pull/1632). # # Should be available in Fog 1.10.0+1. # # Setting account quotas is only supported in Swift 1.8.0+ # using the brand new account_quota middleware introduced in # OpenStack Grizzly (currently unreleased as of 2013/04/03). # # https://github.com/openstack/swift/blob/master/swift/common/middleware/account_quotas.py # auth_url = 'https://identity.test.lan/v2.0/tokens' user = 'admin@test.lan' password = 'secret' Excon.defaults[:ssl_verify_peer] = false # # We are going to use the Identity (Keystone) service # to retrieve the list of tenants available and find # the tenant we want to set the quotas for. # id = Fog::Identity.new :provider => 'OpenStack', :openstack_auth_url => auth_url, :openstack_username => user, :openstack_api_key => password # # Storage service (Swift) # st = Fog::Storage.new :provider => 'OpenStack', :openstack_auth_url => auth_url, :openstack_username => user, :openstack_api_key => password id.tenants.each do |t| # We want to set the account quota for tenant demo@test.lan next unless t.name == 'demo@test.lan' # We've found the tenant, impersonate the account # (the account prefix AUTH_ may be different for you, double check it). puts "Changing account to #{t.name}" st.change_account "AUTH_#{t.id}" # Now we're adding the required header to the demo@test.lan # tenant account, limiting the account bytes to 1048576 (1MB) # # Uploading more than 1MB will return 413: Request Entity Too Large st.request :method => 'POST', :headers => { 'X-Account-Meta-Quota-Bytes' => '1048576' } # We can list the account details to verify the new # header has been added pp st.request :method => 'HEAD' end # Restore the account we were using initially (admin@test.lan) st.reset_account_name fog-1.19.0/lib/fog/openstack/examples/identity/0000755000004100000410000000000012261242552021365 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/examples/identity/basics.rb0000644000004100000410000000334012261242552023156 0ustar www-datawww-data# OpenStack Identity Service (Keystone) Example require 'fog' require 'pp' auth_url = "https://example.net/v2.0/tokens" username = 'admin@example.net' password = 'secret' keystone = Fog::Identity.new :provider => 'OpenStack', :openstack_auth_url => auth_url, :openstack_username => username, :openstack_api_key => password # Optional, self-signed certs #:connection_options => { :ssl_verify_peer => false } # # Listing keystone tenants # keystone.tenants.each do |tenant| # pp tenant end # # List users # keystone.users.each do |user| # # ... pp user end # # Create a new tenant # tenant = keystone.tenants.create :name => 'rubiojr@example.net', :description => 'My foo tenant' # # Create a new user # user = keystone.users.create :name => 'rubiojr@example.net', :tenant_id => tenant.id, :password => 'rubiojr@example.net', :email => 'rubiojr@example.net' # Find the recently created tenant tenant = keystone.tenants.find { |t| t.name == 'rubiojr@example.net' } # Destroy the tenant tenant.destroy # Find the recently created user user = keystone.users.find { |u| u.name == 'rubiojr@example.net' } # Destroy the user user.destroy fog-1.19.0/lib/fog/openstack/examples/compute/0000755000004100000410000000000012261242552021210 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/examples/compute/basics.rb0000644000004100000410000000374712261242552023014 0ustar www-datawww-data# OpenStack Compute (Nova) Example require 'fog' auth_url = "https://example.net/v2.0/tokens" username = 'admin@example.net' password = 'secret' tenant = 'My Compute Tenant' # String compute_client ||= ::Fog::Compute.new(:provider => :openstack, :openstack_api_key => password , :openstack_username => username , :openstack_auth_url => auth_url , :openstack_tenant => tenant) # Create VM # Options include metadata, availability zone, etc... begin vm = compute_client.servers.create(name, image, flavor, options = {}) rescue => e puts JSON.parse(e.response.body)['badRequest']['message'] end # Destroy VM vm = compute_client.servers.get(vm.id) # Retrieve previously created vm by UUID floating_ips = vm.all_addresses # fetch and release its floating IPs floating_ips.each do |address| compute_client.disassociate_address(uuid, address['ip']) compute_client.release_address(address['id']) end vm.destroy # Power operations helper # vm.start / vm.stop / vm.pause should work after this class Server < Fog::Compute::Server def start if state.downcase == 'paused' service.unpause_server(id) # resumes from frozen VM state else service.resume_server(id) # resumes from hibernation end end def stop service.suspend_server(id) # hibernates the VM at hypervisor-level end def pause service.pause_server(id) # stores VM state in RAM end end # Images available at tenant image_names = compute_client.images.map { |image| image['name'] } # Floating IP address pools available at tenant compute_client.addresses.get_address_pools # response.body #=> { 'name' => 'pool1' }, { 'name' => 'pool2' } # VNC console vm.console.body # returns VNC url # "console" => { # "url" => "http://vmvncserver:6080/vnc_auto.html?token=231", # "type" => "novnc" # } fog-1.19.0/lib/fog/openstack/examples/image/0000755000004100000410000000000012261242552020616 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/examples/image/upload-test-image.rb0000644000004100000410000000531212261242552024465 0ustar www-datawww-datarequire 'securerandom' require 'rubygems/package' require 'zlib' require 'fog' # # Download CirrOS 0.3.0 image from launchpad (~6.5MB) to /tmp # and upload it to Glance (the OpenStack Image Service). # # You will need to source OpenStack credentials since the script # reads the following envionment variables: # # OS_PASSWORD # OS_USERNAME # OS_AUTH_URL # OS_TENANT_NAME # # Should work with Fog >= 1.9, ruby 1.8.7 and 2.0 # image_url = "https://launchpadlibrarian.net/83305869/cirros-0.3.0-x86_64-uec.tar.gz" image_out = File.open("/tmp/cirros-image-#{SecureRandom.hex}", 'wb') extract_path = "/tmp/cirros-#{SecureRandom.hex}-dir" ami = "#{extract_path}/cirros-0.3.0-x86_64-blank.img" aki = "#{extract_path}/cirros-0.3.0-x86_64-vmlinuz" ari = "#{extract_path}/cirros-0.3.0-x86_64-initrd" FileUtils.mkdir_p extract_path # Efficient image write puts "Downloading Cirros image..." streamer = lambda do |chunk, remaining_bytes, total_bytes| image_out.write chunk end Excon.get image_url, :response_block => streamer image_out.close puts "Image downloaded to #{image_out.path}" puts "Extracting image contents to #{extract_path}..." Gem::Package::TarReader.new(Zlib::GzipReader.open(image_out.path)).each do |entry| FileUtils.mkdir_p "#{extract_path}/#{File.dirname(entry.full_name)}" File.open "#{extract_path}/#{entry.full_name}", 'w' do |f| f.write entry.read end end image_service = Fog::Image.new({ :provider => 'OpenStack', :openstack_api_key => ENV['OS_PASSWORD'], :openstack_username => ENV["OS_USERNAME"], :openstack_auth_url => ENV["OS_AUTH_URL"] + "/tokens", :openstack_tenant => ENV["OS_TENANT_NAME"] }) puts "Uploading AKI..." aki = image_service.images.create :name => 'cirros-0.3.0-amd64-aki', :size => File.size(aki), :disk_format => 'aki', :container_format => 'aki', :location => aki puts "Uploading ARI..." ari = image_service.images.create :name => 'cirros-0.3.0-amd64-ari', :size => File.size(ari), :disk_format => 'ari', :container_format => 'ari', :location => ari puts "Uploading AMI..." image_service.images.create :name => 'cirros-0.3.0-amd64', :size => File.size(ami), :disk_format => 'ami', :container_format => 'ami', :location => ami, :properties => { 'kernel_id' => aki.id, 'ramdisk_id' => ari.id } fog-1.19.0/lib/fog/openstack/volume.rb0000644000004100000410000001714512261242552017562 0ustar www-datawww-datarequire 'fog/openstack' module Fog module Volume class OpenStack < Fog::Service requires :openstack_auth_url recognizes :openstack_auth_token, :openstack_management_url, :persistent, :openstack_service_type, :openstack_service_name, :openstack_tenant, :openstack_api_key, :openstack_username, :current_user, :current_tenant, :openstack_endpoint_type, :openstack_region model_path 'fog/openstack/models/volume' model :volume collection :volumes model :volume_type collection :volume_types request_path 'fog/openstack/requests/volume' # Volume request :list_volumes request :create_volume request :get_volume_details request :delete_volume request :list_volume_types request :get_volume_type_details request :create_volume_snapshot request :list_snapshots request :get_snapshot_details request :delete_snapshot request :update_quota request :get_quota request :get_quota_defaults request :set_tenant class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = { :users => {}, :tenants => {}, :quota => { 'gigabytes' => 1000, 'volumes' => 10, 'snapshots' => 10 } } end end def self.reset @data = nil end def initialize(options={}) @openstack_username = options[:openstack_username] @openstack_tenant = options[:openstack_tenant] @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @auth_token = Fog::Mock.random_base64(64) @auth_token_expiration = (Time.now.utc + 86400).iso8601 management_url = URI.parse(options[:openstack_auth_url]) management_url.port = 8776 management_url.path = '/v1' @openstack_management_url = management_url.to_s @data ||= { :users => {} } unless @data[:users].find {|u| u['name'] == options[:openstack_username]} id = Fog::Mock.random_numbers(6).to_s @data[:users][id] = { 'id' => id, 'name' => options[:openstack_username], 'email' => "#{options[:openstack_username]}@mock.com", 'tenantId' => Fog::Mock.random_numbers(6).to_s, 'enabled' => true } end end def data self.class.data[@openstack_username] end def reset_data self.class.data.delete(@openstack_username) end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url } end end class Real attr_reader :current_user attr_reader :current_tenant def initialize(options={}) @openstack_auth_token = options[:openstack_auth_token] unless @openstack_auth_token missing_credentials = Array.new @openstack_api_key = options[:openstack_api_key] @openstack_username = options[:openstack_username] missing_credentials << :openstack_api_key unless @openstack_api_key missing_credentials << :openstack_username unless @openstack_username raise ArgumentError, "Missing required arguments: #{missing_credentials.join(', ')}" unless missing_credentials.empty? end @openstack_tenant = options[:openstack_tenant] @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @openstack_management_url = options[:openstack_management_url] @openstack_must_reauthenticate = false @openstack_service_type = options[:openstack_service_type] || ['volume'] @openstack_service_name = options[:openstack_service_name] @openstack_region = options[:openstack_region] @openstack_endpoint_type = options[:openstack_endpoint_type] || 'adminURL' @connection_options = options[:connection_options] || {} @current_user = options[:current_user] @current_tenant = options[:current_tenant] authenticate @persistent = options[:persistent] || false @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url, :current_user => @current_user, :current_tenant => @current_tenant } end def reload @connection.reset end def request(params) begin response = @connection.request(params.merge({ :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Auth-Token' => @auth_token }.merge!(params[:headers] || {}), :path => "#{@path}/#{params[:path]}"#, })) rescue Excon::Errors::Unauthorized => error if error.response.body != 'Bad username or password' # token expiration @openstack_must_reauthenticate = true authenticate retry else # bad credentials raise error end rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Compute::OpenStack::NotFound.slurp(error) else error end end unless response.body.empty? response.body = Fog::JSON.decode(response.body) end response end private def authenticate if !@openstack_management_url || @openstack_must_reauthenticate options = { :openstack_region => @openstack_region, :openstack_tenant => @openstack_tenant, :openstack_api_key => @openstack_api_key, :openstack_username => @openstack_username, :openstack_auth_uri => @openstack_auth_uri, :openstack_auth_token => @openstack_auth_token, :openstack_service_type => @openstack_service_type, :openstack_service_name => @openstack_service_name, :openstack_endpoint_type => @openstack_endpoint_type } credentials = Fog::OpenStack.authenticate_v2(options, @connection_options) @current_user = credentials[:user] @current_tenant = credentials[:tenant] @openstack_must_reauthenticate = false @auth_token = credentials[:token] @openstack_management_url = credentials[:server_management_url] uri = URI.parse(@openstack_management_url) else @auth_token = @openstack_auth_token uri = URI.parse(@openstack_management_url) end @host = uri.host @path = uri.path @path.sub!(/\/$/, '') @port = uri.port @scheme = uri.scheme true end end end end end fog-1.19.0/lib/fog/openstack/orchestration.rb0000644000004100000410000002062112261242552021130 0ustar www-datawww-datarequire 'fog/aws/cloud_formation' module Fog module Orchestration class OpenStack < Fog::Service requires :openstack_auth_url recognizes :openstack_auth_token, :openstack_management_url, :persistent, :openstack_service_type, :openstack_service_name, :openstack_tenant, :openstack_api_key, :openstack_username, :openstack_identity_endpoint, :current_user, :current_tenant, :openstack_region, :openstack_endpoint_type model_path 'fog/openstack/models/orchestration' model :stack collection :stacks request_path 'fog/openstack/requests/orchestration' request :create_stack request :update_stack request :delete_stack request :list_stacks class Mock attr_reader :auth_token attr_reader :auth_token_expiration attr_reader :current_user attr_reader :current_tenant def self.data @data ||= Hash.new do |hash, key| hash[key] = { :stacks => {} } end end def self.reset @data = nil end def initialize(options={}) @openstack_username = options[:openstack_username] @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @current_tenant = options[:openstack_tenant] @auth_token = Fog::Mock.random_base64(64) @auth_token_expiration = (Time.now.utc + 86400).iso8601 management_url = URI.parse(options[:openstack_auth_url]) management_url.port = 8774 management_url.path = '/v1' @openstack_management_url = management_url.to_s identity_public_endpoint = URI.parse(options[:openstack_auth_url]) identity_public_endpoint.port = 5000 @openstack_identity_public_endpoint = identity_public_endpoint.to_s end def data self.class.data["#{@openstack_username}-#{@current_tenant}"] end def reset_data self.class.data.delete("#{@openstack_username}-#{@current_tenant}") end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url, :openstack_identity_endpoint => @openstack_identity_public_endpoint } end end class Real attr_reader :auth_token attr_reader :auth_token_expiration attr_reader :current_user attr_reader :current_tenant def initialize(options={}) @openstack_auth_token = options[:openstack_auth_token] @auth_token = options[:openstack_auth_token] @openstack_identity_public_endpoint = options[:openstack_identity_endpoint] unless @auth_token missing_credentials = Array.new @openstack_api_key = options[:openstack_api_key] @openstack_username = options[:openstack_username] missing_credentials << :openstack_api_key unless @openstack_api_key missing_credentials << :openstack_username unless @openstack_username raise ArgumentError, "Missing required arguments: #{missing_credentials.join(', ')}" unless missing_credentials.empty? end @openstack_tenant = options[:openstack_tenant] @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @openstack_management_url = options[:openstack_management_url] @openstack_must_reauthenticate = false @openstack_service_type = options[:openstack_service_type] || ['orchestration'] @openstack_service_name = options[:openstack_service_name] @openstack_identity_service_type = options[:openstack_identity_service_type] || 'identity' @openstack_endpoint_type = options[:openstack_endpoint_type] || 'publicURL' @openstack_region = options[:openstack_region] @connection_options = options[:connection_options] || {} @current_user = options[:current_user] @current_tenant = options[:current_tenant] authenticate @persistent = options[:persistent] || false @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url, :openstack_identity_endpoint => @openstack_identity_public_endpoint, :openstack_region => @openstack_region, :current_user => @current_user, :current_tenant => @current_tenant } end def reload @connection.reset end def request(params) begin response = @connection.request(params.merge({ :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Auth-Token' => @auth_token, 'X-Auth-User' => @openstack_username, 'X-Auth-Key' => @openstack_api_key }.merge!(params[:headers] || {}), :path => "#{@path}/#{@tenant_id}/#{params[:path]}", :query => params[:query] })) rescue Excon::Errors::Unauthorized => error if error.response.body != 'Bad username or password' # token expiration @openstack_must_reauthenticate = true authenticate retry else # Bad Credentials raise error end rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Compute::OpenStack::NotFound.slurp(error) else error end end if !response.body.empty? and response.get_header('Content-Type') =~ /application\/json/ then response.body = Fog::JSON.decode(response.body) end response end private def authenticate if !@openstack_management_url || @openstack_must_reauthenticate options = { :openstack_api_key => @openstack_api_key, :openstack_username => @openstack_username, :openstack_auth_token => @auth_token, :openstack_auth_uri => @openstack_auth_uri, :openstack_region => @openstack_region, :openstack_tenant => @openstack_tenant, :openstack_service_type => @openstack_service_type, :openstack_service_name => @openstack_service_name, :openstack_identity_service_type => @openstack_identity_service_type, :openstack_endpoint_type => @openstack_endpoint_type } if @openstack_auth_uri.path =~ /\/v2.0\// credentials = Fog::OpenStack.authenticate_v2(options, @connection_options) else credentials = Fog::OpenStack.authenticate_v1(options, @connection_options) end @current_user = credentials[:user] @current_tenant = credentials[:tenant] @openstack_must_reauthenticate = false @auth_token = credentials[:token] @auth_token_expiration = credentials[:expires] @openstack_management_url = credentials[:server_management_url] @openstack_identity_public_endpoint = credentials[:identity_public_endpoint] end uri = URI.parse(@openstack_management_url) @host = uri.host @path, @tenant_id = uri.path.scan(/(\/.*)\/(.*)/).flatten @path.sub!(/\/$/, '') @port = uri.port @scheme = uri.scheme # Not all implementations have identity service in the catalog if @openstack_identity_public_endpoint || @openstack_management_url @identity_connection = Fog::Connection.new( @openstack_identity_public_endpoint || @openstack_management_url, false, @connection_options) end true end end end end end fog-1.19.0/lib/fog/openstack/identity.rb0000644000004100000410000002346012261242552020101 0ustar www-datawww-datarequire 'fog/openstack' module Fog module Identity class OpenStack < Fog::Service requires :openstack_auth_url recognizes :openstack_auth_token, :openstack_management_url, :persistent, :openstack_service_type, :openstack_service_name, :openstack_tenant, :openstack_api_key, :openstack_username, :openstack_current_user_id, :current_user, :current_tenant, :openstack_endpoint_type model_path 'fog/openstack/models/identity' model :tenant collection :tenants model :user collection :users model :role collection :roles model :ec2_credential collection :ec2_credentials request_path 'fog/openstack/requests/identity' request :check_token request :validate_token request :list_tenants request :create_tenant request :get_tenant request :get_tenants_by_id request :get_tenants_by_name request :update_tenant request :delete_tenant request :list_users request :create_user request :update_user request :delete_user request :get_user_by_id request :get_user_by_name request :add_user_to_tenant request :remove_user_from_tenant request :list_endpoints_for_token request :list_roles_for_user_on_tenant request :list_user_global_roles request :create_role request :delete_role request :delete_user_role request :create_user_role request :get_role request :list_roles request :set_tenant request :create_ec2_credential request :delete_ec2_credential request :get_ec2_credential request :list_ec2_credentials class Mock attr_reader :auth_token attr_reader :auth_token_expiration attr_reader :current_user attr_reader :current_tenant attr_reader :unscoped_token def self.data @users ||= {} @roles ||= {} @tenants ||= {} @ec2_credentials ||= Hash.new { |hash, key| hash[key] = {} } @user_tenant_membership ||= {} @data ||= Hash.new do |hash, key| hash[key] = { :users => @users, :roles => @roles, :tenants => @tenants, :ec2_credentials => @ec2_credentials, :user_tenant_membership => @user_tenant_membership } end end def self.reset! @data = nil @users = nil @roles = nil @tenants = nil @ec2_credentials = nil end def initialize(options={}) @openstack_username = options[:openstack_username] || 'admin' @openstack_tenant = options[:openstack_tenant] || 'admin' @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @openstack_management_url = @openstack_auth_uri.to_s @auth_token = Fog::Mock.random_base64(64) @auth_token_expiration = (Time.now.utc + 86400).iso8601 @admin_tenant = self.data[:tenants].values.find do |u| u['name'] == 'admin' end if @openstack_tenant @current_tenant = self.data[:tenants].values.find do |u| u['name'] == @openstack_tenant end unless @current_tenant @current_tenant_id = Fog::Mock.random_hex(32) @current_tenant = self.data[:tenants][@current_tenant_id] = { 'id' => @current_tenant_id, 'name' => @openstack_tenant } else @current_tenant_id = @current_tenant['id'] end else @current_tenant = @admin_tenant end @current_user = self.data[:users].values.find do |u| u['name'] == @openstack_username end @current_tenant_id = Fog::Mock.random_hex(32) unless @current_user @current_user_id = Fog::Mock.random_hex(32) @current_user = self.data[:users][@current_user_id] = { 'id' => @current_user_id, 'name' => @openstack_username, 'email' => "#{@openstack_username}@mock.com", 'tenantId' => Fog::Mock.random_numbers(6).to_s, 'enabled' => true } else @current_user_id = @current_user['id'] end end def data self.class.data[@openstack_username] end def reset_data self.class.data.delete(@openstack_username) end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url, :openstack_current_user_id => @openstack_current_user_id, :current_user => @current_user, :current_tenant => @current_tenant} end end class Real attr_reader :current_user attr_reader :current_tenant attr_reader :unscoped_token def initialize(options={}) @openstack_auth_token = options[:openstack_auth_token] unless @openstack_auth_token missing_credentials = Array.new @openstack_api_key = options[:openstack_api_key] @openstack_username = options[:openstack_username] missing_credentials << :openstack_api_key unless @openstack_api_key missing_credentials << :openstack_username unless @openstack_username raise ArgumentError, "Missing required arguments: #{missing_credentials.join(', ')}" unless missing_credentials.empty? end @openstack_tenant = options[:openstack_tenant] @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @openstack_management_url = options[:openstack_management_url] @openstack_must_reauthenticate = false @openstack_service_type = options[:openstack_service_type] || ['identity'] @openstack_service_name = options[:openstack_service_name] @connection_options = options[:connection_options] || {} @openstack_current_user_id = options[:openstack_current_user_id] @openstack_endpoint_type = options[:openstack_endpoint_type] || 'adminURL' @current_user = options[:current_user] @current_tenant = options[:current_tenant] authenticate @persistent = options[:persistent] || false @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url, :openstack_current_user_id => @openstack_current_user_id, :current_user => @current_user, :current_tenant => @current_tenant } end def reload @connection.reset end def request(params) retried = false begin response = @connection.request(params.merge({ :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Auth-Token' => @auth_token }.merge!(params[:headers] || {}), :path => "#{@path}/#{params[:path]}"#, })) rescue Excon::Errors::Unauthorized => error raise if retried retried = true @openstack_must_reauthenticate = true authenticate retry rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Identity::OpenStack::NotFound.slurp(error) else error end end unless response.body.empty? response.body = Fog::JSON.decode(response.body) end response end private def authenticate if !@openstack_management_url || @openstack_must_reauthenticate options = { :openstack_api_key => @openstack_api_key, :openstack_username => @openstack_username, :openstack_auth_token => @openstack_auth_token, :openstack_auth_uri => @openstack_auth_uri, :openstack_tenant => @openstack_tenant, :openstack_service_type => @openstack_service_type, :openstack_service_name => @openstack_service_name, :openstack_endpoint_type => @openstack_endpoint_type } credentials = Fog::OpenStack.authenticate_v2(options, @connection_options) @current_user = credentials[:user] @current_tenant = credentials[:tenant] @openstack_must_reauthenticate = false @auth_token = credentials[:token] @openstack_management_url = credentials[:server_management_url] @openstack_current_user_id = credentials[:current_user_id] @unscoped_token = credentials[:unscoped_token] uri = URI.parse(@openstack_management_url) else @auth_token = @openstack_auth_token uri = URI.parse(@openstack_management_url) end @host = uri.host @path = uri.path @path.sub!(/\/$/, '') @port = uri.port @scheme = uri.scheme true end end end end end fog-1.19.0/lib/fog/openstack/requests/0000755000004100000410000000000012261242552017571 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/requests/orchestration/0000755000004100000410000000000012261242552022455 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/requests/orchestration/list_stacks.rb0000644000004100000410000000227512261242552025333 0ustar www-datawww-datamodule Fog module Orchestration class OpenStack class Real # List stacks. # # @param options [Hash] # # @return [Excon::Response] # * body [Hash]: # * stacks [Array] - Matching stacks # * stack [Hash]: # * id [String] - # * stack_name [String] - # * description [String] # * links [Array] # * stack_status [String] - # * stack_status_reason [String] # * creation_time [Time] - # * updated_time [Time] - # # # @see http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_ListStacks.html def list_stacks(options = {}) request( :expects => 200, :path => 'stacks', :method => 'GET', :query => options ) end end class Mock def list_stacks(options = {}) stacks = self.data[:stacks].values Excon::Response.new( :body => { 'stacks' => stacks }, :status => 200 ) end end end end end fog-1.19.0/lib/fog/openstack/requests/orchestration/update_stack.rb0000644000004100000410000000221312261242552025447 0ustar www-datawww-datamodule Fog module Orchestration class OpenStack class Real # Update a stack. # # @param [String] stack_id ID of the stack to update. # @param [String] stack_name Name of the stack to update. # @param [Hash] options # * :template [String] Structure containing the template body. # or (one of the two Template parameters is required) # * :template_url [String] URL of file containing the template body. # * :parameters [Hash] Hash of providers to supply to template. # def update_stack(stack_id, stack_name, options = {}) params = { :stack_name => stack_name }.merge(options) request( :expects => 202, :path => "stacks/#{stack_name}/#{stack_id}", :method => 'PUT', :body => Fog::JSON.encode(params) ) end end class Mock def update_stack(stack_name, options = {}) response = Excon::Response.new response.status = 202 response.body = {} response end end end end end fog-1.19.0/lib/fog/openstack/requests/orchestration/create_stack.rb0000644000004100000410000000367612261242552025446 0ustar www-datawww-datamodule Fog module Orchestration class OpenStack class Real # Create a stack. # # * stack_name [String] Name of the stack to create. # * options [Hash]: # * :template_body [String] Structure containing the template body. # or (one of the two Template parameters is required) # * :template_url [String] URL of file containing the template body. # * :disable_rollback [Boolean] Controls rollback on stack creation failure, defaults to false. # * :parameters [Hash] Hash of providers to supply to template # * :timeout_in_minutes [Integer] Minutes to wait before status is set to CREATE_FAILED # # @see http://docs.amazonwebservices.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html def create_stack(stack_name, options = {}) params = { :stack_name => stack_name }.merge(options) request( :expects => 201, :path => 'stacks', :method => 'POST', :body => Fog::JSON.encode(params) ) end end class Mock def create_stack(stack_name, options = {}) stack_id = Fog::Mock.random_hex(32) stack = self.data[:stacks][stack_id] = { 'id' => stack_id, 'stack_name' => stack_name, 'links' => [], 'description' => options[:description], 'stack_status' => 'CREATE_COMPLETE', 'stack_status_reason' => 'Stack successfully created', 'creation_time' => Time.now, 'updated_time' => Time.now } response = Excon::Response.new response.status = 201 response.body = { 'id' => stack_id, 'links'=>[{"href"=>"http://localhost:8004/v1/fake_tenant_id/stacks/#{stack_name}/#{stack_id}", "rel"=>"self"}]} response end end end end end fog-1.19.0/lib/fog/openstack/requests/orchestration/delete_stack.rb0000644000004100000410000000157612261242552025442 0ustar www-datawww-datamodule Fog module Orchestration class OpenStack class Real # Delete a stack. # # @param stack_name [String] Name of the stack to delete. # @param stack_id [String] ID of the stack to delete. # # @return [Excon::Response] # # @see http://docs.amazonwebservices.com/AWSCloudFormation/latest/APIReference/API_DeleteStack.html def delete_stack(stack_name, stack_id) request( :expects => 204, :path => "stacks/#{stack_name}/#{stack_id}", :method => 'DELETE' ) end end class Mock def delete_stack(stack_name, stack_id) self.data[:stacks].delete(stack_id) response = Excon::Response.new response.status = 204 response.body = {} response end end end end end fog-1.19.0/lib/fog/openstack/requests/network/0000755000004100000410000000000012261242552021262 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/requests/network/delete_quota.rb0000644000004100000410000000071012261242552024260 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def delete_quota(tenant_id) request( :expects => 204, :method => 'DELETE', :path => "/quotas/#{tenant_id}" ) end end class Mock def delete_quota(tenant_id) response = Excon::Response.new response.status = 204 response end end end end end fog-1.19.0/lib/fog/openstack/requests/network/associate_lb_health_monitor.rb0000644000004100000410000000200712261242552027332 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def associate_lb_health_monitor(pool_id, health_monitor_id) data = { 'health_monitor' => { 'id' => health_monitor_id, } } request( :body => Fog::JSON.encode(data), :expects => [201], :method => 'POST', :path => "lb/pools/#{pool_id}/health_monitors" ) end end class Mock def associate_lb_health_monitor(pool_id, health_monitor_id) response = Excon::Response.new if pool = list_lb_pools.body['pools'].detect { |_| _['id'] == pool_id } pool['health_monitors'] << health_monitor_id self.data[:lb_pools][pool_id] = pool response.body = { 'health_monitor' => {} } response.status = 200 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/create_lb_vip.rb0000644000004100000410000000400012261242552024377 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def create_lb_vip(subnet_id, pool_id, protocol, protocol_port, options = {}) data = { 'vip' => { 'subnet_id' => subnet_id, 'pool_id' => pool_id, 'protocol' => protocol, 'protocol_port' => protocol_port } } vanilla_options = [:name, :description, :address, :session_persistence, :connection_limit, :admin_state_up, :tenant_id] vanilla_options.reject{ |o| options[o].nil? }.each do |key| data['vip'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => [201], :method => 'POST', :path => 'lb/vips' ) end end class Mock def create_lb_vip(subnet_id, pool_id, protocol, protocol_port, options = {}) response = Excon::Response.new response.status = 201 data = { 'id' => Fog::Mock.random_numbers(6).to_s, 'subnet_id' => subnet_id, 'pool_id' => pool_id, 'protocol' => protocol, 'protocol_port' => protocol_port, 'name' => options[:name], 'description' => options[:description], 'address' => options[:address], 'port_id' => Fog::Mock.random_numbers(6).to_s, 'session_persistence' => options[:session_persistence], 'connection_limit' => options[:connection_limit], 'status' => 'ACTIVE', 'admin_state_up' => options[:admin_state_up], 'tenant_id' => options[:tenant_id], } self.data[:lb_vips][data['id']] = data response.body = { 'vip' => data } response end end end end endfog-1.19.0/lib/fog/openstack/requests/network/update_lb_member.rb0000644000004100000410000000223012261242552025072 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def update_lb_member(member_id, options = {}) data = { 'member' => {} } vanilla_options = [:pool_id, :weight, :admin_state_up] vanilla_options.select{ |o| options.has_key?(o) }.each do |key| data['member'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'PUT', :path => "lb/members/#{member_id}" ) end end class Mock def update_lb_member(member_id, options = {}) response = Excon::Response.new if member = list_lb_members.body['members'].detect { |_| _['id'] == member_id } member['pool_id'] = options[:pool_id] member['weight'] = options[:weight] member['admin_state_up'] = options[:admin_state_up] response.body = { 'member' => member } response.status = 200 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/update_quota.rb0000644000004100000410000000126112261242552024302 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def update_quota(tenant_id, options = {}) request( :body => Fog::JSON.encode({ 'quota' => options} ), :expects => 200, :method => 'PUT', :path => "/quotas/#{tenant_id}" ) end end class Mock def update_quota(tenant_id, options = {}) self.data[:quota_updated] = self.data[:quota].merge options response = Excon::Response.new response.status = 200 response.body = { 'quota' => self.data[:quota_updated] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/network/update_lb_pool.rb0000644000004100000410000000230312261242552024575 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def update_lb_pool(pool_id, options = {}) data = { 'pool' => {} } vanilla_options = [:name, :description, :lb_method, :admin_state_up] vanilla_options.select{ |o| options.has_key?(o) }.each do |key| data['pool'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'PUT', :path => "lb/pools/#{pool_id}" ) end end class Mock def update_lb_pool(pool_id, options = {}) response = Excon::Response.new if pool = list_lb_pools.body['pools'].detect { |_| _['id'] == pool_id } pool['name'] = options[:name] pool['description'] = options[:description] pool['lb_method'] = options[:lb_method] pool['admin_state_up'] = options[:admin_state_up] response.body = { 'pool' => pool } response.status = 200 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/get_quotas.rb0000644000004100000410000000076312261242552023770 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def get_quotas request( :expects => 200, :method => 'GET', :path => "/quotas" ) end end class Mock def get_quotas response = Excon::Response.new response.status = 200 response.body = { 'quotas' => self.data[:quotas] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/network/get_subnet.rb0000644000004100000410000000246412261242552023754 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def get_subnet(subnet_id) request( :expects => [200], :method => 'GET', :path => "subnets/#{subnet_id}" ) end end class Mock def get_subnet(subnet_id) response = Excon::Response.new if data = self.data[:subnets][subnet_id] response.status = 200 response.body = { "subnet" => { "id" => "2e4ec6a4-0150-47f5-8523-e899ac03026e", "name" => "subnet_1", "network_id" => "e624a36d-762b-481f-9b50-4154ceb78bbb", "cidr" => "10.2.2.0/24", "ip_version" => 4, "gateway_ip" => "10.2.2.1", "allocation_pools" => [ { "start" => "10.2.2.2", "end" => "10.2.2.254" } ], "dns_nameservers" => [], "host_routes" => [], "enable_dhcp" => true, "tenant_id" => "f8b26a6032bc47718a7702233ac708b9", } } response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/set_tenant.rb0000644000004100000410000000052012261242552023750 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def set_tenant(tenant) @openstack_must_reauthenticate = true @openstack_tenant = tenant.to_s authenticate end end class Mock def set_tenant(tenant) true end end end end endfog-1.19.0/lib/fog/openstack/requests/network/get_lb_vip.rb0000644000004100000410000000115012261242552023716 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def get_lb_vip(vip_id) request( :expects => [200], :method => 'GET', :path => "lb/vips/#{vip_id}" ) end end class Mock def get_lb_vip(vip_id) response = Excon::Response.new if data = self.data[:lb_vips][vip_id] response.status = 200 response.body = { 'vip' => data } response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/get_lb_pool_stats.rb0000644000004100000410000000147012261242552025314 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def get_lb_pool_stats(pool_id) request( :expects => [200], :method => 'GET', :path => "lb/pools/#{pool_id}/stats" ) end end class Mock def get_lb_pool_stats(pool_id) response = Excon::Response.new if data = self.data[:lb_pools][pool_id] stats = {} stats["active_connections"] = 0 stats["bytes_in"] = 0 stats["bytes_out"] = 0 stats["total_connections"] = 0 response.status = 200 response.body = { 'stats' => stats } response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/list_lb_health_monitors.rb0000644000004100000410000000107412261242552026520 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def list_lb_health_monitors(filters = {}) request( :expects => 200, :method => 'GET', :path => 'lb/health_monitors', :query => filters ) end end class Mock def list_lb_health_monitors(filters = {}) Excon::Response.new( :body => { 'health_monitors' => self.data[:lb_health_monitors].values }, :status => 200 ) end end end end endfog-1.19.0/lib/fog/openstack/requests/network/create_floating_ip.rb0000644000004100000410000000253212261242552025427 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def create_floating_ip(floating_network_id, options = {}) data = { 'floatingip' => { 'floating_network_id' => floating_network_id } } vanilla_options = [:port_id, :tenant_id, :fixed_ip_address ] vanilla_options.reject{ |o| options[o].nil? }.each do |key| data['floatingip'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => [201], :method => 'POST', :path => 'floatingips' ) end end class Mock def create_floating_ip(floating_network_id, options = {}) response = Excon::Response.new response.status = 201 data = { 'id' => floating_network_id, 'floating_network_id' => floating_network_id, 'port_id' => options[:port_id], 'tenant_id' => options[:tenant_id], 'fixed_ip_address' => options[:fixed_ip_address], 'router_id' => nil, } self.data[:floating_ips][data['id']] = data response.body = { 'floatingip' => data } response end end end end end fog-1.19.0/lib/fog/openstack/requests/network/update_router.rb0000644000004100000410000000557512261242552024505 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real # Update Router # # Beyond the name and the administrative state, the only # parameter which can be updated with this operation is # the external gateway. # # router = Fog::Network[:openstack].routers.first # net = Fog::Network[:openstack].networks.first # # # :external_gateway_info can be either a # # Fog::Network::OpenStack::Network or a Hash # # like { 'network_id' => network.id } # Fog::Network[:openstack].update_router router.id, # :name => 'foo', # :external_gateway_info => net, # :admin_state_up => true # # @see http://docs.openstack.org/api/openstack-network/2.0/content/router_update.html def update_router(router_id, options = {}) data = { 'router' => {} } vanilla_options = [:name, :admin_state_up] egi = options[:external_gateway_info] if egi if egi.is_a?(Fog::Network::OpenStack::Network) data['router']['external_gateway_info'] = { 'network_id' => egi.id } elsif egi.is_a?(Hash) and egi['network_id'] data['router']['external_gateway_info'] = egi else raise ArgumentError.new('Invalid external_gateway_info attribute') end end vanilla_options.reject{ |o| options[o].nil? }.each do |key| data['router'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'PUT', :path => "routers/#{router_id}.json" ) end end class Mock def update_router(router_id, options = {}) response = Excon::Response.new router = list_routers.body['routers'].detect do |_| _['id'] == router_id end if router egi = options[:external_gateway_info] if egi if egi.is_a?(Fog::Network::OpenStack::Network) router['external_gateway_info'] = { 'network_id' => egi.id } elsif egi.is_a?(Hash) and egi['network_id'] router['external_gateway_info'] = egi else raise ArgumentError.new('Invalid external_gateway_info attribute') end end options.keys.each do |k| router[k.to_s] = options[k] end response.body = { 'router' => router } response.status = 200 response else raise Fog::Network::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/network/get_network.rb0000644000004100000410000000206012261242552024135 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def get_network(network_id) request( :expects => [200], :method => 'GET', :path => "networks/#{network_id}" ) end end class Mock def get_network(network_id) response = Excon::Response.new if data = self.data[:networks][network_id] response.status = 200 response.body = { 'network' => { 'id' => 'e624a36d-762b-481f-9b50-4154ceb78bbb', 'name' => 'network_1', 'subnets' => [ '2e4ec6a4-0150-47f5-8523-e899ac03026e' ], 'shared' => false, 'status' => 'ACTIVE', 'admin_state_up' => true, 'tenant_id' => 'f8b26a6032bc47718a7702233ac708b9', } } response else raise Fog::Network::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/network/update_lb_vip.rb0000644000004100000410000000256112261242552024430 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def update_lb_vip(vip_id, options = {}) data = { 'vip' => {} } vanilla_options = [:pool_id, :name, :description, :session_persistence, :connection_limit, :admin_state_up] vanilla_options.select{ |o| options.has_key?(o) }.each do |key| data['vip'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'PUT', :path => "lb/vips/#{vip_id}" ) end end class Mock def update_lb_vip(vip_id, options = {}) response = Excon::Response.new if vip = list_lb_vips.body['vips'].detect { |_| _['id'] == vip_id } vip['pool_id'] = options[:pool_id] vip['name'] = options[:name] vip['description'] = options[:description] vip['session_persistence'] = options[:session_persistence] vip['connection_limit'] = options[:connection_limit] vip['admin_state_up'] = options[:admin_state_up] response.body = { 'vip' => vip } response.status = 200 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/get_lb_member.rb0000644000004100000410000000120312261242552024366 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def get_lb_member(member_id) request( :expects => [200], :method => 'GET', :path => "lb/members/#{member_id}" ) end end class Mock def get_lb_member(member_id) response = Excon::Response.new if data = self.data[:lb_members][member_id] response.status = 200 response.body = { 'member' => data } response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/create_subnet.rb0000644000004100000410000000337712261242552024444 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def create_subnet(network_id, cidr, ip_version, options = {}) data = { 'subnet' => { 'network_id' => network_id, 'cidr' => cidr, 'ip_version' => ip_version, } } vanilla_options = [:name, :gateway_ip, :allocation_pools, :dns_nameservers, :host_routes, :enable_dhcp, :tenant_id] vanilla_options.reject{ |o| options[o].nil? }.each do |key| data['subnet'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => [201], :method => 'POST', :path => 'subnets' ) end end class Mock def create_subnet(network_id, cidr, ip_version, options = {}) response = Excon::Response.new response.status = 201 data = { 'id' => Fog::Mock.random_numbers(6).to_s, 'name' => options[:name], 'network_id' => network_id, 'cidr' => cidr, 'ip_version' => ip_version, 'gateway_ip' => options[:gateway_ip], 'allocation_pools' => options[:allocation_pools], 'dns_nameservers' => options[:dns_nameservers], 'host_routes' => options[:host_routes], 'enable_dhcp' => options[:enable_dhcp], 'tenant_id' => options[:tenant_id], } self.data[:subnets][data['id']] = data response.body = { 'subnet' => data } response end end end end endfog-1.19.0/lib/fog/openstack/requests/network/get_floating_ip.rb0000644000004100000410000000227412261242552024746 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def get_floating_ip(floating_ip_id) request( :expects => [200], :method => 'GET', :path => "floatingips/#{floating_ip_id}" ) end end class Mock def get_floating_ip(floating_ip_id) response = Excon::Response.new if data = self.data[:floating_ips][floating_ip_id] response.status = 200 response.body = { "floatingip" => { "id" => "00000000-0000-0000-0000-000000000000", # changed # "floating_ip_id" => floating_ip_id, "port_id" => data["port_id"], "tenant_id" => data["tenant_id"], "fixed_ip_address" => data["fixed_ip_address"], "router_id" => "00000000-0000-0000-0000-000000000000", "floating_ip_address" => data["floating_ip_address"], } } response else raise Fog::Network::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/network/get_port.rb0000644000004100000410000000257212261242552023440 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def get_port(port_id) request( :expects => [200], :method => 'GET', :path => "ports/#{port_id}" ) end end class Mock def get_port(port_id) response = Excon::Response.new if data = self.data[:ports][port_id] response.status = 200 response.body = { 'port' => { 'id' => '5c81d975-5fea-4674-9c1f-b8aa10bf9a79', 'name' => 'port_1', 'network_id' => 'e624a36d-762b-481f-9b50-4154ceb78bbb', 'fixed_ips' => [ { 'ip_address' => '10.2.2.2', 'subnet_id' => '2e4ec6a4-0150-47f5-8523-e899ac03026e', } ], 'mac_address' => 'fa:16:3e:62:91:7f', 'status' => 'ACTIVE', 'admin_state_up' => true, 'device_id' => 'dhcp724fc160-2b2e-597e-b9ed-7f65313cd73f-e624a36d-762b-481f-9b50-4154ceb78bbb', 'device_owner' => 'network:dhcp', 'tenant_id' => 'f8b26a6032bc47718a7702233ac708b9', } } response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/delete_lb_health_monitor.rb0000644000004100000410000000140412261242552026621 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def delete_lb_health_monitor(health_monitor_id) request( :expects => 204, :method => 'DELETE', :path => "lb/health_monitors/#{health_monitor_id}" ) end end class Mock def delete_lb_health_monitor(health_monitor_id) response = Excon::Response.new if list_lb_health_monitors.body['health_monitors'].map { |r| r['id'] }.include? health_monitor_id self.data[:lb_health_monitors].delete(health_monitor_id) response.status = 204 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/update_lb_health_monitor.rb0000644000004100000410000000315212261242552026643 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def update_lb_health_monitor(health_monitor_id, options = {}) data = { 'health_monitor' => {} } vanilla_options = [:delay, :timeout, :max_retries, :http_method, :url_path, :expected_codes, :admin_state_up] vanilla_options.select{ |o| options.has_key?(o) }.each do |key| data['health_monitor'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'PUT', :path => "lb/health_monitors/#{health_monitor_id}" ) end end class Mock def update_lb_health_monitor(health_monitor_id, options = {}) response = Excon::Response.new if health_monitor = list_lb_health_monitors.body['health_monitors'].detect { |_| _['id'] == health_monitor_id } health_monitor['delay'] = options[:delay] health_monitor['timeout'] = options[:timeout] health_monitor['max_retries'] = options[:max_retries] health_monitor['http_method'] = options[:http_method] health_monitor['url_path'] = options[:url_path] health_monitor['expected_codes'] = options[:expected_codes] health_monitor['admin_state_up'] = options[:admin_state_up] response.body = { 'health_monitor' => health_monitor } response.status = 200 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/remove_router_interface.rb0000644000004100000410000000155012261242552026525 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def remove_router_interface(router_id, subnet_id, options = {}) data = { 'subnet_id' => subnet_id, } request( :body => Fog::JSON.encode(data), :expects => [200], :method => 'PUT', :path => "routers/#{router_id}/remove_router_interface" ) end end class Mock def remove_router_interface(router_id, subnet_id, options = {}) response = Excon::Response.new response.status = 201 data = { 'subnet_id' => 'a2f1f29d-571b-4533-907f-5803ab96ead1' } self.data[:routers][data['router_id']] = data response.body = { 'router' => data } response end end end end end fog-1.19.0/lib/fog/openstack/requests/network/create_lb_pool.rb0000644000004100000410000000347712261242552024573 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def create_lb_pool(subnet_id, protocol, lb_method, options = {}) data = { 'pool' => { 'subnet_id' => subnet_id, 'protocol' => protocol, 'lb_method' => lb_method } } vanilla_options = [:name, :description, :admin_state_up, :tenant_id] vanilla_options.reject{ |o| options[o].nil? }.each do |key| data['pool'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => [201], :method => 'POST', :path => 'lb/pools' ) end end class Mock def create_lb_pool(subnet_id, protocol, lb_method, options = {}) response = Excon::Response.new response.status = 201 data = { 'id' => Fog::Mock.random_numbers(6).to_s, 'subnet_id' => subnet_id, 'protocol' => protocol, 'lb_method' => lb_method, 'name' => options[:name], 'description' => options[:description], 'health_monitors' => [], 'members' => [], 'status' => 'ACTIVE', 'admin_state_up' => options[:admin_state_up], 'vip_id' => nil, 'tenant_id' => options[:tenant_id], 'active_connections' => nil, 'bytes_in' => nil, 'bytes_out' => nil, 'total_connections' => nil } self.data[:lb_pools][data['id']] = data response.body = { 'pool' => data } response end end end end endfog-1.19.0/lib/fog/openstack/requests/network/associate_floating_ip.rb0000644000004100000410000000273112261242552026140 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def associate_floating_ip(floating_ip_id, port_id, options = {}) data = { 'floatingip' => { 'port_id' => port_id, } } vanilla_options = [:fixed_ip_address] vanilla_options.reject{ |o| options[o].nil? }.each do |key| data['floatingip'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => [200], :method => 'PUT', :path => "floatingips/#{floating_ip_id}" ) end end class Mock def associate_floating_ip(floating_ip_id, port_id, options = {}) response = Excon::Response.new response.status = 201 data = { 'id' => '00000000-0000-0000-0000-000000000000', 'router_id' => '00000000-0000-0000-0000-000000000000', 'tenant_id' => options["tenant_id"], 'floating_network_id' => options["floating_network_id"], 'fixed_ip_address' => options["fixed_ip_address"], 'floating_ip_address' => options["floating_ip_address"], 'port_id' => port_id, } self.data[:floating_ips][data['floating_ip_id']] = data response.body = { 'floatingip' => data } response end end end end end fog-1.19.0/lib/fog/openstack/requests/network/delete_floating_ip.rb0000644000004100000410000000132612261242552025426 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def delete_floating_ip(floating_ip_id) request( :expects => 204, :method => 'DELETE', :path => "floatingips/#{floating_ip_id}" ) end end class Mock def delete_floating_ip(floating_ip_id) response = Excon::Response.new if list_floating_ips.body['floatingips'].map { |r| r['id'] }.include? floating_ip_id self.data[:floating_ips].delete(floating_ip_id) response.status = 204 response else raise Fog::Network::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/network/create_port.rb0000644000004100000410000000302412261242552024115 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def create_port(network_id, options = {}) data = { 'port' => { 'network_id' => network_id, } } vanilla_options = [:name, :fixed_ips, :mac_address, :admin_state_up, :device_owner, :device_id, :tenant_id] vanilla_options.reject{ |o| options[o].nil? }.each do |key| data['port'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => [201], :method => 'POST', :path => 'ports' ) end end class Mock def create_port(network_id, options = {}) response = Excon::Response.new response.status = 201 data = { 'id' => Fog::Mock.random_numbers(6).to_s, 'name' => options[:name], 'network_id' => network_id, 'fixed_ips' => options[:fixed_ips], 'mac_address' => options[:mac_address], 'status' => 'ACTIVE', 'admin_state_up' => options[:admin_state_up], 'device_owner' => options[:device_owner], 'device_id' => options[:device_id], 'tenant_id' => options[:tenant_id], } self.data[:ports][data['id']] = data response.body = { 'port' => data } response end end end end endfog-1.19.0/lib/fog/openstack/requests/network/add_router_interface.rb0000644000004100000410000000260612261242552025763 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def add_router_interface(router_id, subnet_id, options = {}) data = { 'subnet_id' => subnet_id, } request( :body => Fog::JSON.encode(data), :expects => [200], :method => 'PUT', :path => "routers/#{router_id}/add_router_interface" ) end end class Mock def add_router_interface(router_id, subnet_id, options = {}) response = Excon::Response.new response.status = 201 data = { 'status' => 'ACTIVE', 'name' => '', 'admin_state_up' => true, 'network_id' => '5307648b-e836-4658-8f1a-ff7536870c64', 'tenant_id' => '6b96ff0cb17a4b859e1e575d221683d3', 'device_owner' => 'network:router_interface', 'mac_address' => 'fa:16:3e:f7:d1:9c', 'fixed_ips' => { 'subnet_id' => 'a2f1f29d-571b-4533-907f-5803ab96ead1', 'ip_address' => '10.1.1.1' }, 'id' => '3a44f4e5-1694-493a-a1fb-393881c673a4', 'device_id' => '7177abc4-5ae9-4bb7-b0d4-89e94a4abf3b' } self.data[:routers][data['router_id']] = data response.body = { 'router' => data } response end end end end end fog-1.19.0/lib/fog/openstack/requests/network/disassociate_lb_health_monitor.rb0000644000004100000410000000151012261242552030030 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def disassociate_lb_health_monitor(pool_id, health_monitor_id) request( :expects => [204], :method => 'DELETE', :path => "lb/pools/#{pool_id}/health_monitors/#{health_monitor_id}" ) end end class Mock def disassociate_lb_health_monitor(pool_id, health_monitor_id) response = Excon::Response.new if pool = list_lb_pools.body['pools'].detect { |_| _['id'] == pool_id } pool['health_monitors'].delete(health_monitor_id) self.data[:lb_pools][pool_id] = pool response.status = 204 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/create_router.rb0000644000004100000410000000266612261242552024464 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def create_router(name, options = {}) data = { 'router' => { 'name' => name, } } vanilla_options = [ :admin_state_up, :tenant_id, :network_id, :external_gateway_info, :status, :subnet_id ] vanilla_options.reject{ |o| options[o].nil? }.each do |key| data['router'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => [201], :method => 'POST', :path => 'routers' ) end end class Mock def create_router(name, options = {}) response = Excon::Response.new response.status = 201 data = { 'router' => { 'id' => Fog::Mock.random_numbers(6).to_s, 'status' => options[:status] || 'ACTIVE', 'external_gateway_info' => options[:external_gateway_info], 'name' => name, 'admin_state_up' => options[:admin_state_up], 'tenant_id' => '6b96ff0cb17a4b859e1e575d221683d3' } } self.data[:routers][data['router']['id']] = data['router'] response.body = data response end end end end end fog-1.19.0/lib/fog/openstack/requests/network/delete_lb_member.rb0000644000004100000410000000125412261242552025057 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def delete_lb_member(member_id) request( :expects => 204, :method => 'DELETE', :path => "lb/members/#{member_id}" ) end end class Mock def delete_lb_member(member_id) response = Excon::Response.new if list_lb_members.body['members'].map { |r| r['id'] }.include? member_id self.data[:lb_members].delete(member_id) response.status = 204 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/list_lb_vips.rb0000644000004100000410000000100512261242552024274 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def list_lb_vips(filters = {}) request( :expects => 200, :method => 'GET', :path => 'lb/vips', :query => filters ) end end class Mock def list_lb_vips(filters = {}) Excon::Response.new( :body => { 'vips' => self.data[:lb_vips].values }, :status => 200 ) end end end end endfog-1.19.0/lib/fog/openstack/requests/network/delete_port.rb0000644000004100000410000000121212261242552024111 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def delete_port(port_id) request( :expects => 204, :method => 'DELETE', :path => "ports/#{port_id}" ) end end class Mock def delete_port(port_id) response = Excon::Response.new if list_ports.body['ports'].map { |r| r['id'] }.include? port_id self.data[:ports].delete(port_id) response.status = 204 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/update_port.rb0000644000004100000410000000244012261242552024135 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def update_port(port_id, options = {}) data = { 'port' => {} } vanilla_options = [:name, :fixed_ips, :admin_state_up, :device_owner, :device_id] vanilla_options.select{ |o| options.has_key?(o) }.each do |key| data['port'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'PUT', :path => "ports/#{port_id}.json" ) end end class Mock def update_port(port_id, options = {}) response = Excon::Response.new if port = list_ports.body['ports'].detect { |_| _['id'] == port_id } port['name'] = options[:name] port['fixed_ips'] = options[:fixed_ips] port['admin_state_up'] = options[:admin_state_up] port['device_owner'] = options[:device_owner] port['device_id'] = options[:device_id] response.body = { 'port' => port } response.status = 200 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/list_subnets.rb0000644000004100000410000000101012261242552024315 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def list_subnets(filters = {}) request( :expects => 200, :method => 'GET', :path => 'subnets', :query => filters ) end end class Mock def list_subnets(filters = {}) Excon::Response.new( :body => { 'subnets' => self.data[:subnets].values }, :status => 200 ) end end end end endfog-1.19.0/lib/fog/openstack/requests/network/delete_router.rb0000644000004100000410000000124112261242552024447 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def delete_router(router_id) request( :expects => 204, :method => 'DELETE', :path => "routers/#{router_id}" ) end end class Mock def delete_router(router_id) response = Excon::Response.new if list_routers.body['routers'].map { |r| r['id'] }.include? router_id self.data[:routers].delete(router_id) response.status = 204 response else raise Fog::Network::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/network/disassociate_floating_ip.rb0000644000004100000410000000263112261242552026637 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def disassociate_floating_ip(floating_ip_id, options = {}) data = { 'floatingip' => { 'port_id' => nil, } } vanilla_options = [:fixed_ip_address] vanilla_options.reject{ |o| options[o].nil? }.each do |key| data['floatingip'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => [200], :method => 'PUT', :path => "floatingips/#{floating_ip_id}" ) end end class Mock def disassociate_floating_ip(floating_ip_id, options = {}) response = Excon::Response.new response.status = 200 data = { 'id' => '00000000-0000-0000-0000-000000000000', 'router_id' => nil, 'tenant_id' => options["tenant_id"], 'floating_network_id' => options["floating_network_id"], 'fixed_ip_address' => nil, 'floating_ip_address' => options["floating_ip_address"], 'port_id' => options["port_id"], } self.data[:floating_ips][data['floating_ip_id']] = data response.body = { 'floatingip' => data } response end end end end end fog-1.19.0/lib/fog/openstack/requests/network/delete_subnet.rb0000644000004100000410000000124012261242552024426 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def delete_subnet(subnet_id) request( :expects => 204, :method => 'DELETE', :path => "subnets/#{subnet_id}" ) end end class Mock def delete_subnet(subnet_id) response = Excon::Response.new if list_subnets.body['subnets'].map { |r| r['id'] }.include? subnet_id self.data[:subnets].delete(subnet_id) response.status = 204 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/create_lb_member.rb0000644000004100000410000000301212261242552025052 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def create_lb_member(pool_id, address, protocol_port, weight, options = {}) data = { 'member' => { 'pool_id' => pool_id, 'address' => address, 'protocol_port' => protocol_port, 'weight' => weight } } vanilla_options = [:admin_state_up, :tenant_id] vanilla_options.reject{ |o| options[o].nil? }.each do |key| data['member'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => [201], :method => 'POST', :path => 'lb/members' ) end end class Mock def create_lb_member(pool_id, address, protocol_port, weight, options = {}) response = Excon::Response.new response.status = 201 data = { 'id' => Fog::Mock.random_numbers(6).to_s, 'pool_id' => pool_id, 'address' => address, 'protocol_port' => protocol_port, 'weight' => weight, 'status' => 'ACTIVE', 'admin_state_up' => options[:admin_state_up], 'tenant_id' => options[:tenant_id], } self.data[:lb_members][data['id']] = data response.body = { 'member' => data } response end end end end endfog-1.19.0/lib/fog/openstack/requests/network/delete_network.rb0000644000004100000410000000125312261242552024623 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def delete_network(network_id) request( :expects => 204, :method => 'DELETE', :path => "networks/#{network_id}" ) end end class Mock def delete_network(network_id) response = Excon::Response.new if list_networks.body['networks'].map { |r| r['id'] }.include? network_id self.data[:networks].delete(network_id) response.status = 204 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/list_lb_members.rb0000644000004100000410000000102412261242552024746 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def list_lb_members(filters = {}) request( :expects => 200, :method => 'GET', :path => 'lb/members', :query => filters ) end end class Mock def list_lb_members(filters = {}) Excon::Response.new( :body => { 'members' => self.data[:lb_members].values }, :status => 200 ) end end end end endfog-1.19.0/lib/fog/openstack/requests/network/get_lb_pool.rb0000644000004100000410000000116112261242552024073 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def get_lb_pool(pool_id) request( :expects => [200], :method => 'GET', :path => "lb/pools/#{pool_id}" ) end end class Mock def get_lb_pool(pool_id) response = Excon::Response.new if data = self.data[:lb_pools][pool_id] response.status = 200 response.body = { 'pool' => data } response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/update_subnet.rb0000644000004100000410000000251412261242552024453 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def update_subnet(subnet_id, options = {}) data = { 'subnet' => {} } vanilla_options = [:name, :gateway_ip, :dns_nameservers, :host_routes, :enable_dhcp] vanilla_options.select{ |o| options.has_key?(o) }.each do |key| data['subnet'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'PUT', :path => "subnets/#{subnet_id}" ) end end class Mock def update_subnet(subnet_id, options = {}) response = Excon::Response.new if subnet = list_subnets.body['subnets'].detect { |_| _['id'] == subnet_id } subnet['name'] = options[:name] subnet['gateway_ip'] = options[:gateway_ip] subnet['dns_nameservers'] = options[:dns_nameservers] subnet['host_routes'] = options[:host_routes] subnet['enable_dhcp'] = options[:enable_dhcp] response.body = { 'subnet' => subnet } response.status = 200 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/delete_lb_vip.rb0000644000004100000410000000121312261242552024401 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def delete_lb_vip(vip_id) request( :expects => 204, :method => 'DELETE', :path => "lb/vips/#{vip_id}" ) end end class Mock def delete_lb_vip(vip_id) response = Excon::Response.new if list_lb_vips.body['vips'].map { |r| r['id'] }.include? vip_id self.data[:lb_vips].delete(vip_id) response.status = 204 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/create_network.rb0000644000004100000410000000626112261242552024630 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def create_network(options = {}) data = { 'network' => {} } vanilla_options = [ :name, :shared, :admin_state_up, :tenant_id ] vanilla_options.reject{ |o| options[o].nil? }.each do |key| data['network'][key] = options[key] end # Advanced Features through API Extensions # # Not strictly required but commonly found in OpenStack # installs with Quantum networking. # # @see http://docs.openstack.org/trunk/openstack-network/admin/content/provider_attributes.html provider_options = [ :router_external, :provider_network_type, :provider_segmentation_id, :provider_physical_network ] # Map Fog::Network::OpenStack::Network # model attributes to OpenStack provider attributes aliases = { :provider_network_type => 'provider:network_type', # Not applicable to the "local" or "gre" network types :provider_physical_network => 'provider:physical_network', :provider_segmentation_id => 'provider:segmentation_id', :router_external => 'router:external' } provider_options.reject{ |o| options[o].nil? }.each do |key| aliased_key = aliases[key] || key data['network'][aliased_key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => [201], :method => 'POST', :path => 'networks' ) end end class Mock def create_network(options = {}) response = Excon::Response.new response.status = 201 data = { 'id' => Fog::Mock.random_numbers(6).to_s, 'name' => options[:name], 'shared' => options[:shared], 'subnets' => [], 'status' => 'ACTIVE', 'admin_state_up' => options[:admin_state_up], 'tenant_id' => options[:tenant_id], } # Add provider specific attributes when found # provider_options = [ :router_external, :provider_network_type, :provider_segmentation_id, :provider_physical_network ] aliases = { :provider_network_type => 'provider:network_type', # Not applicable to the "local" or "gre" network types :provider_physical_network => 'provider:physical_network', :provider_segmentation_id => 'provider:segmentation_id', :router_external => 'router:external' } provider_options.reject{ |o| options[o].nil? }.each do |key| aliased_key = aliases[key] || key data[aliased_key] = options[key] end self.data[:networks][data['id']] = data response.body = { 'network' => data } response end end end end end fog-1.19.0/lib/fog/openstack/requests/network/list_lb_pools.rb0000644000004100000410000000101212261242552024445 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def list_lb_pools(filters = {}) request( :expects => 200, :method => 'GET', :path => 'lb/pools', :query => filters ) end end class Mock def list_lb_pools(filters = {}) Excon::Response.new( :body => { 'pools' => self.data[:lb_pools].values }, :status => 200 ) end end end end endfog-1.19.0/lib/fog/openstack/requests/network/list_ports.rb0000644000004100000410000000077612261242552024023 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def list_ports(filters = {}) request( :expects => 200, :method => 'GET', :path => 'ports', :query => filters ) end end class Mock def list_ports(filters = {}) Excon::Response.new( :body => { 'ports' => self.data[:ports].values }, :status => 200 ) end end end end endfog-1.19.0/lib/fog/openstack/requests/network/create_lb_health_monitor.rb0000644000004100000410000000335112261242552026625 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def create_lb_health_monitor(type, delay, timeout, max_retries, options = {}) data = { 'health_monitor' => { 'type' => type, 'delay' => delay, 'timeout' => timeout, 'max_retries' => max_retries } } vanilla_options = [:http_method, :url_path, :expected_codes, :admin_state_up, :tenant_id] vanilla_options.reject{ |o| options[o].nil? }.each do |key| data['health_monitor'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => [201], :method => 'POST', :path => 'lb/health_monitors' ) end end class Mock def create_lb_health_monitor(type, delay, timeout, max_retries, options = {}) response = Excon::Response.new response.status = 201 data = { 'id' => Fog::Mock.random_numbers(6).to_s, 'type' => type, 'delay' => delay, 'timeout' => timeout, 'max_retries' => max_retries, 'http_method' => options[:http_method], 'url_path' => options[:url_path], 'expected_codes' => options[:expected_codes], 'status' => 'ACTIVE', 'admin_state_up' => options[:admin_state_up], 'tenant_id' => options[:tenant_id], } self.data[:lb_health_monitors][data['id']] = data response.body = { 'health_monitor' => data } response end end end end endfog-1.19.0/lib/fog/openstack/requests/network/get_lb_health_monitor.rb0000644000004100000410000000131312261242552026135 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def get_lb_health_monitor(health_monitor_id) request( :expects => [200], :method => 'GET', :path => "lb/health_monitors/#{health_monitor_id}" ) end end class Mock def get_lb_health_monitor(health_monitor_id) response = Excon::Response.new if data = self.data[:lb_health_monitors][health_monitor_id] response.status = 200 response.body = { 'health_monitor' => data } response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/list_routers.rb0000644000004100000410000000101112261242552024336 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def list_routers(filters = {}) request( :expects => 200, :method => 'GET', :path => 'routers', :query => filters ) end end class Mock def list_routers(filters = {}) Excon::Response.new( :body => { 'routers' => self.data[:routers].values }, :status => 200 ) end end end end end fog-1.19.0/lib/fog/openstack/requests/network/get_quota.rb0000644000004100000410000000106112261242552023575 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def get_quota(tenant_id) request( :expects => 200, :method => 'GET', :path => "/quotas/#{tenant_id}" ) end end class Mock def get_quota(tenant_id) response = Excon::Response.new response.status = 200 response.body = { 'quota' => (self.data[:quota_updated] or self.data[:quota]) } response end end end end end fog-1.19.0/lib/fog/openstack/requests/network/list_networks.rb0000644000004100000410000000101512261242552024513 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def list_networks(filters = {}) request( :expects => 200, :method => 'GET', :path => 'networks', :query => filters ) end end class Mock def list_networks(filters = {}) Excon::Response.new( :body => { 'networks' => self.data[:networks].values }, :status => 200 ) end end end end endfog-1.19.0/lib/fog/openstack/requests/network/get_router.rb0000644000004100000410000000126112261242552023766 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def get_router(router_id) request( :expects => [200], :method => 'GET', :path => "routers/#{router_id}" ) end end class Mock def get_router(router_id) response = Excon::Response.new if data = (self.data[:routers].find { |id,value| id == router_id }) response.status = 200 response.body = { 'router' => data[1], } response else raise Fog::Network::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/network/delete_lb_pool.rb0000644000004100000410000000122612261242552024560 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def delete_lb_pool(pool_id) request( :expects => 204, :method => 'DELETE', :path => "lb/pools/#{pool_id}" ) end end class Mock def delete_lb_pool(pool_id) response = Excon::Response.new if list_lb_pools.body['pools'].map { |r| r['id'] }.include? pool_id self.data[:lb_pools].delete(pool_id) response.status = 204 response else raise Fog::Network::OpenStack::NotFound end end end end end endfog-1.19.0/lib/fog/openstack/requests/network/list_floating_ips.rb0000644000004100000410000000104012261242552025313 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def list_floating_ips(filters = {}) request( :expects => 200, :method => 'GET', :path => 'floatingips', :query => filters ) end end class Mock def list_floating_ips(filters = {}) Excon::Response.new( :body => { 'floatingips' => self.data[:floating_ips].values }, :status => 200 ) end end end end end fog-1.19.0/lib/fog/openstack/requests/network/update_network.rb0000644000004100000410000000224112261242552024641 0ustar www-datawww-datamodule Fog module Network class OpenStack class Real def update_network(network_id, options = {}) data = { 'network' => {} } vanilla_options = [:name, :shared, :admin_state_up] vanilla_options.select{ |o| options.has_key?(o) }.each do |key| data['network'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'PUT', :path => "networks/#{network_id}.json" ) end end class Mock def update_network(network_id, options = {}) response = Excon::Response.new if network = list_networks.body['networks'].detect { |_| _['id'] == network_id } network['name'] = options[:name] network['shared'] = options[:shared] network['admin_state_up'] = options[:admin_state_up] response.body = { 'network' => network } response.status = 200 response else raise Fog::Network::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/storage/0000755000004100000410000000000012261242552021235 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/requests/storage/get_container.rb0000644000004100000410000000326612261242552024412 0ustar www-datawww-datamodule Fog module Storage class OpenStack 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 def get_container(container, options = {}) options = options.reject {|key, value| value.nil?} request( :expects => 200, :method => 'GET', :path => Fog::OpenStack.escape(container), :query => {'format' => 'json'}.merge!(options) ) end end end end end fog-1.19.0/lib/fog/openstack/requests/storage/put_object.rb0000644000004100000410000000251012261242552023716 0ustar www-datawww-datamodule Fog module Storage class OpenStack 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 # def put_object(container, object, data, options = {}, &block) if block_given? params = { :request_block => block } headers = options else data = Fog::Storage.parse_data(data) headers = data[:headers].merge!(options) params = { :body => data[:body] } end params.merge!( :expects => 201, :idempotent => !params[:request_block], :headers => headers, :method => 'PUT', :path => "#{Fog::OpenStack.escape(container)}/#{Fog::OpenStack.escape(object)}" ) request(params) end end end end end fog-1.19.0/lib/fog/openstack/requests/storage/put_container.rb0000644000004100000410000000072212261242552024435 0ustar www-datawww-datamodule Fog module Storage class OpenStack class Real # Create a new container # # ==== Parameters # * name<~String> - Name for container, should be < 256 bytes and must not contain '/' # def put_container(name) request( :expects => [201, 202], :method => 'PUT', :path => Fog::OpenStack.escape(name) ) end end end end end fog-1.19.0/lib/fog/openstack/requests/storage/head_object.rb0000644000004100000410000000104312261242552024007 0ustar www-datawww-datamodule Fog module Storage class OpenStack class Real # Get headers for object # # ==== Parameters # * container<~String> - Name of container to look in # * object<~String> - Name of object to look for # def head_object(container, object) request({ :expects => 200, :method => 'HEAD', :path => "#{Fog::OpenStack.escape(container)}/#{Fog::OpenStack.escape(object)}" }, false) end end end end end fog-1.19.0/lib/fog/openstack/requests/storage/get_containers.rb0000644000004100000410000000175212261242552024573 0ustar www-datawww-datamodule Fog module Storage class OpenStack 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 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 end end end fog-1.19.0/lib/fog/openstack/requests/storage/put_object_manifest.rb0000644000004100000410000000060112261242552025603 0ustar www-datawww-datamodule Fog module Storage class OpenStack class Real # 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 end end end fog-1.19.0/lib/fog/openstack/requests/storage/delete_container.rb0000644000004100000410000000066012261242552025070 0ustar www-datawww-datamodule Fog module Storage class OpenStack class Real # Delete an existing container # # ==== Parameters # * name<~String> - Name of container to delete # def delete_container(name) request( :expects => 204, :method => 'DELETE', :path => Fog::OpenStack.escape(name) ) end end end end end fog-1.19.0/lib/fog/openstack/requests/storage/post_set_meta_temp_url_key.rb0000644000004100000410000000211212261242552027203 0ustar www-datawww-datamodule Fog module Storage class OpenStack 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 :openstack_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> # # ==== 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 end end end fog-1.19.0/lib/fog/openstack/requests/storage/put_dynamic_obj_manifest.rb0000644000004100000410000000423212261242552026617 0ustar www-datawww-datamodule Fog module Storage class OpenStack 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::OpenStack.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::OpenStack::NotFound] HTTP 404 # @raise [Excon::Errors::BadRequest] HTTP 400 # @raise [Excon::Errors::Unauthorized] HTTP 401 # @raise [Excon::Errors::HTTPStatusError] # # @see http://docs.openstack.org/api/openstack-object-storage/1.0/content/dynamic-large-object-creation.html def put_dynamic_obj_manifest(container, object, options = {}) path = "#{Fog::OpenStack.escape(container)}/#{Fog::OpenStack.escape(object)}" headers = {'X-Object-Manifest' => path}.merge(options) request( :expects => 201, :headers => headers, :method => 'PUT', :path => path ) end end end end end fog-1.19.0/lib/fog/openstack/requests/storage/delete_static_large_object.rb0000644000004100000410000000362612261242552027102 0ustar www-datawww-datamodule Fog module Storage class OpenStack 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. # # @see http://docs.openstack.org/api/openstack-object-storage/1.0/content/static-large-objects.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::OpenStack.escape(container)}/#{Fog::OpenStack.escape(object)}", :query => { 'multipart-manifest' => 'delete' } }, false) response.body = Fog::JSON.decode(response.body) response end end end end end fog-1.19.0/lib/fog/openstack/requests/storage/get_object_http_url.rb0000644000004100000410000000072312261242552025612 0ustar www-datawww-data# Get an expiring object http url # # ==== 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 def get_object_http_url(container, object, expires, options = {}) create_temp_url(container, object, expires, "GET", options.merge(:scheme => "http")) endfog-1.19.0/lib/fog/openstack/requests/storage/copy_object.rb0000644000004100000410000000171112261242552024062 0ustar www-datawww-datamodule Fog module Storage class OpenStack 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 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::OpenStack.escape(target_container_name)}/#{Fog::OpenStack.escape(target_object_name)}" }) end end end end end fog-1.19.0/lib/fog/openstack/requests/storage/delete_object.rb0000644000004100000410000000103612261242552024352 0ustar www-datawww-datamodule Fog module Storage class OpenStack class Real # Delete an existing object # # ==== Parameters # * container<~String> - Name of container to delete # * object<~String> - Name of object to delete # def delete_object(container, object) request( :expects => 204, :method => 'DELETE', :path => "#{Fog::OpenStack.escape(container)}/#{Fog::OpenStack.escape(object)}" ) end end end end end fog-1.19.0/lib/fog/openstack/requests/storage/head_containers.rb0000644000004100000410000000113212261242552024705 0ustar www-datawww-datamodule Fog module Storage class OpenStack 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 def head_containers request( :expects => 204, :method => 'HEAD', :path => '', :query => {'format' => 'json'} ) end end end end end fog-1.19.0/lib/fog/openstack/requests/storage/get_object_https_url.rb0000644000004100000410000000545212261242552026001 0ustar www-datawww-datamodule Fog module Storage class OpenStack class Real # 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 # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object def get_object_https_url(container, object, expires, options = {}) create_temp_url(container, object, expires, "GET", options.merge(:scheme => "https")) end # creates a temporary url # # ==== 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 # * method<~String> - The method to use for accessing the object (GET, PUT, HEAD) # * scheme<~String> - The scheme to use (http, https) # * options<~Hash> - An optional options hash # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object # # ==== See Also # http://docs.rackspace.com/files/api/v1/cf-devguide/content/Create_TempURL-d1a444.html def create_temp_url(container, object, expires, method, options = {}) raise ArgumentError, "Insufficient parameters specified." unless (container && object && expires && method) raise ArgumentError, "Storage must my instantiated with the :openstack_temp_url_key option" if @openstack_temp_url_key.nil? scheme = options[:scheme] || @scheme # POST not allowed allowed_methods = %w{GET PUT HEAD} unless allowed_methods.include?(method) raise ArgumentError.new("Invalid method '#{method}' specified. Valid methods are: #{allowed_methods.join(', ')}") end expires = expires.to_i object_path_escaped = "#{@path}/#{Fog::OpenStack.escape(container)}/#{Fog::OpenStack.escape(object,"/")}" object_path_unescaped = "#{@path}/#{Fog::OpenStack.escape(container)}/#{object}" string_to_sign = "#{method}\n#{expires}\n#{object_path_unescaped}" hmac = Fog::HMAC.new('sha1', @openstack_temp_url_key) sig = sig_to_hex(hmac.sign(string_to_sign)) "#{scheme}://#{@host}#{object_path_escaped}?temp_url_sig=#{sig}&temp_url_expires=#{expires}" 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 end end end fog-1.19.0/lib/fog/openstack/requests/storage/head_container.rb0000644000004100000410000000135612261242552024532 0ustar www-datawww-datamodule Fog module Storage class OpenStack 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 def head_container(container) request( :expects => 204, :method => 'HEAD', :path => Fog::OpenStack.escape(container), :query => {'format' => 'json'} ) end end end end end fog-1.19.0/lib/fog/openstack/requests/storage/put_static_obj_manifest.rb0000644000004100000410000000534512261242552026470 0ustar www-datawww-datamodule Fog module Storage class OpenStack 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::OpenStack::NotFound] HTTP 404 # @raise [Excon::Errors::BadRequest] HTTP 400 # @raise [Excon::Errors::Unauthorized] HTTP 401 # @raise [Excon::Errors::HTTPStatusError] # # @see http://docs.openstack.org/api/openstack-object-storage/1.0/content/static-large-objects.html def put_static_obj_manifest(container, object, segments, options = {}) request( :expects => 201, :method => 'PUT', :headers => options, :body => Fog::JSON.encode(segments), :path => "#{Fog::OpenStack.escape(container)}/#{Fog::OpenStack.escape(object)}", :query => { 'multipart-manifest' => 'put' } ) end end end end end fog-1.19.0/lib/fog/openstack/requests/storage/get_object.rb0000644000004100000410000000123112261242552023664 0ustar www-datawww-datamodule Fog module Storage class OpenStack class Real # Get details for object # # ==== Parameters # * container<~String> - Name of container to look in # * object<~String> - Name of object to look for # def get_object(container, object, &block) params = { :expects => 200, :method => 'GET', :path => "#{Fog::OpenStack.escape(container)}/#{Fog::OpenStack.escape(object)}" } if block_given? params[:response_block] = block end request(params, false) end end end end end fog-1.19.0/lib/fog/openstack/requests/storage/delete_multiple_objects.rb0000644000004100000410000000612612261242552026455 0ustar www-datawww-datamodule Fog module Storage class OpenStack 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". 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 end end end fog-1.19.0/lib/fog/openstack/requests/volume/0000755000004100000410000000000012261242552021100 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/requests/volume/list_volume_types.rb0000644000004100000410000000176112261242552025220 0ustar www-datawww-datamodule Fog module Volume class OpenStack class Real def list_volume_types(options={}) request( :expects => 200, :method => 'GET', :path => 'types', :query => options ) end end class Mock def list_volume_types(options={}) response = Excon::Response.new response.status = 200 self.data[:volume_types] ||= [ { "id" => "1", "name" => "type 1", "extra_specs" => { "volume_backend_name" => "type 1 backend name" } }, { "id" => "2", "name" => "type 2", "extra_specs" => { "volume_backend_name" => "type 2 backend name" } } ] response.body = { 'volume_types' => self.data[:volume_types] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/volume/update_quota.rb0000644000004100000410000000133512261242552024122 0ustar www-datawww-datamodule Fog module Volume class OpenStack class Real def update_quota(tenant_id, options = {}) options['tenant_id'] = tenant_id request( :body => Fog::JSON.encode({ 'quota_set' => options }), :expects => 200, :method => 'PUT', :path => "/os-quota-sets/#{tenant_id}" ) end end class Mock def update_quota(tenant_id, options = {}) self.data[:quota_updated] = self.data[:quota].merge options response = Excon::Response.new response.status = 200 response.body = { 'quota_set' => self.data[:quota_updated] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/volume/create_volume_snapshot.rb0000644000004100000410000000223712261242552026202 0ustar www-datawww-datamodule Fog module Volume class OpenStack class Real def create_volume_snapshot(volume_id, name, description, force=false) data = { 'snapshot' => { 'volume_id' => volume_id, 'display_name' => name, 'display_description' => description, 'force' => force } } request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'POST', :path => "snapshots" ) end end class Mock def create_volume_snapshot(volume_id, name, description, force=false) response = Excon::Response.new response.status = 202 response.body = { "snapshot"=> { "status"=>"creating", "display_name"=>name, "created_at"=>Time.now, "display_description"=>description, "volume_id"=>volume_id, "id"=>"5", "size"=>1 } } response end end end end end fog-1.19.0/lib/fog/openstack/requests/volume/set_tenant.rb0000644000004100000410000000057712261242552023602 0ustar www-datawww-datamodule Fog module Volume class OpenStack class Real def set_tenant(tenant) @openstack_must_reauthenticate = true @openstack_tenant = tenant.to_s authenticate end end class Mock def set_tenant(tenant) true end end end # class OpenStack end # module Volume end # module Fog fog-1.19.0/lib/fog/openstack/requests/volume/get_quota_defaults.rb0000644000004100000410000000112212261242552025300 0ustar www-datawww-datamodule Fog module Volume class OpenStack class Real def get_quota_defaults(tenant_id) request( :expects => 200, :method => 'GET', :path => "/os-quota-sets/#{tenant_id}/defaults" ) end end class Mock def get_quota_defaults(tenant_id) response = Excon::Response.new response.status = 200 response.body = { 'quota_set' => self.data[:quota].merge({'id' => tenant_id}) } response end end end end end fog-1.19.0/lib/fog/openstack/requests/volume/list_snapshots.rb0000644000004100000410000000115012261242552024477 0ustar www-datawww-datamodule Fog module Volume class OpenStack class Real def list_snapshots(detailed=true) path = detailed ? 'snapshots/detail' : 'snapshots' request( :expects => 200, :method => 'GET', :path => path ) end end class Mock def list_snapshots(detailed=true) response = Excon::Response.new response.status = 200 response.body = { 'snapshots' => [get_snapshot_details.body["snapshot"]] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/volume/get_snapshot_details.rb0000644000004100000410000000160512261242552025632 0ustar www-datawww-datamodule Fog module Volume class OpenStack class Real def get_snapshot_details(snapshot_id) request( :expects => 200, :method => 'GET', :path => "snapshots/#{snapshot_id}" ) end end class Mock def get_snapshot_details(detailed=true) response = Excon::Response.new response.status = 200 response.body = { 'snapshot' => { 'id' => '1', 'display_name' => 'Snapshot1', 'display_description' => 'Volume1 snapshot', 'size' => 1, 'volume_id' => '1', 'status' => 'available', 'created_at' => Time.now } } response end end end end end fog-1.19.0/lib/fog/openstack/requests/volume/create_volume.rb0000644000004100000410000000315112261242552024257 0ustar www-datawww-datamodule Fog module Volume class OpenStack class Real def create_volume(name, description, size, options={}) data = { 'volume' => { 'display_name' => name, 'display_description' => description, 'size' => size } } vanilla_options = [:snapshot_id, :imageRef, :volume_type, :source_volid] vanilla_options.select{|o| options[o]}.each do |key| data['volume'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'POST', :path => "volumes" ) end end class Mock def create_volume(name, description, size, options={}) response = Excon::Response.new response.status = 202 response.body = { 'volume' => { 'id' => Fog::Mock.random_numbers(2), 'display_name' => name, 'display_description' => description, 'size' => size, 'status' => 'creating', 'snapshot_id' => options[:snapshot_id] || nil, 'image_id' => options[:imageRef] || nil, 'volume_type' => nil, 'availability_zone' => 'nova', 'created_at' => Time.now, 'attachments' => [] } } response end end end end end fog-1.19.0/lib/fog/openstack/requests/volume/delete_volume.rb0000644000004100000410000000071212261242552024256 0ustar www-datawww-datamodule Fog module Volume class OpenStack class Real def delete_volume(volume_id) request( :expects => 202, :method => 'DELETE', :path => "volumes/#{volume_id}" ) end end class Mock def delete_volume(volume_id) response = Excon::Response.new response.status = 204 response end end end end end fog-1.19.0/lib/fog/openstack/requests/volume/delete_snapshot.rb0000644000004100000410000000072512261242552024612 0ustar www-datawww-datamodule Fog module Volume class OpenStack class Real def delete_snapshot(snapshot_id) request( :expects => 202, :method => 'DELETE', :path => "snapshots/#{snapshot_id}" ) end end class Mock def delete_snapshot(snapshot_id) response = Excon::Response.new response.status = 204 response end end end end end fog-1.19.0/lib/fog/openstack/requests/volume/get_volume_type_details.rb0000644000004100000410000000134112261242552026340 0ustar www-datawww-datamodule Fog module Volume class OpenStack class Real def get_volume_type_details(volume_type_id) request( :expects => 200, :method => 'GET', :path => "types/#{volume_type_id}" ) end end class Mock def get_volume_details(volume_type_id) response = Excon::Response.new response.status = 200 response.body = { "volume_type" => { "id" => "1", "name" => "type 1", "extra_specs" => { "volume_backend_name" => "type 1 backend name" } } } response end end end end end fog-1.19.0/lib/fog/openstack/requests/volume/get_volume_details.rb0000644000004100000410000000205512261242552025302 0ustar www-datawww-datamodule Fog module Volume class OpenStack class Real def get_volume_details(volume_id) request( :expects => 200, :method => 'GET', :path => "volumes/#{volume_id}" ) end end class Mock def get_volume_details(detailed=true) response = Excon::Response.new response.status = 200 response.body = { 'volume' => { 'id' => '1', 'display_name' => Fog::Mock.random_letters(rand(8) + 5), 'display_description' => Fog::Mock.random_letters(rand(12) + 10), 'size' => 3, 'volume_type' => nil, 'snapshot_id' => '4', 'status' => 'online', 'availability_zone' => 'nova', 'created_at' => Time.now, 'attachments' => [] } } response end end end end end fog-1.19.0/lib/fog/openstack/requests/volume/list_volumes.rb0000644000004100000410000000273712261242552024163 0ustar www-datawww-datamodule Fog module Volume class OpenStack class Real def list_volumes(detailed=true, options={}) path = detailed ? 'volumes/detail' : 'volumes' request( :expects => 200, :method => 'GET', :path => path, :query => options ) end end class Mock def list_volumes(detailed=true, options={}) response = Excon::Response.new response.status = 200 self.data[:volumes] ||= [ { "status" => "available", "display_description" => "test 1 desc", "availability_zone" => "nova", "display_name" => "Volume1", "attachments" => [{}], "volume_type" => nil, "snapshot_id" => nil, "size" => 1, "id" => 1, "created_at" => Time.now, "metadata" => {} }, { "status" => "available", "display_description" => "test 2 desc", "availability_zone" => "nova", "display_name" => "Volume2", "attachments" => [{}], "volume_type" => nil, "snapshot_id" => nil, "size" => 1, "id" => 2, "created_at" => Time.now, "metadata" => {} } ] response.body = { 'volumes' => self.data[:volumes] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/volume/get_quota.rb0000644000004100000410000000112612261242552023415 0ustar www-datawww-datamodule Fog module Volume class OpenStack class Real def get_quota(tenant_id) request( :expects => 200, :method => 'GET', :path => "/os-quota-sets/#{tenant_id}" ) end end class Mock def get_quota(tenant_id) response = Excon::Response.new response.status = 200 response.body = { 'quota_set' => (self.data[:quota_updated] or self.data[:quota]).merge({'id' => tenant_id}) } response end end end end end fog-1.19.0/lib/fog/openstack/requests/metering/0000755000004100000410000000000012261242552021403 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/requests/metering/list_resources.rb0000644000004100000410000000123612261242552024777 0ustar www-datawww-datamodule Fog module Metering class OpenStack class Real def list_resources(options = {}) request( :expects => 200, :method => 'GET', :path => 'resources' ) end end class Mock def list_resources(options = {}) response = Excon::Response.new response.status = 200 response.body = [{ 'resource_id'=>'glance', 'project_id'=>'d646b40dea6347dfb8caee2da1484c56', 'user_id'=>'1d5fd9eda19142289a60ed9330b5d284', 'metadata'=>{}}] response end end end end end fog-1.19.0/lib/fog/openstack/requests/metering/list_meters.rb0000644000004100000410000000206212261242552024262 0ustar www-datawww-datamodule Fog module Metering class OpenStack class Real def list_meters(options=[]) data = { 'q' => Array.new } options.each do |opt| filter = {} ['field', 'op', 'value'].each do |key| filter[key] = opt[key] if opt[key] end data['q'] << filter unless filter.empty? end request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'GET', :path => 'meters' ) end end class Mock def list_meters(options={}) response = Excon::Response.new response.status = 200 response.body = [{ 'user_id'=>'1d5fd9eda19142289a60ed9330b5d284', 'name'=>'image.size', 'resource_id'=>'glance', 'project_id'=>'d646b40dea6347dfb8caee2da1484c56', 'type'=>'gauge', 'unit'=>'bytes'}] response end end end end end fog-1.19.0/lib/fog/openstack/requests/metering/get_samples.rb0000644000004100000410000000247512261242552024243 0ustar www-datawww-datamodule Fog module Metering class OpenStack class Real def get_samples(meter_id, options=[]) data = { 'q' => Array.new } options.each do |opt| filter = {} ['field', 'op', 'value'].each do |key| filter[key] = opt[key] if opt[key] end data['q'] << filter unless filter.empty? end request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'GET', :path => "meters/#{meter_id}" ) end end class Mock def get_samples(meter_id) response = Excon::Response.new response.status = 200 response.body = [{ 'counter_name'=>'image.size', 'user_id'=>'1d5fd9eda19142289a60ed9330b5d284', 'resource_id'=>'glance', 'timestamp'=>'2013-04-03T23:44:21', 'resource_metadata'=>{}, 'source'=>'artificial', 'counter_unit'=>'bytes', 'counter_volume'=>10.0, 'project_id'=>'d646b40dea6347dfb8caee2da1484c56', 'message_id'=>'14e4a902-9cf3-11e2-a054-003048f5eafc', 'counter_type'=>'gauge'}] response end end end end end fog-1.19.0/lib/fog/openstack/requests/metering/get_resource.rb0000644000004100000410000000124512261242552024420 0ustar www-datawww-datamodule Fog module Metering class OpenStack class Real def get_resource(resource_id) request( :expects => 200, :method => 'GET', :path => "resources/#{resource_id}" ) end end class Mock def get_resource(resource_id) response = Excon::Response.new response.status = 200 response.body = { 'resource_id'=>'glance', 'project_id'=>'d646b40dea6347dfb8caee2da1484c56', 'user_id'=>'1d5fd9eda19142289a60ed9330b5d284', 'metadata'=>{}} response end end end end end fog-1.19.0/lib/fog/openstack/requests/metering/get_statistics.rb0000644000004100000410000000250012261242552024756 0ustar www-datawww-datamodule Fog module Metering class OpenStack class Real def get_statistics(meter_id, options={}) data = { 'period' => options['period'], 'q' => Array.new } options['q'].each do |opt| filter = {} ['field', 'op', 'value'].each do |key| filter[key] = opt[key] if opt[key] end data['q'] << filter unless filter.empty? end if options['q'].is_a? Array request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'GET', :path => "meters/#{meter_id}/statistics" ) end end class Mock def get_statistics(meter_id, options={}) response = Excon::Response.new response.status = 200 response.body = [{ 'count'=>143, 'duration_start'=>'2013-04-03T23:44:21', 'min'=>10.0, 'max'=>10.0, 'duration_end'=>'2013-04-04T23:24:21', 'period'=>0, 'period_end'=>'2013-04-04T23:24:21', 'duration'=>85200.0, 'period_start'=>'2013-04-03T23:44:21', 'avg'=>10.0, 'sum'=>1430.0}] response end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/0000755000004100000410000000000012261242552021422 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/requests/identity/get_tenants_by_id.rb0000644000004100000410000000050312261242552025426 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def get_tenants_by_id(tenant_id) request( :expects => [200], :method => 'GET', :path => "tenants/#{tenant_id}" ) end end class Mock end end end end fog-1.19.0/lib/fog/openstack/requests/identity/create_tenant.rb0000644000004100000410000000166112261242552024567 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def create_tenant(attributes) request( :expects => [200], :method => 'POST', :path => "tenants", :body => Fog::JSON.encode({ 'tenant' => attributes }) ) end # def create_tenant end # class Real class Mock def create_tenant(attributes) response = Excon::Response.new response.status = [200, 204][rand(1)] response.body = { 'tenant' => { 'id' => "df9a815161eba9b76cc748fd5c5af73e", 'description' => attributes[:description] || 'normal tenant', 'enabled' => true, 'name' => attributes[:name] || 'default' } } response end # def create_tenant end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/identity/delete_role.rb0000644000004100000410000000117012261242552024231 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def delete_role(role_id) request( :expects => [200, 204], :method => 'DELETE', :path => "/OS-KSADM/roles/#{role_id}" ) end end class Mock def delete_role(role_id) response = Excon::Response.new if self.data[:roles][role_id] self.data[:roles].delete(role_id) response.status = 204 response else raise Fog::Identity::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/add_user_to_tenant.rb0000644000004100000410000000202612261242552025610 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def add_user_to_tenant(tenant_id, user_id, role_id) request( :expects => 200, :method => 'PUT', :path => "/tenants/#{tenant_id}/users/#{user_id}/roles/OS-KSADM/#{role_id}" ) end end # class Real class Mock def add_user_to_tenant(tenant_id, user_id, role_id) role = self.data[:roles][role_id] self.data[:user_tenant_membership][tenant_id] ||= {} self.data[:user_tenant_membership][tenant_id][user_id] ||= [] self.data[:user_tenant_membership][tenant_id][user_id].push(role['id']).uniq! response = Excon::Response.new response.status = 200 response.body = { 'role' => { 'id' => role['id'], 'name' => role['name'] } } response end # def add_user_to_tenant end # class Mock end # class OpenStack end # module Identity end fog-1.19.0/lib/fog/openstack/requests/identity/list_ec2_credentials.rb0000644000004100000410000000230712261242552026032 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real ## # List EC2 credentials for a user. Requires administrator # credentials. # # ==== Parameters # * user_id<~String>: The id of the user to retrieve the credential # for # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'credentials'<~Array>: The user's EC2 credentials # * 'access'<~String>: The access key # * 'secret'<~String>: The secret key # * 'user_id'<~String>: The user id # * 'tenant_id'<~String>: The tenant id def list_ec2_credentials(user_id) request( :expects => [200, 202], :method => 'GET', :path => "users/#{user_id}/credentials/OS-EC2" ) end end class Mock def list_ec2_credentials(user_id) ec2_credentials = self.data[:ec2_credentials][user_id].values response = Excon::Response.new response.status = 200 response.body = { 'credentials' => ec2_credentials } response end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/update_tenant.rb0000644000004100000410000000144512261242552024606 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def update_tenant(id, attributes) request( :expects => [200], :method => 'PUT', :path => "tenants/#{id}", :body => Fog::JSON.encode({ 'tenant' => attributes }) ) end # def create_tenant end # class Real class Mock def update_tenant(id, attributes) response = Excon::Response.new response.status = [200, 204][rand(1)] attributes = {'enabled' => true, 'id' => '1'}.merge(attributes) response.body = { 'tenant' => attributes } response end # def create_tenant end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/identity/list_endpoints_for_token.rb0000644000004100000410000000052712261242552027057 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def list_endpoints_for_token(token_id) request( :expects => [200, 203], :method => 'HEAD', :path => "tokens/#{token_id}/endpoints" ) end end class Mock end end end end fog-1.19.0/lib/fog/openstack/requests/identity/set_tenant.rb0000644000004100000410000000060312261242552024112 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def set_tenant(tenant) @openstack_must_reauthenticate = true @openstack_tenant = tenant.to_s authenticate end end class Mock def set_tenant(tenant) true end end end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/identity/delete_tenant.rb0000644000004100000410000000145112261242552024563 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def delete_tenant(id) request( :expects => [200, 204], :method => 'DELETE', :path => "tenants/#{id}" ) end # def create_tenant end # class Real class Mock def delete_tenant(attributes) response = Excon::Response.new response.status = [200, 204][rand(1)] response.body = { 'tenant' => { 'id' => '1', 'description' => 'Has access to everything', 'enabled' => true, 'name' => 'admin' } } response end # def create_tenant end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/identity/get_user_by_name.rb0000644000004100000410000000113712261242552025260 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def get_user_by_name(name) request( :expects => [200, 203], :method => 'GET', :path => "users?name=#{name}" ) end end class Mock def get_user_by_name(name) response = Excon::Response.new response.status = 200 user = self.data[:users].values.select {|user| user['name'] == name}[0] response.body = { 'user' => user } response end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/list_roles_for_user_on_tenant.rb0000644000004100000410000000172112261242552030100 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def list_roles_for_user_on_tenant(tenant_id, user_id) request( :expects => [200], :method => 'GET', :path => "tenants/#{tenant_id}/users/#{user_id}/roles" ) end # def list_roles_for_user_on_tenant end # class Real class Mock def list_roles_for_user_on_tenant(tenant_id, user_id) self.data[:user_tenant_membership][tenant_id] ||= {} self.data[:user_tenant_membership][tenant_id][user_id] ||= [] roles = self.data[:user_tenant_membership][tenant_id][user_id].map do |role_id| self.data[:roles][role_id] end Excon::Response.new( :body => { 'roles' => roles }, :status => 200 ) end # def list_roles_for_user_on_tenant end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/identity/check_token.rb0000644000004100000410000000054212261242552024225 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def check_token(token_id, tenant_id) request( :expects => [200, 203], :method => 'HEAD', :path => "tokens/#{token_id}?belongsTo=#{tenant_id}" ) end end class Mock end end end end fog-1.19.0/lib/fog/openstack/requests/identity/delete_ec2_credential.rb0000644000004100000410000000215212261242552026134 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real ## # Destroy an EC2 credential for a user. Requires administrator # credentials. # # ==== Parameters # * user_id<~String>: The id of the user to delete the credential # for # * access<~String>: The access key of the credential to destroy # # ==== Returns # * response<~Excon::Response>: # * body<~String>: Empty string def delete_ec2_credential(user_id, access) request( :expects => [200, 204], :method => 'DELETE', :path => "users/#{user_id}/credentials/OS-EC2/#{access}" ) end end class Mock def delete_ec2_credential(user_id, access) raise Fog::Identity::OpenStack::NotFound unless self.data[:ec2_credentials][user_id][access] self.data[:ec2_credentials][user_id].delete access response = Excon::Response.new response.status = 204 response rescue end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/create_ec2_credential.rb0000644000004100000410000000315712261242552026143 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real ## # Create an EC2 credential for a user in a tenant. Requires # administrator credentials. # # ==== Parameters # * user_id<~String>: The id of the user to create an EC2 credential # for # * tenant_id<~String>: The id of the tenant to create the credential # in # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'credential'<~Hash>: Created EC2 credential # * 'access'<~String>: The access key # * 'secret'<~String>: The secret key # * 'user_id'<~String>: The user id # * 'tenant_id'<~String>: The tenant id def create_ec2_credential(user_id, tenant_id) data = { 'tenant_id' => tenant_id } request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'POST', :path => "users/#{user_id}/credentials/OS-EC2" ) end end class Mock def create_ec2_credential(user_id, tenant_id) response = Excon::Response.new response.status = 200 data = { 'access' => Fog::Mock.random_hex(32), 'secret' => Fog::Mock.random_hex(32), 'tenant_id' => tenant_id, 'user_id' => user_id, } self.data[:ec2_credentials][user_id][data['access']] = data response.body = { 'credential' => data } response end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/get_tenant.rb0000644000004100000410000000140212261242552024074 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def get_tenant(id) request( :expects => [200, 204], :method => 'GET', :path => "tenants/#{id}" ) end end # class Real class Mock def get_tenant(id) response = Excon::Response.new response.status = [200, 204][rand(1)] response.body = { 'tenant' => { 'id' => id, 'description' => 'Has access to everything', 'enabled' => true, 'name' => 'admin' } } response end # def list_tenants end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/identity/get_role.rb0000644000004100000410000000123712261242552023552 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def get_role(id) request( :expects => [200, 204], :method => 'GET', :path => "/OS-KSADM/roles/#{id}" ) end end class Mock def get_role(id) response = Excon::Response.new if data = self.data[:roles][id] response.status = 200 response.body = { 'role' => data } response else raise Fog::Identity::OpenStack::NotFound end end end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/identity/create_user.rb0000644000004100000410000000216712261242552024256 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def create_user(name, password, email, tenantId=nil, enabled=true) data = { 'user' => { 'name' => name, 'password' => password, 'tenantId' => tenantId, 'email' => email, 'enabled' => enabled, } } request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'POST', :path => '/users' ) end end class Mock def create_user(name, password, email, tenantId=nil, enabled=true) response = Excon::Response.new response.status = 200 data = { 'id' => Fog::Mock.random_hex(32), 'name' => name, 'email' => email, 'tenantId' => tenantId, 'enabled' => enabled } self.data[:users][data['id']] = data response.body = { 'user' => data } response end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/create_user_role.rb0000644000004100000410000000111012261242552025262 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def create_user_role(tenant_id, user_id, role_id) request( :expects => 200, :method => 'PUT', :path => "/tenants/#{tenant_id}/users/#{user_id}/roles/OS-KSADM/#{role_id}" ) end end class Mock def create_user_role(tenant_id, user_id, role_id) Excon::Response.new( :body => { 'role' => self.data[:roles][role_id] }, :status => 200 ) end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/list_tenants.rb0000644000004100000410000000240712261242552024461 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def list_tenants(limit = nil, marker = nil) params = Hash.new params['limit'] = limit if limit params['marker'] = marker if marker request( :expects => [200, 204], :method => 'GET', :path => "tenants", :query => params ) end end # class Real class Mock def list_tenants Excon::Response.new( :body => { 'tenants_links' => [], 'tenants' => [ {'id' => '1', 'description' => 'Has access to everything', 'enabled' => true, 'name' => 'admin'}, {'id' => '2', 'description' => 'Normal tenant', 'enabled' => true, 'name' => 'default'}, {'id' => '3', 'description' => 'Disabled tenant', 'enabled' => false, 'name' => 'disabled'} ] }, :status => [200, 204][rand(1)] ) end # def list_tenants end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/identity/list_users.rb0000644000004100000410000000147512261242552024152 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def list_users(tenant_id = nil) path = tenant_id ? "tenants/#{tenant_id}/users" : 'users' request( :expects => [200, 204], :method => 'GET', :path => path ) end end # class Real class Mock def list_users(tenant_id = nil) users = self.data[:users].values if tenant_id users = users.select { |user| user['tenantId'] == tenant_id } end Excon::Response.new( :body => { 'users' => users }, :status => 200 ) end end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/identity/list_roles.rb0000644000004100000410000000126112261242552024126 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def list_roles request( :expects => 200, :method => 'GET', :path => '/OS-KSADM/roles' ) end end class Mock def list_roles if self.data[:roles].empty? ['admin', 'Member'].each do |name| id = Fog::Mock.random_hex(32) self.data[:roles][id] = {'id' => id, 'name' => name} end end Excon::Response.new( :body => { 'roles' => self.data[:roles].values }, :status => 200 ) end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/remove_user_from_tenant.rb0000644000004100000410000000106012261242552026673 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def remove_user_from_tenant(tenant_id, user_id, role_id) request( :expects => [200, 204], :method => 'DELETE', :path => "/tenants/#{tenant_id}/users/#{user_id}/roles/OS-KSADM/#{role_id}" ) end end # class Real class Mock def remove_user_from_tenant(tenant_id, user_id, role_id) end # def remove_user_from_tenant end # class Mock end # class OpenStack end # module Identity end fog-1.19.0/lib/fog/openstack/requests/identity/list_user_global_roles.rb0000644000004100000410000000050712261242552026506 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def list_user_global_roles(user_id) request( :expects => [200], :method => 'GET', :path => "users/#{user_id}/roles" ) end end class Mock end end end end fog-1.19.0/lib/fog/openstack/requests/identity/delete_user.rb0000644000004100000410000000116412261242552024251 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def delete_user(user_id) request( :expects => [200, 204], :method => 'DELETE', :path => "users/#{user_id}" ) end end class Mock def delete_user(user_id) self.data[:users].delete( list_users.body['users'].find {|x| x['id'] == user_id }['id']) response = Excon::Response.new response.status = 204 response rescue raise Fog::Identity::OpenStack::NotFound end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/validate_token.rb0000644000004100000410000000054412261242552024743 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def validate_token(token_id, tenant_id) request( :expects => [200, 203], :method => 'GET', :path => "tokens/#{token_id}?belongsTo=#{tenant_id}" ) end end class Mock end end end end fog-1.19.0/lib/fog/openstack/requests/identity/delete_user_role.rb0000644000004100000410000000104112261242552025264 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def delete_user_role(tenant_id, user_id, role_id) request( :expects => 204, :method => 'DELETE', :path => "/tenants/#{tenant_id}/users/#{user_id}/roles/OS-KSADM/#{role_id}" ) end end class Mock def delete_user_role(tenant_id, user_id, role_id) response = Excon::Response.new response.status = 204 response end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/get_ec2_credential.rb0000644000004100000410000000271212261242552025453 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real ## # Retrieves an EC2 credential for a user. Requires administrator # credentials. # # ==== Parameters # * user_id<~String>: The id of the user to retrieve the credential # for # * access<~String>: The access key of the credential to retrieve # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'credential'<~Hash>: The EC2 credential # * 'access'<~String>: The access key # * 'secret'<~String>: The secret key # * 'user_id'<~String>: The user id # * 'tenant_id'<~String>: The tenant id def get_ec2_credential(user_id, access) request( :expects => [200, 202], :method => 'GET', :path => "users/#{user_id}/credentials/OS-EC2/#{access}" ) rescue Excon::Errors::Unauthorized raise Fog::Identity::OpenStack::NotFound end end class Mock def get_ec2_credential(user_id, access) ec2_credential = self.data[:ec2_credentials][user_id][access] raise Fog::OpenStack::Identity::NotFound unless ec2_credential response = Excon::Response.new response.status = 200 response.body = { 'credential' => ec2_credential } response end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/update_user.rb0000644000004100000410000000144512261242552024273 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def update_user(user_id, options = {}) url = options.delete('url') || "/users/#{user_id}" request( :body => Fog::JSON.encode({ 'user' => options }), :expects => 200, :method => 'PUT', :path => url ) end end class Mock def update_user(user_id, options) response = Excon::Response.new if user = self.data[:users][user_id] if options['name'] user['name'] = options['name'] end response.status = 200 response else raise Fog::Identity::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/create_role.rb0000644000004100000410000000137312261242552024237 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def create_role(name) data = { 'role' => { 'name' => name } } request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'POST', :path => '/OS-KSADM/roles' ) end end class Mock def create_role(name) data = { 'id' => Fog::Mock.random_hex(32), 'name' => name } self.data[:roles][data['id']] = data Excon::Response.new( :body => { 'role' => data }, :status => 202 ) end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/get_user_by_id.rb0000644000004100000410000000142012261242552024727 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def get_user_by_id(user_id) request( :expects => [200, 203], :method => 'GET', :path => "users/#{user_id}" ) end end class Mock def get_user_by_id(user_id) response = Excon::Response.new response.status = 200 existing_user = self.data[:users].find do |u| u[0] == user_id || u[1]['name'] == 'mock' end existing_user = existing_user[1] if existing_user response.body = { 'user' => existing_user || create_user('mock', 'mock', 'mock@email.com').body['user'] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/identity/get_tenants_by_name.rb0000644000004100000410000000050012261242552025747 0ustar www-datawww-datamodule Fog module Identity class OpenStack class Real def get_tenants_by_name(name) request( :expects => [200], :method => 'GET', :path => "tenants?name=#{name}" ) end end class Mock end end end end fog-1.19.0/lib/fog/openstack/requests/compute/0000755000004100000410000000000012261242552021245 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/requests/compute/pause_server.rb0000644000004100000410000000115012261242552024272 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real # Pause the server. # # === Parameters # * server_id <~String> - The ID of the server to pause. # === Returns # * success <~Boolean> def pause_server(server_id) body = { 'pause' => nil } server_action(server_id, body).status == 202 end # def pause_server end # class Real class Mock def pause_server(server_id) true end # def pause_server end # class Mock end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/requests/compute/create_key_pair.rb0000644000004100000410000000457012261242552024726 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def create_key_pair(key_name, public_key = nil) data = { 'keypair' => { 'name' => key_name } } data['keypair']['public_key'] = public_key unless public_key.nil? request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'POST', :path => 'os-keypairs.json' ) end end class Mock def create_key_pair(key_name, public_key = nil) response = Excon::Response.new response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-c373a42c-2825-4e60-8d34-99416ea850be", "Content-Type" => "application/json", "Content-Length" => "1289", "Date" => Date.new} response.body = { "keypair" => { "public_key" => "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDCdAZLjljntJbLVVkNHjWFSoKen2nZbk39ZfqhZJOMdeFdz02GWBS45rcuboeGg/gozKRwsLu4N6NLPlYtbK/NapJIvgO/djBp+FQG1QZNtLPsx7j4hVJac3yISGms+Xtu4cEv6j5sFDzAgTQbWez0Z1+9qOq9ngdaoW+YClfQ== vagrant@nova\n", "private_key" => "-----BEGIN RSA PRIVATE KEY-----\nMIICXgIBAAKBgQDCdAZLjljn1tJbLVVkNHjWFSoKen2nZbk39ZfqhZJOMdeFdz02\nGWBS45rcuHboeGg/gozKRwsLu4N6NLPlYtbK/NapJIvgO/djBp+FQG1QZNtLPsx7\nj4hVJac3yISGms+Xtu4cEv6j5sFDzAgTQbWez0Z1+9qOq9ngdaoW+YClfQIDAQAB\nAoGBALBoT9m1vuQ82EONQf2RONqHAsfUzi/SMhEZRgOlv9AemXZkcWyl4uPvxmtd\nEcreiTystAtCHjw7lhCExXthipevUjtIAAt+b3pMn6Oyjad3IRvde6atMdjrje43\n/nftYtuXYyJTsvwEvLYqSioLQ0Nn/XDKhOpcM5tejDHOH35lAkEA+H4r7y9X521u\nIABVAezBWaT/wvdMjx5cwfyYEQjnI1bxfRIqkgoY5gDDBdVbT75UTsHHbHLORQcw\nRjRvS2zgewJBAMhT6eyMonJvHHvC5RcchcY+dWkscIKoOzeyUKMb+7tERQa9/UN2\njYb+jdM0VyL0ruLFwYtl2m34gfmhcXgIvGcCQGzKMEnjHEUBr7jq7EyPbobkqeSd\niDMQQ+PZxmmO0EK0ib0L+v881HG926PuKK/cz+Q7Cif8iznFT+ksg50t6YkCQQC9\nwfcAskqieSuS9A9LcCIrojhXctf0e+T0Ij2N89DlF4sHEuqXf/IZ4IB5gsfTfdE3\nUDnAkK9yogaEbu/r0uKbAkEAy5kl71bIqvKTKsY2mES9ziVxfftl/9UIi5LI+QHb\nmC/c6cTrGVCM71fi2GMxGgBeEea4+7xwoWTL4CxA00kmTg==\n-----END RSA PRIVATE KEY-----\n", "user_id" => "admin", "name" => key_name, "fingerprint" => "97:86:f4:15:68:0c:7b:a7:e5:8f:f0:bd:1f:27:65:ad" } } response end end # mock end # openstack end # compute end # fog fog-1.19.0/lib/fog/openstack/requests/compute/create_flavor.rb0000644000004100000410000000561712261242552024417 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real # PARAMETERS # # name = Name of flavor # ram = Memory in MB # vcpus = Number of VCPUs # disk = Size of local disk in GB # swap = Swap space in MB # rxtx_factor = RX/TX factor def create_flavor(attributes) # Get last flavor id flavor_ids = Array.new flavors = list_flavors_detail.body['flavors'] + list_flavors_detail(:is_public => false).body['flavors'] flavors.each do |flavor| flavor_ids << flavor['id'].to_i end # Set flavor id attributes[:flavor_id] = attributes[:flavor_id] || flavor_ids.sort.last + 1 data = { 'flavor' => { 'name' => attributes[:name], 'ram' => attributes[:ram], 'vcpus' => attributes[:vcpus], 'disk' => attributes[:disk], 'id' => attributes[:flavor_id], 'swap' => attributes[:swap], 'OS-FLV-EXT-DATA:ephemeral' => attributes[:ephemeral], 'os-flavor-access:is_public' => attributes[:is_public], 'rxtx_factor' => attributes[:rxtx_factor] } } request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'POST', :path => 'flavors' ) end end class Mock def create_flavor(attributes) response = Excon::Response.new response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-fdc6f99e-55a2-4ab1-8904-0892753828cf", "Content-Type" => "application/json", "Content-Length" => "356", "Date" => Date.new } response.body = { "flavor" => { "vcpus" => attributes[:vcpus], "disk" => attributes[:disk], "name" => attributes[:name], "links" => [ { "href" => "http://192.168.27.100:8774/v1.1/6733e93c5f5c4eb1bcabc6902ba208d6/flavors/11", "rel" => "self" }, { "href" => "http://192.168.27.100:8774/6733e93c5f5c4eb1bcabc6902ba208d6/flavors/11", "rel" => "bookmark" } ], "rxtx_factor" => attributes[:rxtx_factor] || 1.0, "OS-FLV-EXT-DATA:ephemeral" => attributes[:ephemeral] || 0, "os-flavor-access:is_public" => attributes[:is_public] || false, "OS-FLV-DISABLED:disabled" => attributes[:disabled] || false, "ram" => attributes[:ram], "id" => "11", "swap" => attributes[:swap] || "" } } response end end # mock end # openstack end # compute end # fog fog-1.19.0/lib/fog/openstack/requests/compute/get_host_details.rb0000644000004100000410000000370412261242552025117 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def get_host_details(host) request( :expects => [200, 203], :method => 'GET', :path => "os-hosts/#{host}.json" ) end end class Mock def get_host_details(host) response = Excon::Response.new response.status = 200 response.body = { "host" => [ { "resource" => { "project" => "(total)", "memory_mb" => 64427, "host" => "cn28.la-1-3.morphcloud.net", "cpu" => 12, "disk_gb" => 1608 } }, { "resource" => { "project" => "(used_now)", "memory_mb" => 1753, "host" => "cn28.la-1-3.morphcloud.net", "cpu" => 3, "disk_gb" => 33 } }, { "resource" => { "project" => "(used_max)", "memory_mb" => 7168, "host" => "cn28.la-1-3.morphcloud.net", "cpu" => 3, "disk_gb" => 45 } }, { "resource" => { "project" => "bf8301f5164f4790889a1bc2bfb16d99", "memory_mb" => 5120, "host" => "cn28.la-1-3.morphcloud.net", "cpu" => 2, "disk_gb" => 35 } }, { "resource" => { "project" => "3bb4d0301c5f47d5b4d96a361fcf96f4", "memory_mb" => 2048, "host" => "cn28.la-1-3.morphcloud.net", "cpu" => 1, "disk_gb" => 10 } } ] } response end end # mock end # openstack end # compute end # fog fog-1.19.0/lib/fog/openstack/requests/compute/get_console_output.rb0000644000004100000410000000077712261242552025526 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def get_console_output(server_id, log_length) body = { 'os-getConsoleOutput' => { 'length' => log_length } } server_action(server_id, body) end end class Mock def get_console_output(server_id, log_length) response = Excon::Response.new response.status = 200 response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/delete_security_group.rb0000644000004100000410000000145112261242552026200 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def delete_security_group(security_group_id) request( :expects => 202, :method => 'DELETE', :path => "os-security-groups/#{security_group_id}" ) end end class Mock def delete_security_group(security_group_id) self.data[:security_groups].delete security_group_id.to_s response = Excon::Response.new response.status = 202 response.headers = { "Content-Type" => "text/html; charset=UTF-8", "Content-Length" => "0", "Date" => Date.new } response.body = {} response end end # mock end # openstack end # compute end #fog fog-1.19.0/lib/fog/openstack/requests/compute/get_vnc_console.rb0000644000004100000410000000230312261242552024737 0ustar www-datawww-datamodule Fog module Compute class OpenStack 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) body = { 'os-getVNCConsole' => { 'type' => console_type } } server_action(server_id, body) 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-1.19.0/lib/fog/openstack/requests/compute/create_image.rb0000644000004100000410000000273412261242552024205 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def create_image(server_id, name, metadata={}) body = { 'createImage' => { 'name' => name, 'metadata' => metadata }} data = server_action(server_id, body) image_id = data.headers["Location"].scan(/.*\/(.*)/).flatten[0] get_image_details(image_id) end end class Mock def create_image(server_id, name, metadata={}) response = Excon::Response.new response.status = 202 img_id=Fog::Mock.random_numbers(6).to_s data = { 'id' => img_id, 'server' => {"id"=>"3", "links"=>[{"href"=>"http://nova1:8774/admin/servers/#{server_id}", "rel"=>"bookmark"}]}, 'links' => [{"href"=>"http://nova1:8774/v1.1/admin/images/#{img_id}", "rel"=>"self"}, {"href"=>"http://nova1:8774/admin/images/#{img_id}", "rel"=>"bookmark"}], 'metadata' => metadata || {}, 'name' => name || "server_#{rand(999)}", 'progress' => 0, 'status' => 'SAVING', 'minDisk' => 0, 'minRam' => 0, 'updated' => "", 'created' => "" } self.data[:last_modified][:images][data['id']] = Time.now self.data[:images][data['id']] = data response.body = { 'image' => data } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/confirm_resize_server.rb0000644000004100000410000000064512261242552026203 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def confirm_resize_server(server_id) body = { 'confirmResize' => nil } server_action(server_id, body, 204) end end class Mock def confirm_resize_server(server_id) response = Excon::Response.new response.status = 204 response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/revert_resize_server.rb0000644000004100000410000000130712261242552026051 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def revert_resize_server(server_id) body = { 'revertResize' => nil } server_action(server_id, body) end end class Mock def revert_resize_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-1.19.0/lib/fog/openstack/requests/compute/delete_metadata.rb0000644000004100000410000000102712261242552024674 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def delete_metadata(collection_name, parent_id, key) request( :expects => 204, :method => 'DELETE', :path => "#{collection_name}/#{parent_id}/metadata/#{key}" ) end end class Mock def delete_metadata(collection_name, parent_id, key) response = Excon::Response.new response.status = 204 response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/resume_server.rb0000644000004100000410000000116312261242552024461 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real # Resume the server. # # === Parameters # * server_id <~String> - The ID of the server to be resumed. # === Returns # * success <~Boolean> def resume_server(server_id) body = { 'resume' => nil } server_action(server_id, body).status == 202 end # def resume_server end # class Real class Mock def resume_server(server_id) true end # def resume_server end # class Mock end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/requests/compute/update_quota.rb0000644000004100000410000000133612261242552024270 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def update_quota(tenant_id, options = {}) options['tenant_id'] = tenant_id request( :body => Fog::JSON.encode({ 'quota_set' => options }), :expects => 200, :method => 'PUT', :path => "/os-quota-sets/#{tenant_id}" ) end end class Mock def update_quota(tenant_id, options = {}) self.data[:quota_updated] = self.data[:quota].merge options response = Excon::Response.new response.status = 200 response.body = { 'quota_set' => self.data[:quota_updated] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_flavors.rb0000644000004100000410000000235712261242552024310 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real 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', 'links' => ['https://itdoesntmatterwhatshere.heh'] }, { 'name' => '512 server', 'id' => '2', 'links' => ['https://itdoesntmatterwhatshere.heh'] }, { 'name' => '1GB server', 'id' => '3', 'links' => ['https://itdoesntmatterwhatshere.heh'] }, { 'name' => '2GB server', 'id' => '4', 'links' => ['https://itdoesntmatterwhatshere.heh'] }, { 'name' => '4GB server', 'id' => '5', 'links' => ['https://itdoesntmatterwhatshere.heh'] }, { 'name' => '8GB server', 'id' => '6', 'links' => ['https://itdoesntmatterwhatshere.heh'] }, { 'name' => '15.5GB server', 'id' => '7', 'links' => ['https://itdoesntmatterwhatshere.heh'] } ] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/create_volume_snapshot.rb0000644000004100000410000000224312261242552026344 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def create_volume_snapshot(volume_id, name, description, force=false) data = { 'snapshot' => { 'volume_id' => volume_id, 'display_name' => name, 'display_description' => description, 'force' => force } } request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'POST', :path => "os-snapshots" ) end end class Mock def create_volume_snapshot(volume_id, name, description, force=false) response = Excon::Response.new response.status = 202 response.body = { "snapshot"=> { "status"=>"creating", "display_name"=>name, "created_at"=>Time.now, "display_description"=>description, "volume_id"=>volume_id, "id"=>"5", "size"=>1 } } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/update_meta.rb0000644000004100000410000000220712261242552024063 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def update_meta(collection_name, parent_id, key, value) request( :body => Fog::JSON.encode({ 'meta' => {key => value}}), :expects => 200, :method => 'PUT', :path => "#{collection_name}/#{parent_id}/metadata/#{key}" ) end end class Mock def update_meta(collection_name, parent_id, key, value) if collection_name == "images" then if not list_images_detail.body['images'].detect {|_| _['id'] == parent_id} raise Fog::Compute::OpenStack::NotFound end end if collection_name == "servers" then if not list_servers_detail.body['servers'].detect {|_| _['id'] == parent_id} raise Fog::Compute::OpenStack::NotFound end end #FIXME join w/ existing metadata here response = Excon::Response.new response.body = { "metadata" => {key => value} } response.status = 200 response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/get_flavor_details.rb0000644000004100000410000000353512261242552025435 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def get_flavor_details(flavor_ref) request( :expects => [200, 203], :method => 'GET', :path => "flavors/#{flavor_ref}.json" ) end end class Mock def get_flavor_details(flavor_ref) response = Excon::Response.new flavor = { '1' => { 'id' => '1', 'name' => '256 server', 'ram' => 256, 'disk' => 10, 'swap' => '1', 'vcpus' => 1, 'OS-FLV-EXT-DATA:ephemeral' => 1, 'links' => [] }, '2' => { 'id' => '2', 'name' => '512 server', 'ram' => 512, 'disk' => 20, 'swap' => '1', 'vcpus' => 2, 'OS-FLV-EXT-DATA:ephemeral' => 1, 'links' => [] }, '3' => { 'id' => '3', 'name' => '1GB server', 'ram' => 1024, 'disk' => 40, 'swap' => '2', 'vcpus' => 2, 'OS-FLV-EXT-DATA:ephemeral' => 1, 'links' => [] }, '4' => { 'id' => '4', 'name' => '2GB server', 'ram' => 2048, 'disk' => 80, 'swap' => '4', 'vcpus' => 4, 'OS-FLV-EXT-DATA:ephemeral' => 1, 'links' => [] }, '5' => { 'id' => '5', 'name' => '4GB server', 'ram' => 4096, 'disk' => 160, 'swap' => '8', 'vcpus' => 8, 'OS-FLV-EXT-DATA:ephemeral' => 1, 'links' => [] }, '6' => { 'id' => '6', 'name' => '8GB server', 'ram' => 8192, 'disk' => 320, 'swap' => '16', 'vcpus' => 16, 'OS-FLV-EXT-DATA:ephemeral' => 1, 'links' => [] }, '7' => { 'id' => '7', 'name' => '15.5GB server', 'ram' => 15872, 'disk' => 620, 'swap' => '32', 'vcpus' => 32, 'OS-FLV-EXT-DATA:ephemeral' => 1, 'links' => [] } }[flavor_ref] if flavor response.status = 200 response.body = { 'flavor' => flavor } response else raise Fog::Compute::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/set_tenant.rb0000644000004100000410000000060112261242552023733 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def set_tenant(tenant) @openstack_must_reauthenticate = true @openstack_tenant = tenant.to_s authenticate end end class Mock def set_tenant(tenant) true end end end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/requests/compute/get_security_group.rb0000644000004100000410000000215012261242552025512 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def get_security_group(security_group_id) request( :expects => [200], :method => 'GET', :path => "os-security-groups/#{security_group_id}" ) end end class Mock def get_security_group(security_group_id) security_group = self.data[:security_groups][security_group_id.to_s] response = Excon::Response.new if security_group response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-63a90344-7c4d-42e2-936c-fd748bced1b3", "Content-Type" => "application/json", "Content-Length" => "167", "Date" => Date.new } response.body = { "security_group" => security_group } else raise Fog::Compute::OpenStack::NotFound, "Security group #{security_group_id} does not exist" end response end end # mock end # openstack end #compute end #fog fog-1.19.0/lib/fog/openstack/requests/compute/get_address.rb0000644000004100000410000000174112261242552024061 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def get_address(address_id) request( :expects => [200], :method => 'GET', :path => "os-floating-ips/#{address_id}" ) end end class Mock def get_address(address_id) response = Excon::Response.new response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-d4a21158-a86c-44a6-983a-e25645907f26", "Content-Type" => "application/json", "Content-Length" => "105", "Date"=> Date.new } response.body = { "floating_ip" => { "instance_id" => nil, "ip" => "192.168.27.129", "fixed_ip" => nil, "id" => 1, "pool" => "nova" } } response end end # mock end # openstack end # compute end # fog fog-1.19.0/lib/fog/openstack/requests/compute/get_security_group_rule.rb0000644000004100000410000000241112261242552026541 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def get_security_group_rule(security_group_rule_id) request( :expects => [200], :method => 'GET', :path => "os-security-group-rules/#{security_group_rule_id}" ) end end class Mock def get_security_group_rule(security_group_rule_id) security_group_rule = nil self.data[:security_groups].detect{|id, sg| security_group_rule = sg["rules"].detect{ |sgr| sgr["id"].to_s == security_group_rule_id.to_s }} response = Excon::Response.new if security_group_rule response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-63a90344-7c4d-42e2-936c-fd748bced1b3", "Content-Type" => "application/json", "Content-Length" => "167", "Date" => Date.new } response.body = { "security_group_rule" => security_group_rule } else raise Fog::Compute::OpenStack::NotFound, "Security group rule #{security_group_rule_id} does not exist" end response end end # mock end # openstack end #compute end #fog fog-1.19.0/lib/fog/openstack/requests/compute/remove_fixed_ip.rb0000644000004100000410000000145212261242552024740 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real # Remove an IP address. # # === Parameters # * server_id <~String> - The ID of the server in which to remove an IP from. # * address <~String> - The IP address to be removed. # === Returns # * success <~Boolean> def remove_fixed_ip(server_id, address) body = { 'removeFixedIp' => { 'address' => address } } server_action(server_id, body).status == 202 end # def remove_fixed_ip end # class Real class Mock def remove_fixed_ip(server_id, address) true end # def remove_fixed_ip end # class Mock end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/requests/compute/get_quota_defaults.rb0000644000004100000410000000112312261242552025446 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def get_quota_defaults(tenant_id) request( :expects => 200, :method => 'GET', :path => "/os-quota-sets/#{tenant_id}/defaults" ) end end class Mock def get_quota_defaults(tenant_id) response = Excon::Response.new response.status = 200 response.body = { 'quota_set' => self.data[:quota].merge({'id' => tenant_id}) } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/delete_server.rb0000644000004100000410000000165612261242552024432 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def delete_server(server_id) request( :expects => 204, :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'].detect {|_| _['id'] == server_id} if server['status'] == 'BUILD' response.status = 409 raise(Excon::Errors.status_error({:expects => 204}, response)) else self.data[:last_modified][:servers].delete(server_id) self.data[:servers].delete(server_id) response.status = 204 end response else raise Fog::Compute::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_snapshots.rb0000644000004100000410000000115712261242552024653 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def list_snapshots(detailed=true) path = detailed ? 'os-snapshots/detail' : 'os-snapshots' request( :expects => 200, :method => 'GET', :path => path ) end end class Mock def list_snapshots(detailed=true) response = Excon::Response.new response.status = 200 response.body = { 'snapshots' => [get_snapshot_details.body["snapshot"]] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_images.rb0000644000004100000410000000127312261242552024075 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real 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', 'links'].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'images' => images } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_security_groups.rb0000644000004100000410000000255612261242552026103 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def list_security_groups(server_id = nil) path = "os-security-groups.json" if server_id path = "servers/#{server_id}/#{path}" end request( :expects => [200], :method => 'GET', :path => path ) end end class Mock def list_security_groups(server_id = nil) security_groups = self.data[:security_groups].values groups = if server_id then server_group_names = Array(self.data[:server_security_group_map][server_id]) server_group_names.map do |name| security_groups.find do |sg| sg['name'] == name end end.compact else security_groups end Excon::Response.new( :body => { 'security_groups' => groups }, :headers => { "X-Compute-Request-Id" => "req-#{Fog::Mock.random_base64(36)}", "Content-Type" => "application/json", "Date" => Date.new }, :status => 200 ) end end # mock end # openstack end # compute end # fog fog-1.19.0/lib/fog/openstack/requests/compute/create_security_group.rb0000644000004100000410000000315312261242552026202 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def create_security_group(name, description) data = { 'security_group' => { 'name' => name, 'description' => description } } request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'POST', :path => 'os-security-groups.json' ) end end class Mock def create_security_group(name, description) Fog::Identity::OpenStack.new(:openstack_auth_url => credentials[:openstack_auth_url]) tenant_id = Fog::Identity::OpenStack::Mock.data[current_tenant][:tenants].keys.first security_group_id = Fog::Mock.random_numbers(2).to_i self.data[:security_groups][security_group_id.to_s] = { 'tenant_id' => tenant_id, 'rules' => [], 'id' => security_group_id, 'name' => name, 'description' => description } response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new} response.body = { 'security_group' => self.data[:security_groups][security_group_id.to_s] } response end end # mock end # openstack end # compute end # fog fog-1.19.0/lib/fog/openstack/requests/compute/list_metadata.rb0000644000004100000410000000105012261242552024401 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def list_metadata(collection_name, parent_id) request( :expects => [200, 203], :method => 'GET', :path => "/#{collection_name}/#{parent_id}/metadata.json" ) end end class Mock def list_metadata(collection_name, parent_id) response = Excon::Response.new response.status = 200 response.body = {} response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/get_usage.rb0000644000004100000410000000374012261242552023541 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def get_usage(tenant_id, date_start, date_end) params = Hash.new params[:start] = date_start.utc.iso8601.chop! params[:end] = date_end.utc.iso8601.chop! request( :expects => [200, 203], :method => 'GET', :path => "os-simple-tenant-usage/#{tenant_id}", :query => params ) end end class Mock def get_usage(tenant_id, date_start, date_end) response = Excon::Response.new response.status = 200 response.body = {"tenant_usage"=> {"total_memory_mb_usage" => 0.0, "total_vcpus_usage" => 0.0, "total_hours" => 0.0, "tenant_id" => tenant_id, "stop" => date_start, "start" => date_end, "total_local_gb_usage" => 0.0, "server_usages" =>[{ "hours" => 0.0, "uptime" => 69180, "local_gb" => 0, "ended_at" => nil, "name" => "test server", "tenant_id" => tenant_id, "vcpus" => 1, "memory_mb" => 512, "state" => "active", "flavor" => "m1.tiny", "started_at" => "2012-03-05 09:11:44" } ] } } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/add_flavor_access.rb0000644000004100000410000000142712261242552025220 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def add_flavor_access(flavor_ref, tenant_id) request( :body => Fog::JSON.encode({ "addTenantAccess" => { "tenant" => tenant_id } }), :expects => [200, 203], :method => 'POST', :path => "flavors/#{flavor_ref}/action.json" ) end end class Mock def add_flavor_access(flavor_ref, tenant_id) response = Excon::Response.new response.status = 200 response.body = { "flavor_access" => [{ "tenant_id" => tenant_id.to_s, "flavor_id" => flavor_ref.to_s }] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_usages.rb0000644000004100000410000000306012261242552024113 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def list_usages(date_start = nil, date_end = nil, detailed=false) params = Hash.new params[:start] = date_start.iso8601.gsub(/\+.*/, '') if date_start params[:end] = date_end.iso8601.gsub(/\+.*/, '') if date_end params[:detailed] = (detailed ? '1' : '0') if detailed request( :expects => [200, 203], :method => 'GET', :path => 'os-simple-tenant-usage', :query => params ) end end class Mock def list_usages(date_start = nil, date_end = nil, detailed=false) params = Hash.new response = Excon::Response.new response.status = 200 response.body = {"tenant_usages"=>[{ "total_memory_mb_usage" => 0.00036124444444444445, "total_vcpus_usage" => 7.055555555555556e-07, "start" => "2012-03-06 05:05:56.349001", "tenant_id" => "b97c8abba0c44a0987c63b858a4823e5", "stop" => "2012-03-06 05:05:56.349255", "total_hours" => 7.055555555555556e-07, "total_local_gb_usage" => 0.0 } ] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/allocate_address.rb0000644000004100000410000000203412261242552025062 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def allocate_address(pool = nil) request( :body => Fog::JSON.encode({'pool' => pool}), :expects => [200, 202], :method => 'POST', :path => 'os-floating-ips.json' ) end end class Mock def allocate_address(pool = nil) response = Excon::Response.new response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-d4a21158-a86c-44a6-983a-e25645907f26", "Content-Type" => "application/json", "Content-Length" => "105", "Date"=> Date.new } response.body = { "floating_ip" => { "instance_id" => nil, "ip" => "192.168.27.132", "fixed_ip" => nil, "id" => 4, "pool"=>"nova" } } response end end # mock end # openstack end #compute end fog-1.19.0/lib/fog/openstack/requests/compute/set_metadata.rb0000644000004100000410000000212312261242552024223 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def set_metadata(collection_name, parent_id, metadata = {}) request( :body => Fog::JSON.encode({ 'metadata' => metadata }), :expects => 200, :method => 'PUT', :path => "#{collection_name}/#{parent_id}/metadata" ) end end class Mock def set_metadata(collection_name, parent_id, metadata = {}) if collection_name == "images" then if not list_images_detail.body['images'].detect {|_| _['id'] == parent_id} raise Fog::Compute::OpenStack::NotFound end end if collection_name == "servers" then if not list_servers_detail.body['servers'].detect {|_| _['id'] == parent_id} raise Fog::Compute::OpenStack::NotFound end end response = Excon::Response.new response.body = { "metadata" => metadata } response.status = 200 response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/suspend_server.rb0000644000004100000410000000116612261242552024645 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real # Suspend the server. # # === Parameters # * server_id <~String> - The ID of the server to suspend. # === Returns # * success <~Boolean> def suspend_server(server_id) body = { 'suspend' => nil } server_action(server_id, body).status == 202 end # def suspend_server end # class Real class Mock def suspend_server(server_id) true end # def suspend_server end # class Mock end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/requests/compute/live_migrate_server.rb0000644000004100000410000000123212261242552025625 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def live_migrate_server(server_id, host, block_migration, disk_over_commit) body = { 'os-migrateLive' => { 'host' => host, 'block_migration' => block_migration, 'disk_over_commit' => disk_over_commit, } } server_action(server_id, body) end end class Mock def live_migrate_server(server_id, host, block_migration, disk_over_commit) response = Excon::Response.new response.status = 202 response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/get_snapshot_details.rb0000644000004100000410000000166212261242552026002 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def get_snapshot_details(snapshot_id) request( :expects => 200, :method => 'GET', :path => "os-snapshots/#{snapshot_id}" ) end end class Mock def get_snapshot_details(snapshot_id) response = Excon::Response.new response.status = 200 response.body = { 'snapshot' => { 'id' => '1', 'display_name' => Fog::Mock.random_letters(rand(8) + 5), 'display_description' => Fog::Mock.random_letters(rand(12) + 10), 'size' => 3, 'volume_id' => '4', 'status' => 'online', 'created_at' => Time.now } } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/create_volume.rb0000644000004100000410000000307512261242552024431 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def create_volume(name, description, size, options={}) data = { 'volume' => { 'display_name' => name, 'display_description' => description, 'size' => size } } vanilla_options = ['snapshot_id'] vanilla_options.select{|o| options[o]}.each do |key| data['volume'][key] = options[key] end request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'POST', :path => "os-volumes" ) end end class Mock def create_volume(name, description, size, options={}) response = Excon::Response.new response.status = 202 data = { 'id' => Fog::Mock.random_numbers(2), 'displayName' => name, 'displayDescription' => description, 'size' => size, 'status' => 'creating', 'snapshotId' => nil, 'volumeType' => 'None', 'availabilityZone' => 'nova', 'createdAt' => Time.now.strftime('%FT%T.%6N'), 'attachments' => [], 'metadata' => {} } self.data[:volumes][data['id']] = data response.body = { 'volume' => data } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/unpause_server.rb0000644000004100000410000000116612261242552024644 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real # Unpause the server. # # === Parameters # * server_id <~String> - The ID of the server to unpause. # === Returns # * success <~Boolean> def unpause_server(server_id) body = { 'unpause' => nil } server_action(server_id, body).status == 202 end # def unpause_server end # class Real class Mock def unpause_server(server_id) true end # def unpause_server end # class Mock end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/requests/compute/resize_server.rb0000644000004100000410000000067212261242552024466 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def resize_server(server_id, flavor_ref) body = { 'resize' => { 'flavorRef' => flavor_ref }} server_action(server_id, body) end end class Mock def resize_server(server_id, flavor_ref) response = Excon::Response.new response.status = 202 response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_servers_detail.rb0000644000004100000410000000213012261242552025634 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real # Available filters: name, status, image, flavor, changes_since, reservation_id def list_servers_detail(filters = {}) params = Hash.new filters[:all_tenants] ? params['all_tenants'] = 'True' : params = filters request( :expects => [200, 203], :method => 'GET', :path => 'servers/detail.json', :query => params ) end end class Mock def list_servers_detail(filters = {}) 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-1.19.0/lib/fog/openstack/requests/compute/server_actions.rb0000644000004100000410000000133212261242552024617 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real # Retrieve server actions. # # === Parameters # * server_id <~String> - The ID of the server to query for available actions. # === Returns # * actions <~Array> def server_actions(server_id) request( :expects => 200, :method => 'GET', :path => "servers/#{server_id}/actions" ).body['actions'] end # def server_actions end # class Real class Mock def server_actions(server_id) Array.new end # def server_actions end # class Mock end # class OpenStack end # module Compute end # moduel Fog fog-1.19.0/lib/fog/openstack/requests/compute/remove_flavor_access.rb0000644000004100000410000000134412261242552025763 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def remove_flavor_access(flavor_ref, tenant_id) request( :body => Fog::JSON.encode({ "removeTenantAccess" => { "tenant" => tenant_id.to_s } }), :expects => [200, 203], :method => 'POST', :path => "flavors/#{flavor_ref}/action.json" ) end end class Mock def remove_flavor_access(flavor_ref, tenant_id) response = Excon::Response.new response.status = 200 response.body = { "flavor_access" => [] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/add_fixed_ip.rb0000644000004100000410000000147312261242552024176 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real # Add an IP address on a network. # # === Parameters # * server_id <~String> - The ID of the server in which to add an IP to. # * network_id <~String> - The ID of the network the IP should be on. # === Returns # * success <~Boolean> def add_fixed_ip(server_id, network_id) body = { 'addFixedIp' => { 'networkId' => network_id } } server_action(server_id, body).status == 202 end # def add_fixed_ip end # class Real class Mock def add_fixed_ip(server_id, network_id) true end # def add_fixed_ip end # class Mock end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/requests/compute/delete_volume.rb0000644000004100000410000000124712261242552024427 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def delete_volume(volume_id) request( :expects => 202, :method => 'DELETE', :path => "os-volumes/#{volume_id}" ) end end class Mock def delete_volume(volume_id) response = Excon::Response.new if list_volumes.body['volumes'].map { |v| v['id'] }.include? volume_id self.data[:volumes].delete(volume_id) response.status = 204 response else raise Fog::Compute::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/delete_meta.rb0000644000004100000410000000171112261242552024042 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def delete_meta(collection_name, parent_id, key) request( :expects => 204, :method => 'DELETE', :path => "#{collection_name}/#{parent_id}/metadata/#{key}" ) end end class Mock def delete_meta(collection_name, parent_id, key) if collection_name == "images" then if not list_images_detail.body['images'].detect {|_| _['id'] == parent_id} raise Fog::Compute::OpenStack::NotFound end end if collection_name == "servers" then if not list_servers_detail.body['servers'].detect {|_| _['id'] == parent_id} raise Fog::Compute::OpenStack::NotFound end end response = Excon::Response.new response.status = 204 response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/disassociate_address.rb0000644000004100000410000000116412261242552025754 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def disassociate_address(server_id, ip_address) body = { "removeFloatingIp" => {"address" => ip_address}} server_action(server_id, body) end end class Mock def disassociate_address(server_id, ip_address) response = Excon::Response.new response.status = 202 response.headers = { "Content-Type" => "text/html, charset=UTF-8", "Content-Length" => "0", "Date"=> Date.new } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_tenants_with_flavor_access.rb0000644000004100000410000000122412261242552030225 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def list_tenants_with_flavor_access(flavor_ref) request( :expects => [200, 203], :method => 'GET', :path => "flavors/#{flavor_ref}/os-flavor-access.json" ) end end class Mock def list_tenants_with_flavor_access(flavor_ref) response = Excon::Response.new response.status = 200 response.body = { "flavor_access" => [{ "tenant_id" => @tenant_id.to_s, "flavor_id" => flavor_ref.to_s }] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/rescue_server.rb0000644000004100000410000000115412261242552024447 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real # Rescue the server. # # === Parameters # * server_id <~String> - The ID of the server to be rescued. # === Returns # * success <~Boolean> def rescue_server(server_id) body = { 'rescue' => nil } server_action(server_id, body) == 202 end # def rescue_server end # class Real class Mock def rescue_server(server_id) true end # def rescue_server end # class Mock end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/requests/compute/delete_snapshot.rb0000644000004100000410000000073112261242552024754 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def delete_snapshot(snapshot_id) request( :expects => 202, :method => 'DELETE', :path => "os-snapshots/#{snapshot_id}" ) end end class Mock def delete_snapshot(snapshot_id) response = Excon::Response.new response.status = 204 response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/create_security_group_rule.rb0000644000004100000410000000355412261242552027236 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def create_security_group_rule(parent_group_id, ip_protocol, from_port, to_port, cidr, group_id=nil) data = { 'security_group_rule' => { 'parent_group_id' => parent_group_id, 'ip_protocol' => ip_protocol, 'from_port' => from_port, 'to_port' => to_port, 'cidr' => cidr, 'group_id' => group_id } } request( :expects => 200, :method => 'POST', :body => Fog::JSON.encode(data), :path => 'os-security-group-rules.json' ) end end class Mock def create_security_group_rule(parent_group_id, ip_protocol, from_port, to_port, cidr, group_id=nil) parent_group_id = parent_group_id.to_i response = Excon::Response.new response.status = 200 response.headers = { 'X-Compute-Request-Id' => "req-#{Fog::Mock.random_hex(32)}", 'Content-Type' => 'application/json', 'Content-Length' => Fog::Mock.random_numbers(3).to_s, 'Date' => Date.new } rule = { 'id' => Fog::Mock.random_numbers(2).to_i, 'from_port' => from_port, 'group' => group_id || {}, 'ip_protocol' => ip_protocol, 'to_port' => to_port, 'parent_group_id' => parent_group_id, 'ip_range' => { 'cidr' => cidr } } self.data[:security_groups][parent_group_id.to_s]['rules'].push(rule) response.body = { 'security_group_rule' => rule } response end end # mock end # openstack end # compute end # fog fog-1.19.0/lib/fog/openstack/requests/compute/update_server.rb0000644000004100000410000000147412261242552024450 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def update_server(server_id, options = {}) request( :body => Fog::JSON.encode({ 'server' => options }), :expects => 200, :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'].detect {|_| _['id'] == server_id} if options['name'] server['name'] = options['name'] end response.status = 200 response else raise Fog::Compute::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_images_detail.rb0000644000004100000410000000201112261242552025406 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def list_images_detail(filters = {}) request( :expects => [200, 203], :method => 'GET', :path => 'images/detail.json', :query => filters ) end end class Mock def list_images_detail(filters = {}) 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', 'links', 'minRam', 'minDisk', 'metadata', 'status', 'updated'].include?(key)}} } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/get_volume_details.rb0000644000004100000410000000121712261242552025446 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def get_volume_details(volume_id) request( :expects => 200, :method => 'GET', :path => "os-volumes/#{volume_id}" ) end end class Mock def get_volume_details(volume_id) response = Excon::Response.new if data = self.data[:volumes][volume_id] response.status = 200 response.body = { 'volume' => data } response else raise Fog::Compute::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_hosts.rb0000644000004100000410000000115112261242552023763 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def list_hosts request( :expects => [200, 203], :method => 'GET', :path => 'os-hosts.json' ) end end class Mock def list_hosts response = Excon::Response.new response.status = 200 response.body = { "hosts" => [ {"host_name" => "host.test.net", "service"=>"compute", "zone" => "az1"} ] } response end end # mock end # openstack end # compute end # fog fog-1.19.0/lib/fog/openstack/requests/compute/list_servers.rb0000644000004100000410000000154112261242552024317 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def list_servers(options = {}) params = Hash.new params['all_tenants'] = 'True' if options[:all_tenants] request( :expects => [200, 203], :method => 'GET', :path => 'servers.json', :query => params ) end end class Mock def list_servers(options = {}) response = Excon::Response.new data = list_servers_detail.body['servers'] servers = [] for server in data servers << server.reject { |key, value| !['id', 'name', 'links'].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'servers' => servers } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/reset_server_state.rb0000644000004100000410000000074712261242552025512 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def reset_server_state(server_id, status) body = { 'os-resetState' => { 'state' => status } } server_action(server_id, body, 202) end end class Mock def reset_server_state(server_id, status) response = get_server_details(server_id) response.body['server']['status'] = status.upcase response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/update_metadata.rb0000644000004100000410000000221712261242552024716 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def update_metadata(collection_name, parent_id, metadata = {}) request( :body => Fog::JSON.encode({ 'metadata' => metadata }), :expects => 200, :method => 'POST', :path => "#{collection_name}/#{parent_id}/metadata.json" ) end end class Mock def update_metadata(collection_name, parent_id, metadata = {}) if collection_name == "images" then if not list_images_detail.body['images'].detect {|_| _['id'] == parent_id} raise Fog::Compute::OpenStack::NotFound end end if collection_name == "servers" then if not list_servers_detail.body['servers'].detect {|_| _['id'] == parent_id} raise Fog::Compute::OpenStack::NotFound end end #FIXME join w/ existing metadata here response = Excon::Response.new response.body = { "metadata" => metadata } response.status = 200 response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_addresses.rb0000644000004100000410000000133612261242552024605 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real 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'].detect {|_| _['id'] == server_id} response.status = [200, 203][rand(1)] response.body = { 'addresses' => server['addresses'] } response else raise Fog::Compute::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_tenants.rb0000644000004100000410000000252112261242552024301 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def list_tenants response = @identity_connection.request({ :expects => [200, 204], :headers => {'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Auth-Token' => @auth_token}, :method => 'GET', :path => '/v2.0/tenants' }) response.body = Fog::JSON.decode(response.body) response end end class Mock def list_tenants response = Excon::Response.new response.status = [200, 204][rand(1)] response.body = { 'tenants_links' => [], 'tenants' => [ {'id' => '1', 'description' => 'Has access to everything', 'enabled' => true, 'name' => 'admin'}, {'id' => '2', 'description' => 'Normal tenant', 'enabled' => true, 'name' => 'default'}, {'id' => '3', 'description' => 'Disabled tenant', 'enabled' => false, 'name' => 'disabled'} ] } response end end # class Mock end #class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/requests/compute/delete_image.rb0000644000004100000410000000173712261242552024206 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real 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'].detect {|_| _['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(Excon::Errors.status_error({:expects => 202}, response)) end end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/delete_security_group_rule.rb0000644000004100000410000000176012261242552027232 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def delete_security_group_rule(security_group_rule_id) request( :expects => 202, :method => 'DELETE', :path => "os-security-group-rules/#{security_group_rule_id}" ) end end class Mock def delete_security_group_rule(security_group_rule_id) security_group = self.data[:security_groups].values.detect{|sg| sg["rules"].detect{ |sgr| sgr["id"].to_s == security_group_rule_id.to_s }} security_group["rules"].reject! { |sgr| sgr["id"] == security_group_rule_id } response = Excon::Response.new response.status = 202 response.headers = { "Content-Type" => "text/html; charset=UTF-8", "Content-Length" => "0", "Date" => Date.new } response.body = {} response end end # mock end # openstack end # compute end # fog fog-1.19.0/lib/fog/openstack/requests/compute/list_volumes.rb0000644000004100000410000000105112261242552024314 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def list_volumes(detailed=true) path = detailed ? 'os-volumes/detail' : 'os-volumes' request( :expects => 200, :method => 'GET', :path => path ) end end class Mock def list_volumes(detailed=true) Excon::Response.new( :body => { 'volumes' => self.data[:volumes].values }, :status => 200 ) end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/rebuild_server.rb0000644000004100000410000000206712261242552024613 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def rebuild_server(server_id, image_ref, name, admin_pass=nil, metadata=nil, personality=nil) body = { 'rebuild' => { 'imageRef' => image_ref, 'name' => name }} body['rebuild']['adminPass'] = admin_pass if admin_pass body['rebuild']['metadata'] = metadata if metadata if personality body['rebuild']['personality'] = [] for file in personality body['rebuild']['personality'] << { 'contents' => Base64.encode64(file['contents']), 'path' => file['path'] } end end server_action(server_id, body, 202) end end class Mock def rebuild_server(server_id, image_ref, name, admin_pass=nil, metadata=nil, personality=nil) response = get_server_details(server_id) response.body['server']['status'] = "REBUILD" response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/associate_address.rb0000644000004100000410000000115312261242552025252 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def associate_address(server_id, ip_address) body = { "addFloatingIp" => {"address" => ip_address}} server_action(server_id, body) end end class Mock def associate_address(server_id, ip_address) response = Excon::Response.new response.status = 202 response.headers = { "Content-Type" => "text/html, charset=UTF-8", "Content-Length" => "0", "Date"=> Date.new } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/create_server.rb0000644000004100000410000001433512261242552024431 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def create_server(name, image_ref, flavor_ref, options = {}) data = { 'server' => { 'flavorRef' => flavor_ref, 'imageRef' => image_ref, 'name' => name } } vanilla_options = ['metadata', 'accessIPv4', 'accessIPv6', 'availability_zone', 'user_data', 'key_name', 'adminPass', 'config_drive', 'min_count', 'max_count', 'return_reservation_id' ] vanilla_options.select{|o| options[o]}.each do |key| data['server'][key] = options[key] end if options['security_groups'] # security names requires a hash with a name prefix data['server']['security_groups'] = Array(options['security_groups']).map do |sg| name = if sg.is_a?(Fog::Compute::OpenStack::SecurityGroup) then sg.name else sg end { :name => name } end 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 if options['nics'] data['server']['networks'] = Array(options['nics']).map do |nic| neti = { 'uuid' => nic['net_id'] } neti['fixed_ip'] = nic['v4_fixed_ip'] unless nic['v4_fixed_ip'].nil? neti['port'] = nic['port_id'] unless nic['port_id'].nil? neti end end if options['os:scheduler_hints'] data['os:scheduler_hints'] = options['os:scheduler_hints'] end if options['block_device_mapping'] data['server']['block_device_mapping'] = [options['block_device_mapping']].flatten.map do |mapping| { 'volume_size' => mapping[:volume_size], 'volume_id' => mapping[:volume_id], 'delete_on_termination' => mapping[:delete_on_termination], 'device_name' => mapping[:device_name] } end end path = if data['server']['block_device_mapping'] 'os-volumes_boot.json' else 'servers.json' end request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'POST', :path => path ) end end class Mock def create_server(name, image_ref, flavor_ref, options = {}) response = Excon::Response.new response.status = 202 server_id = Fog::Mock.random_numbers(6).to_s identity = Fog::Identity::OpenStack.new :openstack_auth_url => credentials[:openstack_auth_url] user = identity.users.find { |u| u.name == @openstack_username } user_id = if user then user.id else response = identity.create_user(@openstack_username, 'password', "#{@openstack_username}@example.com") response.body["user"]["id"] end mock_data = { 'addresses' => {}, 'flavor' => {"id" => flavor_ref, "links"=>[{"href"=>"http://nova1:8774/admin/flavors/1", "rel"=>"bookmark"}]}, 'id' => server_id, 'image' => {"id" => image_ref, "links"=>[{"href"=>"http://nova1:8774/admin/images/#{image_ref}", "rel"=>"bookmark"}]}, 'links' => [{"href"=>"http://nova1:8774/v1.1/admin/servers/5", "rel"=>"self"}, {"href"=>"http://nova1:8774/admin/servers/5", "rel"=>"bookmark"}], 'hostId' => "123456789ABCDEF01234567890ABCDEF", 'metadata' => options['metadata'] || {}, 'name' => name || "server_#{rand(999)}", 'accessIPv4' => options['accessIPv4'] || "", 'accessIPv6' => options['accessIPv6'] || "", 'progress' => 0, 'status' => 'BUILD', 'created' => '2012-09-27T00:04:18Z', 'updated' => '2012-09-27T00:04:27Z', 'user_id' => @openstack_username, 'config_drive' => options['config_drive'] || '', } if nics = options['nics'] nics.each do |nic| mock_data["addresses"].merge!( "Public" => [{ 'addr' => Fog::Mock.random_ip }] ) end end response_data = {} if options['return_reservation_id'] == 'True' then response_data = { 'reservation_id' => "r-#{Fog::Mock.random_numbers(6).to_s}" } else response_data = { 'adminPass' => 'password', 'id' => server_id, 'links' => mock_data['links'], } end self.data[:last_modified][:servers][server_id] = Time.now self.data[:servers][server_id] = mock_data if security_groups = options['security_groups'] then groups = Array(options['security_groups']).map do |sg| if sg.is_a?(Fog::Compute::OpenStack::SecurityGroup) then sg.name else sg end end self.data[:server_security_group_map][server_id] = groups response_data['security_groups'] = groups end self.data[:last_modified][:servers][server_id] = Time.now self.data[:servers][server_id] = mock_data if options['return_reservation_id'] == 'True' then response.body = response_data else response.body = { 'server' => response_data } end response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/get_metadata.rb0000644000004100000410000000110012261242552024201 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def get_metadata(collection_name, parent_id, key) request( :expects => [200, 203], :method => 'GET', :path => "#{collection_name}/#{parent_id}/metadata/#{key}" ) end end class Mock def get_metadata(collection_name, parent_id, key) response = Excon::Response.new response.status = 200 response.body = { 'meta' => {} } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_all_addresses.rb0000644000004100000410000000315612261242552025437 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def list_all_addresses request( :expects => [200, 203], :method => 'GET', :path => "os-floating-ips.json" ) end end class Mock def list_all_addresses response = Excon::Response.new response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-d4a21158-a86c-44a6-983a-e25645907f26", "Content-Type" => "application/json", "Content-Length" => "378", "Date"=> Date.new } response.body = { "floating_ips" => [ { "instance_id" => nil, "ip" => "192.168.27.129", "fixed_ip" => nil, "id" => 1, "pool" => "nova" }, { "instance_id" => nil, "ip" => "192.168.27.130", "fixed_ip" => nil, "id" => 2, "pool" => "nova" }, { "instance_id" => nil, "ip" => "192.168.27.131", "fixed_ip" => nil, "id" => 3, "pool" => "nova" }, { "instance_id" => nil, "ip" => "192.168.27.132", "fixed_ip" => nil, "id" => 4, "pool" => "nova" } ] } response end end # mock end # openstack end # Compute end # fog fog-1.19.0/lib/fog/openstack/requests/compute/get_server_volumes.rb0000644000004100000410000000137312261242552025515 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def get_server_volumes(server_id) request( :expects => 200, :method => 'GET', :path => "/servers/#{server_id}/os-volume_attachments" ) end end class Mock def get_server_volumes(server_id) response = Excon::Response.new response.status = 200 data = self.data[:volumes].values.find_all do |vol| vol['attachments'].find { |attachment| attachment["serverId"] == server_id } end response.body = { 'volumeAttachments' => data.collect! { |vol| vol['attachments'] }.flatten(1) } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/delete_key_pair.rb0000644000004100000410000000126712261242552024725 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def delete_key_pair(key_name) request( :expects => 202, :method => 'DELETE', :path => "os-keypairs/#{key_name}" ) end end class Mock def delete_key_pair(key_name) response = Excon::Response.new response.status = 202 response.headers = { "Content-Type" => "text/html; charset=UTF-8", "Content-Length" => "0", "Date" => Date.new } response.body = {} response end end # mock end # openstack end # compute end # fog fog-1.19.0/lib/fog/openstack/requests/compute/list_key_pairs.rb0000644000004100000410000000227712261242552024623 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def list_key_pairs request( :expects => [200, 203], :method => 'GET', :path => 'os-keypairs.json' ) end end class Mock def list_key_pairs response = Excon::Response.new response.status = 200 response.headers = { "X-Compute-Request-Id" => "req-c373a42c-2825-4e60-8d34-99416ea850be", "Content-Type" => "application/json", "Content-Length" => "360", "Date" => Date.new} response.body = { "keypairs" => [{ "keypair" => { "public_key" => "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDCdAZLjln1tJbLVVkNHjWFSoKen2nZbk39ZfqhZJOMdeFdz02GWBS4rcuHboeGg/gozKRwsLu4N6NLPlYtbK/NapJIvgO/djBp+FG1QZNtLPsx7j4hVJac3yISGms+Xtu4cEv6j5sFDzAgTQbWz0Z1+9qOq9ngdaoW+YClfQ== vagrant@nova\n", "name" => "test_key", "fingerprint" => "97:86:f4:15:68:0c:7b:a7:e5:8f:f0:bd:1f:27:65:ad" } }] } response end end # mock end # openstack end # compute end # fog fog-1.19.0/lib/fog/openstack/requests/compute/get_image_details.rb0000644000004100000410000000130712261242552025221 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def get_image_details(image_id) request( :expects => [200, 203], :method => 'GET', :path => "images/#{image_id}.json" ) end end class Mock def get_image_details(image_id) response = Excon::Response.new if image = list_images_detail.body['images'].detect {|_| _['id'] == image_id} response.status = [200, 203][rand(1)] response.body = { 'image' => image } response else raise Fog::Compute::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/get_limits.rb0000644000004100000410000000572012261242552023736 0ustar www-datawww-datamodule Fog module Compute class OpenStack # http://docs.openstack.org/api/openstack-compute/2/content/ProgramaticLimits.html # class Real def get_limits request( :expects => 200, :method => 'GET', :path => '/limits.json' ) end end class Mock def get_limits rate_limits = [ { 'regex' => '.*', 'limit' => [ { 'next-available' => '2012-11-22T16:13:44Z', 'unit' => 'MINUTE', 'verb' => 'POST', 'remaining' => 9, 'value' => 10 }, { 'next-available' => '2012-11-23T00:46:14Z', 'unit' => 'MINUTE', 'verb' => 'PUT', 'remaining' => 10, 'value' => 10 }, { 'next-available' => '2012-11-22T16:14:30Z', 'unit' => 'MINUTE', 'verb' => 'DELETE', 'remaining' => 99, 'value' => 100 } ], 'uri' => '*' }, { 'regex' => '^/servers', 'limit' => [ { 'next-available' => '2012-11-23T00:46:14Z', 'unit' => 'DAY', 'verb' => 'POST', 'remaining' => 50, 'value' => 50} ], 'uri'=>'*/servers' }, { 'regex' => '.*changes-since.*', 'limit' => [ { 'next-available' => '2012-11-23T00:46:14Z', 'unit' => 'MINUTE', 'verb' => 'GET', 'remaining' => 3, 'value' => 3 } ], 'uri' => '*changes-since*' } ] absolute_limits = { # Max 'maxServerMeta' => 128, 'maxTotalInstances' => 10, 'maxPersonality' => 5, 'maxImageMeta' => 128, 'maxPersonalitySize' => 10240, 'maxSecurityGroupRules' => 20, 'maxTotalKeypairs' => 100, 'maxSecurityGroups' => 10, 'maxTotalCores' => 20, 'maxTotalFloatingIps' => 10, 'maxTotalRAMSize' => 51200, # Used 'totalCoresUsed' => -1, 'totalRAMUsed' => -2048, 'totalInstancesUsed' => -1, 'totalSecurityGroupsUsed' => 0, 'totalFloatingIpsUsed' => 0 } Excon::Response.new( :status => 200, :body => { 'limits' => { 'rate' => rate_limits, 'absolute' => absolute_limits } } ) end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_address_pools.rb0000644000004100000410000000110312261242552025461 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def list_address_pools request( :expects => [200, 203], :method => 'GET', :path => "os-floating-ip-pools" ) end end class Mock def list_address_pools response = Excon::Response.new response.status = 200 response.body = { 'floating_ip_pools' => [ { 'name' => 'nova' } ] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/delete_flavor.rb0000644000004100000410000000122312261242552024403 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def delete_flavor(flavor_id) request( :expects => 202, :method => 'DELETE', :path => "flavors/#{flavor_id}" ) end end class Mock def delete_flavor(flavor_id) response = Excon::Response.new response.status = 202 response.headers = { "Content-Type" => "text/html; charset=UTF-8", "Content-Length" => "0", "Date" => Date.new } response end end # mock end # openstack end # compute end # fog fog-1.19.0/lib/fog/openstack/requests/compute/detach_volume.rb0000644000004100000410000000143112261242552024410 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def detach_volume(server_id, attachment_id) request( :expects => 202, :method => 'DELETE', :path => "servers/%s/os-volume_attachments/%s" % [server_id, attachment_id] ) end end class Mock def detach_volume(server_id, attachment_id) response = Excon::Response.new if self.data[:volumes][attachment_id] && self.data[:volumes][attachment_id]['attachments'].reject! { |attachment| attachment['serverId'] == server_id } response.status = 202 response else raise Fog::Compute::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_flavors_detail.rb0000644000004100000410000000331112261242552025621 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def list_flavors_detail(options = {}) request( :expects => [200, 203], :method => 'GET', :path => 'flavors/detail.json', :query => options ) end end class Mock def list_flavors_detail(options = {}) response = Excon::Response.new response.status = 200 response.body = { 'flavors' => [ { 'id' => '1', 'name' => '256 server', 'ram' => 256, 'disk' => 10, 'swap' => '1', 'vcpus' => 1, 'OS-FLV-EXT-DATA:ephemeral' => 1, 'links' => [] }, { 'id' => '2', 'name' => '512 server', 'ram' => 512, 'disk' => 20, 'swap' => '1', 'vcpus' => 2, 'OS-FLV-EXT-DATA:ephemeral' => 1, 'links' => [] }, { 'id' => '3', 'name' => '1GB server', 'ram' => 1024, 'disk' => 40, 'swap' => '2', 'vcpus' => 2, 'OS-FLV-EXT-DATA:ephemeral' => 1, 'links' => [] }, { 'id' => '4', 'name' => '2GB server', 'ram' => 2048, 'disk' => 80, 'swap' => '4', 'vcpus' => 4, 'OS-FLV-EXT-DATA:ephemeral' => 1, 'links' => [] }, { 'id' => '5', 'name' => '4GB server', 'ram' => 4096, 'disk' => 160, 'swap' => '8', 'vcpus' => 8, 'OS-FLV-EXT-DATA:ephemeral' => 1, 'links' => [] }, { 'id' => '6', 'name' => '8GB server', 'ram' => 8192, 'disk' => 320, 'swap' => '16', 'vcpus' => 16, 'OS-FLV-EXT-DATA:ephemeral' => 1, 'links' => [] }, { 'id' => '7', 'name' => '15.5GB server', 'ram' => 15872, 'disk' => 620, 'swap' => '32', 'vcpus' => 32, 'OS-FLV-EXT-DATA:ephemeral' => 1, 'links' => [] } ] } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/reboot_server.rb0000644000004100000410000000066512261242552024461 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real 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-1.19.0/lib/fog/openstack/requests/compute/get_quota.rb0000644000004100000410000000112712261242552023563 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def get_quota(tenant_id) request( :expects => 200, :method => 'GET', :path => "/os-quota-sets/#{tenant_id}" ) end end class Mock def get_quota(tenant_id) response = Excon::Response.new response.status = 200 response.body = { 'quota_set' => (self.data[:quota_updated] or self.data[:quota]).merge({'id' => tenant_id}) } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/server_diagnostics.rb0000644000004100000410000000125112261242552025466 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real # Retrieve server diagnostics. # # === Parameters # * server_id <~String> - The ID of the server to retrieve diagnostics. # === Returns # * actions <~Array> def server_diagnostics(server_id) request( :method => 'GET', :path => "servers/#{server_id}/diagnostics" ) end # def server_diagnostics end # class Real class Mock def server_diagnostics(server_id) end # def server_diagnostics end # class Real end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/requests/compute/change_server_password.rb0000644000004100000410000000074012261242552026330 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def change_server_password(server_id, admin_password) body = { 'changePassword' => { 'adminPass' => admin_password }} server_action(server_id, body) end end class Mock def change_server_password(server_id, admin_password) response = Excon::Response.new response.status = 202 response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_public_addresses.rb0000644000004100000410000000137212261242552026143 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real 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'].detect {|_| _['id'] == server_id} response.status = [200, 203][rand(1)] response.body = { 'public' => server['addresses']['public'] } response else raise Fog::Compute::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/attach_volume.rb0000644000004100000410000000201612261242552024424 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def attach_volume(volume_id, server_id, device) data = { 'volumeAttachment' => { 'volumeId' => volume_id.to_s, 'device' => device } } request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'POST', :path => "servers/%s/os-volume_attachments" % [server_id] ) end end class Mock def attach_volume(volume_id, server_id, device) response = Excon::Response.new response.status = 200 data = { 'id' => volume_id, 'volumeId' => volume_id, 'serverId' => server_id, 'device' => device } self.data[:volumes][volume_id]['attachments'] << data response.body = { 'volumeAttachment' => data } response end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/boot_from_snapshot.rb0000644000004100000410000000241312261242552025477 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def boot_from_snapshot(name, image_ref, flavor_ref, options={}) data = { 'server' => { 'flavorRef' => flavor_ref, 'imageRef' => image_ref, 'name' => name } } vanilla_options = ['metadata', 'accessIPv4', 'accessIPv6', 'availability_zone', 'user_data', 'block_device_mapping', 'key_name', 'security_groups'] vanilla_options.select{|o| options[o]}.each do |key| data['server'][key] = options[key] 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 => '/os-volumes_boot.json' ) end end end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/requests/compute/release_address.rb0000644000004100000410000000125212261242552024717 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def release_address(address_id) request( :expects => [200, 202], :method => 'DELETE', :path => "os-floating-ips/#{address_id}" ) end end class Mock def release_address(address_id) response = Excon::Response.new response.status = 202 response.headers = { "Content-Type" => "text/html; charset=UTF-8", "Content-Length" => "0", "Date" => Date.new } response.body = {} response end end # mock end end end fog-1.19.0/lib/fog/openstack/requests/compute/get_server_details.rb0000644000004100000410000000132212261242552025442 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real 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'].detect {|_| _['id'] == server_id} response.status = [200, 203][rand(1)] response.body = { 'server' => server } response else raise Fog::Compute::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/list_private_addresses.rb0000644000004100000410000000137712261242552026344 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real 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'].detect {|_| _['id'] == server_id} response.status = [200, 203][rand(1)] response.body = { 'private' => server['addresses']['private'] } response else raise Fog::Compute::OpenStack::NotFound end end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/server_action.rb0000644000004100000410000000057012261242552024437 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def server_action(server_id, body, expects=[200,202]) request( :body => Fog::JSON.encode(body), :expects => expects, :method => 'POST', :path => "servers/#{server_id}/action.json" ) end end end end end fog-1.19.0/lib/fog/openstack/requests/compute/migrate_server.rb0000644000004100000410000000061412261242552024611 0ustar www-datawww-datamodule Fog module Compute class OpenStack class Real def migrate_server(server_id) body = { 'migrate' => nil } server_action(server_id, body) end end class Mock def migrate_server(server_id) response = Excon::Response.new response.status = 202 response end end end end end fog-1.19.0/lib/fog/openstack/requests/image/0000755000004100000410000000000012261242552020653 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/requests/image/get_image_by_id.rb0000644000004100000410000000162412261242552024272 0ustar www-datawww-datamodule Fog module Image class OpenStack class Real def get_image_by_id(image_id) request( :expects => [200, 204], :method => 'GET', :path => "images/#{image_id}" ) end end # class Real class Mock def get_image_by_id(image_id) response = Excon::Response.new response.status = [200, 204][rand(1)] response.body = { "images"=>[{ "name"=>"mock-image-name", "size"=>25165824, "disk_format"=>"ami", "container_format"=>"ami", "id"=>"0e09fbd6-43c5-448a-83e9-0d3d05f9747e", "checksum"=>"2f81976cae15c16ef0010c51e3a6c163"}] } response end # def list_tenants end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/image/list_public_images_detailed.rb0000644000004100000410000000147512261242552026700 0ustar www-datawww-datamodule Fog module Image class OpenStack class Real def list_public_images_detailed(attribute=nil, query=nil) if attribute path = "images/detail?#{attribute}=#{URI::encode(query)}" else path = 'images/detail' end request( :expects => [200, 204], :method => 'GET', :path => path ) end end # class Real class Mock def list_public_images_detailed(attribute=nil, query=nil) response = Excon::Response.new response.status = [200, 204][rand(1)] response.body = {'images' => self.data[:images].values} response end # def list_tenants end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/image/create_image.rb0000644000004100000410000000571712261242552023617 0ustar www-datawww-datamodule Fog module Image class OpenStack class Real def create_image(attributes) data = { 'Content-Type' =>'application/octet-stream', 'x-image-meta-name' => attributes[:name], 'x-image-meta-disk-format' => attributes[:disk_format], 'x-image-meta-container-format' => attributes[:container_format], 'x-image-meta-size' => attributes[:size], 'x-image-meta-is-public' => attributes[:is_public], 'x-image-meta-min-ram' => attributes[:min_ram], 'x-image-meta-min-disk' => attributes[:min_disk], 'x-image-meta-checksum' => attributes[:checksum], 'x-image-meta-owner' => attributes[:owner], 'x-glance-api-copy-from' => attributes[:copy_from] }.reject {|k,v| v.nil? } body = String.new if attributes[:location] body = File.open(attributes[:location], "rb") # Make sure the image file size is always present data['x-image-meta-size'] = File.size(body) end unless attributes[:properties].nil? attributes[:properties].each do |key,value| data["x-image-meta-property-#{key}"] = value end end request( :headers => data, :body => body, :expects => 201, :method => 'POST', :path => "images" ) ensure body.close if body.respond_to?(:close) end end class Mock def create_image(attributes) response = Excon::Response.new response.status = 201 image_id = Fog::Mock.random_hex(32) image = self.data[:images][image_id] = { 'name' => attributes[:name], 'size' => attributes[:size] || Fog::Mock.random_numbers(8).to_i, 'min_disk' => attributes[:min_disk] || 0, 'disk_format' => attributes[:disk_format] || 'raw', 'created_at' => Time.now.strftime('%FT%T.%6N'), 'container_format' => attributes[:container_format] || 'bare', 'deleted_at' => nil, 'updated_at' => Time.now.strftime('%FT%T.%6N'), 'checksum' => attributes[:checksum] || Fog::Mock.random_hex(32), 'id' => image_id, 'deleted' => false, 'protected' => false, 'is_public' => attributes[:is_public].to_s == 'true', 'status' => 'queued', 'min_ram' => attributes[:min_ram] || 0, 'owner' => attributes[:owner], 'properties' => attributes[:properties] || {} } response.body = { 'image'=> image } response end end end end end fog-1.19.0/lib/fog/openstack/requests/image/set_tenant.rb0000644000004100000410000000057712261242552023355 0ustar www-datawww-datamodule Fog module Image class OpenStack class Real def set_tenant(tenant) @openstack_must_reauthenticate = true @openstack_tenant = tenant.to_s authenticate end end class Mock def set_tenant(tenant) true end end end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/requests/image/get_image_members.rb0000644000004100000410000000141512261242552024634 0ustar www-datawww-datamodule Fog module Image class OpenStack class Real def get_image_members(image_id) request( :expects => [200, 204], :method => 'GET', :path => "images/#{image_id}/members" ) end end # class Real class Mock def get_image_members(image_id) response = Excon::Response.new response.status = [200, 204][rand(1)] response.body = { "members"=>[ {"member_id"=>"ff528b20431645ebb5fa4b0a71ca002f", "can_share"=>false} ] } response end # def list_tenants end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/image/get_shared_images.rb0000644000004100000410000000142412261242552024633 0ustar www-datawww-datamodule Fog module Image class OpenStack class Real def get_shared_images(tenant_id) request( :expects => [200, 204], :method => 'GET', :path => "shared-images/#{tenant_id}" ) end end # class Real class Mock def get_shared_images(tenant_id) response = Excon::Response.new response.status = [200, 204][rand(1)] response.body = { "shared_images"=>[ {"image_id"=>"ff528b20431645ebb5fa4b0a71ca002f", "can_share"=>false} ] } response end # def list_tenants end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/image/update_image_members.rb0000644000004100000410000000213612261242552025340 0ustar www-datawww-datamodule Fog module Image class OpenStack class Real def update_image_members(image_id, members) # Sample members # [ # {'member_id' => 'tenant1', 'can_share' => true }, # {'member_id' => 'tenant2', 'can_share' => false } # ] data = { 'memberships' => members } request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'PUT', :path => "images/#{image_id}/members" ) end end # class Real class Mock def update_image_members(image_id, members) response = Excon::Response.new response.status = [200, 202][rand(1)] response.body = { 'members' => [ { 'member_id'=>'ff528b20431645ebb5fa4b0a71ca002f', 'can_share' => false }, { 'member_id'=>'ff528b20431645ebb5fa4b0a71ca002f', 'can_share' => true } ] } response end end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/image/remove_member_from_image.rb0000644000004100000410000000116412261242552026213 0ustar www-datawww-datamodule Fog module Image class OpenStack class Real def remove_member_from_image(image_id, member_id) request( :expects => [200, 204], :method => 'DELETE', :path => "images/#{image_id}/members/#{member_id}" ) end end # class Real class Mock def remove_member_from_image(image_id, member_id) response = Excon::Response.new response.status = [200, 204][rand(1)] response end # def list_tenants end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/image/get_image.rb0000644000004100000410000000424512261242552023126 0ustar www-datawww-datamodule Fog module Image class OpenStack class Real def get_image(image_id) request( :expects => [200, 204], :method => 'HEAD', :path => "images/#{image_id}" ) end end # class Real class Mock def get_image(image_id) response = Excon::Response.new response.status = [200, 204][rand(1)] response.headers= {"X-Image-Meta-Is_public"=>"True", "X-Image-Meta-Min_disk"=>"0", "X-Image-Meta-Property-Ramdisk_id"=>"b45aa128-cd36-4ad9-a026-1a1c2bfd8fdc", "X-Image-Meta-Disk_format"=>"ami", "X-Image-Meta-Created_at"=>"2012-02-21T07:32:26", "X-Image-Meta-Container_format"=>"ami", "Etag"=>"2f81976cae15c16ef0010c51e3a6c163", "Location"=>"http://192.168.27.100:9292/v1/images/0e09fbd6-43c5-448a-83e9-0d3d05f9747e", "X-Image-Meta-Protected"=>"False", "Date"=>"Fri, 24 Feb 2012 02:14:25 GMT", "X-Image-Meta-Name"=>"cirros-0.3.0-x86_64-blank", "X-Image-Meta-Min_ram"=>"0", "Content-Type"=>"text/html; charset=UTF-8", "X-Image-Meta-Updated_at"=>"2012-02-21T07:32:29", "X-Image-Meta-Property-Kernel_id"=>"cd28951e-e1c2-4bc5-95d3-f0495abbcdc5", "X-Image-Meta-Size"=>"25165824", "X-Image-Meta-Checksum"=>"2f81976cae15c16ef0010c51e3a6c163", "X-Image-Meta-Deleted"=>"False", "Content-Length"=>"0", "X-Image-Meta-Owner"=>"ff528b20431645ebb5fa4b0a71ca002f", "X-Image-Meta-Status"=>"active", "X-Image-Meta-Id"=>"0e09fbd6-43c5-448a-83e9-0d3d05f9747e"} response.body = "" response end # def list_tenants end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/image/delete_image.rb0000644000004100000410000000070112261242552023602 0ustar www-datawww-datamodule Fog module Image class OpenStack class Real def delete_image(image_id) request( :expects => 200, :method => 'DELETE', :path => "images/#{image_id}" ) end end class Mock def delete_image(image_id) response = Excon::Response.new response.status = 200 response end end end end end fog-1.19.0/lib/fog/openstack/requests/image/add_member_to_image.rb0000644000004100000410000000114712261242552025126 0ustar www-datawww-datamodule Fog module Image class OpenStack class Real def add_member_to_image(image_id, tenant_id) request( :expects => [200, 204], :method => 'PUT', :path => "images/#{image_id}/members/#{tenant_id}" ) end end # class Real class Mock def add_member_to_image(image_id, tenant_id) response = Excon::Response.new response.status = [200, 204][rand(1)] response end # def list_tenants end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/requests/image/update_image.rb0000644000004100000410000000477312261242552023637 0ustar www-datawww-datamodule Fog module Image class OpenStack class Real def update_image(attributes) data = { 'x-image-meta-name' => attributes[:name], 'x-image-meta-disk-format' => attributes[:disk_format], 'x-image-meta-container-format' => attributes[:container_format], 'x-image-meta-size' => attributes[:size], 'x-image-meta-is-public' => attributes[:is_public], 'x-image-meta-min-ram' => attributes[:min_ram], 'x-image-meta-min-disk' => attributes[:min_disk], 'x-image-meta-checksum' => attributes[:checksum], 'x-image-meta-owner' => attributes[:owner] }.reject {|k,v| v.nil? } unless attributes[:properties].nil? attributes[:properties].each do |key,value| data["x-image-meta-property-#{key}"] = value end end request( :headers => data, :expects => 200, :method => 'PUT', :path => "images/#{attributes[:id]}" ) end end class Mock def update_image(attributes) response = Excon::Response.new response.status = 200 image = self.images.last response.body = { 'image'=> { 'name' => attributes[:name] || image.name, 'size' => image.size, 'min_disk' => (attributes[:min_disk] || image.min_disk).to_i, 'disk_format' => attributes[:disk_format] || image.disk_format, 'created_at' => image.created_at, 'container_format' => attributes[:container_format] || image.container_format, 'deleted_at' => nil, 'updated_at' => Time.now.to_s, 'checksum' => image.checksum, 'id' => attributes[:id], 'deleted' => false, 'protected' => false, 'is_public' => attributes[:is_public] || image.is_public, 'status' => image.status, 'min_ram' => (attributes[:min_ram] || image.min_ram).to_i, 'owner' => attributes[:owner] || image.owner, 'properties' => attributes[:properties] || image.properties } } response end end end end end fog-1.19.0/lib/fog/openstack/requests/image/list_public_images.rb0000644000004100000410000000166712261242552025050 0ustar www-datawww-datamodule Fog module Image class OpenStack class Real def list_public_images request( :expects => [200, 204], :method => 'GET', :path => 'images' ) end end # class Real class Mock def list_public_images response = Excon::Response.new response.status = [200, 204][rand(1)] response.body = { "images"=>[{ "name" => Fog::Mock.random_letters(10), "size" => Fog::Mock.random_numbers(8).to_i, "disk_format" => "iso", "container_format" => "bare", "id" => Fog::Mock.random_hex(36), "checksum" => Fog::Mock.random_hex(32)}] } response end # def list_tenants end # class Mock end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/network.rb0000644000004100000410000002606212261242552017742 0ustar www-datawww-datarequire 'fog/openstack' module Fog module Network class OpenStack < Fog::Service SUPPORTED_VERSIONS = /v2(\.0)*/ requires :openstack_auth_url recognizes :openstack_auth_token, :openstack_management_url, :persistent, :openstack_service_type, :openstack_service_name, :openstack_tenant, :openstack_api_key, :openstack_username, :openstack_endpoint_type, :current_user, :current_tenant, :openstack_region ## MODELS # model_path 'fog/openstack/models/network' model :network collection :networks model :port collection :ports model :subnet collection :subnets model :floating_ip collection :floating_ips model :router collection :routers model :lb_pool collection :lb_pools model :lb_member collection :lb_members model :lb_health_monitor collection :lb_health_monitors model :lb_vip collection :lb_vips ## REQUESTS # request_path 'fog/openstack/requests/network' # Network CRUD request :list_networks request :create_network request :delete_network request :get_network request :update_network # Port CRUD request :list_ports request :create_port request :delete_port request :get_port request :update_port # Subnet CRUD request :list_subnets request :create_subnet request :delete_subnet request :get_subnet request :update_subnet # FloatingIp CRUD request :list_floating_ips request :create_floating_ip request :delete_floating_ip request :get_floating_ip request :associate_floating_ip request :disassociate_floating_ip # Router CRUD request :list_routers request :create_router request :delete_router request :get_router request :update_router request :add_router_interface request :remove_router_interface # LBaaS Pool CRUD request :list_lb_pools request :create_lb_pool request :delete_lb_pool request :get_lb_pool request :get_lb_pool_stats request :update_lb_pool # LBaaS Member CRUD request :list_lb_members request :create_lb_member request :delete_lb_member request :get_lb_member request :update_lb_member # LBaaS Health Monitor CRUD request :list_lb_health_monitors request :create_lb_health_monitor request :delete_lb_health_monitor request :get_lb_health_monitor request :update_lb_health_monitor request :associate_lb_health_monitor request :disassociate_lb_health_monitor # LBaaS VIP CRUD request :list_lb_vips request :create_lb_vip request :delete_lb_vip request :get_lb_vip request :update_lb_vip # Tenant request :set_tenant # Quota request :get_quotas request :get_quota request :update_quota request :delete_quota class Mock def self.data @data ||= Hash.new do |hash, key| network_id = Fog::UUID.uuid subnet_id = Fog::UUID.uuid tenant_id = Fog::Mock.random_hex(8) hash[key] = { :networks => { network_id => { 'id' => network_id, 'name' => 'Public', 'subnets' => [subnet_id], 'shared' => true, 'status' => 'ACTIVE', 'tenant_id' => tenant_id, 'provider_network_type' => 'vlan', 'router:external' => false, 'admin_state_up' => true, } }, :ports => {}, :subnets => { subnet_id => { 'id' => subnet_id, 'name' => "Public", 'network_id' => network_id, 'cidr' => "192.168.0.0/22", 'ip_version' => 4, 'gateway_ip' => Fog::Mock.random_ip, 'allocation_pools' => [], 'dns_nameservers' => [Fog::Mock.random_ip, Fog::Mock.random_ip], 'host_routes' => [Fog::Mock.random_ip], 'enable_dhcp' => true, 'tenant_id' => tenant_id, } }, :floating_ips => {}, :routers => {}, :lb_pools => {}, :lb_members => {}, :lb_health_monitors => {}, :lb_vips => {}, :quota => { "subnet" => 10, "router" => 10, "port" => 50, "network" => 10, "floatingip" => 50 }, :quotas => [ { "subnet" => 10, "network" => 10, "floatingip" => 50, "tenant_id" => tenant_id, "router" => 10, "port" => 30 } ], } end end def self.reset @data = nil end def initialize(options={}) @openstack_username = options[:openstack_username] @openstack_tenant = options[:openstack_tenant] end def data self.class.data["#{@openstack_username}-#{@openstack_tenant}"] end def reset_data self.class.data.delete("#{@openstack_username}-#{@openstack_tenant}") end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url } end end class Real attr_reader :current_user attr_reader :current_tenant def initialize(options={}) @openstack_auth_token = options[:openstack_auth_token] unless @openstack_auth_token missing_credentials = Array.new @openstack_api_key = options[:openstack_api_key] @openstack_username = options[:openstack_username] missing_credentials << :openstack_api_key unless @openstack_api_key missing_credentials << :openstack_username unless @openstack_username raise ArgumentError, "Missing required arguments: #{missing_credentials.join(', ')}" unless missing_credentials.empty? end @openstack_tenant = options[:openstack_tenant] @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @openstack_management_url = options[:openstack_management_url] @openstack_must_reauthenticate = false @openstack_service_type = options[:openstack_service_type] || ['network'] @openstack_service_name = options[:openstack_service_name] @openstack_endpoint_type = options[:openstack_endpoint_type] || 'publicURL' @openstack_region = options[:openstack_region] @connection_options = options[:connection_options] || {} @current_user = options[:current_user] @current_tenant = options[:current_tenant] authenticate @persistent = options[:persistent] || false @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url, :current_user => @current_user, :current_tenant => @current_tenant, :openstack_region => @openstack_region } end def reload @connection.reset end def request(params) begin response = @connection.request(params.merge({ :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Auth-Token' => @auth_token }.merge!(params[:headers] || {}), :path => "#{@path}/#{params[:path]}"#, })) rescue Excon::Errors::Unauthorized => error if error.response.body != 'Bad username or password' # token expiration @openstack_must_reauthenticate = true authenticate retry else # bad credentials raise error end rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Network::OpenStack::NotFound.slurp(error) else error end end unless response.body.empty? response.body = Fog::JSON.decode(response.body) end response end private def authenticate if @openstack_must_reauthenticate || @openstack_auth_token.nil? options = { :openstack_tenant => @openstack_tenant, :openstack_api_key => @openstack_api_key, :openstack_username => @openstack_username, :openstack_auth_uri => @openstack_auth_uri, :openstack_auth_token => @openstack_auth_token, :openstack_service_type => @openstack_service_type, :openstack_service_name => @openstack_service_name, :openstack_endpoint_type => @openstack_endpoint_type, :openstack_region => @openstack_region } credentials = Fog::OpenStack.authenticate_v2(options, @connection_options) @current_user = credentials[:user] @current_tenant = credentials[:tenant] @openstack_must_reauthenticate = false @auth_token = credentials[:token] @openstack_management_url = credentials[:server_management_url] uri = URI.parse(@openstack_management_url) else @auth_token = @openstack_auth_token uri = URI.parse(@openstack_management_url) end @host = uri.host @path = uri.path @path.sub!(/\/$/, '') unless @path.match(SUPPORTED_VERSIONS) @path = "/" + Fog::OpenStack.get_supported_version(SUPPORTED_VERSIONS, uri, @auth_token, @connection_options) end @port = uri.port @scheme = uri.scheme true end end end end end fog-1.19.0/lib/fog/openstack/metering.rb0000644000004100000410000001621212261242552020057 0ustar www-datawww-datarequire 'fog/metering' require 'fog/openstack' module Fog module Metering class OpenStack < Fog::Service requires :openstack_auth_url recognizes :openstack_auth_token, :openstack_management_url, :persistent, :openstack_service_type, :openstack_service_name, :openstack_tenant, :openstack_api_key, :openstack_username, :current_user, :current_tenant, :openstack_endpoint_type model_path 'fog/openstack/models/metering' model :resource collection :resources request_path 'fog/openstack/requests/metering' # Metering request :get_resource request :get_samples request :get_statistics request :list_meters request :list_resources class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = { :users => {}, :tenants => {} } end end def self.reset @data = nil end def initialize(options={}) @openstack_username = options[:openstack_username] @openstack_tenant = options[:openstack_tenant] @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @auth_token = Fog::Mock.random_base64(64) @auth_token_expiration = (Time.now.utc + 86400).iso8601 management_url = URI.parse(options[:openstack_auth_url]) management_url.port = 8776 management_url.path = '/v1' @openstack_management_url = management_url.to_s @data ||= { :users => {} } unless @data[:users].find {|u| u['name'] == options[:openstack_username]} id = Fog::Mock.random_numbers(6).to_s @data[:users][id] = { 'id' => id, 'name' => options[:openstack_username], 'email' => "#{options[:openstack_username]}@mock.com", 'tenantId' => Fog::Mock.random_numbers(6).to_s, 'enabled' => true } end end def data self.class.data[@openstack_username] end def reset_data self.class.data.delete(@openstack_username) end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url } end end class Real attr_reader :current_user attr_reader :current_tenant def initialize(options={}) @openstack_auth_token = options[:openstack_auth_token] unless @openstack_auth_token missing_credentials = Array.new @openstack_api_key = options[:openstack_api_key] @openstack_username = options[:openstack_username] missing_credentials << :openstack_api_key unless @openstack_api_key missing_credentials << :openstack_username unless @openstack_username raise ArgumentError, "Missing required arguments: #{missing_credentials.join(', ')}" unless missing_credentials.empty? end @openstack_tenant = options[:openstack_tenant] @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @openstack_management_url = options[:openstack_management_url] @openstack_must_reauthenticate = false @openstack_service_type = options[:openstack_service_type] || ['metering'] @openstack_service_name = options[:openstack_service_name] @openstack_endpoint_type = options[:openstack_endpoint_type] || 'adminURL' @connection_options = options[:connection_options] || {} @current_user = options[:current_user] @current_tenant = options[:current_tenant] authenticate @persistent = options[:persistent] || false @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url, :current_user => @current_user, :current_tenant => @current_tenant } end def reload @connection.reset end def request(params) begin response = @connection.request(params.merge({ :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Auth-Token' => @auth_token }.merge!(params[:headers] || {}), :path => "#{@path}/v2/#{params[:path]}"#, # Causes errors for some requests like tenants?limit=1 # :query => ('ignore_awful_caching' << Time.now.to_i.to_s) })) rescue Excon::Errors::Unauthorized => error if error.response.body != 'Bad username or password' # token expiration @openstack_must_reauthenticate = true authenticate retry else # bad credentials raise error end rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Compute::OpenStack::NotFound.slurp(error) else error end end unless response.body.empty? response.body = Fog::JSON.decode(response.body) end response end private def authenticate if !@openstack_management_url || @openstack_must_reauthenticate options = { :openstack_tenant => @openstack_tenant, :openstack_api_key => @openstack_api_key, :openstack_username => @openstack_username, :openstack_auth_uri => @openstack_auth_uri, :openstack_auth_token => @openstack_auth_token, :openstack_service_type => @openstack_service_type, :openstack_service_name => @openstack_service_name, :openstack_endpoint_type => @openstack_endpoint_type } credentials = Fog::OpenStack.authenticate_v2(options, @connection_options) @current_user = credentials[:user] @current_tenant = credentials[:tenant] @openstack_must_reauthenticate = false @auth_token = credentials[:token] @openstack_management_url = credentials[:server_management_url] uri = URI.parse(@openstack_management_url) else @auth_token = @openstack_auth_token uri = URI.parse(@openstack_management_url) end @host = uri.host @path = uri.path @path.sub!(/\/$/, '') @port = uri.port @scheme = uri.scheme true end end end end end fog-1.19.0/lib/fog/openstack/models/0000755000004100000410000000000012261242552017201 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/models/orchestration/0000755000004100000410000000000012261242552022065 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/models/orchestration/stacks.rb0000644000004100000410000000071012261242552023700 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/orchestration/stack' module Fog module Orchestration class OpenStack class Stacks < Fog::Collection model Fog::Orchestration::OpenStack::Stack def all load(service.list_stacks.body['stacks']) end def find_by_id(id) self.find {|stack| stack.id == id} end alias_method :get, :find_by_id end end end end fog-1.19.0/lib/fog/openstack/models/orchestration/stack.rb0000644000004100000410000000221612261242552023520 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Orchestration class OpenStack class Stack < Fog::Model identity :id attribute :stack_name attribute :stack_status attribute :stack_status_reason attribute :creation_time attribute :updated_time attribute :id attribute :template_url attribute :template attribute :parameters attribute :timeout_in_minutes def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def save requires :stack_name identity ? update : create end def create requires :stack_name service.create_stack(stack_name, self.attributes) self end def update requires :stack_name service.update_stack(stack_name, self.attributes) self end def destroy requires :id service.delete_stack(self.stack_name, self.id) true end end end end end fog-1.19.0/lib/fog/openstack/models/network/0000755000004100000410000000000012261242552020672 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/models/network/lb_pools.rb0000644000004100000410000000127612261242552023036 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/network/lb_pool' module Fog module Network class OpenStack class LbPools < Fog::Collection attribute :filters model Fog::Network::OpenStack::LbPool def initialize(attributes) self.filters ||= {} super end def all(filters = filters) self.filters = filters load(service.list_lb_pools(filters).body['pools']) end def get(pool_id) if pool = service.get_lb_pool(pool_id).body['pool'] new(pool) end rescue Fog::Network::OpenStack::NotFound nil end end end end endfog-1.19.0/lib/fog/openstack/models/network/lb_health_monitor.rb0000644000004100000410000000356012261242552024714 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Network class OpenStack class LbHealthMonitor < Fog::Model identity :id attribute :type attribute :delay attribute :timeout attribute :max_retries attribute :http_method attribute :url_path attribute :expected_codes attribute :status attribute :admin_state_up attribute :tenant_id def initialize(attributes) prepare_service_value(attributes) super end def save requires :type, :delay, :timeout, :max_retries identity ? update : create end def create requires :type, :delay, :timeout, :max_retries merge_attributes(service.create_lb_health_monitor(self.type, self.delay, self.timeout, self.max_retries, self.attributes).body['health_monitor']) self end def update requires :id, :type, :delay, :timeout, :max_retries merge_attributes(service.update_lb_health_monitor(self.id, self.attributes).body['health_monitor']) self end def destroy requires :id service.delete_lb_health_monitor(self.id) true end def associate_to_pool(pool_id) requires :id service.associate_lb_health_monitor(pool_id, self.id) true end def disassociate_from_pool(pool_id) requires :id service.disassociate_lb_health_monitor(pool_id, self.id) true end end end end endfog-1.19.0/lib/fog/openstack/models/network/router.rb0000644000004100000410000000265412261242552022546 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Network class OpenStack # The Layer-3 Networking Extensions (router) # # A logical entity for forwarding packets across internal # subnets and NATting them on external networks through # an appropriate external gateway. # # @see http://docs.openstack.org/api/openstack-network/2.0/content/router_ext.html class Router < Fog::Model identity :id attribute :name attribute :admin_state_up attribute :tenant_id attribute :external_gateway_info attribute :status def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def save requires :name identity ? update : create end def create requires :name merge_attributes(service.create_router(self.name, self.attributes).body['router']) self end def update requires :id merge_attributes(service.update_router(self.id, self.attributes).body['router']) self end def destroy requires :id service.delete_router(self.id) true end end end end end fog-1.19.0/lib/fog/openstack/models/network/lb_member.rb0000644000004100000410000000263612261242552023152 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Network class OpenStack class LbMember < Fog::Model identity :id attribute :pool_id attribute :address attribute :protocol_port attribute :weight attribute :status attribute :admin_state_up attribute :tenant_id def initialize(attributes) prepare_service_value(attributes) super end def save requires :pool_id, :address, :protocol_port, :weight identity ? update : create end def create requires :pool_id, :address, :protocol_port, :weight merge_attributes(service.create_lb_member(self.pool_id, self.address, self.protocol_port, self.weight, self.attributes).body['member']) self end def update requires :id, :pool_id, :address, :protocol_port, :weight merge_attributes(service.update_lb_member(self.id, self.attributes).body['member']) self end def destroy requires :id service.delete_lb_member(self.id) true end end end end endfog-1.19.0/lib/fog/openstack/models/network/floating_ip.rb0000644000004100000410000000172112261242552023513 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Network class OpenStack class FloatingIp < Fog::Model identity :id attribute :floating_network_id attribute :port_id attribute :tenant_id attribute :fixed_ip_address attribute :floating_ip_address def initialize(attributes) @connection = attributes[:connection] super end def save requires :floating_network_id identity ? update : create end def create requires :floating_network_id merge_attributes(service.create_floating_ip(self.floating_network_id, self.attributes).body['floatingip']) self end def update self end def destroy requires :id service.delete_floating_ip(self.id) true end end end end end fog-1.19.0/lib/fog/openstack/models/network/lb_health_monitors.rb0000644000004100000410000000145212261242552025075 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/network/lb_health_monitor' module Fog module Network class OpenStack class LbHealthMonitors < Fog::Collection attribute :filters model Fog::Network::OpenStack::LbHealthMonitor def initialize(attributes) self.filters ||= {} super end def all(filters = filters) self.filters = filters load(service.list_lb_health_monitors(filters).body['health_monitors']) end def get(health_monitor_id) if health_monitor = service.get_lb_health_monitor(health_monitor_id).body['health_monitor'] new(health_monitor) end rescue Fog::Network::OpenStack::NotFound nil end end end end endfog-1.19.0/lib/fog/openstack/models/network/subnets.rb0000644000004100000410000000131012261242552022675 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/network/subnet' module Fog module Network class OpenStack class Subnets < Fog::Collection attribute :filters model Fog::Network::OpenStack::Subnet def initialize(attributes) self.filters ||= {} super end def all(filters = filters) self.filters = filters load(service.list_subnets(filters).body['subnets']) end def get(subnet_id) if subnet = service.get_subnet(subnet_id).body['subnet'] new(subnet) end rescue Fog::Network::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/network/network.rb0000644000004100000410000000262712261242552022717 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Network class OpenStack class Network < Fog::Model identity :id attribute :name attribute :subnets attribute :shared attribute :status attribute :admin_state_up attribute :tenant_id attribute :provider_network_type, :aliases => 'provider:network_type' attribute :provider_physical_network, :aliases => 'provider:physical_network' attribute :provider_segmentation_id, :aliases => 'provider:segmentation_id' attribute :router_external, :aliases => 'router:external' def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def save identity ? update : create end def create merge_attributes(service.create_network(self.attributes).body['network']) self end def update requires :id merge_attributes(service.update_network(self.id, self.attributes).body['network']) self end def destroy requires :id service.delete_network(self.id) true end end end end end fog-1.19.0/lib/fog/openstack/models/network/routers.rb0000644000004100000410000000131012261242552022715 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/network/router' module Fog module Network class OpenStack class Routers < Fog::Collection attribute :filters model Fog::Network::OpenStack::Router def initialize(attributes) self.filters ||= {} super end def all(filters = filters) self.filters = filters load(service.list_routers(filters).body['routers']) end def get(router_id) if router = service.get_router(router_id).body['router'] new(router) end rescue Fog::Network::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/network/subnet.rb0000644000004100000410000000273412261242552022525 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Network class OpenStack class Subnet < Fog::Model identity :id attribute :name attribute :network_id attribute :cidr attribute :ip_version attribute :gateway_ip attribute :allocation_pools attribute :dns_nameservers attribute :host_routes attribute :enable_dhcp attribute :tenant_id def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def save requires :network_id, :cidr, :ip_version identity ? update : create end def create requires :network_id, :cidr, :ip_version merge_attributes(service.create_subnet(self.network_id, self.cidr, self.ip_version, self.attributes).body['subnet']) self end def update requires :id, :network_id, :cidr, :ip_version merge_attributes(service.update_subnet(self.id, self.attributes).body['subnet']) self end def destroy requires :id service.delete_subnet(self.id) true end end end end end fog-1.19.0/lib/fog/openstack/models/network/lb_vips.rb0000644000004100000410000000126312261242552022657 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/network/lb_vip' module Fog module Network class OpenStack class LbVips < Fog::Collection attribute :filters model Fog::Network::OpenStack::LbVip def initialize(attributes) self.filters ||= {} super end def all(filters = filters) self.filters = filters load(service.list_lb_vips(filters).body['vips']) end def get(vip_id) if vip = service.get_lb_vip(vip_id).body['vip'] new(vip) end rescue Fog::Network::OpenStack::NotFound nil end end end end endfog-1.19.0/lib/fog/openstack/models/network/floating_ips.rb0000644000004100000410000000141012261242552023671 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/network/floating_ip' module Fog module Network class OpenStack class FloatingIps < Fog::Collection attribute :filters model Fog::Network::OpenStack::FloatingIp def initialize(attributes) self.filters ||= {} super end def all(filters = filters) self.filters = filters load(service.list_floating_ips(filters).body['floatingips']) end def get(floating_network_id) if floating_ip = connection.get_floating_ip(floating_network_id).body['floatingip'] new(floating_ip) end rescue Fog::Network::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/network/port.rb0000644000004100000410000000235012261242552022203 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Network class OpenStack class Port < Fog::Model identity :id attribute :name attribute :network_id attribute :fixed_ips attribute :mac_address attribute :status attribute :admin_state_up attribute :device_owner attribute :device_id attribute :tenant_id def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def save requires :network_id identity ? update : create end def create requires :network_id merge_attributes(service.create_port(self.network_id, self.attributes).body['port']) self end def update requires :id, :network_id merge_attributes(service.update_port(self.id, self.attributes).body['port']) self end def destroy requires :id service.delete_port(self.id) true end end end end end fog-1.19.0/lib/fog/openstack/models/network/lb_members.rb0000644000004100000410000000132412261242552023326 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/network/lb_member' module Fog module Network class OpenStack class LbMembers < Fog::Collection attribute :filters model Fog::Network::OpenStack::LbMember def initialize(attributes) self.filters ||= {} super end def all(filters = filters) self.filters = filters load(service.list_lb_members(filters).body['members']) end def get(member_id) if member = service.get_lb_member(member_id).body['member'] new(member) end rescue Fog::Network::OpenStack::NotFound nil end end end end endfog-1.19.0/lib/fog/openstack/models/network/ports.rb0000644000004100000410000000126212261242552022367 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/network/port' module Fog module Network class OpenStack class Ports < Fog::Collection attribute :filters model Fog::Network::OpenStack::Port def initialize(attributes) self.filters ||= {} super end def all(filters = filters) self.filters = filters load(service.list_ports(filters).body['ports']) end def get(port_id) if port = service.get_port(port_id).body['port'] new(port) end rescue Fog::Network::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/network/lb_vip.rb0000644000004100000410000000311212261242552022467 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Network class OpenStack class LbVip < Fog::Model identity :id attribute :subnet_id attribute :pool_id attribute :protocol attribute :protocol_port attribute :name attribute :description attribute :address attribute :port_id attribute :session_persistence attribute :connection_limit attribute :status attribute :admin_state_up attribute :tenant_id def initialize(attributes) prepare_service_value(attributes) super end def save requires :subnet_id, :pool_id, :protocol, :protocol_port identity ? update : create end def create requires :subnet_id, :pool_id, :protocol, :protocol_port merge_attributes(service.create_lb_vip(self.subnet_id, self.pool_id, self.protocol, self.protocol_port, self.attributes).body['vip']) self end def update requires :id, :subnet_id, :pool_id, :protocol, :protocol_port merge_attributes(service.update_lb_vip(self.id, self.attributes).body['vip']) self end def destroy requires :id service.delete_lb_vip(self.id) true end end end end end fog-1.19.0/lib/fog/openstack/models/network/lb_pool.rb0000644000004100000410000000404512261242552022650 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Network class OpenStack class LbPool < Fog::Model identity :id attribute :subnet_id attribute :protocol attribute :lb_method attribute :name attribute :description attribute :health_monitors attribute :members attribute :status attribute :admin_state_up attribute :vip_id attribute :tenant_id attribute :active_connections attribute :bytes_in attribute :bytes_out attribute :total_connections def initialize(attributes) prepare_service_value(attributes) super end def save requires :subnet_id, :protocol, :lb_method identity ? update : create end def create requires :subnet_id, :protocol, :lb_method merge_attributes(service.create_lb_pool(self.subnet_id, self.protocol, self.lb_method, self.attributes).body['pool']) self end def update requires :id, :subnet_id, :protocol, :lb_method merge_attributes(service.update_lb_pool(self.id, self.attributes).body['pool']) self end def destroy requires :id service.delete_lb_pool(self.id) true end def stats requires :id merge_attributes(service.get_lb_pool_stats(self.id).body['stats']) self end def associate_health_monitor(health_monitor_id) requires :id service.associate_lb_health_monitor(self.id, health_monitor_id) true end def disassociate_health_monitor(health_monitor_id) requires :id service.disassociate_lb_health_monitor(self.id, health_monitor_id) true end end end end end fog-1.19.0/lib/fog/openstack/models/network/networks.rb0000644000004100000410000000132312261242552023072 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/network/network' module Fog module Network class OpenStack class Networks < Fog::Collection attribute :filters model Fog::Network::OpenStack::Network def initialize(attributes) self.filters ||= {} super end def all(filters = filters) self.filters = filters load(service.list_networks(filters).body['networks']) end def get(network_id) if network = service.get_network(network_id).body['network'] new(network) end rescue Fog::Network::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/storage/0000755000004100000410000000000012261242552020645 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/models/storage/directory.rb0000644000004100000410000000173212261242552023201 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/openstack/models/storage/files' module Fog module Storage class OpenStack class Directory < Fog::Model identity :key, :aliases => 'name' attribute :bytes, :aliases => 'X-Container-Bytes-Used' attribute :count, :aliases => 'X-Container-Object-Count' def destroy requires :key service.delete_container(key) true rescue Excon::Errors::NotFound false end def files @files ||= begin Fog::Storage::OpenStack::Files.new( :directory => self, :service => service ) end end def public=(new_public) @public = new_public end def public_url raise NotImplementedError end def save requires :key service.put_container(key) true end end end end end fog-1.19.0/lib/fog/openstack/models/storage/files.rb0000644000004100000410000000512512261242552022277 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/storage/file' module Fog module Storage class OpenStack class Files < Fog::Collection attribute :directory attribute :limit attribute :marker attribute :path attribute :prefix model Fog::Storage::OpenStack::File 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 alias :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 def get(key, &block) requires :directory data = service.get_object(directory.key, key, &block) file_data = data.headers.merge({ :body => data.body, :key => key }) new(file_data) rescue Fog::Storage::OpenStack::NotFound nil end def get_url(key) requires :directory if self.directory.public_url "#{self.directory.public_url}/#{Fog::OpenStack.escape(key, '/')}" end end def get_http_url(key, expires, options = {}) requires :directory service.get_object_http_url(directory.key, key, expires, options) end def get_https_url(key, expires, options = {}) requires :directory service.get_object_https_url(directory.key, key, expires, options) end 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::OpenStack::NotFound nil end def new(attributes = {}) requires :directory super({ :directory => directory }.merge!(attributes)) end end end end end fog-1.19.0/lib/fog/openstack/models/storage/directories.rb0000644000004100000410000000175112261242552023512 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/storage/directory' module Fog module Storage class OpenStack class Directories < Fog::Collection model Fog::Storage::OpenStack::Directory def all data = service.get_containers.body load(data) end def get(key, options = {}) data = service.get_container(key, options) directory = new(:key => key) 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.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::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/storage/file.rb0000644000004100000410000001170612261242552022116 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Storage class OpenStack class File < Fog::Model identity :key, :aliases => 'name' attribute :content_length, :aliases => ['bytes', 'Content-Length'], :type => :integer attribute :content_type, :aliases => ['content_type', 'Content-Type'] attribute :content_disposition, :aliases => ['content_disposition', 'Content-Disposition'] attribute :etag, :aliases => ['hash', 'Etag'] attribute :last_modified, :aliases => ['last_modified', 'Last-Modified'], :type => :time attribute :access_control_allow_origin, :aliases => ['Access-Control-Allow-Origin'] attribute :origin, :aliases => ['Origin'] def body attributes[:body] ||= if last_modified collection.get(identity).body else '' end end def body=(new_body) attributes[:body] = new_body end def directory @directory end 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 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 def destroy requires :directory, :key service.delete_object(directory.key, key) true end def metadata @metadata ||= headers_to_metadata end def owner=(new_owner) if new_owner attributes[:owner] = { :display_name => new_owner['DisplayName'], :id => new_owner['ID'] } end end def public=(new_public) new_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 # def url(expires, options = {}) requires :directory, :key self.service.create_temp_url(directory.key, key, expires, "GET", options) end def public_url requires :key self.collection.get_url(self.key) end def save(options = {}) requires :body, :directory, :key options['Content-Type'] = content_type if content_type options['Content-Disposition'] = content_disposition if content_disposition options['Access-Control-Allow-Origin'] = access_control_allow_origin if access_control_allow_origin options['Origin'] = origin if origin options.merge!(metadata_to_headers) data = service.put_object(directory.key, key, body, options) update_attributes_from(data) refresh_metadata self.content_length = Fog::Storage.get_body_size(body) self.content_type ||= Fog::Storage.get_content_type(body) true end private def directory=(new_directory) @directory = new_directory end def refresh_metadata metadata.reject! {|k, v| v.nil? } end def headers_to_metadata key_map = key_mapping Hash[metadata_attributes.map {|k, v| [key_map[k], v] }] end def key_mapping key_map = metadata_attributes key_map.each_pair {|k, v| key_map[k] = header_to_key(k)} end def header_to_key(opt) opt.gsub(metadata_prefix, '').split('-').map {|k| k[0, 1].downcase + k[1..-1]}.join('_').to_sym end def metadata_to_headers header_map = header_mapping Hash[metadata.map {|k, v| [header_map[k], v] }] end def header_mapping header_map = metadata.dup header_map.each_pair {|k, v| header_map[k] = key_to_header(k)} end def key_to_header(key) metadata_prefix + key.to_s.split(/[-_]/).map(&:capitalize).join('-') end def metadata_attributes if last_modified headers = service.head_object(directory.key, self.key).headers headers.reject! {|k, v| !metadata_attribute?(k)} else {} end end def metadata_attribute?(key) key.to_s =~ /^#{metadata_prefix}/ end def metadata_prefix "X-Object-Meta-" end def update_attributes_from(data) merge_attributes(data.headers.reject {|key, value| ['Content-Length', 'Content-Type'].include?(key)}) end end end end end fog-1.19.0/lib/fog/openstack/models/volume/0000755000004100000410000000000012261242552020510 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/models/volume/volume.rb0000644000004100000410000000236612261242552022353 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Volume class OpenStack class Volume < Fog::Model identity :id attribute :display_name, :aliases => 'displayName' attribute :display_description, :aliases => 'displayDescription' attribute :status attribute :size attribute :volume_type, :aliases => ['volumeType', 'type'] attribute :snapshot_id, :aliases => 'snapshotId' attribute :imageRef, :aliases => 'image_id' attribute :availability_zone, :aliases => 'availabilityZone' attribute :created_at, :aliases => 'createdAt' attribute :attachments attribute :source_volid def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def save requires :display_name, :size data = service.create_volume(display_name, display_description, size, attributes) merge_attributes(data.body['volume']) true end def destroy requires :id service.delete_volume(id) true end end end end end fog-1.19.0/lib/fog/openstack/models/volume/volume_types.rb0000644000004100000410000000124412261242552023571 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/volume/volume_type' module Fog module Volume class OpenStack class VolumeTypes < Fog::Collection model Fog::Volume::OpenStack::VolumeType def all(options = {}) response = service.list_volume_types(options) load(response.body['volume_types']) end def get(volume_type_id) if volume_type = service.get_volume_type_details(volume_type_id).body['volume_type'] new(volume_type) end rescue Fog::Volume::OpenStack::NotFound nil end alias_method :find_by_id, :get end end end end fog-1.19.0/lib/fog/openstack/models/volume/volumes.rb0000644000004100000410000000145512261242552022534 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/volume/volume' module Fog module Volume class OpenStack class Volumes < Fog::Collection model Fog::Volume::OpenStack::Volume def all(options = {:detailed => true}) # the parameter has been "detailed = true" before. Make sure we are # backwards compatible detailed = options.is_a?(Hash) ? options.delete(:detailed) : options load(service.list_volumes(detailed, options).body['volumes']) end def get(volume_id) if volume = service.get_volume_details(volume_id).body['volume'] new(volume) end rescue Fog::Volume::OpenStack::NotFound nil end alias_method :find_by_id, :get end end end end fog-1.19.0/lib/fog/openstack/models/volume/volume_type.rb0000644000004100000410000000063012261242552023404 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Volume class OpenStack class VolumeType < Fog::Model identity :id attribute :name attribute :volume_backend_name def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end end end end end fog-1.19.0/lib/fog/openstack/models/metering/0000755000004100000410000000000012261242552021013 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/models/metering/meter.rb0000644000004100000410000000000012261242552022442 0ustar www-datawww-datafog-1.19.0/lib/fog/openstack/models/metering/meters.rb0000644000004100000410000000000012261242552022625 0ustar www-datawww-datafog-1.19.0/lib/fog/openstack/models/metering/resources.rb0000644000004100000410000000102512261242552023350 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/metering/resource' module Fog module Metering class OpenStack class Resources < Fog::Collection model Fog::Metering::OpenStack::Resource def all(detailed=true) load(service.list_resources.body) end def find_by_id(resource_id) resource = service.get_resource(resource_id).body new(resource) rescue Fog::Metering::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/metering/resource.rb0000644000004100000410000000055512261242552023174 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Metering class OpenStack class Resource < Fog::Model identity :resource_id attribute :project_id attribute :user_id attribute :metadata def initialize(attributes) prepare_service_value(attributes) super end end end end end fog-1.19.0/lib/fog/openstack/models/identity/0000755000004100000410000000000012261242552021032 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/models/identity/ec2_credential.rb0000644000004100000410000000201312261242552024216 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Identity class OpenStack class Ec2Credential < Fog::Model identity :access, :aliases => 'access_key' attribute :secret, :aliases => 'secret_key' attribute :tenant_id attribute :user_id def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def destroy requires :access requires :user_id service.delete_ec2_credential user_id, access true end def save raise Fog::Errors::Error, 'Existing credentials cannot be altered' if access self.user_id ||= user.id self.tenant_id ||= user.tenant_id requires :user_id, :tenant_id data = service.create_ec2_credential user_id, tenant_id merge_attributes(data.body['credential']) true end end end end end fog-1.19.0/lib/fog/openstack/models/identity/roles.rb0000644000004100000410000000065112261242552022505 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/identity/role' module Fog module Identity class OpenStack class Roles < Fog::Collection model Fog::Identity::OpenStack::Role def all load(service.list_roles.body['roles']) end def get(id) service.get_role(id) end end end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/models/identity/role.rb0000644000004100000410000000223412261242552022321 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Identity class OpenStack class Role < Fog::Model identity :id attribute :name def save requires :name data = service.create_role(name) merge_attributes(data.body['role']) true end def destroy requires :id service.delete_role(id) true end def add_to_user(user, tenant) add_remove_to_user(user, tenant, :add) end def remove_to_user(user, tenant) add_remove_to_user(user, tenant, :remove) end private def add_remove_to_user(user, tenant, ops) requires :id user_id = get_id(user) tenant_id = get_id(tenant) case ops when :add service.create_user_role(tenant_id, user_id, id).status == 200 when :remove service.delete_user_role(tenant_id, user_id, id).status == 204 end end def get_id(_) _.is_a?(String) ? _ : _.id end end # class Role end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/models/identity/user.rb0000644000004100000410000000367612261242552022351 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Identity class OpenStack class User < Fog::Model identity :id attribute :email attribute :enabled attribute :name attribute :tenant_id, :aliases => 'tenantId' attribute :password attr_accessor :email, :name, :tenant_id, :enabled, :password def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def ec2_credentials requires :id service.ec2_credentials(:user => self) end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :name, :tenant_id, :password enabled = true if enabled.nil? data = service.create_user(name, password, email, tenant_id, enabled) merge_attributes(data.body['user']) true end def update(options = {}) requires :id options.merge('id' => id) response = service.update_user(id, options) true end def update_password(password) update({'password' => password, 'url' => "/users/#{id}/OS-KSADM/password"}) end def update_tenant(tenant) tenant = tenant.id if tenant.class != String update({:tenantId => tenant, 'url' => "/users/#{id}/OS-KSADM/tenant"}) end def update_enabled(enabled) update({:enabled => enabled, 'url' => "/users/#{id}/OS-KSADM/enabled"}) end def destroy requires :id service.delete_user(id) true end def roles(tenant_id = self.tenant_id) service.list_roles_for_user_on_tenant(tenant_id, self.id).body['roles'] end end # class User end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/models/identity/ec2_credentials.rb0000644000004100000410000000252412261242552024410 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/identity/ec2_credential' module Fog module Identity class OpenStack class Ec2Credentials < Fog::Collection model Fog::Identity::OpenStack::Ec2Credential attribute :user def all user_id = user ? user.id : nil ec2_credentials = service.list_ec2_credentials(user_id) load(ec2_credentials.body['credentials']) end def create(attributes = {}) if user then attributes[:user_id] ||= user.id attributes[:tenant_id] ||= user.tenant_id end super attributes end def destroy(access_key) ec2_credential = self.find_by_access_key(access_key) ec2_credential.destroy end def find_by_access_key(access_key) user_id = user ? user.id : nil ec2_credential = self.find { |ec2_credential| ec2_credential.access == access_key } unless ec2_credential then response = service.get_ec2_credential(user_id, access_key) body = response.body['credential'] body = body.merge 'service' => service ec2_credential = Fog::Identity::OpenStack::EC2Credential.new(body) end ec2_credential end end end end end fog-1.19.0/lib/fog/openstack/models/identity/users.rb0000644000004100000410000000140712261242552022522 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/identity/user' module Fog module Identity class OpenStack class Users < Fog::Collection model Fog::Identity::OpenStack::User attribute :tenant_id def all load(service.list_users(tenant_id).body['users']) end def find_by_id(id) self.find {|user| user.id == id} || Fog::Identity::OpenStack::User.new( service.get_user_by_id(id).body['user'].merge( 'service' => service ) ) end def destroy(id) user = self.find_by_id(id) user.destroy end end # class Users end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/models/identity/tenant.rb0000644000004100000410000000252012261242552022647 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Identity class OpenStack class Tenant < Fog::Model identity :id attribute :description attribute :enabled attribute :name def to_s self.name end def roles_for(user) service.roles( :tenant => self, :user => user) end def users requires :id service.users(:tenant_id => self.id) end def destroy requires :id service.delete_tenant(self.id) true end def update(attr = nil) requires :id merge_attributes( service.update_tenant(self.id, attr || attributes).body['tenant']) self end def save requires :name identity ? update : create end def create merge_attributes( service.create_tenant(attributes).body['tenant']) self end def grant_user_role(user_id, role_id) service.add_user_to_tenant(self.id, user_id, role_id) end def revoke_user_role(user_id, role_id) service.remove_user_from_tenant(self.id, user_id, role_id) end end # class Tenant end # class OpenStack end # module Identity end # module Fog fog-1.19.0/lib/fog/openstack/models/identity/tenants.rb0000644000004100000410000000144012261242552023032 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/identity/tenant' module Fog module Identity class OpenStack class Tenants < Fog::Collection model Fog::Identity::OpenStack::Tenant def all load(service.list_tenants.body['tenants']) end def find_by_id(id) cached_tenant = self.find {|tenant| tenant.id == id} return cached_tenant if cached_tenant tenant_hash = service.get_tenant(id).body['tenant'] Fog::Identity::OpenStack::Tenant.new( tenant_hash.merge(:service => service)) end def destroy(id) tenant = self.find_by_id(id) tenant.destroy end end # class Tenants end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/models/compute/0000755000004100000410000000000012261242552020655 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/models/compute/address.rb0000644000004100000410000000314612261242552022633 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class OpenStack class Address < Fog::Model identity :id attribute :ip attribute :pool attribute :fixed_ip attribute :instance_id def initialize(attributes = {}) # assign server first to prevent race condition with persisted? self.server = attributes.delete(:server) super end def destroy requires :id service.release_address(id) true end def server=(new_server) if new_server associate(new_server) else disassociate end end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? data = service.allocate_address(pool).body['floating_ip'] new_attributes = data.reject {|key,value| !['id', 'instance_id', 'ip', 'fixed_ip'].include?(key)} merge_attributes(new_attributes) if @server self.server = @server end true end private def associate(new_server) unless persisted? @server = new_server else @server = nil self.instance_id = new_server.id service.associate_address(instance_id, ip) end end def disassociate @server = nil if persisted? service.disassociate_address(instance_id, ip) end self.instance_id = nil end end end end end fog-1.19.0/lib/fog/openstack/models/compute/addresses.rb0000644000004100000410000000122712261242552023161 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/compute/address' module Fog module Compute class OpenStack class Addresses < Fog::Collection model Fog::Compute::OpenStack::Address def all load(service.list_all_addresses.body['floating_ips']) end def get(address_id) if address = service.get_address(address_id).body['floating_ip'] new(address) end rescue Fog::Compute::OpenStack::NotFound nil end def get_address_pools service.list_address_pools.body['floating_ip_pools'] end end end end end fog-1.19.0/lib/fog/openstack/models/compute/security_group_rules.rb0000644000004100000410000000106412261242552025500 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/compute/security_group_rule' module Fog module Compute class OpenStack class SecurityGroupRules < Fog::Collection model Fog::Compute::OpenStack::SecurityGroupRule def get(security_group_rule_id) if security_group_rule_id body = service.get_security_group_rule(security_group_rule_id).body new(body['security_group_rule']) end rescue Fog::Compute::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/compute/volume.rb0000644000004100000410000000307012261242552022511 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/openstack/models/compute/metadata' module Fog module Compute class OpenStack class Volume < Fog::Model identity :id attribute :name, :aliases => 'displayName' attribute :description, :aliases => 'displayDescription' attribute :status attribute :size attribute :type, :aliases => 'volumeType' attribute :snapshot_id, :aliases => 'snapshotId' attribute :availability_zone, :aliases => 'availabilityZone' attribute :created_at, :aliases => 'createdAt' attribute :attachments def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def save requires :name, :description, :size data = service.create_volume(name, description, size, attributes) merge_attributes(data.body['volume']) true end def destroy requires :id service.delete_volume(id) true end def attach(server_id, name) requires :id data = service.attach_volume(id, server_id, name) merge_attributes(:attachments => attachments << data.body['volumeAttachment']) true end def detach(server_id, attachment_id) requires :id service.detach_volume(server_id, attachment_id) true end end end end end fog-1.19.0/lib/fog/openstack/models/compute/images.rb0000644000004100000410000000156312261242552022454 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/compute/image' module Fog module Compute class OpenStack class Images < Fog::Collection attribute :filters model Fog::Compute::OpenStack::Image attribute :server def initialize(attributes) self.filters ||= {} super end def all(filters = filters) self.filters = filters data = service.list_images_detail(filters).body['images'] images = load(data) if server self.replace(self.select {|image| image.server_id == server.id}) end images end def get(image_id) data = service.get_image_details(image_id).body['image'] new(data) rescue Fog::Compute::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/compute/security_group.rb0000644000004100000410000000377312261242552024277 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class OpenStack class SecurityGroup < Fog::Model identity :id attribute :name attribute :description attribute :security_group_rules, :aliases => "rules" attribute :tenant_id def security_group_rules Fog::Compute::OpenStack::SecurityGroupRules.new(:service => service).load(attributes[:security_group_rules]) end def rules Fog::Logger.deprecation('#rules is deprecated. Use #security_group_rules instead') attributes[:security_group_rules] end # no one should be calling this because it doesn't do anything # useful but we deprecated the rules attribute and need to maintain the API def rules=(new_rules) Fog::Logger.deprecation('#rules= is deprecated. Use the Fog::Compute::Openstack::SecurityGroupRules collection to create new rules.') attributes[:security_group_rules] = new_rules end def save requires :name, :description data = service.create_security_group(name, description) merge_attributes(data.body['security_group']) true end def destroy requires :id service.delete_security_group(id) true end def create_security_group_rule(min, max, ip_protocol = "tcp", cidr = "0.0.0.0/0", group_id = nil) Fog::Logger.deprecation('#create_security_group_rule is deprecated. Use the Fog::Compute::Openstack::SecurityGroupRules collection to create new rules.') requires :id service.create_security_group_rule(id, ip_protocol, min, max, cidr, group_id) end def delete_security_group_rule(rule_id) Fog::Logger.deprecation('#create_security_group_rule is deprecated. Use the Fog::Compute::Openstack::SecurityGroupRule objects to destroy rules.') service.delete_security_group_rule(rule_id) true end end end end end fog-1.19.0/lib/fog/openstack/models/compute/metadatum.rb0000644000004100000410000000110012261242552023153 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/openstack/models/meta_parent' module Fog module Compute class OpenStack class Metadatum < Fog::Model include Fog::Compute::OpenStack::MetaParent identity :key attribute :value def destroy requires :identity service.delete_meta(collection_name, @parent.id, key) true end def save requires :identity, :value service.update_meta(collection_name, @parent.id, key, value) true end end end end end fog-1.19.0/lib/fog/openstack/models/compute/servers.rb0000644000004100000410000000167412261242552022703 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/compute/server' module Fog module Compute class OpenStack class Servers < Fog::Collection attribute :filters model Fog::Compute::OpenStack::Server def initialize(attributes) self.filters ||= {} super end def all(filters = filters) self.filters = filters data = service.list_servers_detail(filters).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::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/compute/key_pairs.rb0000644000004100000410000000121412261242552023166 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/compute/key_pair' module Fog module Compute class OpenStack class KeyPairs < Fog::Collection model Fog::Compute::OpenStack::KeyPair def all items = Array.new service.list_key_pairs.body['keypairs'].each do |kp| items = items + kp.values end load(items) end def get(key_pair_name) if key_pair_name self.all.select {|kp| kp.name == key_pair_name}.first end rescue Fog::Compute::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/compute/security_groups.rb0000644000004100000410000000113212261242552024445 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/compute/security_group' module Fog module Compute class OpenStack class SecurityGroups < Fog::Collection model Fog::Compute::OpenStack::SecurityGroup def all load(service.list_security_groups.body['security_groups']) end def get(security_group_id) if security_group_id new(service.get_security_group(security_group_id).body['security_group']) end rescue Fog::Compute::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/compute/metadata.rb0000644000004100000410000000345312261242552022767 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/meta_parent' require 'fog/openstack/models/compute/metadatum' require 'fog/openstack/models/compute/image' require 'fog/openstack/models/compute/server' module Fog module Compute class OpenStack class Metadata < Fog::Collection model Fog::Compute::OpenStack::Metadatum include Fog::Compute::OpenStack::MetaParent def all requires :parent metadata = service.list_metadata(collection_name, @parent.id).body['metadata'] metas = [] metadata.each_pair {|k,v| metas << {"key" => k, "value" => v} } unless metadata.nil? load(metas) end def get(key) requires :parent data = service.get_metadata(collection_name, @parent.id, key).body["meta"] metas = [] data.each_pair {|k,v| metas << {"key" => k, "value" => v} } new(metas[0]) rescue Fog::Compute::OpenStack::NotFound nil end def update(data=nil) requires :parent service.update_metadata(collection_name, @parent.id, to_hash(data)) end def set(data=nil) requires :parent service.set_metadata(collection_name, @parent.id, to_hash(data)) end def new(attributes = {}) requires :parent super({ :parent => @parent }.merge!(attributes)) end def to_hash(data=nil) if data.nil? data={} self.each do |meta| if meta.is_a?(Fog::Compute::OpenStack::Metadatum) then data.store(meta.key, meta.value) else data.store(meta["key"], meta["value"]) end end end data end end end end end fog-1.19.0/lib/fog/openstack/models/compute/network.rb0000644000004100000410000000042212261242552022671 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class OpenStack class Network < Fog::Model identity :id attribute :name attribute :addresses end # class Network end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/models/compute/snapshot.rb0000644000004100000410000000205312261242552023041 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/openstack/models/compute/metadata' module Fog module Compute class OpenStack class Snapshot < Fog::Model identity :id attribute :name, :aliases => 'displayName' attribute :description, :aliases => 'displayDescription' attribute :volume_id, :aliases => 'volumeId' attribute :status attribute :size attribute :created_at, :aliases => 'createdAt' def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def save(force=false) requires :volume_id, :name, :description data = service.create_volume_snapshot(volume_id, name, description, force) merge_attributes(data.body['snapshot']) true end def destroy requires :id service.delete_snapshot(id) true end end end end end fog-1.19.0/lib/fog/openstack/models/compute/hosts.rb0000644000004100000410000000116212261242552022342 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/compute/host' module Fog module Compute class OpenStack class Hosts < Fog::Collection model Fog::Compute::OpenStack::Host def all data = service.list_hosts.body['hosts'] load(data) end def get(host_name) if host = service.get_host_details(host_name).body['host'] new({ 'host_name' => host_name, 'details' => host} ) end rescue Fog::Compute::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/compute/flavors.rb0000644000004100000410000000107012261242552022654 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/compute/flavor' module Fog module Compute class OpenStack class Flavors < Fog::Collection model Fog::Compute::OpenStack::Flavor def all(options = {}) data = service.list_flavors_detail(options).body['flavors'] load(data) end def get(flavor_id) data = service.get_flavor_details(flavor_id).body['flavor'] new(data) rescue Fog::Compute::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/compute/key_pair.rb0000644000004100000410000000256012261242552023010 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class OpenStack class KeyPair < Fog::Model identity :name attribute :fingerprint attribute :public_key attribute :private_key attribute :user_id attribute :id attr_accessor :public_key def destroy requires :name service.delete_key_pair(name) true end def save requires :name data = if public_key service.create_key_pair(name, public_key).body['keypair'] else service.create_key_pair(name).body['keypair'] end new_attributes = data.reject {|key,value| !['fingerprint', 'public_key', 'name', 'private_key', 'user_id'].include?(key)} merge_attributes(new_attributes) true end def write(path="#{ENV['HOME']}/.ssh/fog_#{Fog.credential.to_s}_#{name}.pem") if writable? split_private_key = private_key.split(/\n/) File.open(path, "w") do |f| split_private_key.each {|line| f.puts line} f.chmod 0600 end "Key file built: #{path}" else "Invalid private key" end end def writable? !!(private_key && ENV.has_key?('HOME')) end end end end end fog-1.19.0/lib/fog/openstack/models/compute/host.rb0000644000004100000410000000132112261242552022154 0ustar www-datawww-datarequire 'fog/compute/models/server' require 'fog/openstack/models/compute/metadata' module Fog module Compute class OpenStack class Host < Fog::Model attribute :host_name attribute :service_name attribute :details attribute :zone def initialize(attributes) attributes["service_name"] = attributes.delete "service" # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def details service.get_host_details(self.host_name).body['host'] rescue Fog::Compute::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/compute/volumes.rb0000644000004100000410000000106212261242552022673 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/compute/volume' module Fog module Compute class OpenStack class Volumes < Fog::Collection model Fog::Compute::OpenStack::Volume def all(detailed=true) load(service.list_volumes(detailed).body['volumes']) end def get(volume_id) if volume = service.get_volume_details(volume_id).body['volume'] new(volume) end rescue Fog::Compute::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/compute/security_group_rule.rb0000644000004100000410000000145412261242552025320 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class OpenStack class SecurityGroupRule < Fog::Model identity :id attribute :from_port attribute :group attribute :ip_protocol attribute :to_port attribute :parent_group_id attribute :ip_range def save requires :ip_protocol, :from_port, :to_port, :parent_group_id cidr = ip_range && ip_range["cidr"] if rule = service.create_security_group_rule(parent_group_id, ip_protocol, from_port, to_port, cidr, group).data[:body] merge_attributes(rule["security_group_rule"]) end end def destroy requires :id service.delete_security_group_rule(id) true end end end end end fog-1.19.0/lib/fog/openstack/models/compute/flavor.rb0000644000004100000410000000241112261242552022471 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class OpenStack class Flavor < Fog::Model identity :id attribute :name attribute :ram attribute :disk attribute :vcpus attribute :links attribute :swap attribute :rxtx_factor attribute :ephemeral, :aliases => 'OS-FLV-EXT-DATA:ephemeral' attribute :is_public, :aliases => 'os-flavor-access:is_public' attribute :disabled, :aliases => 'OS-FLV-DISABLED:disabled' def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def save requires :name, :ram, :vcpus, :disk attributes[:ephemeral] = self.ephemeral || 0 attributes[:is_public] = self.is_public || false attributes[:disabled] = self.disabled || false attributes[:swap] = self.swap || 0 attributes[:rxtx_factor] = self.rxtx_factor || 1.0 merge_attributes(service.create_flavor(self.attributes).body['flavor']) self end def destroy requires :id service.delete_flavor(self.id) true end end end end end fog-1.19.0/lib/fog/openstack/models/compute/tenant.rb0000644000004100000410000000077312261242552022502 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class OpenStack class Tenant < Fog::Model identity :id attribute :description attribute :enabled attribute :name def to_s self.name end def usage(start_date, end_date) requires :id service.get_usage(self.id, start_date, end_date).body['tenant_usage'] end end # class Tenant end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/models/compute/tenants.rb0000644000004100000410000000117412261242552022661 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/compute/tenant' module Fog module Compute class OpenStack class Tenants < Fog::Collection model Fog::Compute::OpenStack::Tenant def all load(service.list_tenants.body['tenants']) end def usages(start_date = nil, end_date = nil, details = false) service.list_usages(start_date, end_date, details).body['tenant_usages'] end def find_by_id(id) self.find {|tenant| tenant.id == id} end end # class Tenants end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/models/compute/snapshots.rb0000644000004100000410000000111012261242552023215 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/compute/snapshot' module Fog module Compute class OpenStack class Snapshots < Fog::Collection model Fog::Compute::OpenStack::Snapshot def all(detailed=true) load(service.list_snapshots(detailed).body['snapshots']) end def get(snapshot_id) if snapshot = service.get_snapshot_details(snapshot_id).body['snapshot'] new(snapshot) end rescue Fog::Compute::OpenStack::NotFound nil end end end end end fog-1.19.0/lib/fog/openstack/models/compute/server.rb0000644000004100000410000002235012261242552022512 0ustar www-datawww-datarequire 'fog/compute/models/server' require 'fog/openstack/models/compute/metadata' module Fog module Compute class OpenStack class Server < Fog::Compute::Server identity :id attribute :instance_name, :aliases => 'OS-EXT-SRV-ATTR:instance_name' attribute :addresses attribute :flavor attribute :host_id, :aliases => 'hostId' attribute :image attribute :metadata attribute :links attribute :name attribute :personality attribute :progress attribute :accessIPv4 attribute :accessIPv6 attribute :availability_zone, :aliases => 'OS-EXT-AZ:availability_zone' attribute :user_data_encoded attribute :state, :aliases => 'status' attribute :created, :type => :time attribute :updated, :type => :time attribute :tenant_id attribute :user_id attribute :key_name attribute :fault attribute :config_drive attribute :os_dcf_disk_config, :aliases => 'OS-DCF:diskConfig' attribute :os_ext_srv_attr_host, :aliases => 'OS-EXT-SRV-ATTR:host' attribute :os_ext_srv_attr_hypervisor_hostname, :aliases => 'OS-EXT-SRV-ATTR:hypervisor_hostname' attribute :os_ext_srv_attr_instance_name, :aliases => 'OS-EXT-SRV-ATTR:instance_name' attribute :os_ext_sts_power_state, :aliases => 'OS-EXT-STS:power_state' attribute :os_ext_sts_task_state, :aliases => 'OS-EXT-STS:task_state' attribute :os_ext_sts_vm_state, :aliases => 'OS-EXT-STS:vm_state' attr_reader :password attr_writer :image_ref, :flavor_ref, :nics, :os_scheduler_hints attr_accessor :block_device_mapping def initialize(attributes={}) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) self.security_groups = attributes.delete(:security_groups) self.min_count = attributes.delete(:min_count) self.max_count = attributes.delete(:max_count) self.nics = attributes.delete(:nics) self.os_scheduler_hints = attributes.delete(:os_scheduler_hints) self.block_device_mapping = attributes.delete(:block_device_mapping) super end def metadata @metadata ||= begin Fog::Compute::OpenStack::Metadata.new({ :service => service, :parent => self }) end end def metadata=(new_metadata={}) return unless new_metadata metas = [] new_metadata.each_pair {|k,v| metas << {"key" => k, "value" => v} } @metadata = metadata.load(metas) end def user_data=(ascii_userdata) self.user_data_encoded = [ascii_userdata].pack('m') end def destroy requires :id service.delete_server(id) true end def images requires :id service.images(:server => self) end def all_addresses # currently openstack API does not tell us what is a floating ip vs a fixed ip for the vm listing, # we fall back to get all addresses and filter sadly. @all_addresses ||= service.list_all_addresses.body["floating_ips"].select{|data| data['instance_id'] == id} end def reload @all_addresses = nil super end # returns all ip_addresses for a given instance # this includes both the fixed ip(s) and the floating ip(s) def ip_addresses addresses.values.flatten.map{|x| x['addr']} end def floating_ip_addresses all_addresses.map{|addr| addr["ip"]} end alias_method :public_ip_addresses, :floating_ip_addresses def floating_ip_address floating_ip_addresses.first end alias_method :public_ip_address, :floating_ip_address def private_ip_addresses ip_addresses - floating_ip_addresses end def private_ip_address private_ip_addresses.first end def image_ref @image_ref end def image_ref=(new_image_ref) @image_ref = new_image_ref end def flavor_ref @flavor_ref end def flavor_ref=(new_flavor_ref) @flavor_ref = new_flavor_ref end def ready? self.state == 'ACTIVE' end def change_password(admin_password) requires :id service.change_server_password(id, admin_password) true end def rebuild(image_ref, name, admin_pass=nil, metadata=nil, personality=nil) requires :id service.rebuild_server(id, image_ref, name, admin_pass, metadata, personality) true end def resize(flavor_ref) requires :id service.resize_server(id, flavor_ref) true end def revert_resize requires :id service.revert_resize_server(id) true end def confirm_resize requires :id service.confirm_resize_server(id) true end def security_groups requires :id groups = service.list_security_groups(id).body['security_groups'] groups.map do |group| sg = Fog::Compute::OpenStack::SecurityGroup.new group sg.connection = service sg end end def security_groups=(new_security_groups) @security_groups = new_security_groups end def reboot(type = 'SOFT') requires :id service.reboot_server(id, type) true end def create_image(name, metadata={}) requires :id service.create_image(id, name, metadata) end def console(log_length = nil) requires :id service.get_console_output(id, log_length) end def migrate requires :id service.migrate_server(id) end def live_migrate(host, block_migration, disk_over_commit) requires :id service.live_migrate_server(id, host, block_migration, disk_over_commit) end def associate_address(floating_ip) requires :id service.associate_address id, floating_ip end def disassociate_address(floating_ip) requires :id service.disassociate_address id, floating_ip end def reset_vm_state(vm_state) requires :id service.reset_server_state id, vm_state end def min_count=(new_min_count) @min_count = new_min_count end def max_count=(new_max_count) @max_count = new_max_count end def networks service.networks(:server => self) end def volumes requires :id service.volumes.find_all do |vol| vol.attachments.find { |attachment| attachment["serverId"] == id } end end def volume_attachments requires :id service.get_server_volumes(id).body['volumeAttachments'] end def attach_volume(volume_id, device_name) requires :id service.attach_volume(volume_id, id, device_name) true end def detach_volume(volume_id) requires :id service.detach_volume(id, volume_id) true end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :flavor_ref, :name requires_one :image_ref, :block_device_mapping options = { 'personality' => personality, 'accessIPv4' => accessIPv4, 'accessIPv6' => accessIPv6, 'availability_zone' => availability_zone, 'user_data' => user_data_encoded, 'key_name' => key_name, 'config_drive' => config_drive, 'security_groups' => @security_groups, 'min_count' => @min_count, 'max_count' => @max_count, 'nics' => @nics, 'os:scheduler_hints' => @os_scheduler_hints, 'block_device_mapping' => @block_device_mapping } options['metadata'] = metadata.to_hash unless @metadata.nil? options = options.reject {|key, value| value.nil?} data = service.create_server(name, image_ref, flavor_ref, options) merge_attributes(data.body['server']) true end def setup(credentials = {}) requires :public_ip_address, :identity, :public_key, :username Fog::SSH.new(public_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-1.19.0/lib/fog/openstack/models/compute/image.rb0000644000004100000410000000241612261242552022267 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/openstack/models/compute/metadata' module Fog module Compute class OpenStack class Image < Fog::Model identity :id attribute :name attribute :created_at, :aliases => 'created' attribute :updated_at, :aliases => 'updated' attribute :progress attribute :status attribute :minDisk attribute :minRam attribute :server, :aliases => 'server' attribute :metadata attribute :links def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def metadata @metadata ||= begin Fog::Compute::OpenStack::Metadata.new({ :service => service, :parent => self }) end end def metadata=(new_metadata={}) metas = [] new_metadata.each_pair {|k,v| metas << {"key" => k, "value" => v} } metadata.load(metas) end def destroy requires :id service.delete_image(id) true end def ready? status == 'ACTIVE' end end end end end fog-1.19.0/lib/fog/openstack/models/compute/networks.rb0000644000004100000410000000126412261242552023061 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/compute/network' module Fog module Compute class OpenStack class Networks < Fog::Collection model Fog::Compute::OpenStack::Network attribute :server def all requires :server networks = Array.new server.addresses.each_with_index do |address, index| networks << { :id => index + 1, :name => address[0], :addresses => address[1].map {|a| a['addr'] } } end load(networks) end end # class Networks end # class OpenStack end # module Compute end # module Fog fog-1.19.0/lib/fog/openstack/models/image/0000755000004100000410000000000012261242552020263 5ustar www-datawww-datafog-1.19.0/lib/fog/openstack/models/image/images.rb0000644000004100000410000000312112261242552022052 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openstack/models/image/image' module Fog module Image class OpenStack class Images < Fog::Collection model Fog::Image::OpenStack::Image def all load(service.list_public_images_detailed.body['images']) end def details load(service.list_public_images_detailed.body['images']) end def find_by_id(id) all.find {|image| image.id == id} end alias_method :get, :find_by_id def public images = load(service.list_public_images_detailed.body['images']) images.delete_if{|image| image.is_public == false} end def private images = load(service.list_public_images_detailed.body['images']) images.delete_if{|image| image.is_public} end def destroy(id) image = self.find_by_id(id) image.destroy end def method_missing(method_sym, *arguments, &block) if method_sym.to_s =~ /^find_by_(.*)$/ load(service.list_public_images_detailed($1 ,arguments.first).body['images']) else super end end def find_by_size_min(size) find_attribute(__method__, size) end def find_by_size_max(size) find_attribute(__method__, size) end def find_attribute(attribute,value) attribute = attribute.to_s.gsub("find_by_", "") load(service.list_public_images_detailed(attribute , value).body['images']) end end end end end fog-1.19.0/lib/fog/openstack/models/image/image.rb0000644000004100000410000000373612261242552021703 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Image class OpenStack class Image < Fog::Model identity :id attribute :name attribute :size attribute :disk_format attribute :container_format attribute :id attribute :checksum #detailed attribute :min_disk attribute :created_at attribute :deleted_at attribute :updated_at attribute :deleted attribute :protected attribute :is_public attribute :status attribute :min_ram attribute :owner attribute :properties attribute :location attribute :copy_from def initialize(attributes) # Old 'connection' is renamed as service and should be used instead prepare_service_value(attributes) super end def save requires :name identity ? update : create end def create requires :name merge_attributes(service.create_image(self.attributes).body['image']) self end def update requires :name merge_attributes(service.update_image(self.attributes).body['image']) self end def destroy requires :id service.delete_image(self.id) true end def add_member(member_id) requires :id service.add_member_to_image(self.id, member_id) end def remove_member(member_id) requires :id service.remove_member_from_image(self.id, member_id) end def update_members(members) requires :id service.update_image_members(self.id, members) end def members requires :id service.get_image_members(self.id).body['members'] end def metadata requires :id service.get_image(self.id).headers end end end end end fog-1.19.0/lib/fog/openstack/models/meta_parent.rb0000644000004100000410000000126512261242552022031 0ustar www-datawww-datamodule Fog module Compute class OpenStack module MetaParent def parent @parent end def parent=(new_parent) @parent = new_parent end def collection_name if @parent.class == Fog::Compute::OpenStack::Image return "images" elsif @parent.class == Fog::Compute::OpenStack::Server return "servers" else raise "Metadata is not supported for this model type." end end def metas_to_hash(metas) hash = {} metas.each { |meta| hash.store(meta.key, meta.value) } hash end end end end end fog-1.19.0/lib/fog/openstack/CHANGELOG.md0000644000004100000410000000251412261242552017531 0ustar www-datawww-data# 1.10.1 2013/04/04 ## Storage * Added storage (Swift) example to set account quotas: https://github.com/fog/fog/blob/master/lib/fog/openstack/examples/storage/set-account-quota.rb * Added account impersonation to the storage service Now it's possible to use an admin account with a reseller role to impersonate other accounts and set account metadata headers. See the account quotas example included in this release ## Network * create_network request updated Implements provider extensions when creating networks. See http://docs.openstack.org/trunk/openstack-network/admin/content/provider_attributes.html * Network Router support (Quantum) Added router model/collection and related requests. * New network service example See https://github.com/fog/fog/blob/master/lib/fog/openstack/examples/network/network_subnets_routers.rb * :openstack_endpoint_type parameter was added to the network service ## Image * Added basic image service example (Glance) Download CirrOS 0.3.0 image from launchpad (~6.5MB) to /tmp and upload it to Glance. See https://github.com/fog/fog/blob/master/lib/fog/openstack/examples/image/upload-test-image.rb * Check for glance version (fog only supports v1) ## Compute * create_server and the Server model where updated to allow booting a VM with NICs (net_id, port_id, fixed_ip). fog-1.19.0/lib/fog/openstack/image.rb0000644000004100000410000001733712261242552017340 0ustar www-datawww-datarequire 'fog/openstack' module Fog module Image class OpenStack < Fog::Service SUPPORTED_VERSIONS = /v1(\.(0|1))*/ requires :openstack_auth_url recognizes :openstack_auth_token, :openstack_management_url, :persistent, :openstack_service_type, :openstack_service_name, :openstack_tenant, :openstack_api_key, :openstack_username, :current_user, :current_tenant, :openstack_endpoint_type, :openstack_region model_path 'fog/openstack/models/image' model :image collection :images request_path 'fog/openstack/requests/image' request :list_public_images request :list_public_images_detailed request :get_image request :create_image request :update_image request :get_image_members request :update_image_members request :get_shared_images request :add_member_to_image request :remove_member_from_image request :delete_image request :get_image_by_id request :set_tenant class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = { :images => {} } end end def self.reset @data = nil end def initialize(options={}) @openstack_username = options[:openstack_username] @openstack_tenant = options[:openstack_tenant] @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @auth_token = Fog::Mock.random_base64(64) @auth_token_expiration = (Time.now.utc + 86400).iso8601 management_url = URI.parse(options[:openstack_auth_url]) management_url.port = 9292 management_url.path = '/v1' @openstack_management_url = management_url.to_s @data ||= { :users => {} } unless @data[:users].find {|u| u['name'] == options[:openstack_username]} id = Fog::Mock.random_numbers(6).to_s @data[:users][id] = { 'id' => id, 'name' => options[:openstack_username], 'email' => "#{options[:openstack_username]}@mock.com", 'tenantId' => Fog::Mock.random_numbers(6).to_s, 'enabled' => true } end end def data self.class.data[@openstack_username] end def reset_data self.class.data.delete(@openstack_username) end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_region => @openstack_region, :openstack_management_url => @openstack_management_url } end end class Real attr_reader :current_user attr_reader :current_tenant def initialize(options={}) @openstack_auth_token = options[:openstack_auth_token] unless @openstack_auth_token missing_credentials = Array.new @openstack_api_key = options[:openstack_api_key] @openstack_username = options[:openstack_username] missing_credentials << :openstack_api_key unless @openstack_api_key missing_credentials << :openstack_username unless @openstack_username raise ArgumentError, "Missing required arguments: #{missing_credentials.join(', ')}" unless missing_credentials.empty? end @openstack_tenant = options[:openstack_tenant] @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @openstack_management_url = options[:openstack_management_url] @openstack_must_reauthenticate = false @openstack_service_type = options[:openstack_service_type] || ['image'] @openstack_service_name = options[:openstack_service_name] @openstack_endpoint_type = options[:openstack_endpoint_type] || 'adminURL' @openstack_region = options[:openstack_region] @connection_options = options[:connection_options] || {} @current_user = options[:current_user] @current_tenant = options[:current_tenant] authenticate @persistent = options[:persistent] || false @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url, :current_user => @current_user, :current_tenant => @current_tenant } end def reload @connection.reset end def request(params) begin response = @connection.request(params.merge({ :headers => { 'Content-Type' => 'application/json', 'X-Auth-Token' => @auth_token }.merge!(params[:headers] || {}), :path => "#{@path}/#{params[:path]}"#, })) rescue Excon::Errors::Unauthorized => error if error.response.body != 'Bad username or password' # token expiration @openstack_must_reauthenticate = true authenticate retry else # bad credentials raise error end rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Compute::OpenStack::NotFound.slurp(error) else error end end unless response.body.empty? response.body = Fog::JSON.decode(response.body) end response end private def authenticate if !@openstack_management_url || @openstack_must_reauthenticate options = { :openstack_tenant => @openstack_tenant, :openstack_api_key => @openstack_api_key, :openstack_username => @openstack_username, :openstack_auth_uri => @openstack_auth_uri, :openstack_region => @openstack_region, :openstack_auth_token => @openstack_auth_token, :openstack_service_type => @openstack_service_type, :openstack_service_name => @openstack_service_name, :openstack_endpoint_type => @openstack_endpoint_type } credentials = Fog::OpenStack.authenticate_v2(options, @connection_options) @current_user = credentials[:user] @current_tenant = credentials[:tenant] @openstack_must_reauthenticate = false @auth_token = credentials[:token] @openstack_management_url = credentials[:server_management_url] uri = URI.parse(@openstack_management_url) else @auth_token = @openstack_auth_token uri = URI.parse(@openstack_management_url) end @host = uri.host @path = uri.path @path.sub!(/\/$/, '') unless @path.match(SUPPORTED_VERSIONS) @path = "/" + Fog::OpenStack.get_supported_version(SUPPORTED_VERSIONS, uri, @auth_token, @connection_options) end @port = uri.port @scheme = uri.scheme true end end end end end fog-1.19.0/lib/fog/openstack/compute.rb0000644000004100000410000003461612261242552017731 0ustar www-datawww-datarequire 'fog/compute' require 'fog/openstack' module Fog module Compute class OpenStack < Fog::Service requires :openstack_auth_url recognizes :openstack_auth_token, :openstack_management_url, :persistent, :openstack_service_type, :openstack_service_name, :openstack_tenant, :openstack_api_key, :openstack_username, :openstack_identity_endpoint, :current_user, :current_tenant, :openstack_region, :openstack_endpoint_type ## MODELS # model_path 'fog/openstack/models/compute' model :server collection :servers model :image collection :images model :flavor collection :flavors model :metadatum collection :metadata model :address collection :addresses model :security_group collection :security_groups model :security_group_rule collection :security_group_rules model :key_pair collection :key_pairs model :tenant collection :tenants model :volume collection :volumes model :network collection :networks model :snapshot collection :snapshots model :host collection :hosts ## REQUESTS # request_path 'fog/openstack/requests/compute' # Server CRUD request :list_servers request :list_servers_detail request :create_server request :get_server_details request :update_server request :delete_server # Server Actions request :server_actions request :server_action request :reboot_server request :rebuild_server request :resize_server request :confirm_resize_server request :revert_resize_server request :pause_server request :unpause_server request :suspend_server request :resume_server request :rescue_server request :change_server_password request :add_fixed_ip request :remove_fixed_ip request :server_diagnostics request :boot_from_snapshot request :reset_server_state # Server Extenstions request :get_console_output request :get_vnc_console request :live_migrate_server request :migrate_server # Image CRUD request :list_images request :list_images_detail request :create_image request :get_image_details request :delete_image # Flavor CRUD request :list_flavors request :list_flavors_detail request :get_flavor_details request :create_flavor request :delete_flavor # Flavor Access request :add_flavor_access request :remove_flavor_access request :list_tenants_with_flavor_access # Metadata request :list_metadata request :get_metadata request :set_metadata request :update_metadata request :delete_metadata # Metadatam request :delete_meta request :update_meta # Address request :list_addresses request :list_address_pools request :list_all_addresses request :list_private_addresses request :list_public_addresses request :get_address request :allocate_address request :associate_address request :release_address request :disassociate_address # Security Group request :list_security_groups request :get_security_group request :create_security_group request :create_security_group_rule request :delete_security_group request :delete_security_group_rule request :get_security_group_rule # Key Pair request :list_key_pairs request :create_key_pair request :delete_key_pair # Tenant request :list_tenants request :set_tenant request :get_limits # Volume request :list_volumes request :create_volume request :get_volume_details request :delete_volume request :attach_volume request :detach_volume request :get_server_volumes request :create_volume_snapshot request :list_snapshots request :get_snapshot_details request :delete_snapshot # Usage request :list_usages request :get_usage # Quota request :get_quota request :get_quota_defaults request :update_quota # Hosts request :list_hosts request :get_host_details class Mock attr_reader :auth_token attr_reader :auth_token_expiration attr_reader :current_user attr_reader :current_tenant def self.data @data ||= Hash.new do |hash, key| hash[key] = { :last_modified => { :images => {}, :servers => {}, :key_pairs => {}, :security_groups => {}, :addresses => {} }, :images => { "0e09fbd6-43c5-448a-83e9-0d3d05f9747e" => { "id"=>"0e09fbd6-43c5-448a-83e9-0d3d05f9747e", "name"=>"cirros-0.3.0-x86_64-blank", 'progress' => 100, 'status' => "ACTIVE", 'updated' => "", 'minRam' => 0, 'minDisk' => 0, 'metadata' => {}, 'links' => [{"href"=>"http://nova1:8774/v1.1/admin/images/1", "rel"=>"self"}, {"href"=>"http://nova1:8774/admin/images/2", "rel"=>"bookmark"}] } }, :servers => {}, :key_pairs => {}, :security_groups => { 0 => { "id" => 0, "tenant_id" => Fog::Mock.random_hex(8), "name" => "default", "description" => "default", "rules" => [ { "id" => 0, "parent_group_id" => 0, "from_port" => 68, "to_port" => 68, "ip_protocol" => "udp", "ip_range" => { "cidr" => "0.0.0.0/0" }, "group" => {}, }, ], }, }, :server_security_group_map => {}, :addresses => {}, :quota => { 'security_group_rules' => 20, 'security_groups' => 10, 'injected_file_content_bytes' => 10240, 'injected_file_path_bytes' => 256, 'injected_files' => 5, 'metadata_items' => 128, 'floating_ips' => 10, 'instances' => 10, 'key_pairs' => 10, 'gigabytes' => 5000, 'volumes' => 10, 'cores' => 20, 'ram' => 51200 }, :volumes => {} } end end def self.reset @data = nil end def initialize(options={}) @openstack_username = options[:openstack_username] @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @current_tenant = options[:openstack_tenant] @auth_token = Fog::Mock.random_base64(64) @auth_token_expiration = (Time.now.utc + 86400).iso8601 management_url = URI.parse(options[:openstack_auth_url]) management_url.port = 8774 management_url.path = '/v1.1/1' @openstack_management_url = management_url.to_s identity_public_endpoint = URI.parse(options[:openstack_auth_url]) identity_public_endpoint.port = 5000 @openstack_identity_public_endpoint = identity_public_endpoint.to_s end def data self.class.data["#{@openstack_username}-#{@current_tenant}"] end def reset_data self.class.data.delete("#{@openstack_username}-#{@current_tenant}") end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url, :openstack_identity_endpoint => @openstack_identity_public_endpoint } end end class Real attr_reader :auth_token attr_reader :auth_token_expiration attr_reader :current_user attr_reader :current_tenant def initialize(options={}) @openstack_auth_token = options[:openstack_auth_token] @auth_token = options[:openstack_auth_token] @openstack_identity_public_endpoint = options[:openstack_identity_endpoint] unless @auth_token missing_credentials = Array.new @openstack_api_key = options[:openstack_api_key] @openstack_username = options[:openstack_username] missing_credentials << :openstack_api_key unless @openstack_api_key missing_credentials << :openstack_username unless @openstack_username raise ArgumentError, "Missing required arguments: #{missing_credentials.join(', ')}" unless missing_credentials.empty? end @openstack_tenant = options[:openstack_tenant] @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @openstack_management_url = options[:openstack_management_url] @openstack_must_reauthenticate = false @openstack_service_type = options[:openstack_service_type] || ['nova', 'compute'] @openstack_service_name = options[:openstack_service_name] @openstack_identity_service_type = options[:openstack_identity_service_type] || 'identity' @openstack_endpoint_type = options[:openstack_endpoint_type] || 'publicURL' @openstack_region = options[:openstack_region] @connection_options = options[:connection_options] || {} @current_user = options[:current_user] @current_tenant = options[:current_tenant] authenticate @persistent = options[:persistent] || false @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url, :openstack_identity_endpoint => @openstack_identity_public_endpoint, :openstack_region => @openstack_region, :current_user => @current_user, :current_tenant => @current_tenant } end def reload @connection.reset end def request(params) begin response = @connection.request(params.merge({ :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Auth-Token' => @auth_token }.merge!(params[:headers] || {}), :path => "#{@path}/#{@tenant_id}/#{params[:path]}", :query => params[:query] })) rescue Excon::Errors::Unauthorized => error if error.response.body != 'Bad username or password' # token expiration @openstack_must_reauthenticate = true authenticate retry else # Bad Credentials raise error end rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Compute::OpenStack::NotFound.slurp(error) else error end end if !response.body.empty? and response.get_header('Content-Type') == 'application/json' response.body = Fog::JSON.decode(response.body) end response end private def authenticate if !@openstack_management_url || @openstack_must_reauthenticate options = { :openstack_api_key => @openstack_api_key, :openstack_username => @openstack_username, :openstack_auth_token => @auth_token, :openstack_auth_uri => @openstack_auth_uri, :openstack_region => @openstack_region, :openstack_tenant => @openstack_tenant, :openstack_service_type => @openstack_service_type, :openstack_service_name => @openstack_service_name, :openstack_identity_service_type => @openstack_identity_service_type, :openstack_endpoint_type => @openstack_endpoint_type } if @openstack_auth_uri.path =~ /\/v2.0\// credentials = Fog::OpenStack.authenticate_v2(options, @connection_options) else credentials = Fog::OpenStack.authenticate_v1(options, @connection_options) end @current_user = credentials[:user] @current_tenant = credentials[:tenant] @openstack_must_reauthenticate = false @auth_token = credentials[:token] @auth_token_expiration = credentials[:expires] @openstack_management_url = credentials[:server_management_url] @openstack_identity_public_endpoint = credentials[:identity_public_endpoint] end uri = URI.parse(@openstack_management_url) @host = uri.host @path, @tenant_id = uri.path.scan(/(\/.*)\/(.*)/).flatten @path.sub!(/\/$/, '') unless @path.match(/1\.1|v2/) raise Fog::OpenStack::Errors::ServiceUnavailable.new( "OpenStack binding only supports version 2 (a.k.a. 1.1)") end @port = uri.port @scheme = uri.scheme # Not all implementations have identity service in the catalog if @openstack_identity_public_endpoint || @openstack_management_url @identity_connection = Fog::Connection.new( @openstack_identity_public_endpoint || @openstack_management_url, false, @connection_options) end true end end end end end fog-1.19.0/lib/fog/openstack/storage.rb0000644000004100000410000001631512261242552017715 0ustar www-datawww-datarequire 'fog/openstack' require 'fog/storage' module Fog module Storage class OpenStack < Fog::Service requires :openstack_auth_url, :openstack_username, :openstack_api_key recognizes :persistent, :openstack_service_name, :openstack_service_type, :openstack_tenant, :openstack_region, :openstack_temp_url_key model_path 'fog/openstack/models/storage' model :directory collection :directories model :file collection :files request_path 'fog/openstack/requests/storage' request :copy_object request :delete_container request :delete_object request :delete_multiple_objects request :delete_static_large_object request :get_container request :get_containers request :get_object request :get_object_http_url request :get_object_https_url request :head_container request :head_containers request :head_object request :put_container request :put_object request :put_object_manifest request :put_dynamic_obj_manifest request :put_static_obj_manifest request :post_set_meta_temp_url_key class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = {} end end def self.reset @data = nil end def initialize(options={}) @openstack_api_key = options[:openstack_api_key] @openstack_username = options[:openstack_username] @path = '/v1/AUTH_1234' end def data self.class.data[@openstack_username] end def reset_data self.class.data.delete(@openstack_username) end def change_account(account) @original_path ||= @path version_string = @original_path.split('/')[1] @path = "/#{version_string}/#{account}" end def reset_account_name @path = @original_path end end class Real def initialize(options={}) @openstack_api_key = options[:openstack_api_key] @openstack_username = options[:openstack_username] @openstack_auth_url = options[:openstack_auth_url] @openstack_auth_token = options[:openstack_auth_token] @openstack_storage_url = options[:openstack_storage_url] @openstack_must_reauthenticate = false @openstack_service_type = options[:openstack_service_type] || 'object-store' @openstack_service_name = options[:openstack_service_name] @openstack_region = options[:openstack_region] @openstack_tenant = options[:openstack_tenant] @connection_options = options[:connection_options] || {} @openstack_temp_url_key = options[:openstack_temp_url_key] authenticate @persistent = options[:persistent] || false @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def reload @connection.reset end # Change the current account while re-using the auth token. # # This is usefull when you have an admin role and you're able # to HEAD other user accounts, set quotas, list files, etc. # # For example: # # # List current user account details # service = Fog::Storage[:openstack] # service.request :method => 'HEAD' # # Would return something like: # # Account: AUTH_1234 # Date: Tue, 05 Mar 2013 16:50:52 GMT # X-Account-Bytes-Used: 0 (0.00 Bytes) # X-Account-Container-Count: 0 # X-Account-Object-Count: 0 # # Now let's change the account # # service.change_account('AUTH_3333') # service.request :method => 'HEAD' # # Would return something like: # # Account: AUTH_3333 # Date: Tue, 05 Mar 2013 16:51:53 GMT # X-Account-Bytes-Used: 23423433 # X-Account-Container-Count: 2 # X-Account-Object-Count: 10 # # If we wan't to go back to our original admin account: # # service.reset_account_name # def change_account(account) @original_path ||= @path version_string = @path.split('/')[1] @path = "/#{version_string}/#{account}" end def reset_account_name @path = @original_path end def request(params, parse_json = true) begin response = @connection.request(params.merge({ :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Auth-Token' => @auth_token }.merge!(params[:headers] || {}), :path => "#{@path}/#{params[:path]}", })) rescue Excon::Errors::Unauthorized => error if error.response.body != 'Bad username or password' # token expiration @openstack_must_reauthenticate = true authenticate retry else # bad credentials raise error end rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Storage::OpenStack::NotFound.slurp(error) else error end end if !response.body.empty? && parse_json && response.headers['Content-Type'] =~ %r{application/json} response.body = Fog::JSON.decode(response.body) end response end private def authenticate if !@openstack_management_url || @openstack_must_reauthenticate options = { :openstack_api_key => @openstack_api_key, :openstack_username => @openstack_username, :openstack_auth_uri => URI.parse(@openstack_auth_url), :openstack_service_type => @openstack_service_type, :openstack_service_name => @openstack_service_name, :openstack_region => @openstack_region, :openstack_tenant => @openstack_tenant, :openstack_endpoint_type => 'publicURL' } credentials = Fog::OpenStack.authenticate(options, @connection_options) @current_user = credentials[:user] @current_tenant = credentials[:tenant] @openstack_must_reauthenticate = false @auth_token = credentials[:token] @openstack_management_url = credentials[:server_management_url] uri = URI.parse(@openstack_management_url) else @auth_token = @openstack_auth_token uri = URI.parse(@openstack_management_url) end @host = uri.host @path = uri.path @path.sub!(/\/$/, '') @port = uri.port @scheme = uri.scheme true end end end end end fog-1.19.0/lib/fog/core/0000755000004100000410000000000012261242551014656 5ustar www-datawww-datafog-1.19.0/lib/fog/core/class_from_string.rb0000644000004100000410000000136212261242551020723 0ustar www-datawww-datamodule Fog # get class by string or nil def self.class_from_string classname, defaultpath="" if classname and classname.is_a? String then chain = classname.split("::") klass = Kernel chain.each do |klass_string| klass = klass.const_get klass_string end if klass.is_a? Class then klass elsif defaultpath != nil then Fog.class_from_string((defaultpath.split("::")+chain).join("::"), nil) else nil end elsif classname and classname.is_a? Class then classname else nil end rescue NameError defaultpath != nil ? Fog.class_from_string((defaultpath.split("::")+chain).join("::"), nil) : nil end end fog-1.19.0/lib/fog/core/ssh.rb0000644000004100000410000000712612261242551016006 0ustar www-datawww-datarequire 'delegate' module Fog module SSH def self.new(address, username, options = {}) if Fog.mocking? Fog::SSH::Mock.new(address, username, options) else Fog::SSH::Real.new(address, username, options) end end class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = [] end end def self.reset @data= nil end def initialize(address, username, options) @address = address @username = username @options = options end def run(commands, &blk) self.class.data[@address] << {:commands => commands, :username => @username, :options => @options} end end class Real def initialize(address, username, options) require 'net/ssh' key_manager = Net::SSH::Authentication::KeyManager.new(nil, options) unless options[:key_data] || options[:keys] || options[:password] || key_manager.agent raise ArgumentError.new(':key_data, :keys, :password or a loaded ssh-agent is required to initialize SSH') end options[:timeout] ||= 30 if options[:key_data] || options[:keys] options[:keys_only] = true #Explicitly set these so net-ssh doesn't add the default keys #as seen at https://github.com/net-ssh/net-ssh/blob/master/lib/net/ssh/authentication/session.rb#L131-146 options[:keys] = [] unless options[:keys] options[:key_data] = [] unless options[:key_data] end @address = address @username = username @options = { :paranoid => false }.merge(options) end def run(commands, &blk) commands = [*commands] results = [] begin Net::SSH.start(@address, @username, @options) do |ssh| commands.each do |command| result = Result.new(command) ssh.open_channel do |ssh_channel| ssh_channel.request_pty ssh_channel.exec(command) do |channel, success| unless success raise "Could not execute command: #{command.inspect}" end channel.on_data do |ch, data| result.stdout << data yield [data, ''] if blk end channel.on_extended_data do |ch, type, data| next unless type == 1 result.stderr << data yield ['', data] if blk end channel.on_request('exit-status') do |ch, data| result.status = data.read_long end channel.on_request('exit-signal') do |ch, data| result.status = 255 end end end ssh.loop results << result end end rescue Net::SSH::HostKeyMismatch => exception exception.remember_host! sleep 0.2 retry end results end end class Result attr_accessor :command, :stderr, :stdout, :status def display_stdout data = stdout.split("\r\n") if data.is_a?(String) Formatador.display_line(data) elsif data.is_a?(Array) Formatador.display_lines(data) end end def display_stderr Formatador.display_line(stderr.split("\r\n")) end def initialize(command) @command = command @stderr = '' @stdout = '' end end end end fog-1.19.0/lib/fog/core/model.rb0000644000004100000410000000453212261242551016307 0ustar www-datawww-datarequire "fog/core/deprecated_connection_accessors" module Fog class Model extend Fog::Attributes::ClassMethods include Fog::Attributes::InstanceMethods include Fog::Core::DeprecatedConnectionAccessors attr_accessor :collection attr_reader :service def initialize(new_attributes = {}) # TODO Remove compatibility with old connection option @service = new_attributes.delete(:service) if @service.nil? && new_attributes[:connection] Fog::Logger.deprecation("Passing :connection option is deprecated, use :service instead [light_black](#{caller.first})[/]") @service = new_attributes[:connection] end merge_attributes(new_attributes) end def inspect Thread.current[:formatador] ||= Formatador.new data = "#{Thread.current[:formatador].indentation}<#{self.class.name}" Thread.current[:formatador].indent do unless self.class.attributes.empty? data << "\n#{Thread.current[:formatador].indentation}" data << self.class.attributes.map {|attribute| "#{attribute}=#{send(attribute).inspect}"}.join(",\n#{Thread.current[:formatador].indentation}") end end data << "\n#{Thread.current[:formatador].indentation}>" data end def reload requires :identity return unless data = begin collection.get(identity) rescue Excon::Errors::SocketError nil end new_attributes = data.attributes merge_attributes(new_attributes) self end def to_json(options = {}) Fog::JSON.encode(attributes) end def symbolize_keys(hash) return nil if hash.nil? hash.inject({}) do |options, (key, value)| options[(key.to_sym rescue key) || key] = value options end end def wait_for(timeout=Fog.timeout, interval=1, &block) reload_has_succeeded = false duration = Fog.wait_for(timeout, interval) do # Note that duration = false if it times out if reload reload_has_succeeded = true instance_eval(&block) else false end end if reload_has_succeeded return duration # false if timeout; otherwise {:duration => elapsed time } else raise Fog::Errors::Error.new("Reload failed, #{self.class} #{self.identity} not present.") end end end end fog-1.19.0/lib/fog/core/uuid.rb0000644000004100000410000000071212261242551016151 0ustar www-datawww-datarequire 'securerandom' module Fog class UUID class << self def uuid if supported? SecureRandom.uuid else ary = SecureRandom.random_bytes(16).unpack("NnnnnN") ary[2] = (ary[2] & 0x0fff) | 0x4000 ary[3] = (ary[3] & 0x3fff) | 0x8000 "%08x-%04x-%04x-%04x-%04x%08x" % ary end end def supported? SecureRandom.respond_to?(:uuid) end end end endfog-1.19.0/lib/fog/core/deprecation.rb0000644000004100000410000000121112261242551017473 0ustar www-datawww-datamodule Fog module Deprecation def deprecate(older, newer) module_eval <<-EOS, __FILE__, __LINE__ def #{older}(*args) Fog::Logger.deprecation("#{self} => ##{older} is deprecated, use ##{newer} instead [light_black](#{caller.first})[/]") send(:#{newer}, *args) end EOS end def self_deprecate(older, newer) module_eval <<-EOS, __FILE__, __LINE__ def self.#{older}(*args) Fog::Logger.deprecation("#{self} => ##{older} is deprecated, use ##{newer} instead [light_black](#{caller.first})[/]") send(:#{newer}, *args) end EOS end end end fog-1.19.0/lib/fog/core/wait_for_defaults.rb0000644000004100000410000000062512261242551020707 0ustar www-datawww-datamodule Fog @interval = 1 def self.interval @interval end def self.interval=(interval) raise ArgumentError, "interval must be non-negative" unless interval >= 0 @interval = interval end @timeout = 600 def self.timeout @timeout end def self.timeout=(timeout) raise ArgumentError, "timeout must be non-negative" unless timeout >= 0 @timeout = timeout end end fog-1.19.0/lib/fog/core/wait_for.rb0000644000004100000410000000064212261242551017017 0ustar www-datawww-datamodule Fog def self.wait_for(timeout=Fog.timeout, interval=Fog.interval, &block) duration = 0 start = Time.now until yield || duration > timeout sleep(interval.to_f) duration = Time.now - start end if duration > timeout raise Errors::TimeoutError.new("The specified wait_for timeout (#{timeout} seconds) was exceeded") else { :duration => duration } end end end fog-1.19.0/lib/fog/core/connection.rb0000644000004100000410000000677312261242551017357 0ustar www-datawww-datamodule Fog module Core # Fog::Core::Connection is a generic class to contain a HTTP link to an API. # # It is intended to be subclassed by providers who can then add their own # modifications such as authentication or response object. # class Connection # Prepares the connection and sets defaults for any future requests. # # @param [String] url The destination URL # @param persistent [Boolean] # @param [Hash] params # @option params [String] :body Default text to be sent over a socket. Only used if :body absent in Connection#request params # @option params [Hash] :headers The default headers to supply in a request. Only used if params[:headers] is not supplied to Connection#request # @option params [String] :host The destination host's reachable DNS name or IP, in the form of a String # @option params [String] :path Default path; appears after 'scheme://host:port/'. Only used if params[:path] is not supplied to Connection#request # @option params [Fixnum] :port The port on which to connect, to the destination host # @option params [Hash] :query Default query; appended to the 'scheme://host:port/path/' in the form of '?key=value'. Will only be used if params[:query] is not supplied to Connection#request # @option params [String] :scheme The protocol; 'https' causes OpenSSL to be used # @option params [String] :proxy Proxy server; e.g. 'http://myproxy.com:8888' # @option params [Fixnum] :retry_limit Set how many times we'll retry a failed request. (Default 4) # @option params [Class] :instrumentor Responds to #instrument as in ActiveSupport::Notifications # @option params [String] :instrumentor_name Name prefix for #instrument events. Defaults to 'excon' # def initialize(url, persistent=false, params={}) unless params.has_key?(:debug_response) params[:debug_response] = true end params[:headers] ||= {} params[:headers]['User-Agent'] ||= "fog/#{Fog::VERSION}" params.merge!(:persistent => params.fetch(:persistent, persistent)) @excon = Excon.new(url, params) end # Makes a request using the connection using Excon # # @param [Hash] params # @option params [String] :body text to be sent over a socket # @option params [Hash] :headers The default headers to supply in a request # @option params [String] :host The destination host's reachable DNS name or IP, in the form of a String # @option params [String] :path appears after 'scheme://host:port/' # @option params [Fixnum] :port The port on which to connect, to the destination host # @option params [Hash] :query appended to the 'scheme://host:port/path/' in the form of '?key=value' # @option params [String] :scheme The protocol; 'https' causes OpenSSL to be used # @option params [Proc] :response_block # # @return [Excon::Response] # # @raise [Excon::Errors::StubNotFound] # @raise [Excon::Errors::Timeout] # @raise [Excon::Errors::SocketError] # def request(params, &block) @excon.request(params, &block) end # Make {#request} available even when it has been overidden by a subclass # to allow backwards compatibility. # alias_method :original_request, :request protected :original_request # Closes the connection # def reset @excon.reset end end end end fog-1.19.0/lib/fog/core/errors.rb0000644000004100000410000000540112261242551016517 0ustar www-datawww-datamodule Fog module Errors class Error < StandardError attr_accessor :verbose def self.slurp(error, message = nil) new_error = new(message || error.message) new_error.set_backtrace(error.backtrace) new_error.verbose = error.message new_error end end class MockNotImplemented < Fog::Errors::Error; end class NotFound < Fog::Errors::Error; end class LoadError < LoadError; end class TimeoutError< Fog::Errors::Error; end class NotImplemented < Fog::Errors::Error; end # @return [String] The error message that will be raised, if credentials cannot be found def self.missing_credentials missing_credentials_message = <<-YML Missing Credentials To run as '#{Fog.credential}', add the following to your resource config file: #{Fog.credentials_path} An alternate file may be used by placing its path in the FOG_RC environment variable ####################################################### # Fog Credentials File # # Key-value pairs should look like: # :aws_access_key_id: 022QF06E7MXBSAMPLE :#{Fog.credential}: :aws_access_key_id: :aws_secret_access_key: :bluebox_api_key: :bluebox_customer_id: :brightbox_client_id: :brightbox_secret: :clodo_api_key: :clodo_username: :go_grid_api_key: :go_grid_shared_secret: :google_client_email: :google_key_location: :google_project: :google_storage_access_key_id: :google_storage_secret_access_key: :hp_access_key: :hp_secret_key: :hp_tenant_id: :hp_avl_zone: :linode_api_key: :local_root: :bare_metal_cloud_password: :bare_metal_cloud_username: :public_key_path: :private_key_path: :openstack_api_key: :openstack_username: :openstack_auth_url: :openstack_tenant: :openstack_region: :ovirt_username: :ovirt_password: :ovirt_url: :libvirt_uri: :rackspace_api_key: :rackspace_username: :rackspace_servicenet: :rackspace_cdn_ssl: :riakcs_access_key_id: :riakcs_secret_access_key: :stormondemand_username: :stormondemand_password: :terremark_username: :terremark_password: :voxel_api_key: :voxel_api_secret: :zerigo_email: :zerigo_token: :dnsimple_email: :dnsimple_password: :dnsmadeeasy_api_key: :dnsmadeeasy_secret_key: :dreamhost_api_key: :cloudstack_host: :cloudstack_api_key: :cloudstack_secret_access_key: :vsphere_server: :vsphere_username: :vsphere_password: :libvirt_username: :libvirt_password: :libvirt_uri: :libvirt_ip_command: :ibm_username: :ibm_password: :vcloud_director_host: :vcloud_director_username: :vcloud_director_password: # # End of Fog Credentials File ####################################################### YML raise(Fog::Errors::LoadError.new(missing_credentials_message)) end end end fog-1.19.0/lib/fog/core/time.rb0000644000004100000410000000121512261242551016140 0ustar www-datawww-datarequire 'time' module Fog class Time < ::Time DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] def self.now at((::Time.now - offset).to_i) end def self.now=(new_now) old_now = ::Time.now @offset = old_now - new_now new_now end def self.offset @offset ||= 0 end def to_date_header self.utc.strftime("#{DAYS[self.utc.wday]}, %d #{MONTHS[self.utc.month - 1]} %Y %H:%M:%S +0000") end def to_iso8601_basic self.utc.strftime('%Y%m%dT%H%M%SZ') end end end fog-1.19.0/lib/fog/core/parser.rb0000644000004100000410000000530112261242551016476 0ustar www-datawww-datarequire "nokogiri" module Fog module Parsers class Base < Nokogiri::XML::SAX::Document attr_reader :response def initialize reset end def attr_value(name, attrs) (entry = attrs.detect {|a, v| a == name }) && entry.last end def reset @response = {} end def characters(string) @value ||= '' @value << string end # ############################################################################### # This is a workaround. Original implementation from Nokogiri is overwritten with # one that does not join namespace prefix with local name. def start_element_namespace name, attrs = [], prefix = nil, uri = nil, ns = [] start_element name, attrs end def end_element_namespace name, prefix = nil, uri = nil end_element name end # ############################################################################### def start_element(name, attrs = []) @value = nil end def value @value && @value.dup end end end end module Fog class ToHashDocument < Nokogiri::XML::SAX::Document def initialize @stack = [] end def characters(string) @value ||= '' @value << string.strip end def end_element(name) last = @stack.pop if last.empty? && @value.empty? @stack.last[name.to_sym] = '' elsif last == {:i_nil=>"true"} @stack.last[name.to_sym] = nil elsif !@value.empty? @stack.last[name.to_sym] = @value end @value = '' end def body @stack.first end def response body end def start_element(name, attributes = []) @value = '' parsed_attributes = {} until attributes.empty? if attributes.first.is_a?(Array) key, value = attributes.shift else key, value = attributes.shift, attributes.shift end parsed_attributes[key.gsub(':','_').to_sym] = value end if @stack.last.is_a?(Array) @stack.last << {name.to_sym => parsed_attributes} else data = if @stack.empty? @stack.push(parsed_attributes) parsed_attributes elsif @stack.last[name.to_sym] unless @stack.last[name.to_sym].is_a?(Array) @stack.last[name.to_sym] = [@stack.last[name.to_sym]] end @stack.last[name.to_sym] << parsed_attributes @stack.last[name.to_sym].last else @stack.last[name.to_sym] = {} @stack.last[name.to_sym].merge!(parsed_attributes) @stack.last[name.to_sym] end @stack.push(data) end end end end fog-1.19.0/lib/fog/core/logger.rb0000644000004100000410000000201712261242551016462 0ustar www-datawww-datamodule Fog class Logger @channels = { :deprecation => ::STDOUT, :warning => ::STDOUT } @channels[:debug] = ::STDOUT if ENV['DEBUG'] def self.[](channel) @channels[channel] end def self.[]=(channel, value) @channels[channel] = value end def self.debug(message) self.write(:debug, "[light_black][fog][DEBUG] #{message}[/]\n") end def self.deprecation(message) self.write(:deprecation, "[yellow][fog][DEPRECATION] #{message}[/]\n") end def self.warning(message) self.write(:warning, "[yellow][fog][WARNING] #{message}[/]\n") end def self.write(key, value) if channel = @channels[key] message = if channel.tty? value.gsub(Formatador::PARSE_REGEX) { "\e[#{Formatador::STYLES[$1.to_sym]}m" }.gsub(Formatador::INDENT_REGEX, '') else value.gsub(Formatador::PARSE_REGEX, '').gsub(Formatador::INDENT_REGEX, '') end channel.write(message) end nil end end end fog-1.19.0/lib/fog/core/provider.rb0000644000004100000410000000140212261242551017032 0ustar www-datawww-datamodule Fog def self.providers @providers ||= {} end def self.providers=(new_providers) @providers = new_providers end module Provider def self.extended(base) provider = base.to_s.split('::').last Fog.providers[provider.downcase.to_sym] = provider end def [](service_key) eval(@services_registry[service_key]).new end def service(new_service, path, constant_string) Fog.services[new_service] ||= [] Fog.services[new_service] |= [self.to_s.split('::').last.downcase.to_sym] @services_registry ||= {} @services_registry[new_service] = [self.to_s, constant_string].join('::') require File.join('fog', path) end def services @services_registry.keys end end end fog-1.19.0/lib/fog/core/mock.rb0000644000004100000410000000462212261242551016140 0ustar www-datawww-datamodule Fog @mocking = false def self.mock! @mocking = true end def self.unmock! @mocking = false end def self.mock? @mocking end def self.mocking? @mocking end module Mock @delay = 1 def self.delay @delay end def self.delay=(new_delay) raise ArgumentError, "delay must be non-negative" unless new_delay >= 0 @delay = new_delay end def self.not_implemented(message = 'Contributions welcome!') raise Fog::Errors::MockNotImplemented.new(message) end def self.random_ip(opts = {:version => :v4}) version = opts[:version] if version == :v6 bit_length = 128 family = Socket::AF_INET6 elsif version == :v4 bit_length = 32 family = Socket::AF_INET else raise ArgumentError, "Unknown IP version: #{version}" end seed = 1 + rand((2**bit_length)-1) IPAddr.new(seed, family).to_s end def self.random_base64(length) random_selection( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", length ) end def self.random_hex(length) max = ('f' * length).to_i(16) rand(max).to_s(16).rjust(length, '0') end def self.random_letters(length) random_selection( 'abcdefghijklmnopqrstuvwxyz', length ) end def self.random_numbers(length) max = ('9' * length).to_i rand(max).to_s end def self.random_letters_and_numbers(length) random_selection( 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', length ) end def self.random_selection(characters, length) selection = '' length.times do position = rand(characters.length) selection << characters[position..position] end selection end def self.reset mocked_services = [] Fog.constants.map do |x| x_const = Fog.const_get(x) x_const.respond_to?(:constants) && x_const.constants.map do |y| y_const = x_const.const_get(y) y_const.respond_to?(:constants) && y_const.constants.map do |z| if z.to_sym == :Mock mocked_services << y_const.const_get(z) end end end end for mocked_service in mocked_services next unless mocked_service.respond_to?(:reset) mocked_service.reset end end end end fog-1.19.0/lib/fog/core/hmac.rb0000644000004100000410000000170012261242551016111 0ustar www-datawww-datamodule Fog class HMAC def initialize(type, key) @key = key case type when 'sha1' setup_sha1 when 'sha256' setup_sha256 end end def sign(data) @signer.call(data) end private def setup_sha1 @digest = OpenSSL::Digest.new('sha1') @signer = lambda do |data| OpenSSL::HMAC.digest(@digest, @key, data) end end def setup_sha256 begin @digest = OpenSSL::Digest.new('sha256') @signer = lambda do |data| OpenSSL::HMAC.digest(@digest, @key, data) end rescue RuntimeError => error unless error.message == 'Unsupported digest algorithm (sha256).' raise error else require 'hmac-sha2' @hmac = ::HMAC::SHA256.new(@key) @signer = lambda do |data| @hmac.update(data) @hmac.digest end end end end end end fog-1.19.0/lib/fog/core/deprecated/0000755000004100000410000000000012261242551016756 5ustar www-datawww-datafog-1.19.0/lib/fog/core/deprecated/connection.rb0000644000004100000410000000124112261242551021440 0ustar www-datawww-datarequire "fog/xml" module Fog # @deprecated Use {Fog::Core::Connection} or {XML::SAXParserConnection} if you # require the response body to be parsed. # # The Connection class is a wrapper around an instance of Excon::Connection # supporting {#request} and {#reset} only. # # {#request} includes an option to perform SAX parsing for XML APIs. # # @see https://github.com/geemus/excon/blob/master/lib/excon/connection.rb # class Connection < Fog::XML::SAXParserConnection def request(params, &block) if (parser = params.delete(:parser)) super(parser, params) else original_request(params) end end end end fog-1.19.0/lib/fog/core/current_machine.rb0000644000004100000410000000173512261242551020357 0ustar www-datawww-datarequire 'thread' module Fog class CurrentMachine @@lock = Mutex.new AMAZON_AWS_CHECK_IP = 'http://checkip.amazonaws.com' def self.ip_address= ip_address @@lock.synchronize do @@ip_address = ip_address end end # Get the ip address of the machine from which this command is run. It is # recommended that you surround calls to this function with a timeout block # to ensure optimum performance in the case where the amazonaws checkip # service is unavailable. # # @example Get the current ip address # begin # Timeout::timeout(5) do # puts "Your ip address is #{Fog::CurrentMachine.ip_address}" # end # rescue Timeout::Error # puts "Service timeout" # end # # @raise [Excon::Errors::Error] if the net/http request fails. def self.ip_address @@lock.synchronize do @@ip_address ||= Excon.get(AMAZON_AWS_CHECK_IP).body.chomp end end end end fog-1.19.0/lib/fog/core/credentials.rb0000644000004100000410000000367512261242551017513 0ustar www-datawww-datarequire 'yaml' module Fog require 'fog/core/deprecation' # Assign a new credential to use from configuration file # @param [String, Symbol] new_credential name of new credential to use # @ return [Symbol] name of the new credential def self.credential=(new_credential) @credentials = nil @credential = new_credential && new_credential.to_sym end # @return [String, Symbol] The credential to use in Fog def self.credential @credential ||= ( ENV["FOG_CREDENTIAL"] && ENV["FOG_CREDENTIAL"].to_sym ) || :default end # @return [String] The path for configuration_file def self.credentials_path @credential_path ||= begin path = ENV["FOG_RC"] || (ENV['HOME'] && File.directory?(ENV['HOME']) && '~/.fog') File.expand_path(path) if path rescue nil end end # @return [String] The new path for credentials file def self.credentials_path=(new_credentials_path) @credentials = nil @credential_path = new_credentials_path end # @return [Hash] The credentials pulled from the configuration file # @raise [LoadError] Configuration unavailable in configuration file def self.credentials @credentials ||= begin if credentials_path && File.exists?(credentials_path) credentials = self.symbolize_credentials(YAML.load_file(credentials_path)) (credentials && credentials[credential]) || Fog::Errors.missing_credentials else {} end end end # @return [Hash] The newly assigned credentials def self.credentials=(new_credentials) @credentials = new_credentials end def self.symbolize_credential?(key) ![:headers].include?(key) end def self.symbolize_credentials(args) if args.is_a? Hash copy = Array.new args.each do |key, value| obj = symbolize_credential?(key) ? self.symbolize_credentials(value) : value copy.push(key.to_sym, obj) end Hash[*copy] else args end end end fog-1.19.0/lib/fog/core/collection.rb0000644000004100000410000001001312261242551017331 0ustar www-datawww-datarequire "fog/core/deprecated_connection_accessors" module Fog class Collection < Array extend Fog::Attributes::ClassMethods include Fog::Attributes::InstanceMethods include Fog::Core::DeprecatedConnectionAccessors attr_reader :service Array.public_instance_methods(false).each do |method| unless [:reject, :select, :slice].include?(method.to_sym) class_eval <<-EOS, __FILE__, __LINE__ def #{method}(*args) unless @loaded lazy_load end super end EOS end end %w[reject select slice].each do |method| class_eval <<-EOS, __FILE__, __LINE__ def #{method}(*args) unless @loaded lazy_load end data = super self.clone.clear.concat(data) end EOS end def self.model(new_model=nil) if new_model == nil @model else @model = new_model end end remove_method :clear def clear @loaded = true super end def create(attributes = {}) object = new(attributes) object.save object end def destroy(identity) object = new(:identity => identity) object.destroy end # Creates a new Fog::Collection based around the passed service # # @param [Hash] attributes # @option attributes [Fog::Service] service Instance of a service # # @return [Fog::Collection] # def initialize(attributes = {}) @service = attributes.delete(:service) @loaded = false merge_attributes(attributes) end remove_method :inspect def inspect Thread.current[:formatador] ||= Formatador.new data = "#{Thread.current[:formatador].indentation}<#{self.class.name}\n" Thread.current[:formatador].indent do unless self.class.attributes.empty? data << "#{Thread.current[:formatador].indentation}" data << self.class.attributes.map {|attribute| "#{attribute}=#{send(attribute).inspect}"}.join(",\n#{Thread.current[:formatador].indentation}") data << "\n" end data << "#{Thread.current[:formatador].indentation}[" unless self.empty? data << "\n" Thread.current[:formatador].indent do data << self.map {|member| member.inspect}.join(",\n") data << "\n" end data << Thread.current[:formatador].indentation end data << "]\n" end data << "#{Thread.current[:formatador].indentation}>" data end def load(objects) clear for object in objects self << new(object) end self end def model self.class.instance_variable_get('@model') end def new(attributes = {}) unless attributes.is_a?(::Hash) raise(ArgumentError.new("Initialization parameters must be an attributes hash, got #{attributes.class} #{attributes.inspect}")) end model.new( { :collection => self, :service => service }.merge(attributes) ) end def reload clear lazy_load self end def table(attributes = nil) Formatador.display_table(self.map {|instance| instance.attributes}, attributes) end def to_json(options = {}) Fog::JSON.encode(self.map {|member| member.attributes}) end private def lazy_load self.all end end # Base class for collection classes whose 'all' method returns only a single page of results and passes the # 'Marker' option along as self.filters[:marker] class PagedCollection < Collection def each(filters=filters) if block_given? begin page = self.all(filters) # We need to explicitly use the base 'each' method here on the page, otherwise we get infinite recursion base_each = Fog::Collection.instance_method(:each) base_each.bind(page).call { |item| yield item } end while self.filters[:marker] end self end end end fog-1.19.0/lib/fog/core/attributes.rb0000644000004100000410000001362212261242551017375 0ustar www-datawww-datamodule Fog module Attributes module ClassMethods def _load(marshalled) new(Marshal.load(marshalled)) end def aliases @aliases ||= {} end def attributes @attributes ||= [] end def attribute(name, options = {}) class_eval <<-EOS, __FILE__, __LINE__ def #{name} attributes[:#{name}] end EOS case options[:type] when :boolean class_eval <<-EOS, __FILE__, __LINE__ def #{name}=(new_#{name}) attributes[:#{name}] = case new_#{name} when true,'true' true when false,'false' false end end EOS when :float class_eval <<-EOS, __FILE__, __LINE__ def #{name}=(new_#{name}) attributes[:#{name}] = new_#{name}.to_f end EOS when :integer class_eval <<-EOS, __FILE__, __LINE__ def #{name}=(new_#{name}) attributes[:#{name}] = new_#{name}.to_i end EOS when :string class_eval <<-EOS, __FILE__, __LINE__ def #{name}=(new_#{name}) attributes[:#{name}] = new_#{name}.to_s end EOS when :time class_eval <<-EOS, __FILE__, __LINE__ def #{name}=(new_#{name}) attributes[:#{name}] = if new_#{name}.nil? || new_#{name} == "" || new_#{name}.is_a?(Time) new_#{name} else Time.parse(new_#{name}) end end EOS when :array class_eval <<-EOS, __FILE__, __LINE__ def #{name}=(new_#{name}) attributes[:#{name}] = [*new_#{name}] end EOS else if squash = options[:squash] class_eval <<-EOS, __FILE__, __LINE__ def #{name}=(new_data) if new_data.is_a?(Hash) if new_data.has_key?(:'#{squash}') attributes[:#{name}] = new_data[:'#{squash}'] elsif new_data.has_key?("#{squash}") attributes[:#{name}] = new_data["#{squash}"] else attributes[:#{name}] = [ new_data ] end else attributes[:#{name}] = new_data end end EOS else class_eval <<-EOS, __FILE__, __LINE__ def #{name}=(new_#{name}) attributes[:#{name}] = new_#{name} end EOS end end @attributes ||= [] @attributes |= [name] for new_alias in [*options[:aliases]] aliases[new_alias] = name end end def identity(name, options = {}) @identity = name self.attribute(name, options) end def ignore_attributes(*args) @ignored_attributes = args.collect {|attr| attr.to_s } end def ignored_attributes @ignored_attributes ||= [] end end module InstanceMethods def _dump(level) Marshal.dump(attributes) end def attributes @attributes ||= {} end def dup copy = super copy.dup_attributes! copy end def identity send(self.class.instance_variable_get('@identity')) end def identity=(new_identity) send("#{self.class.instance_variable_get('@identity')}=", new_identity) end def merge_attributes(new_attributes = {}) for key, value in new_attributes unless self.class.ignored_attributes.include?(key) if aliased_key = self.class.aliases[key] send("#{aliased_key}=", value) elsif self.respond_to?("#{key}=",true) send("#{key}=", value) else attributes[key] = value end end end self end # Returns true if a remote resource has been assigned an # identity and we can assume it has been persisted. # # @return [Boolean] def persisted? !!identity end # Returns true if a remote resource has not been assigned an # identity. # # This was added for a ActiveRecord like feel but has been # outdated by ActiveModel API using {#persisted?} # # @deprecated Use inverted form of {#persisted?} # @return [Boolean] def new_record? Fog::Logger.deprecation("#new_record? is deprecated, use !persisted? instead [light_black](#{caller.first})[/]") !persisted? end # check that the attributes specified in args exist and is not nil def requires(*args) missing = missing_attributes(args) if missing.length == 1 raise(ArgumentError, "#{missing.first} is required for this operation") elsif missing.any? raise(ArgumentError, "#{missing[0...-1].join(", ")} and #{missing[-1]} are required for this operation") end end def requires_one(*args) missing = missing_attributes(args) if missing.length == args.length raise(ArgumentError, "#{missing[0...-1].join(", ")} or #{missing[-1]} are required for this operation") end end protected def missing_attributes(args) missing = [] for arg in [:service] | args unless send("#{arg}") || attributes.has_key?(arg) missing << arg end end missing end def dup_attributes! @attributes = @attributes.dup if @attributes end private def remap_attributes(attributes, mapping) for key, value in mapping if attributes.key?(key) attributes[value] = attributes.delete(key) end end end end end end fog-1.19.0/lib/fog/core/scp.rb0000644000004100000410000000615412261242551015776 0ustar www-datawww-datamodule Fog module SCP def self.new(address, username, options = {}) if Fog.mocking? Fog::SCP::Mock.new(address, username, options) else Fog::SCP::Real.new(address, username, options) end end class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = [] end end def initialize(address, username, options) @address = address @username = username @options = options end def upload(local_path, remote_path, upload_options = {}) self.class.data[@address] << { :username => @username, :options => @options, :local_path => local_path, :remote_path => remote_path, :upload_options => upload_options } end def download(remote_path, local_path, download_options = {}) self.class.data[@address] << { :username => @username, :options => @options, :remote_path => remote_path, :local_path => local_path, :download_options => download_options } end end class Real def initialize(address, username, options) require 'net/scp' key_manager = Net::SSH::Authentication::KeyManager.new(nil, options) unless options[:key_data] || options[:keys] || options[:password] || key_manager.agent raise ArgumentError.new(':key_data, :keys, :password or a loaded ssh-agent is required to initialize SSH') end options[:timeout] = 30 if options[:key_data] || options[:keys] options[:keys_only] = true #Explicitly set these so net-ssh doesn't add the default keys #as seen at https://github.com/net-ssh/net-ssh/blob/master/lib/net/ssh/authentication/session.rb#L131-146 options[:keys] = [] unless options[:keys] options[:key_data] = [] unless options[:key_data] end @address = address @username = username @options = { :paranoid => false }.merge(options) end def upload(local_path, remote_path, upload_options = {}, &block) begin Net::SCP.start(@address, @username, @options) do |scp| scp.upload!(local_path, remote_path, upload_options) do |ch, name, sent, total| block.call(ch, name, sent, total) if block end end rescue Exception => error raise error end end def download(remote_path, local_path, download_options = {}, &block) begin Net::SCP.start(@address, @username, @options) do |scp| scp.download!(remote_path, local_path, download_options) do |ch, name, sent, total| block.call(ch, name, sent, total) if block end end rescue Exception => error raise error end end end end end fog-1.19.0/lib/fog/core/service.rb0000644000004100000410000001240212261242551016642 0ustar www-datawww-datamodule Fog def self.services @services ||= {} end class Service class Error < Fog::Errors::Error; end class NotFound < Fog::Errors::NotFound; end module NoLeakInspector def inspect "#<#{self.class}:#{self.object_id} #{(self.instance_variables - service.secrets).map {|iv| [iv, self.instance_variable_get(iv).inspect].join('=')}.join(' ')}>" end end module Collections def collections service.collections end def mocked_requests service.mocked_requests end def requests service.requests end end class << self def inherited(child) child.class_eval <<-EOS, __FILE__, __LINE__ class Error < Fog::Service::Error; end class NotFound < Fog::Service::NotFound; end module Collections include Fog::Service::Collections def service #{child} end end def self.service #{child} end EOS end def new(options={}) options = Fog.symbolize_credentials(options) options = fetch_credentials(options).merge(options) validate_options(options) coerce_options(options) setup_requirements if Fog.mocking? service::Mock.send(:include, service::Collections) service::Mock.new(options) else service::Real.send(:include, service::Collections) service::Real.send(:include, service::NoLeakInspector) service::Real.new(options) end end def fetch_credentials(options) # attempt to load credentials from config file begin Fog.credentials.reject {|key, value| !(recognized | requirements).include?(key)} rescue LoadError # if there are no configured credentials, do nothing {} end end def setup_requirements if superclass.respond_to?(:setup_requirements) superclass.setup_requirements end @required ||= false unless @required for collection in collections require [@model_path, collection].join('/') constant = collection.to_s.split('_').map {|characters| characters[0...1].upcase << characters[1..-1]}.join('') service::Collections.module_eval <<-EOS, __FILE__, __LINE__ def #{collection}(attributes = {}) #{service}::#{constant}.new({:service => self}.merge(attributes)) end EOS end for model in models require [@model_path, model].join('/') end for request in requests require [@request_path, request].join('/') if service::Mock.method_defined?(request) mocked_requests << request else service::Mock.module_eval <<-EOS, __FILE__, __LINE__ def #{request}(*args) Fog::Mock.not_implemented end EOS end end @required = true end end def model_path(new_path) @model_path = new_path end def collection(new_collection) collections << new_collection end def collections @collections ||= [] end def coerce_options(options) options.each do |key, value| value_string = value.to_s.downcase if value.nil? options.delete(key) elsif value == value_string.to_i.to_s options[key] = value.to_i else options[key] = case value_string when 'false' false when 'true' true else value end end end end def mocked_requests @mocked_requests ||= [] end def model(new_model) models << new_model end def models @models ||= [] end def request_path(new_path) @request_path = new_path end def request(new_request) requests << new_request end def requests @requests ||= [] end def secrets(*args) if args.empty? @secrets ||= [] else args.inject(secrets) do |secrets, secret| secrets << "@#{secret}".to_sym end end end def requires(*args) requirements.concat(args) end def requirements @requirements ||= [] end def recognizes(*args) recognized.concat(args) end def recognized @recognized ||= [:connection_options] end def validate_options(options) keys = [] for key, value in options unless value.nil? keys << key end end missing = requirements - keys unless missing.empty? raise ArgumentError, "Missing required arguments: #{missing.join(', ')}" end unless recognizes.empty? unrecognized = options.keys - requirements - recognized unless unrecognized.empty? Fog::Logger.warning("Unrecognized arguments: #{unrecognized.join(', ')}") end end end end end end fog-1.19.0/lib/fog/core/deprecated_connection_accessors.rb0000644000004100000410000000276712261242551023603 0ustar www-datawww-datamodule Fog module Core # This module covers the shared code used by models and collections # that deprecates the confusing usage of 'connection' which was # actually intended to be an instance of Fog::Service module DeprecatedConnectionAccessors # Sets the Service but using the wrong name! # # @deprecated The connection name was wrong and confusing since it refered to the service # @param [Fog::Service] service An instance of a Fog service this collection is for # def connection=(service) Fog::Logger.deprecation("#connection= is deprecated, pass :service in at creation [light_black](#{caller.first})[/]") @service = service end # Returns the Service the collection is part of # # @deprecated #connection is deprecated due to confusing name, use #service instead # @return [Fog::Service] # def connection Fog::Logger.deprecation("#connection is deprecated, use #service instead [light_black](#{caller.first})[/]") @service end # Prepares the value of the service based on the passed attributes # # @note Intended for use where the service is required before the normal # initializer runs. The logic is run there with deprecation warnings. # # @param [Hash] attributes # @return [Fog::Service] # def prepare_service_value(attributes) @service = attributes[:service] || attributes[:connection] end end end end fog-1.19.0/lib/fog/vcloud.rb0000644000004100000410000000021012261242552015541 0ustar www-datawww-datarequire 'fog/core' module Fog module Vcloud extend Fog::Provider service(:compute, 'vcloud/compute', 'Compute') end end fog-1.19.0/lib/fog/schema/0000755000004100000410000000000012261242552015167 5ustar www-datawww-datafog-1.19.0/lib/fog/schema/data_validator.rb0000644000004100000410000001310512261242552020472 0ustar www-datawww-datamodule Fog module Schema # This validates a data object against a Ruby based schema to see # if they match. # # * An object matches the schema if +==+ or +===+ returns +true+ # * Hashes match if all the key's values match the classes given # in the schema as well. This can be configured in the options # * Arrays match when every element in the data matches the case # given in the schema. # # The schema and validation are very simple and probably not # suitable for some cases. # # The following classes can be used to check for special behaviour # # * Fog::Boolean - value may be +true+ or +false+ # * Fog::Nullable::Boolean - value may be +true+, +false+ or +nil+ # * Fog::Nullable::Integer - value may be an Integer or +nil+ # * Fog::Nullable::String # * Fog::Nullable::Time # * Fog::Nullable::Float # * Fog::Nullable::Hash # * Fog::Nullable::Array # # All the "nullable" objects will pass if the value is of the class # or if it is +nil+. This allows you to match APIs that may include # keys when the value is not available in some cases but will # always be a String. Such as an password that is only displayed # on the reset action. # # The keys for "nullable" resources should always be present but # original matcher had a bug that allowed these to also appear to # work as optional keys/values. # # If you need the original behaviour, data with a missing key is # still valid, then you may pass the +:allow_optional_rules+ # option to the #validate method. # # That is not recommended because you are describing a schema # with optional keys in a format that does not support it. # # Setting +:allow_extra_keys+ as +true+ allows the data to # contain keys not declared by the schema and still pass. This # is useful if new attributes appear in the API in a backwards # compatible manner and can be ignored. # # This is the behaviour you would have seen with +strict+ being # +false+ in the original test helper. # # @example Schema example # { # "id" => String, # "ram" => Integer, # "disks" => [ # "size" => Float # ], # "dns_name" => Fog::Nullable::String, # "active" => Fog::Boolean, # "created" => DateTime # } # class DataValidator def initialize @message = nil end # Checks if the data structure matches the schema passed in and # returns +true+ if it fits. # # @param [Object] data Hash or Array to check # @param [Object] schema Schema pattern to check against # @param [Boolean] options # @option options [Boolean] :allow_extra_keys # If +true+ does not fail if extra keys are in the data # that are not in the schema. # @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! # # @return [Boolean] Did the data fit the schema? def validate(data, schema, options = {}) valid = validate_value(schema, data, options) unless valid @message = "#{data.inspect} does not match #{schema.inspect}" end valid end # This returns the last message set by the validator # # @return [String] def message @message end private # This contains a slightly modified version of the Hashidator gem # but unfortunately the gem does not cope with Array schemas. # # @see https://github.com/vangberg/hashidator/blob/master/lib/hashidator.rb # def validate_value(validator, value, options) Fog::Logger.write :debug, "[yellow][DEBUG] #{value.inspect} against #{validator.inspect}[/]\n" case validator when Array return false if value.is_a?(Hash) value.respond_to?(:all?) && value.all? {|x| validate_value(validator[0], x, options)} when Symbol value.respond_to? validator when Hash return false if value.is_a?(Array) # When being strict values not specified in the schema are fails unless options[:allow_extra_keys] if value.respond_to?(:empty?) # Validator is empty but values are not return false if !value.empty? && validator.empty? end end unless options[:allow_optional_rules] if value.respond_to?(:empty?) # Validator has rules left but no more values return false if value.empty? && !validator.empty? end end validator.all? do |key, sub_validator| Fog::Logger.write :debug, "[blue][DEBUG] #{key.inspect} against #{sub_validator.inspect}[/]\n" validate_value(sub_validator, value[key], options) end else result = validator == value result = validator === value unless result # Repeat unless we have a Boolean already unless (result.is_a?(TrueClass) || result.is_a?(FalseClass)) result = validate_value(result, value, options) end if result Fog::Logger.write :debug, "[green][DEBUG] Validation passed: #{value.inspect} against #{validator.inspect}[/]\n" else Fog::Logger.write :debug, "[red][DEBUG] Validation failed: #{value.inspect} against #{validator.inspect}[/]\n" end result end end end end end fog-1.19.0/lib/fog/xml.rb0000644000004100000410000000102512261242552015052 0ustar www-datawww-datarequire "nokogiri" require "fog/core/parser" module Fog # @note Extracting XML components out of core is a work in progress. # # The {XML} module includes functionality that is common between APIs using # XML to send and receive data. # # The intent is to provide common code for provider APIs using XML but not # require it for those using JSON. # # @todo Add +require "fog/xml"+ and/or +include Fog::XML+ to providers using # its services # module XML end end require "fog/xml/sax_parser_connection" fog-1.19.0/lib/fog/cdn.rb0000644000004100000410000000111612261242551015016 0ustar www-datawww-datamodule Fog module CDN def self.[](provider) self.new(:provider => provider) end def self.new(attributes) attributes = attributes.dup # prevent delete from having side effects provider = attributes.delete(:provider).to_s.downcase.to_sym if self.providers.include?(provider) require "fog/#{provider}/cdn" return Fog::CDN.const_get(Fog.providers[provider]).new(attributes) end raise ArgumentError.new("#{provider} is not a recognized cdn provider") end def self.providers Fog.services[:cdn] end end end fog-1.19.0/lib/fog/vcloud/0000755000004100000410000000000012261242552015223 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud/examples/0000755000004100000410000000000012261242552017041 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud/examples/more_on_vapps.md0000644000004100000410000000131412261242552022231 0ustar www-datawww-data# More on vApps ## Checking running or stopped selected_vapp = connection.servers.service.vapps.detect { |n| n.name == 'vapp-name' } selected_vapp.on? selected_vapp.off? ## Wait for app to come up or stop selected_vapp.wait_for { selected_vapp.on? } selected_vapp.wait_for { selected_vapp.off? } ## Delete vApp selected_vapp = connection.servers.service.vapps.detect { |n| n.name == 'vapp-name' } vapp = connection.servers.service.get_vapp(selected_vapp.href) if vapp.on? vapp.service.undeploy selected_vapp.href #undeploy to stop vApp vapp.wait_for { vapp.off? } end vapp.wait_for { vapp.off? } #double check vapp.service.delete_vapp selected_vapp.href fog-1.19.0/lib/fog/vcloud/examples/get_vapp_information.md0000644000004100000410000000044312261242552023576 0ustar www-datawww-data# Get network information - To see all vApps list connection.servers.service.vapps - To see details of a particular vApp selected_vapp = connection.servers.service.vapps.detect { |n| n.name == 'vapp-name' } connection.servers.service.get_vapp(selected_vapp.href) fog-1.19.0/lib/fog/vcloud/examples/creating_a_connection.md0000644000004100000410000000142512261242552023700 0ustar www-datawww-data# Creating a connection connection = Fog::Compute.new( :provider => :vcloud, :vcloud_username => "username@org-name", :vcloud_password => password, :vcloud_host => vendor-api-endpoint-host, :vcloud_default_vdc => default_vdc_uri, :connection_options => { :ssl_verify_peer => false, :omit_default_port => true } ) - Refer to links in [vcloud/examples/README.md](/lib/fog/vcloud/examples/REAME.md) for find various different uris - connection_options are passed down to `excon`, which is used by fog to make http requests. - We using `omit_default_port`, as currently excon adds port to host entry in headers, which might not be compatible with various vendors. fog-1.19.0/lib/fog/vcloud/examples/get_network_information.md0000644000004100000410000000045412261242552024323 0ustar www-datawww-data# Get network information - To see all networks list connection.servers.service.networks - To see details of a particular network selected_nw = connection.servers.service.networks.detect { |n| n.name == 'Default' } connection.servers.service.get_network(selected_nw.href) fog-1.19.0/lib/fog/vcloud/examples/creating_a_vapp.md0000644000004100000410000000105612261242552022507 0ustar www-datawww-data# Creating a vApp connection.servers.create( :vdc_uri => vdc-uuid, :catalog_item_uri => catalog-uuid, :name => vApp-name, :network_uri => network-uri, :network_name => network-name, :connection_options => { :ssl_verify_peer => false, :omit_default_port => true } ) - Not most of the uris can be found by understanding the vcloud api eg various network information can be retrieved by `connection.servers.service.networks` fog-1.19.0/lib/fog/vcloud/examples/README.md0000644000004100000410000000517012261242552020323 0ustar www-datawww-data# Using vCloud API via fog _contributor @singhgarima_ For more information about fog [README](/README.md), or visit their website [fog.io](www.fog.io). ## Vcloud API Some useful links to get started on the vCloud API: - [http://www.vmware.com/pdf/vcd_15_api_guide.pdf](http://www.vmware.com/pdf/vcd_15_api_guide.pdf) - [vCloud API Programming Guide](http://pubs.vmware.com/vcd-51/index.jsp?topic=%2Fcom.vmware.vcloud.api.doc_51%2FGUID-86CA32C2-3753-49B2-A471-1CE460109ADB.html) ## Terminology - Organization: An Organization is the fundamental vCloud Director grouping that contains users, the vApps that they create, and the resources the vApps use. It is a top-level container in a cloud that contains one or more Organization Virtual Data Centers (Org vDCs) and Catalog entities. It owns all the virtual resources for a cloud instance and can have many Org vDCs.[1] - vApp: VMware vApp is a format for packaging and managing applications. A vApp can contain multiple virtual machines.[2] - VM: A virtualized personal computer environment in which a guest operating system and associated application software can run. Multiple virtual machines can operate on the same managed host machine concurrently.[3] - Catalogs & Catalog-Items: Catalog is used in organizations for storing content. Example: base images. Each item stored in catalog is referred as catalog item. - vDC: Virtual Data Center. These are of two kinds provider vDCs (accessible to multiple organizations), and organization vDCs (accessible only by a given organization). In fog we refer to organization vDCs. - Networks: You can setup various internal networks and assign various internal ip ranges to them ## What is the difference between a virtual appliance and a virtual machine? A virtual machine is a tightly isolated software container created to run on virtualized platforms. It has four key virtualized resources (CPU, RAM, Storage, and Networking); but requires the installation of an Operating System and runs on one or more applications. A virtual appliance functions very much like a virtual machine, possessing the four key characteristics of compatibility, isolation, encapsulation, and hardware independence. However, a virtual appliance contains a pre-installed, pre-configured Operating System and an application stack optimized to provide a specific set of services.[3] **References** - [1] http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1026316 - [2] http://www.vmware.com/pdf/vsphere4/r40/vsp_40_admin_guide.pdf - [3] http://www.vmware.com/technical-resources/virtualization-topics/virtual-appliances/faqs fog-1.19.0/lib/fog/vcloud/requests/0000755000004100000410000000000012261242552017076 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud/requests/compute/0000755000004100000410000000000012261242552020552 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud/requests/compute/get_organization.rb0000644000004100000410000000020412261242552024436 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_organization end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_customization_options.rb0000644000004100000410000000021412261242552026416 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_customization_options end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_task_list.rb0000644000004100000410000000020112261242552023724 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_task_list end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_task.rb0000644000004100000410000000017412261242552022702 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_task end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_vm_memory.rb0000644000004100000410000000045212261242552023751 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real def get_vm_memory(href, parse = true) request( :expects => 200, :uri => href, :parse => parse ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/configure_vm_memory.rb0000644000004100000410000000361412261242552025156 0ustar www-datawww-data# -*- coding: utf-8 -*- module Fog module Vcloud class Compute class Real def configure_vm_memory(vm_data) edit_uri = vm_data.select {|k,v| k == :Link && v[:rel] == 'edit'} edit_uri = edit_uri.kind_of?(Array) ? edit_uri.flatten[1][:href] : edit_uri[:Link][:href] body = < byte * 2^20 Memory Size #{vm_data[:'rasd:VirtualQuantity']} MB of memory 5 0 4 #{vm_data[:'rasd:VirtualQuantity']} 0 EOF request( :body => body, :expects => 202, :headers => { 'Content-Type' => vm_data[:"vcloud_type"] || 'application/vnd.vmware.vcloud.rasdItem+xml' }, :method => 'PUT', :uri => edit_uri, :parse => true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/delete_metadata.rb0000644000004100000410000000022112261242552024174 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :delete_metadata, 202, "DELETE" end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_vm_disks.rb0000644000004100000410000000044512261242552023560 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real def get_vm_disks(href) request( :expects => 200, :uri => href, :parse => true#false#true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_server.rb0000644000004100000410000000017512261242552023247 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_server end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_vapp_template.rb0000644000004100000410000000020512261242552024574 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_vapp_template end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/configure_node.rb0000644000004100000410000000201412261242552024062 0ustar www-datawww-datamodule Fog module Vcloud class Compute module Shared private def generate_configure_node_request(node_data) builder = Builder::XmlMarkup.new builder.NodeService(:"xmlns:i" => "http://www.w3.org/2001/XMLSchema-instance", :xmlns => "urn:tmrk:eCloudExtensions-2.0") { builder.Name(node_data[:name]) builder.Enabled(node_data[:enabled].to_s) builder.Description(node_data[:description]) } end end class Real include Shared def configure_node(node_uri, node_data) validate_node_data(node_data, true) request( :body => generate_configure_node_request(node_data), :expects => 200, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.nodeService+xml'}, :method => 'PUT', :uri => node_uri, :parse => true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/power_off.rb0000644000004100000410000000021112261242552023057 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :power_off, 202, 'POST' end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/undeploy.rb0000644000004100000410000000221612261242552022737 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real def undeploy(vapp_uri, save_state = false) # builder = Builder::XmlMarkup.new # builder.UndeployVAppParams(:xmlns => 'http://www.vmware.com/vcloud/v1', # :saveState => save_state) {} builder = if version =='1.0' "" else < shutdown EOF end request( :body => builder, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.undeployVAppParams+xml' }, :method => 'POST', :uri => vapp_uri + '/action/undeploy', :parse => true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_network.rb0000644000004100000410000000017612261242552023433 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_network end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/power_shutdown.rb0000644000004100000410000000021712261242552024166 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :power_shutdown, 204, 'POST' end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/clone_vapp.rb0000644000004100000410000000251112261242552023224 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real def validate_clone_vapp_options(options) valid_opts = [:name, :poweron] unless valid_opts.all? { |opt| options.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(valid_opts - options.keys).map(&:inspect).join(", ")}") end end def generate_clone_vapp_request(uri, options) xml = Builder::XmlMarkup.new xml.CloneVAppParams(xmlns.merge!(:name => options[:name], :deploy => "true", :powerOn => options[:poweron])) { xml.VApp( :href => uri, :type => "application/vnd.vmware.vcloud.vApp+xml", :xmlns => "http://www.vmware.com/vcloud/v0.8") } end def clone_vapp(vdc_uri, vapp_uri, options = {}) unless options.has_key?(:poweron) options[:poweron] = "false" end validate_clone_vapp_options(options) request( :body => generate_clone_vapp_request(vapp_uri, options), :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.cloneVAppParams+xml'}, :method => 'POST', :uri => vdc_uri + '/action/clonevapp', :parse => true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_network_extensions.rb0000644000004100000410000000021212261242552025701 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_network_extensions end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/login.rb0000644000004100000410000000102312261242552022203 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real def login headers = { 'Authorization' => authorization_header } uri = if version == '1.0' "#{base_url}/login" else "#{base_path_url}/sessions" end unauthenticated_request({ :expects => 200, :headers => headers, :method => 'POST', :parse => true, :uri => uri }) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/configure_network_ip.rb0000644000004100000410000000257312261242552025330 0ustar www-datawww-datamodule Fog module Vcloud class Compute module Shared private def validate_network_ip_data(network_ip_data) valid_opts = [:id, :href, :name, :status, :server] unless valid_opts.all? { |opt| network_ip_data.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(valid_opts - network_ip_data.keys).map(&:inspect).join(", ")}") end end end class Real include Shared def configure_network_ip(network_ip_uri, network_ip_data) validate_network_ip_data(network_ip_data) request( :body => generate_configure_network_ip_request(network_ip_data), :expects => 200, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.ip+xml' }, :method => 'PUT', :uri => network_ip_uri, :parse => true ) end private def generate_configure_network_ip_request(network_ip_data) builder = Builder::XmlMarkup.new builder.IpAddress(xmlns) { builder.Id(network_ip_data[:id]) builder.Href(network_ip_data[:href]) builder.Name(network_ip_data[:name]) builder.Status(network_ip_data[:status]) builder.Server(network_ip_data[:server]) } end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/configure_vapp.rb0000644000004100000410000001322512261242552024111 0ustar www-datawww-datamodule Fog module Vcloud class Compute module Shared private def validate_vapp_data(vapp_data) valid_opts = [:name, :cpus, :memory, :disks] unless valid_opts.all? { |opt| vapp_data.has_key?(opt) } raise ArgumentError.new("Required Vapp data missing: #{(valid_opts - vapp_data.keys).map(&:inspect).join(", ")}") end end end class Real include Shared def generate_configure_vapp_request(vapp_uri, vapp_data) rasd_xmlns = { "xmlns" => "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData" } xml = Nokogiri::XML(request( :uri => vapp_uri).body) xml.root['name'] = vapp_data[:name] #cpu xml.at("//xmlns:ResourceType[.='3']/..", rasd_xmlns).at('.//xmlns:VirtualQuantity', rasd_xmlns).content = vapp_data[:cpus] #memory xml.at("//xmlns:ResourceType[.='4']/..", rasd_xmlns).at('.//xmlns:VirtualQuantity', rasd_xmlns).content = vapp_data[:memory] #disks real_disks = xml.xpath("//xmlns:ResourceType[ .='17']/..", rasd_xmlns) real_disk_numbers = real_disks.map { |disk| disk.at('.//xmlns:AddressOnParent', rasd_xmlns).content } disk_numbers = vapp_data[:disks].map { |vdisk| vdisk[:number].to_s } if vapp_data[:disks].length < real_disks.length #Assume we're removing a disk remove_disk_numbers = real_disk_numbers - disk_numbers remove_disk_numbers.each do |number| if result = xml.at("//xmlns:ResourceType[ .='17']/../xmlns:AddressOnParent[.='#{number}']/..", rasd_xmlns) result.remove end end elsif vapp_data[:disks].length > real_disks.length add_disk_numbers = disk_numbers - real_disk_numbers add_disk_numbers.each do |number| new_disk = real_disks.first.dup new_disk.at('.//xmlns:AddressOnParent', rasd_xmlns).content = -1 new_disk.at('.//xmlns:VirtualQuantity', rasd_xmlns).content = vapp_data[:disks].detect { |disk| disk[:number].to_s == number.to_s }[:size] real_disks.first.parent << new_disk end end #puts xml.root.to_s xml.root.to_s #builder = Builder::XmlMarkup.new #builder.Vapp(:href => vapp_uri.to_s, # :type => 'application/vnd.vmware.vcloud.vApp+xml', # :name => vapp_data[:name], # :status => 2, # :size => 0, # :xmlns => 'http://www.vmware.com/vcloud/v0.8', # :"xmlns:xsi" => 'http://www.w3.org/2001/XMLSchema-instance', # :"xmlns:xsd" => 'http://www.w3.org/2001/XMLSchema') { # #builder.VirtualHardwareSection(:xmlns => 'http://schemas.dmtf.org/ovf/envelope/1') { # builder.Section(:"xsi:type" => "q2:VirtualHardwareSection_Type", :xmlns => "http://schemas.dmtf.org/ovf/envelope/1", :"xmlns:q2" => "http://www.vmware.com/vcloud/v0.8") { # builder.Info('Virtual Hardware') # builder.Item(:xmlns => 'http://schemas.dmtf.org/ovf/envelope/1') { # #builder.Item { # builder.InstanceID(1, :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.ResourceType(3, :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.VirtualQuantity(vapp_data[:cpus], :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # } # builder.Item(:xmlns => 'http://schemas.dmtf.org/ovf/envelope/1') { # #builder.Item { # builder.InstanceID(2, :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.ResourceType(4, :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.VirtualQuantity(vapp_data[:memory], :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # } # vapp_data[:disks].each do |disk_data| # #builder.Item(:xmlns => 'http://schemas.dmtf.org/ovf/envelope/1') { # builder.Item { # builder.AddressOnParent(disk_data[:number], :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.HostResource(disk_data[:resource], :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.InstanceID(9, :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.ResourceType(17, :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.VirtualQuantity(disk_data[:size], :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # } # end # # } #} end def configure_vapp(vapp_uri, vapp_data) validate_vapp_data(vapp_data) request( :body => generate_configure_vapp_request(vapp_uri, vapp_data), :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.vApp+xml' }, :method => 'PUT', :uri => vapp_uri, :parse => true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_vdc.rb0000644000004100000410000000017212261242552022512 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_vdc end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/configure_vm.rb0000644000004100000410000001401212261242552023560 0ustar www-datawww-datamodule Fog module Vcloud class Compute module Shared private def validate_vm_data(vm_data) valid_opts = [:name, :cpus, :memory, :disks] unless valid_opts.all? { |opt| vm_data.has_key?(opt) } raise ArgumentError.new("Required vm data missing: #{(valid_opts - vm_data.keys).map(&:inspect).join(", ")}") end end end class Real include Shared def generate_configure_vm_request(vm_data) xmlns = 'http://schemas.dmtf.org/ovf/envelope/1' xmlns_vcloud = 'http://www.vmware.com/vcloud/v1' xmlns_rasd = 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData' xmlns_vssd = 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData' builder = Builder::XmlMarkup.new(:target=>STDOUT, :indent=>2) # TODO - remove params builder.VirtualHardwareSection( :"vcloud:href" => vm_data[:"vcloud_href"], :"vcloud:type" => vm_data[:"vcloud_type"], :name => vm_data[:name], :status => 2, :size => 0, :xmlns => xmlns, :"xmlns:vcloud" => xmlns_vcloud, :"xmlns:rasd" => xmlns_rasd, :"xmlns:vssd" => xmlns_vssd) { #builder.VirtualHardwareSection(:xmlns => 'http://schemas.dmtf.org/ovf/envelope/1') { builder.Info(vm_data[:"ovf:Info"]) if system = vm_data[:"ovf:System"] builder.System { builder.ElementName(system[:"vssd:ElementName"], :xmlns => xmlns_vssd) if system[:"vssd:ElementName"] builder.InstanceID(system[:"vssd:InstanceID"], :xmlns => xmlns_vssd) if system[:"vssd:InstanceID"] builder.VirtualSystemIdentifier(system[:"vssd:VirtualSystemIdentifier"], :xmlns => xmlns_vssd) if system[:"vssd:VirtualSystemIdentifier"] builder.VirtualSystemType(system[:"vssd:VirtualSystemType"], :xmlns => xmlns_vssd) if system[:"vssd:VirtualSystemType"] } end vm_data[:'ovf:Item'].each do |oi| builder.Item { builder.Address(oi[:'rasd:Address'], :xmlns => xmlns_rasd) if oi[:'rasd:Address'] builder.AddressOnParent(oi[:'rasd:AddressOnParent'], :xmlns => xmlns_rasd) if oi[:'rasd:AddressOnParent'] builder.AutomaticAllocation(oi[:'rasd:AutomaticAllocation'], :xmlns => xmlns_rasd) if oi[:'rasd:AutomaticAllocation'] builder.Connection(oi[:'rasd:Connection'], :xmlns => xmlns_rasd) if oi[:'rasd:Connection'] builder.Description(oi[:'rasd:Description'], :xmlns => xmlns_rasd) if oi[:'rasd:Description'] builder.ElementName(oi[:'rasd:ElementName'], :xmlns => xmlns_rasd) if oi[:'rasd:ElementName'] builder.InstanceID(oi[:'rasd:InstanceID'], :xmlns => xmlns_rasd) if oi[:'rasd:InstanceID'] builder.ResourceSubType(oi[:'rasd:ResourceSubType'], :xmlns => xmlns_rasd) if oi[:'rasd:ResourceSubType'] builder.ResourceType(oi[:'rasd:ResourceType'], :xmlns => xmlns_rasd) if oi[:'rasd:ResourceType'] if hr = oi[:'rasd:HostResource'] attrs = {} attrs[] end } end # builder.Item(:xmlns => 'http://schemas.dmtf.org/ovf/envelope/1') { # #builder.Item { # builder.InstanceID(1, :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.ResourceType(3, :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.VirtualQuantity(vm_data[:cpus], :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # } # builder.Item(:xmlns => 'http://schemas.dmtf.org/ovf/envelope/1') { # #builder.Item { # builder.InstanceID(2, :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.ResourceType(4, :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.VirtualQuantity(vm_data[:memory], :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # } # vm_data[:disks].each do |disk_data| # #builder.Item(:xmlns => 'http://schemas.dmtf.org/ovf/envelope/1') { # builder.Item { # builder.AddressOnParent(disk_data[:number], :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.HostResource(disk_data[:resource], :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.InstanceID(9, :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.ResourceType(17, :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # builder.VirtualQuantity(disk_data[:size], :xmlns => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData') # } # end } end def configure_vm(vm_uri, vm_data) validate_vm_data(vm_data) request( :body => generate_configure_vm_request(vm_uri, vm_data), :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.vm+xml' }, :method => 'PUT', :uri => vm_uri, :parse => true ) end end end end endfog-1.19.0/lib/fog/vcloud/requests/compute/delete_node.rb0000644000004100000410000000022512261242552023345 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :delete_node, 200, 'DELETE', {}, "" end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/configure_network.rb0000644000004100000410000000255712261242552024642 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real def validate_network_data(network_data, configure=false) valid_opts = [:id, :href, :name, :address, :broadcast, :gateway] unless valid_opts.all? { |opt| network_data.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(valid_opts - network_data.keys).map(&:inspect).join(", ")}") end end def configure_network(network_uri, network_data) validate_network_data(network_data) request( :body => generate_configure_network_request(network_data), :expects => 200, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.networkService+xml'}, :method => 'PUT', :uri => network_uri, :parse => true ) end private def generate_configure_network_request(network_data) builder = Builder::XmlMarkup.new builder.Network(xmlns) { builder.Id(network_data[:id]) builder.Href(network_data[:href]) builder.Name(network_data[:name]) builder.Address(network_data[:address]) builder.BroadcastAddress(network_data[:broadcast]) builder.GatewayAddress(network_data[:gateway]) } end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/configure_vm_password.rb0000644000004100000410000000331212261242552025503 0ustar www-datawww-data# -*- encoding: utf-8 -*- module Fog module Vcloud class Compute class Real def configure_vm_password(vmdata) edit_uri = vmdata[:href] body = < Specifies Guest OS Customization Settings true false #{vmdata[:VirtualMachineId]} false false true false #{vmdata[:AdminPassword]} false #{vmdata[:ComputerName]} EOF request( :body => body, :expects => 202, :headers => {'Content-Type' => vmdata[:type] }, :method => 'PUT', :uri => "#{edit_uri}", :parse => true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/power_reset.rb0000644000004100000410000000021412261242552023432 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :power_reset, 202, 'POST' end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_catalog.rb0000644000004100000410000000017612261242552023354 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_catalog end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/configure_metadata.rb0000644000004100000410000000202112261242552024713 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real def configure_metadata(opts= {}) valid_opts = [:key, :value, :href] unless valid_opts.all? { |opt| opts.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(valid_opts - opts.keys).map(&:inspect).join(", ")}") end body = < #{opts[:key]} #{opts[:value]} EOF request( :body => body, :expects => 202, # it returns a task object :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.metadata+xml' }, :method => 'POST', :uri => opts[:href], :parse => true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/configure_vm_name_description.rb0000644000004100000410000000130412261242552027163 0ustar www-datawww-data# -*- coding: utf-8 -*- module Fog module Vcloud class Compute class Real def configure_vm_name_description(edit_href, name, description) body = < #{description} EOF request( :body => body, :expects => 202, :headers => {'Content-Type' => "application/vnd.vmware.vcloud.vApp+xml"}, :method => 'PUT', :uri => edit_href, :parse => true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_vapp.rb0000644000004100000410000000017312261242552022705 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_vapp end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/instantiate_vapp_template.rb0000644000004100000410000000735212261242552026352 0ustar www-datawww-datamodule Fog module Vcloud class Compute module Shared private def validate_instantiate_vapp_template_options options # :network_uri removed, if not specified will use template network config. valid_opts = [:catalog_item_uri, :name, :vdc_uri] unless valid_opts.all? { |opt| options.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(valid_opts - options.keys).map(&:inspect).join(", ")}") end catalog_item_uri = options[:catalog_item_uri] # Figure out the template_uri catalog_item = get_catalog_item( catalog_item_uri ).body catalog_item[:Entity] = [ catalog_item[:Entity] ] if catalog_item[:Entity].is_a?(Hash) catalog_item[:Link] = [ catalog_item[:Link] ] if catalog_item[:Link].is_a?(Hash) options[:template_uri] = begin catalog_item[:Entity].detect { |entity| entity[:type] == "application/vnd.vmware.vcloud.vAppTemplate+xml" }[:href] rescue raise RuntimeError.new("Unable to locate template uri for #{catalog_item_uri}") end customization_options = begin get_vapp_template(options[:template_uri]).body[:Children][:Vm][:GuestCustomizationSection] rescue raise RuntimeError.new("Unable to get customization options for #{catalog_item_uri}") end # Check to see if we can set the password if options[:password] and customization_options[:AdminPasswordEnabled] == "false" raise ArgumentError.new("This catalog item (#{catalog_item_uri}) does not allow setting a password.") end # According to the docs if CustomizePassword is "true" then we NEED to set a password if customization_options[:AdminPasswordEnabled] == "true" and customization_options[:AdminPasswordAuto] == "false" and ( options[:password].nil? or options[:password].empty? ) raise ArgumentError.new("This catalog item (#{catalog_item_uri}) requires a :password to instantiate.") end end def generate_instantiate_vapp_template_request(options) xml = Builder::XmlMarkup.new xml.InstantiateVAppTemplateParams(xmlns.merge!(:name => options[:name], :"xml:lang" => "en")) { xml.Description(options[:description]) xml.InstantiationParams { if options[:network_uri] # TODO - implement properly xml.NetworkConfigSection { xml.tag!("ovf:Info"){ "Configuration parameters for logical networks" } xml.NetworkConfig("networkName" => options[:network_name]) { # xml.NetworkAssociation( :href => options[:network_uri] ) xml.Configuration { xml.ParentNetwork("name" => options[:network_name], "href" => options[:network_uri]) xml.FenceMode("bridged") } } } end } # The template xml.Source(:href => options[:template_uri]) xml.AllEULAsAccepted("true") } end end class Real include Shared def instantiate_vapp_template options = {} validate_instantiate_vapp_template_options options request( :body => generate_instantiate_vapp_template_request(options), :expects => 201, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml'}, :method => 'POST', :uri => options[:vdc_uri] + '/action/instantiateVAppTemplate', :parse => true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_metadata.rb0000644000004100000410000000017712261242552023523 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_metadata end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/configure_org_network.rb0000644000004100000410000001351212261242552025502 0ustar www-datawww-data# -*- coding: utf-8 -*- module Fog module Vcloud class Compute class Real def generate_outbound_rule() outbound_rule = < true OUTGOING allow true -1 Any -1 Any out false EOF outbound_rule end def generate_tcp_rules(tcp_ports) firewall_rules = "" tcp_ports.each do |port| firewall_rules << < true #{port} allow true #{port} Any -1 Any in false EOF end firewall_rules end def generate_udp_rules(udp_ports) firewall_rules = "" udp_ports.each do |port| firewall_rules << < true #{port} allow true #{port} Any -1 Any in false EOF end firewall_rules end def generate_configure_org_network_request(vapp_id, vapp_network, vapp_network_uri, org_network, org_network_uri, enable_firewall=false, portmap=nil) firewall_body = "" if not enable_firewall firewall_body = "false" else firewall_rules = generate_outbound_rule + generate_tcp_rules(portmap["TCP"]) + generate_udp_rules(portmap["UDP"]) firewall_body = <true drop false #{firewall_rules} EOF end body = < The configuration parameters for logical networks natRouted true #{firewall_body} true ipTranslation allowTraffic false bridged true EOF end def configure_org_network(vapp_id, vapp_network, vapp_network_uri, org_network, org_network_uri, enable_firewall=false, port_map=nil) body = generate_configure_org_network_request(vapp_id, vapp_network, vapp_network_uri, org_network, org_network_uri, enable_firewall, port_map) #puts ("Body: #{body}") request( :body => body, :expects => 202, :headers => {'Content-Type' => 'Application/vnd.vmware.vcloud.networkConfigSection+xml' }, :method => 'PUT', :uri => "#{vapp_id}/networkConfigSection", :parse => true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_network_ips.rb0000644000004100000410000000031212261242552024276 0ustar www-datawww-data# # AFAICT - This is basically undocumented - 6/18/2010 - freeformz # module Fog module Vcloud class Compute class Real basic_request :get_network_ips end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/configure_vm_disks.rb0000644000004100000410000001113312261242552024756 0ustar www-datawww-data# -*- coding: utf-8 -*- # # # # 0 # SCSI Controller # SCSI Controller 0 # 2 # lsilogic # 6 # # # 0 # Hard disk # Hard disk 1 # # 2000 # 2 # 17 # # # 0 # IDE Controller # IDE Controller 0 # 3 # 5 # # module Fog module Vcloud class Compute class Real def generate_configure_vm_disks_request(href, disk_data) xmlns = { "xmlns:rasd" => "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData", "xmlns" => "http://www.vmware.com/vcloud/v1" } # Get the XML from the API, parse it. xml = Nokogiri::XML(request( :uri => href).body) #xml.root['name'] = vapp_data[:name] #disks real_disks = xml.xpath("//rasd:ResourceType[ .='17']/..", xmlns) real_disk_numbers = real_disks.map { |disk| disk.at('.//rasd:AddressOnParent', xmlns).content } disk_numbers = disk_data.map { |vdisk| vdisk[:"rasd:AddressOnParent"].to_s } if disk_data.length < real_disks.length #Assume we're removing a disk remove_disk_numbers = real_disk_numbers - disk_numbers remove_disk_numbers.each do |number| if result = xml.at("//rasd:ResourceType[ .='17']/../rasd:AddressOnParent[.='#{number}']/..", xmlns) result.remove end end elsif disk_data.length > real_disks.length add_disk_numbers = disk_numbers - real_disk_numbers add_disk_numbers.each do |number| new_disk = real_disks.first.dup new_disk.at('.//rasd:AddressOnParent', xmlns).content = number.to_i #-1 new_disk.at('.//rasd:HostResource', xmlns)["vcloud:capacity"] = disk_data.detect { |disk| disk[:'rasd:AddressOnParent'].to_s == number.to_s }[:'rasd:HostResource'][:vcloud_capacity].to_s # nokogiri bug? shouldn't need to add this explicitly. new_disk.at('.//rasd:HostResource', xmlns)["xmlns:vcloud"] = xmlns['xmlns'] new_disk.at('.//rasd:InstanceID', xmlns).content = (2000 + number.to_i).to_s new_disk.at('.//rasd:ElementName', xmlns).content = "Hard disk #{number.to_i + 1}" real_disks.first.parent << new_disk end end xml.to_s end def configure_vm_disks(vm_href, disk_data) disk_href = vm_href + '/virtualHardwareSection/disks' body = generate_configure_vm_disks_request(disk_href, disk_data) request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.rasdItem+xml' }, :method => 'PUT', :uri => disk_href, :parse => true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/configure_vm_network.rb0000644000004100000410000000266712261242552025346 0ustar www-datawww-data# -*- encoding: utf-8 -*- module Fog module Vcloud class Compute class Real def configure_vm_network(network_info) edit_uri = network_info.select {|k,v| k == :Link && v[:rel] == 'edit'} edit_uri = edit_uri.kind_of?(Array) ? edit_uri.flatten[1][:href] : edit_uri[:Link][:href] body = < Specifies the available VM network connections 0 0 true #{network_info[:NetworkConnection][:IpAddressAllocationMode]} EOF request( :body => body, :expects => 202, :headers => {'Content-Type' => network_info[:"type"] }, :method => 'PUT', :uri => "#{edit_uri}", :parse => true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/configure_vm_cpus.rb0000644000004100000410000000363612261242552024624 0ustar www-datawww-data# -*- encoding: utf-8 -*- module Fog module Vcloud class Compute class Real def configure_vm_cpus(vm_data) edit_uri = vm_data.select {|k,v| k == :Link && v[:rel] == 'edit'} edit_uri = edit_uri.kind_of?(Array) ? edit_uri.flatten[1][:href] : edit_uri[:Link][:href] body = < hertz * 10^6 Number of Virtual CPUs #{vm_data[:'rasd:VirtualQuantity']} virtual CPU(s) 4 0 3 #{vm_data[:'rasd:VirtualQuantity']} 0 EOF request( :body => body, :expects => 202, :headers => { 'Content-Type' => vm_data[:"vcloud_type"] || 'application/vnd.vmware.vcloud.rasdItem+xml' }, :method => 'PUT', :uri => "#{edit_uri}", :parse => true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/power_on.rb0000644000004100000410000000021112261242552022721 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :power_on, 202, 'POST' end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/delete_vapp.rb0000644000004100000410000000021512261242552023365 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :delete_vapp, 202, "DELETE" end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_network_ip.rb0000644000004100000410000000031312261242552024114 0ustar www-datawww-data# # AFAICT this is basically undocumented ATM - 6/18/2010 - freeformz # module Fog module Vcloud class Compute class Real basic_request :get_network_ip end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/configure_vm_customization_script.rb0000644000004100000410000000266212261242552030144 0ustar www-datawww-data# -*- encoding: utf-8 -*- module Fog module Vcloud class Compute class Real def configure_vm_customization_script(vmdata) edit_uri = vmdata[:href] body = < Specifies Guest OS Customization Settings true #{CGI.escapeHTML(vmdata[:CustomizationScript])} #{vmdata[:ComputerName]} EOF request( :body => body, :expects => 202, :headers => {'Content-Type' => vmdata[:type] }, :method => 'PUT', :uri => "#{edit_uri}", :parse => true ) end end end end end fog-1.19.0/lib/fog/vcloud/requests/compute/get_catalog_item.rb0000644000004100000410000000020312261242552024361 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_catalog_item end end end end fog-1.19.0/lib/fog/vcloud/models/0000755000004100000410000000000012261242552016506 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud/models/compute/0000755000004100000410000000000012261242552020162 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud/models/compute/task.rb0000644000004100000410000000113712261242552021453 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Task < Fog::Vcloud::Model identity :href, :aliases => :Href attribute :links, :aliases => :Link, :type => :array ignore_attributes :xmlns, :xmlns_i, :xmlns_xsi, :xmlns_xsd attribute :status attribute :type attribute :result, :aliases => :Result attribute :owner, :aliases => :Owner attribute :start_time, :aliases => :startTime, :type => :time attribute :end_time, :aliases => :endTime, :type => :time attribute :error, :aliases => :Error end end end end fog-1.19.0/lib/fog/vcloud/models/compute/ips.rb0000644000004100000410000000130212261242552021276 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/ip' module Fog module Vcloud class Compute class Ips < Fog::Vcloud::Collection model Fog::Vcloud::Compute::Ip undef_method :create attribute :href def all self.href = service.default_vdc_href unless self.href check_href!( :messages => "Ips href of a Network you want to enumerate" ) if data = service.get_network_ips(href).body[:IpAddress] load(data) end end def get(uri) if data = service.get_network_ip(uri).body new(data) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/organization.rb0000644000004100000410000000224012261242552023211 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Organization < Fog::Vcloud::Model identity :href, :aliases => :Href attribute :links, :aliases => :Link, :type => :array ignore_attributes :xmlns, :xmlns_i, :xmlns_xsi, :xmlns_xsd attribute :name attribute :description, :aliases => :Description attribute :type attribute :full_name, :aliases => :FullName def networks @networks ||= Fog::Vcloud::Compute::Networks. new( :service => service, :href => href ) end def tasks load_unless_loaded! @tasks ||= Fog::Vcloud::Compute::Tasks. new( :service => service, :href => other_links.find{|l| l[:type] == 'application/vnd.vmware.vcloud.tasksList+xml'}[:href] ) end def vdcs @vdcs ||= Fog::Vcloud::Compute::Vdcs. new( :service => service, :href => href ) end def catalogs @catalogs ||= Fog::Vcloud::Compute::Catalogs. new( :service => service, :href => href ) end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/servers.rb0000644000004100000410000000205612261242552022203 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/server' module Fog module Vcloud class Compute class Servers < Fog::Vcloud::Collection undef_method :create model Fog::Vcloud::Compute::Server attribute :href, :aliases => :Href def all check_href!("Vapp") vapp.load_unless_loaded! load(vapp.children||[]) end def get(uri) service.get_vapp(uri) rescue Fog::Errors::NotFound nil end def create options check_href! options[:vdc_uri] = href data = service.instantiate_vapp_template(options).body object = new(data) object end private def vapp @vapp ||= (attributes[:vapp] || init_vapp) end def init_vapp Fog::Vcloud::Compute::Vapp.new( :service => service, :href => self.href, :collection => Fog::Vcloud::Compute::Vapps.new(:service => service) ) end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/vdc.rb0000644000004100000410000000251312261242552021264 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Vdc < Fog::Vcloud::Model identity :href, :aliases => :Href attribute :links, :aliases => :Link, :type => :array ignore_attributes :xmlns, :xmlns_i, :xmlns_xsi, :xmlns_xsd attribute :name attribute :type attribute :description, :aliases => :Description attribute :network_quota, :aliases => :NetworkQuota, :type => :integer attribute :nic_quota, :aliases => :NicQuota, :type => :integer attribute :vm_quota, :aliases => :VmQuota, :type => :integer attribute :is_enabled, :aliases => :IsEnabled, :type => :boolean attribute :compute_capacity, :aliases => :ComputeCapacity attribute :storage_capacity, :aliases => :StorageCapacity attribute :available_networks, :aliases => :AvailableNetworks, :squash => :Network attribute :resource_entities, :aliases => :ResourceEntities, :squash => :ResourceEntity has_up :organization def networks @networks ||= Fog::Vcloud::Compute::Networks. new( :service => service, :href => href ) end def vapps @vapps ||= Fog::Vcloud::Compute::Vapps. new( :service => service, :href => href ) end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/catalogs.rb0000644000004100000410000000161012261242552022302 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/catalog' module Fog module Vcloud class Compute class Catalogs < Fog::Vcloud::Collection model Fog::Vcloud::Compute::Catalog attribute :organization_uri def all org_uri = self.organization_uri || service.default_organization_uri data = service.get_organization(org_uri).links.select { |link| link[:type] == "application/vnd.vmware.vcloud.catalog+xml" } load(data) end def get(uri) service.get_catalog(uri) rescue Fog::Errors::NotFound nil end def item_by_name(name) res = nil items = all.collect { |catalog| catalog.catalog_items } items.each do |i| i.collect do |ii| res = ii if ii.name == name end end res end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/network.rb0000644000004100000410000000126712261242552022206 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Network < Fog::Vcloud::Model identity :href, :aliases => :Href attribute :links, :aliases => :Link, :type => :array ignore_attributes :xmlns, :xmlns_i, :xmlns_xsi, :xmlns_xsd attribute :name, :aliases => :Name attribute :description, :aliases => :Description attribute :configuration, :aliases => :Configuration attribute :provider_info, :aliases => :ProviderInfo def parent_network return nil if configuration[:ParentNetwork].nil? @parent_network ||= service.get_network(configuration[:ParentNetwork][:href]) end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/catalog.rb0000644000004100000410000000077612261242552022133 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Catalog < Fog::Vcloud::Model identity :href, :aliases => :Href attribute :links, :aliases => :Link, :type => :array ignore_attributes :xmlns, :xmlns_i, :xmlns_xsi, :xmlns_xsd attribute :type attribute :name def catalog_items @catalog_items ||= Fog::Vcloud::Compute::CatalogItems. new( :service => service, :href => href ) end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/ip.rb0000644000004100000410000000166712261242552021131 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Ip < Fog::Vcloud::Model identity :href, :aliases => :Href attribute :links, :aliases => :Link, :type => :array ignore_attributes :xmlns, :xmlns_i, :xmlns_xsi, :xmlns_xsd attribute :name, :aliases => :Name attribute :status, :aliases => :Status attribute :server, :aliases => :Server attribute :id, :aliases => :Id, :type => :integer def save if @changed service.configure_network_ip( href, _compose_network_ip_data ) end true end def reload super @changed = false self end private def _compose_network_ip_data { :id => id, :href => href, :name => name, :status => status, :server => server } end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/tag.rb0000644000004100000410000000070012261242552021257 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Tag < Fog::Vcloud::Model identity :href, :aliases => :Href attribute :links, :aliases => :Link, :type => :array ignore_attributes :xmlns, :xmlns_i, :xmlns_xsi, :xmlns_xsd attribute :key, :aliases => :Key attribute :value, :aliases => :Value def destroy service.delete_metadata(href) end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/tags.rb0000644000004100000410000000122512261242552021445 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/tag' module Fog module Vcloud class Compute class Tags < Fog::Vcloud::Collection undef_method :create model Fog::Vcloud::Compute::Tag attribute :href, :aliases => :Href def all metadata = service.get_metadata(self.href) load(metadata.body[:MetadataEntry]) if metadata.body[:MetadataEntry] end def get(uri) service.get_metadata(uri) rescue Fog::Errors::NotFound nil end def create(opts) service.configure_metadata(opts.merge(href: href)) end end end end endfog-1.19.0/lib/fog/vcloud/models/compute/catalog_items.rb0000644000004100000410000000144412261242552023325 0ustar www-datawww-datamodule Fog module Vcloud class Compute class CatalogItems < Fog::Vcloud::Collection undef_method :create model Fog::Vcloud::Compute::CatalogItem attribute :href, :aliases => :Href def all catalog_item_info = service.get_catalog_item(self.href) items = service.get_catalog_item(self.href).body[:CatalogItems] if items.size > 0 data = items[:CatalogItem] load(data) end end def get(uri) if data = service.get_catalog_item(uri) new(data.body) end rescue Fog::Errors::NotFound nil end def organization_uri @organization_uri ||= service.default_organization_uri end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/vapp.rb0000644000004100000410000000262112261242552021456 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/helpers/status' module Fog module Vcloud class Compute class Vapp < Fog::Vcloud::Model include Fog::Vcloud::Compute::Helpers::Status identity :href, :aliases => :Href attribute :links, :aliases => :Link, :type => :array ignore_attributes :xmlns, :xmlns_i, :xmlns_xsi, :xmlns_xsd attribute :name attribute :type attribute :status attribute :description, :aliases => :Description attribute :deployed, :type => :boolean attribute :children, :aliases => :Children, :squash => :Vm attribute :lease_settings, :aliases => :LeaseSettingsSection attribute :network_configs, :aliases => :NetworkConfigSection has_up :vdc def servers @servers ||= Fog::Vcloud::Compute::Servers. new( :service => service, :href => href, :vapp => self ) end def networks @networks ||= Fog::Vcloud::Compute::Networks. new( :service => service, :href => href ) end def ready? reload_status # always ensure we have the correct status status != '0' end private def reload_status vapp = service.get_vapp(href) self.status = vapp.status end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/catalog_item.rb0000644000004100000410000000237712261242552023150 0ustar www-datawww-datamodule Fog module Vcloud class Compute class CatalogItem < Fog::Vcloud::Model identity :href, :aliases => :Href attribute :links, :aliases => :Link, :type => :array ignore_attributes :xmlns, :xmlns_i, :xmlns_xsi, :xmlns_xsd attribute :type attribute :name attribute :entity, :aliases => :Entity attribute :link, :aliases => :Link attribute :property, :aliases => :Property def customization_options load_unless_loaded! if data = service.get_customization_options( link[:href] ).body data.delete_if { |key, value| [:xmlns_i, :xmlns].include?(key) } data else nil end end def password_enabled? load_unless_loaded! customization_options = service.get_vapp_template(self.entity[:href]).body[:Children][:Vm][:GuestCustomizationSection] return false if customization_options[:AdminPasswordEnabled] == "false" return true if customization_options[:AdminPasswordEnabled] == "true" \ and customization_options[:AdminPasswordAuto] == "false" \ and ( options[:password].nil? or options[:password].empty? ) end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/vdcs.rb0000644000004100000410000000133012261242552021443 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/vdc' module Fog module Vcloud class Compute class Vdcs < Collection model Fog::Vcloud::Compute::Vdc undef_method :create attribute :href def all data = service.get_organization(org_uri).links.select { |link| link[:type] == "application/vnd.vmware.vcloud.vdc+xml" } data.each { |link| link.delete_if { |key, value| [:rel].include?(key) } } load(data) end def get(uri) service.get_vdc(uri) rescue Fog::Errors::NotFound nil end private def org_uri self.href ||= service.default_organization_uri end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/vapps.rb0000644000004100000410000000104312261242552021636 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/vapp' module Fog module Vcloud class Compute class Vapps < Collection model Fog::Vcloud::Compute::Vapp undef_method :create attribute :href def all load([service.get_vdc(service.default_vdc_href).resource_entities].flatten.select { |re| re[:type] == "application/vnd.vmware.vcloud.vApp+xml" }) end def get(uri) service.get_vapp(uri) rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/helpers/0000755000004100000410000000000012261242552021624 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud/models/compute/helpers/status.rb0000644000004100000410000000125612261242552023500 0ustar www-datawww-datamodule Fog module Vcloud class Compute module Helpers module Status def friendly_status load_unless_loaded! case status when '0' 'creating' when '8' 'off' when '4' 'on' else 'unknown' end end def on? reload_status status == '4' end def off? reload_status status == '8' end def reload_status reload # always ensure we have the correct status end end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/server.rb0000644000004100000410000002423512261242552022023 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/helpers/status' module Fog module Vcloud class Compute class Server < Fog::Vcloud::Model include Fog::Vcloud::Compute::Helpers::Status identity :href, :aliases => :Href attribute :links, :aliases => :Link, :type => :array ignore_attributes :xmlns, :xmlns_i, :xmlns_xsi, :xmlns_xsd attribute :type attribute :name attribute :status attribute :deployed, :type => :boolean attribute :description, :aliases => :Description attribute :vapp_scoped_local_id, :aliases => :VAppScopedLocalId attribute :network_connections, :aliases => :NetworkConnectionSection#, :squash => :NetworkConnection attribute :virtual_hardware, :aliases => :'ovf:VirtualHardwareSection', :squash => :'ovf:Item' attribute :guest_customization, :aliases => :GuestCustomizationSection attribute :operating_system, :aliases => :'ovf:OperatingSystemSection' attribute :tasks, :aliases => :Tasks, :type => :array has_up :vapp def tags Fog::Vcloud::Compute::Tags.new(:service => service, :href => href + '/metadata') end def customization_script load_unless_loaded! self.guest_customization[:CustomizationScript] end def customization_script=(custom_script) @changed = true @update_custom_script = custom_script end def computer_name load_unless_loaded! self.guest_customization[:ComputerName] end def os_desc load_unless_loaded! self.operating_system[:'ovf:Description'] end def os_type load_unless_loaded! self.operating_system[:vmw_osType] end def ip_addresses load_unless_loaded! [self.network_connections].flatten.collect{|n| n[:IpAddress] } end def ready? reload_status # always ensure we have the correct status running_tasks = self.tasks && self.tasks.flatten.any? {|ti| ti.kind_of?(Hash) && ti[:status] == 'running' } status != '0' && !running_tasks # 0 is provisioning, and no running tasks end def power_on power_operation( :power_on => :powerOn ) end def power_off power_operation( :power_off => :powerOff ) end def shutdown power_operation( :power_shutdown => :shutdown ) end def power_reset power_operation( :power_reset => :reset ) end # This is the real power-off operation def undeploy service.undeploy href end def graceful_restart requires :href shutdown wait_for { off? } power_on end def name=(new_name) attributes[:name] = new_name @changed = true end def password guest_customization[:AdminPassword] end def password=(password) return if password.nil? or password.size == 0 @changed = true @update_password = password end def cpus if cpu_mess { :count => cpu_mess[:"rasd:VirtualQuantity"].to_i, :units => cpu_mess[:"rasd:AllocationUnits"] } end end def cpus=(qty) return if qty.nil? or qty.size == 0 @changed = true @update_cpu_value = qty qty end def memory if memory_mess { :amount => memory_mess[:"rasd:VirtualQuantity"].to_i, :units => memory_mess[:"rasd:AllocationUnits"] } end end def memory=(amount) return if amount.nil? or amount.size == 0 @changed = true @update_memory_value = amount amount end def network network_connections[:NetworkConnection] if network_connections end def network=(network_info) @changed = true @update_network = network_info network_info end def disks disk_mess.map do |dm| { :number => dm[:"rasd:AddressOnParent"].to_i, :size => dm[:"rasd:HostResource"][:vcloud_capacity].to_i, :resource => dm[:"rasd:HostResource"], :disk_data => dm } end end def add_disk(size) if @disk_change == :deleted raise RuntimeError, "Can't add a disk w/o saving changes or reloading" else load_unless_loaded! @disk_change = :added @add_disk = { :'rasd:HostResource' => {:vcloud_capacity => size}, :'rasd:AddressOnParent' => (disk_mess.map { |dm| dm[:'rasd:AddressOnParent'] }.sort.last.to_i + 1).to_s, :'rasd:ResourceType' => '17' } end true end def delete_disk(number) if @disk_change == :added raise RuntimeError, "Can't delete a disk w/o saving changes or reloading" else load_unless_loaded! unless number == 0 @disk_change = :deleted @remove_disk = number end end true end def description=(description) @description_changed = true unless attributes[:description] == description || attributes[:description] == nil attributes[:description] = description end def name=(name) @name_changed = true unless attributes[:name] == name || attributes[:name] == nil attributes[:name] = name end def reload reset_tracking super end def save unless persisted? #Lame ... raise RuntimeError, "Should not be here" else if on? if @changed raise RuntimeError, "Can't save cpu, name or memory changes while the VM is on." end end if @update_custom_script guest_customization[:CustomizationScript] = @update_custom_script.to_s service.configure_vm_customization_script(guest_customization) wait_for { ready? } end if @update_password guest_customization[:AdminPassword] = @update_password.to_s service.configure_vm_password(guest_customization) wait_for { ready? } end if @update_cpu_value cpu_mess[:"rasd:VirtualQuantity"] = @update_cpu_value.to_s service.configure_vm_cpus(cpu_mess) wait_for { ready? } end if @update_memory_value memory_mess[:"rasd:VirtualQuantity"] = @update_memory_value.to_s service.configure_vm_memory(memory_mess) wait_for { ready? } end if @update_network network_connections[:NetworkConnection][:network] = @update_network[:network_name] network_connections[:NetworkConnection][:IpAddressAllocationMode] = @update_network[:network_mode] service.configure_vm_network(network_connections) wait_for { ready? } end if @disk_change == :deleted data = disk_mess.delete_if do |vh| vh[:'rasd:ResourceType'] == '17' && vh[:'rasd:AddressOnParent'].to_s == @remove_disk.to_s end service.configure_vm_disks(self.href, data) wait_for { ready? } end if @disk_change == :added data = disk_mess data << @add_disk service.configure_vm_disks(self.href, data) wait_for { ready? } end if @name_changed || @description_changed edit_uri = links.select {|i| i[:rel] == 'edit'} edit_uri = edit_uri.kind_of?(Array) ? edit_uri.flatten[0][:href] : edit_uri[:href] service.configure_vm_name_description(edit_uri, self.name, self.description) wait_for { ready? } end end reset_tracking true end def destroy if on? undeploy wait_for { off? } end wait_for { off? } # be sure.. wait_for { ready? } # be doubly sure.. sleep 2 # API lies. need to give it some time to be happy. service.delete_vapp(href).body[:status] == "running" end alias :delete :destroy private def reset_tracking @disk_change = false @changed = false @update_password = nil @update_cpu_value = nil @update_memory_value = nil @update_network = nil @name_changed = false @description_changed = nil end def _compose_vapp_data { :name => name, :cpus => cpus[:count], :memory => memory[:amount], :disks => disks } end def memory_mess load_unless_loaded! if virtual_hardware virtual_hardware.detect { |item| item[:"rasd:ResourceType"] == "4" } end end def cpu_mess load_unless_loaded! if virtual_hardware virtual_hardware.detect { |item| item[:"rasd:ResourceType"] == "3" } end end def disk_mess load_unless_loaded! if virtual_hardware virtual_hardware.select { |item| item[:"rasd:ResourceType"] == "17" } else [] end end def power_operation(op) requires :href begin service.send(op.keys.first, href + "/power/action/#{op.values.first}" ) rescue Excon::Errors::InternalServerError => e #Frankly we shouldn't get here ... raise e unless e.to_s =~ /because it is already powered o(n|ff)/ end true end def reload_status server = service.get_server(href) self.status = server.status self.tasks = server.tasks end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/organizations.rb0000644000004100000410000000121212261242552023372 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/organization' module Fog module Vcloud class Compute class Organizations < Collection model Fog::Vcloud::Compute::Organization undef_method :create def all raw_orgs = if service.version == '1.0' service.login else service.request(service.basic_request_params("#{service.base_path_url}/org/")) end data = raw_orgs.body[:Org] load(data) end def get(uri) service.get_organization(uri) rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/tasks.rb0000644000004100000410000000110012261242552021624 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/task' module Fog module Vcloud class Compute class Tasks < Fog::Vcloud::Collection model Fog::Vcloud::Compute::Task attribute :href, :aliases => :Href def all self.href = service.default_vdc_href unless self.href check_href! if data = service.get_task_list(href).body[:Task] load(data) end end def get(uri) service.get_task(uri) rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/vcloud/models/compute/networks.rb0000644000004100000410000000256612261242552022374 0ustar www-datawww-datarequire 'fog/vcloud/models/compute/network' module Fog module Vcloud class Compute class Networks < Fog::Vcloud::Collection undef_method :create model Fog::Vcloud::Compute::Network attribute :href def all self.href = service.default_vdc_href unless self.href data = nil if self.href =~ /\/vdc\// check_href!("Vdc") data = [service.get_vdc(self.href).available_networks].flatten.compact.reject{|n| n == '' } elsif self.href =~ /\/org\// check_href!("Org") data = service.get_organization(self.href).links.select{|l| l[:type] == network_type_id } elsif self.href =~ /\/vApp\// check_href!("Vapp") data = [(service.get_vapp(self.href).network_configs||{})[:NetworkConfig]].flatten.compact.collect{|n| n[:Configuration][:ParentNetwork] unless n[:Configuration].nil? }.compact end load([*data]) unless data.nil? end def get(uri) service.get_network(uri) rescue Fog::Errors::NotFound nil end private def network_type_id if service.version == '1.0' 'application/vnd.vmware.vcloud.network+xml' else 'application/vnd.vmware.vcloud.orgNetwork+xml' end end end end end end fog-1.19.0/lib/fog/vcloud/compute.rb0000644000004100000410000002561612261242552017236 0ustar www-datawww-datarequire 'fog/vcloud' require 'fog/compute' module Fog module Vcloud class Collection < Fog::Collection def load(objects) objects = [ objects ] if objects.is_a?(Hash) super end def check_href!(opts = {}) self.href = service.default_vdc_href unless href unless href if opts.is_a?(String) t = Hash.new t[:parent] = opts opts = t end msg = ":href missing, call with a :href pointing to #{if opts[:message] opts[:message] elsif opts[:parent] "the #{opts[:parent]} whos #{self.class.to_s.split('::').last.downcase} you want to enumerate" else "the resource" end}" raise Fog::Errors::Error.new(msg) end end end end end module Fog module Vcloud class Model < Fog::Model attr_accessor :loaded alias_method :loaded?, :loaded def reload instance = super @loaded = true instance end def load_unless_loaded! unless @loaded reload end end def link_up load_unless_loaded! self.links.find{|l| l[:rel] == 'up' } end def self.has_up(item) class_eval <<-EOS, __FILE__,__LINE__ def #{item} load_unless_loaded! service.get_#{item}(link_up[:href]) end EOS end end end end module Fog module Vcloud class Compute < Fog::Service BASE_PATH = '/api' DEFAULT_VERSION = '1.5' SUPPORTED_VERSIONS = [ '1.5', '1.0' ] PORT = 443 SCHEME = 'https' attr_writer :default_organization_uri requires :vcloud_username, :vcloud_password, :vcloud_host recognizes :vcloud_port, :vcloud_scheme, :vcloud_path, :vcloud_default_vdc, :vcloud_version, :vcloud_base_path recognizes :provider # remove post deprecation model_path 'fog/vcloud/models/compute' model :catalog collection :catalogs model :catalog_item model :catalog_items model :ip collection :ips model :network collection :networks model :server collection :servers model :task collection :tasks model :vapp collection :vapps model :vdc collection :vdcs model :organization collection :organizations model :tag collection :tags request_path 'fog/vcloud/requests/compute' request :clone_vapp request :configure_network request :configure_network_ip request :configure_vapp request :configure_vm_memory request :configure_vm_cpus request :configure_org_network request :configure_vm_name_description request :configure_vm_disks request :configure_vm_password request :configure_vm_network request :delete_vapp request :get_catalog_item request :get_customization_options request :get_network_ip request :get_network_ips request :get_network_extensions request :get_task_list request :get_vapp_template request :get_vm_disks request :get_vm_memory request :instantiate_vapp_template request :login request :power_off request :power_on request :power_reset request :power_shutdown request :undeploy request :get_metadata request :delete_metadata request :configure_metadata request :configure_vm_customization_script class Mock def initialize(options={}) Fog::Mock.not_implemented end end class Real class << self def basic_request(*args) self.class_eval <<-EOS, __FILE__,__LINE__ def #{args[0]}(uri) request( { :expects => #{args[1] || 200}, :method => '#{args[2] || 'GET'}', :headers => #{args[3] ? args[3].inspect : '{}'}, :body => '#{args[4] ? args[4] : ''}', :parse => true, :uri => uri } ) end EOS end def unauthenticated_basic_request(*args) self.class_eval <<-EOS, __FILE__,__LINE__ def #{args[0]}(uri) unauthenticated_request({ :expects => #{args[1] || 200}, :method => '#{args[2] || 'GET'}', :headers => #{args[3] ? args[3].inspect : '{}'}, :parse => true, :uri => uri }) end EOS end end attr_reader :version def initialize(options = {}) require 'builder' require 'fog/core/parser' @connections = {} @connection_options = options[:connection_options] || {} @persistent = options[:persistent] @username = options[:vcloud_username] @password = options[:vcloud_password] @host = options[:vcloud_host] @base_path = options[:vcloud_base_path] || Fog::Vcloud::Compute::BASE_PATH @version = options[:vcloud_version] || Fog::Vcloud::Compute::DEFAULT_VERSION @path = options[:vcloud_path] || "#{@base_path}/v#{@version}" @port = options[:vcloud_port] || Fog::Vcloud::Compute::PORT @scheme = options[:vcloud_scheme] || Fog::Vcloud::Compute::SCHEME @vdc_href = options[:vcloud_default_vdc] end def reload @connections.each_value { |k,v| v.reset if v } end def default_organization_uri @default_organization_uri ||= organizations.first.href @default_organization_uri end def default_vdc_href if @vdc_href.nil? unless @login_results do_login end org = organizations.first vdc = get_organization(org.href).links.find { |item| item[:type] == 'application/vnd.vmware.vcloud.vdc+xml'} @vdc_href = vdc[:href] end @vdc_href end # login handles the auth, but we just need the Set-Cookie # header from that call. def do_login @login_results = login @cookie = @login_results.headers['Set-Cookie'] || @login_results.headers['set-cookie'] end def ensure_unparsed(uri) if uri.is_a?(String) uri else uri.to_s end end def xmlns if version == '1.0' { "xmlns" => "http://www.vmware.com/vcloud/v1", "xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1", "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", "xmlns:xsd" => "http://www.w3.org/2001/XMLSchema" } else { 'xmlns' => "http://www.vmware.com/vcloud/v1.5", "xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1", "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", "xmlns:xsd" => "http://www.w3.org/2001/XMLSchema" } end end # If the cookie isn't set, do a get_organizations call to set it # and try the request. # If we get an Unauthorized error, we assume the token expired, re-auth and try again def request(params) unless @cookie do_login end begin do_request(params) rescue Excon::Errors::Unauthorized do_login do_request(params) end end def basic_request_params(uri,*args) { :expects => args[0] || 200, :method => args[1] || 'GET', :headers => args[2] ? args[2].inspect : {}, :body => args[3] ? args[3] : '', :parse => true, :uri => uri } end def base_path_url "#{@scheme}://#{@host}:#{@port}#{@base_path}" end private def ensure_parsed(uri) if uri.is_a?(String) URI.parse(uri) else uri end end # Don't need to set the cookie for these or retry them if the cookie timed out def unauthenticated_request(params) do_request(params) end def base_url "#{@scheme}://#{@host}:#{@port}#{@path}" end # Use this to set the Authorization header for login def authorization_header "Basic #{Base64.encode64("#{@username}:#{@password}").delete("\r\n")}" end # Actually do the request def do_request(params) # Convert the uri to a URI if it's a string. if params[:uri].is_a?(String) params[:uri] = URI.parse(params[:uri]) end host_url = "#{params[:uri].scheme}://#{params[:uri].host}#{params[:uri].port ? ":#{params[:uri].port}" : ''}" # Hash connections on the host_url ... There's nothing to say we won't get URI's that go to # different hosts. @connections[host_url] ||= Fog::Connection.new(host_url, @persistent, @connection_options) # Set headers to an empty hash if none are set. headers = params[:headers] || {} headers['Accept'] = 'application/*+xml;version=1.5' if version == '1.5' # Add our auth cookie to the headers if @cookie headers.merge!('Cookie' => @cookie) end # Make the request response = @connections[host_url].request({ :body => params[:body] || '', :expects => params[:expects] || 200, :headers => headers, :method => params[:method] || 'GET', :path => params[:uri].path }) # Parse the response body into a hash unless response.body.empty? if params[:parse] document = Fog::ToHashDocument.new parser = Nokogiri::XML::SAX::PushParser.new(document) parser << response.body parser.finish response.body = document.body end end response end end def self.item_requests(*types) types.each{|t| item_request(t) } end def self.item_request(type) Fog::Vcloud::Compute::Real.class_eval <<-EOS, __FILE__,__LINE__ def get_#{type}(uri) Fog::Vcloud::Compute::#{type.to_s.capitalize}.new( self.request(basic_request_params(uri)).body.merge( :service => self, :collection => Fog::Vcloud::Compute::#{type.to_s.capitalize}s.new( :service => self ) ) ) end EOS end item_requests :organization, :vdc, :network, :vapp, :server, :catalog, :task end end end fog-1.19.0/lib/fog/json.rb0000644000004100000410000000222212261242552015223 0ustar www-datawww-datarequire "multi_json" module Fog # @note Extracting JSON components out of core is a work in progress. # # The {JSON} module includes functionality that is common between APIs using # JSON to send and receive data. # # The intent is to provide common code for provider APIs using JSON but not # require it for those using XML. # module JSON class EncodeError < Fog::Errors::Error; end class DecodeError < Fog::Errors::Error; end def self.sanitize(data) case data when Array data.map {|datum| sanitize(datum)} when Hash for key, value in data data[key] = sanitize(value) end when ::Time data.strftime("%Y-%m-%dT%H:%M:%SZ") else data end end # Do the MultiJson introspection at this level so we can define our encode/decode methods and perform # the introspection only once rather than once per call. def self.encode(obj) MultiJson.encode(obj) rescue => err raise EncodeError.slurp(err) end def self.decode(obj) MultiJson.decode(obj) rescue => err raise DecodeError.slurp(err) end end end fog-1.19.0/lib/fog/go_grid/0000755000004100000410000000000012261242551015340 5ustar www-datawww-datafog-1.19.0/lib/fog/go_grid/requests/0000755000004100000410000000000012261242551017213 5ustar www-datawww-datafog-1.19.0/lib/fog/go_grid/requests/compute/0000755000004100000410000000000012261242551020667 5ustar www-datawww-datafog-1.19.0/lib/fog/go_grid/requests/compute/support_password_get.rb0000644000004100000410000000113712261242551025513 0ustar www-datawww-datamodule Fog module Compute class GoGrid class Real # Get one or more passwords by id # # ==== Parameters # * options<~Hash>: # * 'id'<~String> - id of the password to retrieve # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def support_password_get(id, options={}) request( :path => 'support/password/get', :query => { 'id' => id }.merge!(options) ) end end end end end fog-1.19.0/lib/fog/go_grid/requests/compute/grid_server_get.rb0000644000004100000410000000102412261242551024363 0ustar www-datawww-datamodule Fog module Compute class GoGrid class Real # Get one or more servers by name # # ==== Parameters # * 'server'<~String> - id or name of server(s) to lookup # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def grid_server_get(servers) request( :path => 'grid/server/get', :query => {'server' => [*servers]} ) end end end end end fog-1.19.0/lib/fog/go_grid/requests/compute/grid_server_power.rb0000644000004100000410000000117112261242551024743 0ustar www-datawww-datamodule Fog module Compute class GoGrid class Real # Start, Stop or Restart a server # # ==== Parameters # * 'server'<~String> - id or name of server to power # * 'power'<~String> - power operation, in ['restart', 'start', 'stop'] # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def grid_server_power(server, power) request( :path => 'grid/server/power', :query => {'server' => server, 'power' => power} ) end end end end end fog-1.19.0/lib/fog/go_grid/requests/compute/grid_ip_list.rb0000644000004100000410000000145312261242551023667 0ustar www-datawww-datamodule Fog module Compute class GoGrid class Real # List ips # # ==== Parameters # * options<~Hash>: # * 'datacenter'<~String> - datacenter to limit results to # * 'ip.state'<~String> - state to limit results to in ip.state # * 'ip.type'<~String> - type to limit results to in ip.type # * 'num_items'<~Integer> - Number of items to return # * 'page'<~Integer> - Page index for paginated results # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def grid_ip_list(options={}) request( :path => 'grid/ip/list', :query => options ) end end end end end fog-1.19.0/lib/fog/go_grid/requests/compute/common_lookup_list.rb0000644000004100000410000000133012261242551025125 0ustar www-datawww-datamodule Fog module Compute class GoGrid class Real # List options and lookups # # ==== Parameters # * 'lookup'<~String> - the lookup to be listed # * options<~Hash>: # * 'sort'<~String> - column to sort result by in ['description', 'id', 'name'] # * 'asc'<~String> - order to sort in ['true','false'] # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def common_lookup_list(lookup, options={}) request( :path => 'common/lookup/list', :query => {'lookup' => lookup}.merge!(options) ) end end end end end fog-1.19.0/lib/fog/go_grid/requests/compute/grid_image_get.rb0000644000004100000410000000165712261242551024153 0ustar www-datawww-datamodule Fog module Compute class GoGrid class Real # List images # # ==== Parameters # * options<~Hash>: # * 'id'<~String> - ID of the image # * 'name'<~String> - Name of the image # * 'image'<~String> - ID(s) or Name(s) of the images to retrive. Can be speicifed multiple times # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def grid_image_get(options={}) request( :path => 'grid/image/get', :query => options ) end end class Mock def grid_image_get(options={}) #response = Excon::Response.new #images = self.data[:list].values #for image in images # case image['state'] # when 'Available' end end end end end fog-1.19.0/lib/fog/go_grid/requests/compute/grid_server_add.rb0000644000004100000410000000215212261242551024337 0ustar www-datawww-datamodule Fog module Compute class GoGrid class Real # Create a new server # # ==== Parameters # * 'name'<~String> - name of the server, 20 or fewer characters # * 'image'<~String> - image to use, in grid_image_list # * 'ip'<~String> - initial public ip for this server # * 'options'<~Hash>: # * 'server.ram'<~String> - flavor to use, in common_lookup_list('server.ram') # * 'description'<~String> - description of this server # * 'isSandbox'<~String> - treat this server as image sandbox? in ['true', 'false'] # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def grid_server_add(image, ip, name, server_ram, options={}) request( :path => 'grid/server/add', :query => { 'image' => image, 'ip' => ip, 'name' => name, 'server.ram' => server_ram }.merge!(options) ) end end end end end fog-1.19.0/lib/fog/go_grid/requests/compute/grid_image_list.rb0000644000004100000410000000223712261242551024342 0ustar www-datawww-datamodule Fog module Compute class GoGrid class Real # List images # # ==== Parameters # * options<~Hash>: # * 'datacenter'<~String> - datacenter to limit results to # * 'isPublic'<~String> - If true only returns public images, in ['false', 'true'] # * 'num_items'<~Integer> - Number of items to return # * 'page'<~Integer> - Page index for paginated results # * 'state'<~String> - state to limit results to, in ['Saving', 'Available'] # * 'type'<~String> - image type to limit results to # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def grid_image_list(options={}) request( :path => 'grid/image/list', :query => options ) end end class Mock def grid_image_list(options={}) #response = Excon::Response.new #images = self.data[:list].values #for image in images # case image['state'] # when 'Available' end end end end end fog-1.19.0/lib/fog/go_grid/requests/compute/grid_server_delete.rb0000644000004100000410000000100212261242551025042 0ustar www-datawww-datamodule Fog module Compute class GoGrid class Real # Delete a server # # ==== Parameters # * 'server'<~String> - id or name of server to delete # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def grid_server_delete(server) request( :path => 'grid/server/delete', :query => {'server' => server} ) end end end end end fog-1.19.0/lib/fog/go_grid/requests/compute/grid_loadbalancer_list.rb0000644000004100000410000000125112261242551025662 0ustar www-datawww-datamodule Fog module Compute class GoGrid class Real # List load balancers # # ==== Parameters # * options<~Hash>: # * 'datacenter'<~String> - datacenter to limit results to # * 'num_items'<~Integer> - Number of items to return # * 'page'<~Integer> - Page index for paginated results # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def grid_loadbalancer_list(options={}) request( :path => 'grid/loadbalancer/list', :query => options ) end end end end end fog-1.19.0/lib/fog/go_grid/requests/compute/grid_server_list.rb0000644000004100000410000000150412261242551024562 0ustar www-datawww-datamodule Fog module Compute class GoGrid class Real # List servers # # ==== Parameters # * options<~Hash>: # * 'datacenter'<~String> - datacenter to limit results to # * 'isSandbox'<~String> - If true only returns Image Sandbox servers, in ['false', 'true'] # * 'num_items'<~Integer> - Number of items to return # * 'page'<~Integer> - Page index for paginated results # * 'server.type'<~String> - server type to limit results to # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def grid_server_list(options={}) request( :path => 'grid/server/list', :query => options ) end end end end end fog-1.19.0/lib/fog/go_grid/requests/compute/support_password_list.rb0000644000004100000410000000152012261242551025703 0ustar www-datawww-datamodule Fog module Compute class GoGrid class Real # List passwords # # ==== Parameters # * options<~Hash>: # * 'datacenter'<~String> - datacenter to limit results to # * 'isSandbox'<~String> - If true only returns Image Sandbox servers, in ['false', 'true'] # * 'num_items'<~Integer> - Number of items to return # * 'page'<~Integer> - Page index for paginated results # * 'server.type'<~String> - server type to limit results to # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def support_password_list(options={}) request( :path => 'support/password/list', :query => options ) end end end end end fog-1.19.0/lib/fog/go_grid/models/0000755000004100000410000000000012261242551016623 5ustar www-datawww-datafog-1.19.0/lib/fog/go_grid/models/compute/0000755000004100000410000000000012261242551020277 5ustar www-datawww-datafog-1.19.0/lib/fog/go_grid/models/compute/images.rb0000644000004100000410000000122212261242551022066 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/go_grid/models/compute/image' module Fog module Compute class GoGrid class Images < Fog::Collection model Fog::Compute::GoGrid::Image attribute :server def all data = service.grid_image_list.body['list'] load(data) if server self.replace(self.select {|image| image.server_id == server.id}) end end def get(image_id) response = service.grid_image_get.body['list'][image_id] new(data) rescue Fog::Compute::GoGrid::NotFound nil end end end end end fog-1.19.0/lib/fog/go_grid/models/compute/servers.rb0000644000004100000410000000134412261242551022317 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/go_grid/models/compute/server' module Fog module Compute class GoGrid class Servers < Fog::Collection model Fog::Compute::GoGrid::Server def all data = service.grid_server_list.body['list'] load(data) end def bootstrap(new_attributes = {}) server = create(new_attributes) server.wait_for { ready? } server.setup server end def get(server_id) if server_id && server = service.grid_server_get(server_id).body['list'].first new(server) end rescue Fog::Compute::GoGrid::NotFound nil end end end end end fog-1.19.0/lib/fog/go_grid/models/compute/password.rb0000644000004100000410000000170612261242551022472 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class GoGrid class Password < Fog::Model identity :id attribute :server_id attribute :applicationtype attribute :username attribute :password_id, :aliases => 'id' attribute :password attribute :server def initialize(attributes={}) super end def destroy requires :id service.grid_server_destroy(id) true end def image requires :image_id service.grid_image_get(image_id) end def ready? @state == 'On' end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :password_id data = service.support_password_list() merge_attributes(data.body) true end end end end end fog-1.19.0/lib/fog/go_grid/models/compute/passwords.rb0000644000004100000410000000143412261242551022653 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/go_grid/models/compute/password' module Fog module Compute class GoGrid class Passwords < Fog::Collection model Fog::Compute::GoGrid::Password def all data = service.support_password_list.body['list'] load(data) end def bootstrap(new_attributes = {}) password = create(new_attributes) password.wait_for { ready? } password end def get(id) #if server_id && server = service.grid_server_get(server_id).body['list'] if id && server = service.support_password_get(id).body['list'] new(server) end rescue Fog::Compute::GoGrid::NotFound nil end end end end end fog-1.19.0/lib/fog/go_grid/models/compute/server.rb0000644000004100000410000000506312261242551022136 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class GoGrid class BlockInstantiationError < StandardError; end class Server < Fog::Compute::Server extend Fog::Deprecation deprecate(:ip, :public_ip_address) identity :id attribute :name attribute :image_id # id or name attribute :public_ip_address, :aliases => 'ip', :squash => 'ip' attribute :memory # server.ram attribute :state attribute :description # Optional attribute :sandbox # Optional. Default: False def initialize(attributes={}) image_id ||= 'ubuntu_10_04_LTS_64_base' # Ubuntu 10.04 LTS 64bit super end def destroy requires :id service.grid_server_delete(id) true end def image requires :image_id service.grid_image_get(:image => image_id) end def private_ip_address nil end def ready? @state && @state["name"] == 'On' end def reload requires :name begin if data = collection.get(name) new_attributes = data.attributes merge_attributes(new_attributes) self end rescue Excon::Errors::BadRequest false end end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :name, :image_id, :memory, :public_ip_address options = { 'isSandbox' => sandbox, 'image' => image_id } options = options.reject {|key, value| value.nil?} data = service.grid_server_add(image, public_ip_address, name, memory, options) merge_attributes(data.body) true end def setup(credentials = {}) requires :identity, :public_ip_address, :public_key, :username Fog::SSH.new(public_ip_address, username, credentials).run([ %{mkdir .ssh}, %{echo "#{public_key}" >> ~/.ssh/authorized_keys}, %{passwd -l root}, %{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-1.19.0/lib/fog/go_grid/models/compute/image.rb0000644000004100000410000000260012261242551021704 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class GoGrid class Image < Fog::Model identity :id attribute :name attribute :description attribute :friendly_name, :aliases => 'friendlyName' attribute :created_at, :aliases => 'createdTime' attribute :updated_at, :aliases => 'updatedTime' attribute :server_id, :aliases => 'id' attribute :state attribute :price attribute :location attribute :billingtokens attribute :os attribute :architecture attribute :type attribute :active, :aliases => 'isActive' attribute :public, :aliases => 'isPublic' attribute :object_type, :aliases => 'object' attribute :owner def server=(new_server) requires :id @server_id = new_server.id end def destroy requires :id service.grid_server_delete(id) true end def ready? status == 'Available' end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :server_id data = service.grid_server_add(server_id, 'name' => name) merge_attributes(data.body['image']) true end end end end end fog-1.19.0/lib/fog/go_grid/compute.rb0000644000004100000410000000614612261242551017350 0ustar www-datawww-datarequire 'fog/go_grid' require 'fog/compute' module Fog module Compute class GoGrid < Fog::Service requires :go_grid_api_key, :go_grid_shared_secret recognizes :host, :path, :port, :scheme, :persistent model_path 'fog/go_grid/models/compute' model :image collection :images model :server collection :servers model :password collection :passwords request_path 'fog/go_grid/requests/compute' request :common_lookup_list request :grid_image_get request :grid_image_list request :grid_ip_list request :grid_loadbalancer_list request :grid_server_add request :grid_server_delete request :grid_server_get request :grid_server_list request :grid_server_power request :support_password_get request :support_password_list class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = {} end end def self.reset @data = nil end def initialize(options={}) @go_grid_api_key = options[:go_grid_api_key] @go_grid_shared_secret = options[:go_grid_shared_secret] end def data self.class.data[@go_grid_api_key] end def reset_data self.class.data.delete(@go_grid_api_key) end end class Real def initialize(options={}) require 'digest/md5' @go_grid_api_key = options[:go_grid_api_key] @go_grid_shared_secret = options[:go_grid_shared_secret] @connection_options = options[:connection_options] || {} @host = options[:host] || "api.gogrid.com" @path = options[:path] || "/api" @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def reload @connection.reset end def request(params) params = { :expects => 200, :method => 'GET' }.merge!(params) params[:query] ||= {} params[:query].merge!({ 'api_key' => @go_grid_api_key, 'format' => 'json', 'sig' => Digest::MD5.hexdigest("#{@go_grid_api_key}#{@go_grid_shared_secret}#{Time.now.to_i}"), 'v' => '1.5' }) begin response = @connection.request( params.merge!(:path => "#{@path}/#{params[:path]}") ) rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Compute::GoGrid::NotFound.slurp(error) else error end end unless response.body.empty? response.body = Fog::JSON.decode(response.body) end response end end end end end fog-1.19.0/lib/fog/vmfusion/0000755000004100000410000000000012261242552015575 5ustar www-datawww-datafog-1.19.0/lib/fog/vmfusion/models/0000755000004100000410000000000012261242552017060 5ustar www-datawww-datafog-1.19.0/lib/fog/vmfusion/models/compute/0000755000004100000410000000000012261242552020534 5ustar www-datawww-datafog-1.19.0/lib/fog/vmfusion/models/compute/servers.rb0000644000004100000410000000161712261242552022557 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vmfusion/models/compute/server' module Fog module Compute class Vmfusion class Servers < Fog::Collection model Fog::Compute::Vmfusion::Server def all(filter = nil) data = [] states = ::Fission::VM.all_with_status.data filter = {} if filter.nil? unless filter.has_key?(:name) vms=::Fission::VM.all.data vms.each do |vm| data << { :raw => { :fission => vm, :state => states[vm.name] } } end else data << { :raw => { :fission => ::Fission::VM.new(filter[:name]), :state => states[filter[:name]] } } end load(data) end def get(name) self.all(:name => name).first end end end end end fog-1.19.0/lib/fog/vmfusion/models/compute/server.rb0000644000004100000410000001576112261242552022401 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class Vmfusion class Server < Fog::Compute::Server identity :name attribute :ipaddress attribute :power_state attribute :mac_addresses attribute :path attr_accessor :password # There is currently no documented model of creating VMs from scratch # sans Fusion's wizard. def save raise Fog::Errors::Error.new('Creating a new vm is not yet supported') end # Fussion doesn't have the concept of templates so one just clones # regular VMs. def clone(name) requires :raw ::Fission::VM.clone(@raw[:fission].name,name) return service.servers.get(name) end # Destroy, deletes the VM from the local disk but only hard stops the VM # before doing so if you set :force to true. def destroy(options = { :force => false }) requires :raw if ready? if options[:force] stop end end @raw[:fission].delete end # Start is pretty self explanatory...if you pass :headless as true you # won't get a console on launch. def start(options = { :headless => false }) requires :raw unless ready? @raw[:fission].start(:headless => options[:headless]) return true else return false end end # We're covering a lot of bases here with the different ways one can # stop a VM from running. # Stop is a hard stop, like pulling out the power cord. def stop requires :raw if ready? @raw[:fission].stop(:hard => true) return true else return false end end # Halt and poweroff are just synonyms for stop. def halt stop end def poweroff stop end # This is a graceful shutdown but Fusion is only capable of a graceful # shutdown if tools are installed. Fusion does the right thing though # and if graceful can't be initiated it just does a hard stop. def shutdown requires :raw if ready? @raw[:fission].stop return true else return false end end # Attempt a graceful shutdown, wait for the VM to completely shutdown # and then start it again. def reboot if ready? shutdown wait_for { ! ready? } start return true else return false end end # Resuming from suspend is the same thing as start to Fusion. def resume start end def suspend requires :raw if ready? @raw[:fission].suspend return true else return false end end # Fusion VM Metadata. # The power state of the VM is commonly going to be three values; # running, not running, or suspended. def power_state requires :raw @raw[:fission].state.data end def ready? requires :raw @raw[:fission].running?.data end # Path to the VM's vmx file on the local disk. def path requires :raw @raw[:fission].path end # We obtain the first ipaddress. This should generally be a safe # assumption for Fusion. Even if an address is provided via NAT, # bridge, or host only it will by accessible from the host machine the # VM resides on. def ipaddress requires :raw ip(@raw[:fission]) end # Keeping these three methods around for API compatibility reasons. # Makes the vmfusion provider function similar to cloud providers and # the vsphere provider. Future goal is to add an actual private and # public concept. Needs changes to fission and a determination what is # a public or private address here; bridge, nat, host-only. def public_ip_address ipaddress end def private_ip_address ipaddress end def state power_state end # Collecting all mac_addresses the VM has...mostly just because we are # doing the same thing for the vSphere provider. def mac_addresses requires :raw macs(@raw[:fission]) end # Sets up a conveinent way to SSH into a Fusion VM using credentials # stored in your .fog file. # Simply spawn an SSH session. def ssh(commands) super(commands, password ? {:password => password} : {}) end # SCP something to our VM. def scp(local_path, remote_path, upload_options = {}) requires :ipaddress, :username scp_options = {} scp_options[:password] = password unless self.password.nil? scp_options[:key_data] = [private_key] if self.private_key Fog::SCP.new(ipaddress, username, scp_options).upload(local_path, remote_path, upload_options) end # Sets up a new SSH key on the VM so one doesn't need to use a password # ever again. def setup(credentials = {}) requires :public_key, :ipaddress, :username credentials[:password] = password unless self.password.nil? credentails[:key_data] = [private_key] if self.private_key commands = [ %{mkdir .ssh}, ] if public_key commands << %{echo "#{public_key}" >> ~/.ssh/authorized_keys} end # wait for domain to be ready Timeout::timeout(360) do begin Timeout::timeout(8) do Fog::SSH.new(ipaddress, username, credentials.merge(:timeout => 4)).run('pwd') end rescue Errno::ECONNREFUSED sleep(2) retry rescue Net::SSH::AuthenticationFailed, Timeout::Error retry end end Fog::SSH.new(ipaddress, username, credentials).run(commands) end private def ip(fission) first_int = fission.network_info.data.keys.first fission.network_info.data[first_int]['ip_address'] end def macs(fission) fission.mac_addresses.data end def raw @raw end def raw=(new_raw) @raw = new_raw raw_attributes = { :name => new_raw[:fission].name, :power_state => new_raw[:state], :ipaddress => ip(new_raw[:fission]), :mac_addresses => macs(new_raw[:fission]), :path => new_raw[:fission].path } merge_attributes(raw_attributes) end end end end end fog-1.19.0/lib/fog/vmfusion/compute.rb0000644000004100000410000000110212261242552017570 0ustar www-datawww-datarequire 'fog/vmfusion' require 'fog/compute' module Fog module Compute class Vmfusion < Fog::Service model_path 'fog/vmfusion/models/compute' model :server collection :servers class Mock def initialize(options={}) Fog::Mock.not_implemented end end class Real def initialize(options={}) begin require 'fission' rescue LoadError => e retry if require('rubygems') raise e.message end end end end end end fog-1.19.0/lib/fog/cloudsigma.rb0000644000004100000410000000021612261242551016401 0ustar www-datawww-datarequire 'fog/core' module Fog module CloudSigma extend Fog::Provider service(:compute, 'cloudsigma/compute', 'Compute') end end fog-1.19.0/lib/fog/dnsimple/0000755000004100000410000000000012261242551015541 5ustar www-datawww-datafog-1.19.0/lib/fog/dnsimple/requests/0000755000004100000410000000000012261242551017414 5ustar www-datawww-datafog-1.19.0/lib/fog/dnsimple/requests/dns/0000755000004100000410000000000012261242551020200 5ustar www-datawww-datafog-1.19.0/lib/fog/dnsimple/requests/dns/list_records.rb0000644000004100000410000000203612261242551023222 0ustar www-datawww-datamodule Fog module DNS class DNSimple class Real # Get the list of records for the specific domain. # # ==== Parameters # * domain<~String> # ==== Returns # * response<~Excon::Response>: # * records # * name<~String> # * ttl<~Integer> # * created_at<~String> # * special_type<~String> # * updated_at<~String> # * domain_id<~Integer> # * id<~Integer> # * content<~String> # * record_type<~String> # * prio<~Integer> def list_records(domain) request( :expects => 200, :method => "GET", :path => "/domains/#{domain}/records" ) end end class Mock def list_records(domain) response = Excon::Response.new response.status = 200 response.body = self.data[:records][domain] || [] response end end end end end fog-1.19.0/lib/fog/dnsimple/requests/dns/get_domain.rb0000644000004100000410000000244012261242551022633 0ustar www-datawww-datamodule Fog module DNS class DNSimple class Real # Get the details for a specific domain in your account. You # may pass either the domain numeric ID or the domain name # itself. # # ==== Parameters # * id<~String> - domain name or numeric ID # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'domain'<~Hash> # * 'name'<~String> # * 'expires_at'<~String> # * 'created_at'<~String> # * 'registration_status'<~String> # * 'updated_at'<~String> # * 'registrant_id'<~Integer> # * 'id'<~Integer> # * 'user_id'<~Integer> # * 'name_server_status'<~String> def get_domain(id) request( :expects => 200, :method => "GET", :path => "/domains/#{id}" ) end end class Mock def get_domain(id) domain = self.data[:domains].detect { |domain| domain["domain"]["id"] == id } response = Excon::Response.new response.status = 200 response.body = domain response end end end end end fog-1.19.0/lib/fog/dnsimple/requests/dns/create_record.rb0000644000004100000410000000370212261242551023330 0ustar www-datawww-datamodule Fog module DNS class DNSimple class Real # Create a new host in the specified zone # # ==== Parameters # * domain<~String> # * name<~String> # * type<~String> # * content<~String> # * options<~Hash> - optional # * priority<~Integer> # * ttl<~Integer> # ==== Returns # * response<~Excon::Response>: # * body<~Hash> # * name<~String> # * ttl<~Integer> # * created_at<~String> # * special_type<~String> # * updated_at<~String> # * domain_id<~Integer> # * id<~Integer> # * content<~String> # * record_type<~String> # * prio<~Integer> def create_record(domain, name, type, content, options = {}) body = { "record" => { "name" => name, "record_type" => type, "content" => content } } body["record"].merge!(options) request( :body => Fog::JSON.encode(body), :expects => 201, :method => 'POST', :path => "/domains/#{domain}/records" ) end end class Mock def create_record(domain, name, type, content, options = {}) response = Excon::Response.new response.status = 201 body = { "record" => { "name" => name, "record_type" => type, "content" => content, "created_at" => Time.now.iso8601, "updated_at" => Time.now.iso8601, "id" => Fog::Mock.random_numbers(1).to_i, "domain_id" => domain }.merge(options) } self.data[:records][domain] ||= [] self.data[:records][domain] << body response.body = body response end end end end end fog-1.19.0/lib/fog/dnsimple/requests/dns/create_domain.rb0000644000004100000410000000345512261242551023326 0ustar www-datawww-datamodule Fog module DNS class DNSimple class Real # Create a single domain in DNSimple in your account. # ==== Parameters # * name<~String> - domain name to host (ie example.com) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'name'<~String> def create_domain(name) body = { "domain" => { "name" => name } } request( :body => Fog::JSON.encode(body), :expects => 201, :method => 'POST', :path => '/domains' ) end end class Mock def create_domain(name) response = Excon::Response.new response.status = 201 body = { "domain" => { "auto_renew" => nil, "created_at" => Time.now.iso8601, "expires_on" => Date.today + 365, "id" => Fog::Mock.random_numbers(1).to_i, "language" => nil, "lockable" => true, "name" => name, "name_server_status" => "unknown", "registrant_id" => nil, "state" => "registered", "token" => "4fIFYWYiJayvL2tkf_mkBkqC4L+4RtYqDA", "unicode_name" => name, "updated_at" => Time.now.iso8601, "user_id" => 1, "record_count" => 0, "service_count" => 0, "private_whois?" => false } } self.data[:domains] << body response.body = body response end end end end end fog-1.19.0/lib/fog/dnsimple/requests/dns/delete_record.rb0000644000004100000410000000134512261242551023330 0ustar www-datawww-datamodule Fog module DNS class DNSimple class Real # Delete the record with the given ID for the given domain. # # ==== Parameters # * domain<~String> # * record_id<~String> def delete_record(domain, record_id) request( :expects => 200, :method => "DELETE", :path => "/domains/#{domain}/records/#{record_id}" ) end end class Mock def delete_record(domain, record_id) self.data[:records][domain].reject! { |record| record["record"]["id"] == record_id } response = Excon::Response.new response.status = 200 response end end end end end fog-1.19.0/lib/fog/dnsimple/requests/dns/update_record.rb0000644000004100000410000000320412261242551023344 0ustar www-datawww-datamodule Fog module DNS class DNSimple class Real # Update the given record for the given domain. # # ==== Parameters # * domain<~String> # * record_id<~String> # * options<~Hash> - optional # * type<~String> # * content<~String> # * priority<~Integer> # * ttl<~Integer> # ==== Returns # * response<~Excon::Response>: # * record<~Hash> # * name<~String> # * ttl<~Integer> # * created_at<~String> # * special_type<~String> # * updated_at<~String> # * domain_id<~Integer> # * id<~Integer> # * content<~String> # * record_type<~String> # * prio<~Integer> def update_record(domain, record_id, options) body = { "record" => options } request( :body => Fog::JSON.encode(body), :expects => 200, :method => "PUT", :path => "/domains/#{domain}/records/#{record_id}" ) end end class Mock def update_record(domain, record_id, options) record = self.data[:records][domain].detect { |record| record["record"]["id"] == record_id } response = Excon::Response.new if record.nil? response.status = 400 else response.status = 200 record["record"].merge!(options) record["record"]["updated_at"] = Time.now.iso8601 response.body = record end response end end end end end fog-1.19.0/lib/fog/dnsimple/requests/dns/get_record.rb0000644000004100000410000000305712261242551022647 0ustar www-datawww-datamodule Fog module DNS class DNSimple class Real # Gets record from given domain. # # ==== Parameters # * domain<~String> # * record_id<~String> # ==== Returns # * response<~Excon::Response>: # * record<~Hash> # * name<~String> # * ttl<~Integer> # * created_at<~String> # * special_type<~String> # * updated_at<~String> # * domain_id<~Integer> # * id<~Integer> # * content<~String> # * record_type<~String> # * prio<~Integer> def get_record(domain, record_id) request( :expects => 200, :method => "GET", :path => "/domains/#{domain}/records/#{record_id}" ) end end class Mock def get_record(domain, record_id) response = Excon::Response.new if self.data[:records].has_key? domain response.status = 200 response.body = self.data[:records][domain].detect { |record| record["record"]["id"] == record_id } if response.body.nil? response.status = 404 response.body = { "error" => "Couldn't find Record with id = #{record_id}" } end else response.status = 404 response.body = { "error" => "Couldn't find Domain with name = #{domain}" } end response end end end end end fog-1.19.0/lib/fog/dnsimple/requests/dns/list_domains.rb0000644000004100000410000000227212261242551023215 0ustar www-datawww-datamodule Fog module DNS class DNSimple class Real # Get the details for a specific domain in your account. You # may pass either the domain numeric ID or the domain name itself. # ==== Parameters # * id<~String> - domain name or numeric ID # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'domains'<~Array> # * 'name'<~String> # * 'expires_at'<~String> # * 'created_at'<~String> # * 'registration_status'<~String> # * 'updated_at'<~String> # * 'registrant_id'<~Integer> # * 'id'<~Integer> # * 'user_id'<~Integer> # * 'name_server_status'<~String> def list_domains request( :expects => 200, :method => 'GET', :path => '/domains' ) end end class Mock def list_domains response = Excon::Response.new response.status = 200 response.body = self.data[:domains] response end end end end end fog-1.19.0/lib/fog/dnsimple/requests/dns/delete_domain.rb0000644000004100000410000000167112261242551023323 0ustar www-datawww-datamodule Fog module DNS class DNSimple class Real # Delete the given domain from your account. You may use # either the domain ID or the domain name. # # Please note that for domains which are registered with # DNSimple this will not delete the domain from the registry. # # ==== Parameters # * name<~String> - domain name or numeric ID # def delete_domain(name) request( :expects => 200, :method => 'DELETE', :path => "/domains/#{name}" ) end end class Mock def delete_domain(name) self.data[:records].delete name self.data[:domains].reject! { |domain| domain["domain"]["name"] == name } response = Excon::Response.new response.status = 200 response end end end end end fog-1.19.0/lib/fog/dnsimple/dns.rb0000644000004100000410000000526012261242551016655 0ustar www-datawww-datarequire 'fog/dnsimple' require 'fog/dns' module Fog module DNS class DNSimple < Fog::Service requires :dnsimple_email, :dnsimple_password recognizes :dnsimple_url, :host, :path, :port, :scheme, :persistent model_path 'fog/dnsimple/models/dns' model :record collection :records model :zone collection :zones request_path 'fog/dnsimple/requests/dns' request :list_domains request :create_domain request :get_domain request :delete_domain request :create_record request :list_records request :update_record request :delete_record request :get_record class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = { :domains => [], :records => {} } end end def self.reset @data = nil end def initialize(options={}) @dnsimple_email = options[:dnsimple_email] @dnsimple_password = options[:dnsimple_password] end def data self.class.data[@dnsimple_email] end def reset_data self.class.data.delete(@dnsimple_email) end end class Real def initialize(options={}) @dnsimple_email = options[:dnsimple_email] @dnsimple_password = options[:dnsimple_password] @connection_options = options[:connection_options] || {} if options[:dnsimple_url] uri = URI.parse(options[:dnsimple_url]) options[:host] = uri.host options[:port] = uri.port options[:scheme] = uri.scheme end @host = options[:host] || "dnsimple.com" @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def reload @connection.reset end def request(params) params[:headers] ||= {} key = "#{@dnsimple_email}:#{@dnsimple_password}" params[:headers].merge!({ "Authorization" => "Basic " + Base64.encode64(key).gsub("\n",''), "Accept" => "application/json", "Content-Type" => "application/json" }) response = @connection.request(params) unless response.body.empty? response.body = Fog::JSON.decode(response.body) end response end end end end end fog-1.19.0/lib/fog/dnsimple/models/0000755000004100000410000000000012261242551017024 5ustar www-datawww-datafog-1.19.0/lib/fog/dnsimple/models/dns/0000755000004100000410000000000012261242551017610 5ustar www-datawww-datafog-1.19.0/lib/fog/dnsimple/models/dns/zones.rb0000644000004100000410000000102012261242551021264 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/dnsimple/models/dns/zone' module Fog module DNS class DNSimple class Zones < Fog::Collection model Fog::DNS::DNSimple::Zone def all clear data = service.list_domains.body.map {|zone| zone['domain']} load(data) end def get(zone_id) data = service.get_domain(zone_id).body['domain'] new(data) rescue Excon::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/dnsimple/models/dns/record.rb0000644000004100000410000000274312261242551021421 0ustar www-datawww-datarequire 'fog/core/model' module Fog module DNS class DNSimple class Record < Fog::Model extend Fog::Deprecation deprecate :ip, :value deprecate :ip=, :value= identity :id attribute :name attribute :value, :aliases => "content" attribute :ttl attribute :created_at attribute :updated_at attribute :zone_id, :aliases => "domain_id" attribute :type, :aliases => "record_type" attribute :priority, :aliases => "prio" def initialize(attributes={}) super end def destroy service.delete_record(zone.id, identity) true end def zone @zone end def save requires :name, :type, :value options = {} options[:prio] = priority if priority options[:ttl] = ttl if ttl # decide whether its a new record or update of an existing if id.nil? data = service.create_record(zone.id, name, type, value, options) else options[:name] = name if name options[:content] = value if value options[:type] = type if type data = service.update_record(zone.id, id, options) end merge_attributes(data.body["record"]) true end private def zone=(new_zone) @zone = new_zone end end end end end fog-1.19.0/lib/fog/dnsimple/models/dns/zone.rb0000644000004100000410000000166712261242551021122 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/dnsimple/models/dns/records' module Fog module DNS class DNSimple class Zone < Fog::Model identity :id attribute :domain, :aliases => 'name' attribute :created_at attribute :updated_at def destroy service.delete_domain(identity) true end def records @records ||= begin Fog::DNS::DNSimple::Records.new( :zone => self, :service => service ) end end def nameservers [ "ns1.dnsimple.com", "ns2.dnsimple.com", "ns3.dnsimple.com", "ns4.dnsimple.com", ] end def save requires :domain data = service.create_domain(domain).body["domain"] merge_attributes(data) true end end end end end fog-1.19.0/lib/fog/dnsimple/models/dns/records.rb0000644000004100000410000000137012261242551021577 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/dnsimple/models/dns/record' module Fog module DNS class DNSimple class Records < Fog::Collection attribute :zone model Fog::DNS::DNSimple::Record def all requires :zone clear data = service.list_records(zone.id).body.map {|record| record['record']} load(data) end def get(record_id) requires :zone data = service.get_record(zone.id, record_id).body["record"] new(data) rescue Excon::Errors::NotFound nil end def new(attributes = {}) requires :zone super({ :zone => zone }.merge!(attributes)) end end end end end fog-1.19.0/lib/fog/internet_archive.rb0000644000004100000410000002022412261242552017605 0ustar www-datawww-datarequire 'fog/core' require 'fog/internet_archive/signaturev4' module Fog module InternetArchive COMPLIANT_BUCKET_NAMES = /^(?:[a-z]|\d(?!\d{0,2}(?:\.\d{1,3}){3}$))(?:[a-z0-9]|\-(?![\.])){1,61}[a-z0-9]$/ DOMAIN_NAME = 'archive.org' API_DOMAIN_NAME = 's3.us.' + DOMAIN_NAME extend Fog::Provider service(:storage, 'internet_archive/storage', 'Storage') def self.indexed_param(key, values) params = {} unless key.include?('%d') key << '.%d' end [*values].each_with_index do |value, index| if value.respond_to?('keys') k = format(key, index + 1) value.each do | vkey, vvalue | params["#{k}.#{vkey}"] = vvalue end else params[format(key, index + 1)] = value end end params end def self.serialize_keys(key, value, options = {}) case value when Hash value.each do | k, v | options.merge!(serialize_keys("#{key}.#{k}", v)) end return options when Array value.each_with_index do | it, idx | options.merge!(serialize_keys("#{key}.member.#{(idx + 1)}", it)) end return options else return {key => value} end end def self.indexed_request_param(name, values) idx = -1 Array(values).inject({}) do |params, value| params["#{name}.#{idx += 1}"] = value params end end def self.indexed_filters(filters) params = {} filters.keys.each_with_index do |key, key_index| key_index += 1 params[format('Filter.%d.Name', key_index)] = key [*filters[key]].each_with_index do |value, value_index| value_index += 1 params[format('Filter.%d.Value.%d', key_index, value_index)] = value end end params end def self.escape(string) string.gsub(/([^a-zA-Z0-9_.\-~]+)/) { "%" + $1.unpack("H2" * $1.bytesize).join("%").upcase } end def self.signed_params(params, options = {}) params.merge!({ 'AWSAccessKeyId' => options[:ia_access_key_id], 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => '2', 'Timestamp' => Time.now.utc.strftime("%Y-%m-%dT%H:%M:%SZ"), 'Version' => options[:version] }) params.merge!({ 'SecurityToken' => options[:ia_session_token] }) if options[:ia_session_token] body = '' for key in params.keys.sort unless (value = params[key]).nil? body << "#{key}=#{escape(value.to_s)}&" end end string_to_sign = "POST\n#{options[:host]}:#{options[:port]}\n#{options[:path]}\n" << body.chop signed_string = options[:hmac].sign(string_to_sign) body << "Signature=#{escape(Base64.encode64(signed_string).chomp!)}" body end class Mock def self.arn(vendor, account_id, path, region = nil) "arn:aws:#{vendor}:#{region}:#{account_id}:#{path}" end def self.availability_zone(region) "#{region}#{Fog::Mock.random_selection('abcd', 1)}" end def self.box_usage sprintf("%0.10f", rand / 100).to_f end def self.console_output # "[ 0.000000] Linux version 2.6.18-xenU-ec2-v1.2 (root@domU-12-31-39-07-51-82) (gcc version 4.1.2 20070626 (Red Hat 4.1.2-13)) #2 SMP Wed Aug 19 09:04:38 EDT 2009" Base64.decode64("WyAwLjAwMDAwMF0gTGludXggdmVyc2lvbiAyLjYuMTgteGVuVS1lYzItdjEu\nMiAocm9vdEBkb21VLTEyLTMxLTM5LTA3LTUxLTgyKSAoZ2NjIHZlcnNpb24g\nNC4xLjIgMjAwNzA2MjYgKFJlZCBIYXQgNC4xLjItMTMpKSAjMiBTTVAgV2Vk\nIEF1ZyAxOSAwOTowNDozOCBFRFQgMjAwOQ==\n") end def self.dns_name_for(ip_address) "ec2-#{ip_address.gsub('.','-')}.compute-1.amazonaws.com" end def self.private_dns_name_for(ip_address) "ip-#{ip_address.gsub('.','-')}.ec2.internal" end def self.image path = [] (rand(3) + 2).times do path << Fog::Mock.random_letters(rand(9) + 8) end { "imageOwnerId" => Fog::Mock.random_letters(rand(5) + 4), "blockDeviceMapping" => [], "productCodes" => [], "kernelId" => kernel_id, "ramdiskId" => ramdisk_id, "imageState" => "available", "imageId" => image_id, "architecture" => "i386", "isPublic" => true, "imageLocation" => path.join('/'), "imageType" => "machine", "rootDeviceType" => ["ebs","instance-store"][rand(2)], "rootDeviceName" => "/dev/sda1" } end def self.image_id "ami-#{Fog::Mock.random_hex(8)}" end def self.key_fingerprint fingerprint = [] 20.times do fingerprint << Fog::Mock.random_hex(2) end fingerprint.join(':') end def self.instance_id "i-#{Fog::Mock.random_hex(8)}" end def self.ip_address ip = [] 4.times do ip << Fog::Mock.random_numbers(rand(3) + 1).to_i.to_s # remove leading 0 end ip.join('.') end def self.private_ip_address ip_address.gsub(/^\d{1,3}\./,"10.") end def self.kernel_id "aki-#{Fog::Mock.random_hex(8)}" end def self.key_material OpenSSL::PKey::RSA.generate(1024).to_s end def self.owner_id Fog::Mock.random_numbers(12) end def self.ramdisk_id "ari-#{Fog::Mock.random_hex(8)}" end def self.request_id request_id = [] request_id << Fog::Mock.random_hex(8) 3.times do request_id << Fog::Mock.random_hex(4) end request_id << Fog::Mock.random_hex(12) request_id.join('-') end class << self alias :reserved_instances_id :request_id alias :reserved_instances_offering_id :request_id alias :sqs_message_id :request_id alias :sqs_sender_id :request_id end def self.reservation_id "r-#{Fog::Mock.random_hex(8)}" end def self.snapshot_id "snap-#{Fog::Mock.random_hex(8)}" end def self.volume_id "vol-#{Fog::Mock.random_hex(8)}" end def self.security_group_id "sg-#{Fog::Mock.random_hex(8)}" end def self.network_interface_id "eni-#{Fog::Mock.random_hex(8)}" end def self.internet_gateway_id "igw-#{Fog::Mock.random_hex(8)}" end def self.dhcp_options_id "dopt-#{Fog::Mock.random_hex(8)}" end def self.vpc_id "vpc-#{Fog::Mock.random_hex(8)}" end def self.subnet_id "subnet-#{Fog::Mock.random_hex(8)}" end def self.zone_id "zone-#{Fog::Mock.random_hex(8)}" end def self.change_id "change-#{Fog::Mock.random_hex(8)}" end def self.nameservers [ 'ns-2048.awsdns-64.com', 'ns-2049.awsdns-65.net', 'ns-2050.awsdns-66.org', 'ns-2051.awsdns-67.co.uk' ] end def self.key_id(length=21) #Probably close enough Fog::Mock.random_selection('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',length) end def self.rds_address(db_name,region) "#{db_name}.#{Fog::Mock.random_letters(rand(12) + 4)}.#{region}.rds.amazonaws.com" end end def self.parse_security_group_options(group_name, options) options ||= Hash.new if group_name.is_a?(Hash) options = group_name elsif group_name if options.key?('GroupName') raise Fog::Compute::InternetArchive::Error, 'Arguments specified both group_name and GroupName in options' end options = options.clone options['GroupName'] = group_name end name_specified = options.key?('GroupName') && !options['GroupName'].nil? group_id_specified = options.key?('GroupId') && !options['GroupId'].nil? unless name_specified || group_id_specified raise Fog::Compute::InternetArchive::Error, 'Neither GroupName nor GroupId specified' end if name_specified && group_id_specified options.delete('GroupName') end options end end end fog-1.19.0/lib/fog/vcloud_director/0000755000004100000410000000000012261242552017116 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud_director/requests/0000755000004100000410000000000012261242552020771 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud_director/requests/compute/0000755000004100000410000000000012261242552022445 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud_director/requests/compute/post_clone_media.rb0000644000004100000410000000701312261242552026277 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Create a copy of a media object. # # The response includes a Task element. You can monitor the task to to # track the creation of the vApp template. # # @param [String] vdc_id Object identifier of the vDC. # @param [String] source_id Object identifier of the source media # object. # @param [Hash] options # @option options [String] :Description Optional description. # @option options [Boolean] :IsSourceDelete A value of true deletes the # Source object after successful completion of the copy operation. # Defaults to false if empty or missing. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-CloneMedia.html # @since vCloud API version 0.9 def post_clone_media(vdc_id, source_id, options={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5' } CloneMediaParams(attrs) { if options.key?(:Description) Description options[:Description] end Source(:href => "#{end_point}media/#{source_id}") if options.key?(:IsSourceDelete) IsSourceDelete options[:IsSourceDelete] end } end.to_xml response = request( :body => body, :expects => 201, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.cloneMediaParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vdc/#{vdc_id}/action/cloneMedia" ) ensure_list! response.body, :Files, :File response end end class Mock def post_clone_media(vdc_id, source_id, options={}) # TODO: check this happens. unless source_media = data[:medias][source_id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.media:#{source_id})\"." ) end unless data[:vdcs][vdc_id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.vdc:#{vdc_id})\"." ) end media_id = uuid media_name = "#{source_media[:name]}-copy-#{uuid}" owner = { :href => make_href("media/#{media_id}"), :type => 'application/vnd.vmware.vcloud.media+xml' } task_id = enqueue_task( "Copy Media File #{media_name}(#{media_id})", 'vdcCopyMedia', owner, :on_success => lambda do data[:medias][media_id][:status] = 1 end ) media = source_media.dup.merge( :name => media_name, :status => 0, :tasks => [task_id] ) data[:medias][media_id] = media body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location }.merge(media_body(media_id)) Excon::Response.new( :status => 201, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_organization.rb0000644000004100000410000000704112261242552026337 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve an organization. # # @param [String] id The object identifier of the organization. # @return [Excon:Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-Organization.html # @since vCloud API version 0.9 def get_organization(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "org/#{id}" ) ensure_list! response.body, :Tasks, :Task response end end class Mock def get_organization(id) unless id == data[:org][:uuid] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"com.vmware.vcloud.entity.org:#{id}\"" ) end org = data[:org] body = {:href=>make_href("org/#{id}"), :type=>"application/vnd.vmware.vcloud.org+xml", :id=>"urn:vcloud:org:#{id}", :name=>org[:name], :Link=> [{:href=>make_href("tasksList/#{id}"), :type=>"application/vnd.vmware.vcloud.tasksList+xml", :rel=>"down"}, {:href=>make_href("admin/org/#{id}/catalogs"), :type=>"application/vnd.vmware.admin.catalog+xml", :rel=>"add"}, {:href=>make_href("org/#{id}/metadata"), :type=>"application/vnd.vmware.vcloud.metadata+xml", :rel=>"down"}], :Description=>org[:description]||'', :Tasks=>{:Task=>[]}, :FullName=>org[:full_name]} body[:Link] += data[:catalogs].map do |catalog_id, catalog| [{:href=>make_href("catalog/#{catalog_id}"), :name=>catalog[:name], :type=>"application/vnd.vmware.vcloud.catalog+xml", :rel=>"down"}, {:href=>make_href("org/#{id}/catalog/#{catalog_id}/controlAccess/"), :type=>"application/vnd.vmware.vcloud.controlAccess+xml", :rel=>"down"}, {:href=> make_href("org/#{id}/catalog/#{catalog_id}/action/controlAccess"), :type=>"application/vnd.vmware.vcloud.controlAccess+xml", :rel=>"controlAccess"}] end.flatten body[:Link] += data[:networks].map do |network_id, network| {:href=>make_href("network/#{network_id}"), :name=>network[:name], :type=>"application/vnd.vmware.vcloud.orgNetwork+xml", :rel=>"down"} end body[:Link] += data[:vdcs].map do |vdc_id, vdc| {:href=>make_href("vdc/#{vdc_id}"), :name=>vdc[:name], :type=>"application/vnd.vmware.vcloud.vdc+xml", :rel=>"down"} end if api_version.to_f >= 5.1 body[:Link] << {:href=>make_href('supportedSystemsInfo/'), :type=>"application/vnd.vmware.vcloud.supportedSystemsInfo+xml", :rel=>"down"} end Excon::Response.new( :body => body, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :status => 200 ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/put_disk_metadata_item_metadata.rb0000644000004100000410000000333112261242552031332 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Set the value for the specified metadata key to the value provided, # overwriting any existing value. # # @param [String] id Object identifier of the disk. # @param [String] key Key of the metadata item. # @param [Boolean,DateTime,Fixnum,String] value Value of the metadata # item. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/PUT-DiskMetadataItem-metadata.html # @since vCloud API version 5.1 def put_disk_metadata_item_metadata(id, key, value) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance' } MetadataValue(attrs) { type = case value when TrueClass, FalseClass then 'MetadataBooleanValue'; when DateTime then 'MetadataDateTimeValue'; when Fixnum then 'MetadataNumberValue'; else 'MetadataStringValue' end TypedValue('xsi:type' => type) { Value value } } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.metadata.value+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "disk/#{id}/metadata/#{URI.escape(key)}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_media_metadata.rb0000644000004100000410000000136312261242552026553 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve metadata associated with a media object. # # @param [String] id Object identifier of the media object # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-MediaMetadata.html # @since vCloud API version 1.5 def get_media_metadata(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "media/#{id}/metadata" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vapp_owner.rb0000644000004100000410000000131412261242552026010 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the owner of a vApp. # # @param [String] id Object identifier of the vApp. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VAppOwner.html # @since vCloud API version 1.5 def get_vapp_owner(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/owner" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_href.rb0000644000004100000410000000075612261242552024565 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # This is used for manual testing. # # @api private def get_href(href) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :override_path => true, :path => URI.parse(href).path ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_org_vdc_gateways.rb0000644000004100000410000000575312261242552027172 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :get_edge_gateways, :get_org_vdc_gateways # List all gateways for this Org vDC. # # @param [String] id Object identifier of the vDC. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-OrgVdcGateways.html # @since vCloud API version 5.1 def get_org_vdc_gateways(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "admin/vdc/#{id}/edgeGateways" ) ensure_list! response.body, :EdgeGatewayRecord response end end class Mock def get_org_vdc_gateways(vdc_id) unless data[:vdcs][vdc_id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.vdc:#{vdc_id})\"." ) end body = {:xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :total => "1", :pageSize => "25", :page => "1", :name => "edgeGateways", :type => "application/vnd.vmware.vcloud.query.records+xml", :href => make_href("admin/vdc/#{vdc_id}edgeGateways?page=1&pageSize=25&format=records"), :xsi_schemaLocation => xsi_schema_location, :Link => [{:rel => "alternate", :type => "application/vnd.vmware.vcloud.query.references+xml", :href => make_href("admin/vdc/#{vdc_id}edgeGateways?page=1&pageSize=25&format=references")}, {:rel => "alternate", :type => "application/vnd.vmware.vcloud.query.idrecords+xml", :href => make_href("admin/vdc/#{vdc_id}edgeGateways?page=1&pageSize=25&format=records")}], :EdgeGatewayRecord => []} vdc_edge_gateways = data[:edge_gateways].select do |id, edge_gateway| edge_gateway[:vdc] == vdc_id end body[:EdgeGatewayRecord] += vdc_edge_gateways.map do |id, edge_gateway| {:vdc => make_href("vdc/#{vdc_id}"), :numberOfOrgNetworks => "1", :numberOfExtNetworks => "1", :name => edge_gateway[:name], :isBusy => "false", :haStatus => "DISABLED", :gatewayStatus => "READY", :href => make_href("admin/edgeGateway/#{id}"), :isSyslogServerSettingInSync => "true"} end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_answer_vm_pending_question.rb0000644000004100000410000000233212261242552031473 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Answer a question being asked by a VM. # # @param [String] id Object identifier of the VM. # @param [Integer] choice_id Choice ID of this answer. # @param [String] question_id Question ID of the question. # @return [Excon::Response] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-AnswerVmPendingQuestion.html # @since vCloud API version 0.9 def post_answer_pending_vm_question(id, choice_id, question_id) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5' } VmAnswerQuestion(attrs) { ChoiceId choice_id QuestionId question_id } end.to_xml request( :body => body, :expects => 204, # this might be wrong :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.vmPendingAnswer+xml'}, :method => 'POST', :path => "vApp/#{id}/quesiton/action/answer" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_media_owner.rb0000644000004100000410000000444112261242552026125 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the owner of a media object. # # @param [String] id Object identifier of the media object. # @return [Excon::Response] # * body<~Hash>: # * :href<~String> - The URI of the media object. # * :type<~String> - The MIME type of the media object. # * :Link<~Hash>: # * :href<~String> - # * :type<~String> - # * :rel<~String> - # * :User<~Hash> - Reference to the user who is the owner of this # media object. # * :href<~String> - The URI of the user. # * :name<~String> - The name of the user. # * :type<~String> - The MIME type of the user. # # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-MediaOwner.html # @since vCloud API version 1.5 def get_media_owner(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "media/#{id}/owner" ) end end class Mock def get_media_owner(id) unless data[:medias][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'No access to entity "com.vmware.vcloud.entity.media:%s".' % id ) end body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location, :Link => { :href => make_href("media/#{id}"), :type => 'application/vnd.vmware.vcloud.media+xml', :rel => 'up' }, :User => { :href => make_href("admin/user/#{user_uuid}"), :name => user_name, :type => 'application/vnd.vmware.admin.user+xml', } } Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{@version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_update_media_metadata.rb0000644000004100000410000000356012261242552030324 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Merge the metadata provided in the request with existing metadata. # # @param [String] id Object identifier of the media object. # @param [Hash{String=>Boolean,DateTime,Fixnum,String}] metadata # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-UpdateMediaMetadata.html # @since vCloud API version 1.5 def post_update_media_metadata(id, metadata={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance' } Metadata(attrs) { metadata.each do |key, value| MetadataEntry { Key key if api_version.to_f < 5.1 Value value else type = case value when TrueClass, FalseClass then 'MetadataBooleanValue'; when DateTime then 'MetadataDateTimeValue'; when Fixnum then 'MetadataNumberValue'; else 'MetadataStringValue' end TypedValue('xsi:type' => type) { Value value } end } end } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.metadata+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "media/#{id}/metadata/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_task_list.rb0000644000004100000410000001432012261242552025626 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :get_tasks_list, :get_task_list # Retrieve a list of this organization's queued, running, or recently # completed tasks. # # @param [String] id Object identifier of the organization. # @return [Excon::Response] # * body<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :id<~String> - The entity identifier, expressed in URN format. # The value of this attribute uniquely identifies the entity, # persists for the life of the entity, and is never reused. # * :name<~String> - The name of the entity. # * :Task<~Array>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :id<~String> - The entity identifier, expressed in URN # format. The value of this attribute uniquely identifies the # entity, persists for the life of the entity, and is never # reused. # * :operationKey<~String> - Optional unique identifier to # support idempotent semantics for create and delete # operations. # * :name<~String> - The name of the entity. # * :cancelRequested<~String> - Whether user has requested this # processing to be canceled. # * :endTime<~String> - The date and time that processing of the # task was completed. May not be present if the task is still # being executed. # * :expiryTime<~String> - The date and time at which the task # resource will be destroyed and no longer available for # retrieval. May not be present if the task has not been # executed or is still being executed. # * :operation<~String> - A message describing the operation that # is tracked by this task. # * :operationName<~String> - The short name of the operation # that is tracked by this task. # * :serviceNamespace<~String> - Identifier of the service that # created the task. # * :startTime<~String> - The date and time the system started # executing the task. May not be present if the task has not # been executed yet. # * :status<~String> - The execution status of the task. # * :Link<~Array>: # * :Description<~String> - Optional description. # * :Owner<~Hash> - Reference to the owner of the task. This is # typically the object that the task is creating or updating. # * :href<~String> - Contains the URI to the entity. # * :name<~String> - Contains the name of the entity. # * :type<~String> - Contains the type of the entity. # * :Error<~Hash> - Represents error information from a failed # task. # * :majorErrorCode<~String> - The class of the error. Matches # the HTTP status code. # * :message<~String> - An one line, human-readable message # describing the error that occurred. # * :minorErrorCode<~String> - Resource-specific error code. # * :stackTrace<~String> - The stack trace of the exception. # * :vendorSpecificErrorCode<~String> - A vendor- or # implementation-specific error code that can reference # specific modules or source lines for diagnostic purposes. # * :User<~Hash> - The user who started the task. # * :href<~String> - Contains the URI to the entity. # * :name<~String> - Contains the name of the entity. # * :type<~String> - Contains the type of the entity. # * :Organization<~Hash> - The organization to which the :User # belongs. # * :href<~String> - Contains the URI to the entity. # * :name<~String> - Contains the name of the entity. # * :type<~String> - Contains the type of the entity. # * :Progress<~String> - Read-only indicator of task progress as # an approximate percentage between 0 and 100. Not available # for all tasks. # * :Params # * :Details<~String> - Detailed message about the task. Also # contained by the :Owner entity when task status is # preRunning. # # @raise [Fog::Compute::VcloudDirector::BadRequest] # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-TaskList.html # @since vCloud API version 0.9 def get_task_list(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "tasksList/#{id}" ) ensure_list! response.body, :Task response end end class Mock def get_task_list(id) unless id == data[:org][:uuid] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"com.vmware.vcloud.entity.org:#{id}\"." ) end body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location, :href => make_href("tasksList/#{id}"), :type => "application/vnd.vmware.vcloud.tasksList+xml", :name => "Tasks Lists", :Task => data[:tasks].keys.map {|task_id| task_body(task_id)} } Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_task.rb0000644000004100000410000001644712261242552024607 0ustar www-datawww-datarequire 'date' module Fog module Compute class VcloudDirector class Real # Retrieve a task. # # @param [String] id The object identifier of the task. # @return [Excon::Response] # * body<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :id<~String> - The entity identifier, expressed in URN format. # The value of this attribute uniquely identifies the entity, # persists for the life of the entity, and is never reused. # * :operationKey<~String> - Optional unique identifier to support # idempotent semantics for create and delete operations. # * :name<~String> - The name of the entity. # * :cancelRequested<~String> - Whether user has requested this # processing to be canceled. # * :endTime<~String> - The date and time that processing of the # task was completed. May not be present if the task is still # being executed. # * :expiryTime<~String> - The date and time at which the task # resource will be destroyed and no longer available for # retrieval. May not be present if the task has not been executed # or is still being executed. # * :operation<~String> - A message describing the operation that # is tracked by this task. # * :operationName<~String> - The short name of the operation that # is tracked by this task. # * :serviceNamespace<~String> - Identifier of the service that # created the task. # * :startTime<~String> - The date and time the system started # executing the task. May not be present if the task has not been # executed yet. # * :status<~String> - The execution status of the task. # * :Link<~Array>: # * :Description<~String> - Optional description. # * :Owner<~Hash> - Reference to the owner of the task. This is # typically the object that the task is creating or updating. # * :href<~String> - Contains the URI to the entity. # * :name<~String> - Contains the name of the entity. # * :type<~String> - Contains the type of the entity. # * :Error<~Hash> - Represents error information from a failed # task. # * :majorErrorCode<~String> - The class of the error. Matches # the HTTP status code. # * :message<~String> - An one line, human-readable message # describing the error that occurred. # * :minorErrorCode<~String> - Resource-specific error code. # * :stackTrace<~String> - The stack trace of the exception. # * :vendorSpecificErrorCode<~String> - A vendor- or # implementation-specific error code that can reference # specific modules or source lines for diagnostic purposes. # * :User<~Hash> - The user who started the task. # * :href<~String> - Contains the URI to the entity. # * :name<~String> - Contains the name of the entity. # * :type<~String> - Contains the type of the entity. # * :Organization<~Hash> - The organization to which the :User # belongs. # * :href<~String> - Contains the URI to the entity. # * :name<~String> - Contains the name of the entity. # * :type<~String> - Contains the type of the entity. # * :Progress<~String> - Read-only indicator of task progress as an # approximate percentage between 0 and 100. Not available for all # tasks. # * :Params # * :Details<~String> - Detailed message about the task. Also # contained by the :Owner entity when task status is preRunning. # # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-Task.html # @since vCloud API version 0.9 def get_task(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "task/#{id}" ) # vCloud Director bug: Owner may be absent for some tasks, fix # targeted for 5.1.3 (due out at the beginning Q1 2014). # # We'd prefer that Owner is always present; if nothing else, this # let's the tests pass. response.body[:Owner] ||= {:href => '', :name => nil, :type => nil} response end end class Mock def get_task(id) unless data[:tasks][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location }.merge(task_body(id)) Excon::Response.new( :status => 200, :headers => {'Type' => "application/#{body[:type]};version=#{api_version}"}, :body => body ) end private # @param [String] id Object identifier of the task. # @return [Hash] def task_body(id) task = data[:tasks][id] body = { :href => make_href("tasks/#{id}"), :type => 'application/vnd.vmware.vcloud.task+xml', :id => "urn:vcloud:tasl:#{id}", :name => task[:name], :cancelRequested => task[:cancel_requested].to_s, :expiryTime => task[:expiry_time].strftime('%Y-%m-%dT%H:%M:%S%z'), :operation => task[:operation], :operationName => task[:operation_name], :serviceNamespace => task[:service_namespace], :status => task[:status], :Link => [], :Owner => task[:owner], :User => { # for now, always the current user :href => make_href("admin/user/#{user_uuid}"), :name => user_name, :type => 'application/vnd.vmware.admin.user+xml', }, :Organization => { # for now, always the current org :href => make_href("org/#{data[:org][:uuid]}"), :name => data[:org][:name], :type => 'application/vnd.vmware.vcloud.org+xml', }, :Progress => task[:progress].to_s, :Details => task[:details] || '', } body[:endTime] = task[:end_time].strftime('%Y-%m-%dT%H:%M:%S%z') if task[:end_time] body[:startTime] = task[:start_time].strftime('%Y-%m-%dT%H:%M:%S%z') if task[:start_time] body[:Description] = task[:description] if task[:description] if task[:status] == 'running' body[:Link] << { :href => make_href("task/#{id}/action/cancel"), :type => 'application/vnd.vmware.vcloud.task+xml', :rel => 'cancel', } end body end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/put_memory.rb0000644000004100000410000000457612261242552025206 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :put_vm_memory, :put_memory # Update the RASD item that specifies memory properties of a VM. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @param [Integer] memory Memory size in Megabytes. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/PUT-Memory.html # @since vCloud API version 0.9 def put_memory(id, memory) data = < byte * 2^20 Memory Size #{memory} MB of memory 5 0 4 #{memory} 0 EOF request( :body => data, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.rasdItem+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/virtualHardwareSection/memory" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vm.rb0000644000004100000410000000130012261242552024245 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/parsers/compute/vm' # Retrieve a vApp or VM. # # @note This should probably be deprecated. # # @param [String] id Object identifier of the vApp or VM. # @return [Excon::Response] # * body<~Hash>: # # @see #get_vapp def get_vm(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Compute::VcloudDirector::Vm.new, :path => "vApp/#{id}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/delete_vapp_template_metadata_item_metadata.rb0000644000004100000410000000157212261242552033700 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Delete the specified key and its value from vApp template or VM # metadata. # # @param [String] id Object identifier of the vApp template or VM. # @param [String] key Key of the metadata item. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/DELETE-VAppTemplateMetadataItem-metadata.html # @since vCloud API version 1.5 def delete_vapp_template_metadata_item_metadata(id, key) request( :expects => 202, :method => 'DELETE', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/metadata/#{URI.escape(key)}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_remove_all_snapshots.rb0000644000004100000410000000161312261242552030267 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Removes all user created snapshots for a vApp or virtual machine. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the vApp or virtual machine. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-RemoveAllSnapshots.html # @since vCloud API version 5.1 def post_remove_all_snapshots(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/action/removeAllSnapshots" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_reboot_vapp.rb0000644000004100000410000000207712261242552026365 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Reboot a vApp or VM. # # If used on a vApp, reboots all VMs in the vApp. If used on a VM, # reboots the VM. This operation is available only for a vApp or VM # that is powered on. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the vApp or VM. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::BadRequest] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-RebootVApp.html # @since vCloud API version 0.9 def post_reboot_vapp(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/power/action/reboot" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_disks_rasd_items_list.rb0000644000004100000410000000147512261242552030222 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve all RASD items that specify hard disk and hard disk # controller properties of a VM. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-DisksRasdItemsList.html # @since vCloud API version 0.9 def get_disks_rasd_items_list(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/virtualHardwareSection/disks" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/delete_vapp_metadata_item_metadata.rb0000644000004100000410000000175612261242552032011 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :delete_metadata, :delete_vapp_metadata_item_metadata require 'fog/vcloud_director/parsers/compute/metadata' # Delete the specified key and its value from vApp or VM metadata. # # @param [String] id Object identifier of the vApp or VM. # @param [String] key Key of the metadata item. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/DELETE-VAppMetadataItem-metadata.html # @since vCloud API version 1.5 def delete_vapp_metadata_item_metadata(id, key) request( :expects => 202, :method => 'DELETE', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/metadata/#{URI.escape(key)}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_catalog_item_metadata.rb0000644000004100000410000000141312261242552030120 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve all metadata associated with a catalog item. # # @param [String] id Object identifier of the catalog item. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-CatalogItemMetadata.html # @since vCloud API version 1.5 def get_catalog_item_metadata(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "catalogItem/#{id}/metadata" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_allocated_ip_addresses.rb0000644000004100000410000000142212261242552030305 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a list of IP addresses allocated to the network. # # @param [String] id Object identifier of the network. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-AllocatedIpAddresses.html # @since vCloud API version 5.1 def get_allocated_ip_addresses(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "network/#{id}/allocatedAddresses" ) end end end end end ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootfog-1.19.0/lib/fog/vcloud_director/requests/compute/get_guest_customization_system_section_vapp_template.rbfog-1.19.0/lib/fog/vcloud_director/requests/compute/get_guest_customization_system_section_vapp_temp0000644000004100000410000000150412261242552034551 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves the guest customization section of a VM. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-GuestCustomizationSystemSection-vAppTemplate.html # @since vCloud API version 1.0 def get_guest_customization_system_section_vapp_template(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/guestCustomizationSection" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_control_access_params_vapp.rb0000644000004100000410000000137512261242552031231 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve access control information for a vApp. # # @param [String] id Object identifier of the vApp. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-ControlAccessParams-vApp.html # @since vCloud API 0.9 def get_control_access_params_vapp(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/controlAccess" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_serial_ports_items_list.rb0000644000004100000410000000144612261242552030600 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve all RASD items that specify serial port properties of a VM. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-SerialPortsItemsList.html # @since vCloud API version 1.5 def get_serial_ports_items_list(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/virtualHardwareSection/serialPorts" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/put_vapp_metadata_item_metadata.rb0000644000004100000410000000352612261242552031354 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Set the value for the specified metadata key to the value provided, # overwriting any existing value. # # @param [String] id Object identifier of the vApp or VM. # @param [String] key Key of the metadata item. # @param [Boolean,DateTime,Fixnum,String] value Value of the metadata # item. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/PUT-VAppMetadataItem-metadata.html # @since vCloud API version 1.5 def put_vapp_metadata_item_metadata(id, key, value) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance' } MetadataValue(attrs) { if api_version.to_f < 5.1 Value value else type = case value when TrueClass, FalseClass then 'MetadataBooleanValue'; when DateTime then 'MetadataDateTimeValue'; when Fixnum then 'MetadataNumberValue'; else 'MetadataStringValue' end TypedValue('xsi:type' => type) { Value value } end } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.metadata.value+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/metadata/#{URI.escape(key)}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vdc_metadata_item_metadata.rb0000644000004100000410000000164112261242552031125 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the value of the specified key from virtual datacenter # metadata. # # @param [String] id Object identifier of the network. # @param [String] domain # @param [String] key Key of the metadata. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VdcMetadataItem-metadata.html # @since vCloud API version 1.5 def get_vdc_metadata_item_metadata(id, domain, key) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "admin/vdc/#{id}/metadata/#{URI.escape(key)})" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_lease_settings_section_vapp_template.rb0000644000004100000410000000147112261242552033312 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves the lease settings section of a vApp template. # # @param [String] id Object identifier of the vApp template. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-LeaseSettingsSection-vAppTemplate.html # @since vCloud API version 0.9 def get_lease_settings_section_vapp_template(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/leaseSettingsSection" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_virtual_hardware_section.rb0000644000004100000410000000175312261242552030726 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the virtual hardware section of a VM. # # This operation retrieves the entire VirtualHardwareSection of a VM. # You can also retrieve many RASD item elements of a # VirtualHardwareSection individually, or as groups of related items. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VirtualHardwareSection.html # @since vCloud API version 0.9 def get_virtual_hardware_section(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/virtualHardwareSection/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_product_sections_vapp_template.rb0000644000004100000410000000150712261242552032144 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a list of ProductSection elements from a vApp template or # VM. # # @param [String] id Object identifier of the vApp template or VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-ProductSections-vAppTemplate.html # @since vCloud API version 1.5 def get_product_sections_vapp_template(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/productSections" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_network_config_section_vapp.rb0000644000004100000410000000142212261242552031420 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the network config section of a vApp. # # @param [String] id The object identifier of the vApp. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-NetworkConfigSection-vApp.html # @since vCloud API version 0.9 def get_network_config_section_vapp(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/networkConfigSection/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vm_disks.rb0000644000004100000410000000173412261242552025455 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/parsers/compute/disks' # Retrieve all RASD items that specify hard disk and hard disk # controller properties of a VM. # # @deprecated Use {#get_disks_rasd_items_list} instead. # @todo Log deprecation warning. # # @param [String] id # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-DisksRasdItemsList.html # @since vCloud API version 0.9 def get_vm_disks(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Compute::VcloudDirector::Disks.new, :path => "vApp/#{id}/virtualHardwareSection/disks" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_reset_vapp.rb0000644000004100000410000000207112261242552026207 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Reset a vApp or VM. # # If used on a vApp, resets all VMs in the vApp. If used on a VM, # resets the VM. This operation is available only for a vApp or VM that # is powered on. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the vApp or VM. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::BadRequest] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-ResetVApp.html # @since vCloud API version 0.9 def post_reset_vapp(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/power/action/reset" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_cpu_rasd_item.rb0000644000004100000410000000152712261242552026454 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :get_vm_cpu, :get_cpu_rasd_item # Retrieve the RASD item that specifies CPU properties of a VM. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-CpuRasdItem.html # @since vCloud API version 0.9 def get_cpu_rasd_item(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/virtualHardwareSection/cpu" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_upload_media.rb0000644000004100000410000001027412261242552026466 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Upload a media image. # # The response includes an upload link for the media image. # # @param [String] vdc_id Object identifier of the vDC. # @param [String] name The name of the media image. # @param [String] image_type Media image type. One of: iso, floppy. # @param [Integer] size Size of the media file, in bytes. # @param [Hash] options # @option options [String] :operationKey Optional unique identifier to # support idempotent semantics for create and delete operations. # @option options [String] :Description Optional description. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::BadRequest] # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-UploadMedia.html # @since vCloud API version 0.9 # @todo Support vDC Storage Profiles. def post_upload_media(vdc_id, name, image_type, size, options={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', :name => name, :imageType => image_type, :size => size } attrs[:operationKey] = options[:operationKey] if options.key?(:operationKey) Media(attrs) { if options.key?(:Description) Description options[:Description] end } end.to_xml response = request( :body => body, :expects => 201, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.media+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vdc/#{vdc_id}/media" ) ensure_list! response.body, :Files, :File response end end class Mock def post_upload_media(vdc_id, name, image_type, size, options={}) unless ['iso','floppy'].include?(image_type) raise Fog::Compute::VcloudDirector::BadRequest.new( 'The value of parameter imageType is incorrect.' ) end unless size.to_s =~ /^\d+$/ raise Fog::Compute::VcloudDirector::BadRequest.new( 'validation error on field \'size\': must be greater than or equal to 0' ) end unless data[:vdcs][vdc_id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.vdc:#{vdc_id})\"." ) end media_id = uuid file_id = uuid owner = { :href => make_href("media/#{media_id}"), :type => 'application/vnd.vmware.vcloud.media+xml' } task_id = enqueue_task( "Importing Media File #{name}(#{file_id})", 'vdcUploadMedia', owner, :on_success => lambda do media = data[:medias][media_id] media[:file][:bytes_transferred] = media[:size] media[:status] = 1 end ) media = { :description => options[:Description], :file => { :bytes_transferred => 0, :uuid => file_id }, :image_type => image_type, :name => name, :size => size.to_i, :status => 0, :tasks => [task_id], :vdc_id => vdc_id, :vdc_storage_class => data[:vdc_storage_classes].detect {|k,v| v[:default]}.first } data[:medias][media_id] = media body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location }.merge(media_body(media_id)) Excon::Response.new( :status => 201, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_create_org_vdc_network.rb0000644000004100000410000001514212261242552030561 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/generators/compute/org_vdc_network' # Create an Org vDC network. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # Produce media type(s): # application/vnd.vmware.vcloud.orgVdcNetwork+xml # Output type: # OrgVdcNetworkType # # @param [String] vdc_id Object identifier of the vDC # @param [String] name The name of the entity. # @param [Hash] options # @option options [String] :Description Optional description. # @option options [Hash] :Configuration Network configuration. # @option options [Hash] :EdgeGateway EdgeGateway that connects this # Org vDC network. Applicable only for routed networks. # @option options [Hash] :ServiceConfig Specifies the service # configuration for an isolated Org vDC networks. # @option options [Boolean] :IsShared True if this network is shared # to multiple Org vDCs. # * :Configuration<~Hash>: NetworkConfigurationType # * :IpScopes<~Hash>: # * :IpScope<~Hash>: # * :IsInherited<~Boolean>: ? # * :Gateway<~String>: IP address of gw # * :Netmask<~String>: Subnet mask of network # * :Dns1<~String>: Primary DNS server. # * :Dns2<~String>: Secondary DNS server. # * :DnsSuffix<~String>: DNS suffix. # * :IsEnabled<~String>: Indicates if subnet is enabled or not. # Default value is True. # * :IpRanges<~Array>: IP ranges used for static pool allocation # in the network. Array of Hashes of: # * :StartAddress - start IP in range # * :EndAddress - end IP in range # * :EdgeGateway<~Hash>: EdgeGateway that connects this Org vDC # network. Applicable only for routed networks. # * :ServiceConfig<~Hash>: Specifies the service configuration for an # isolated network # # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-CreateOrgVdcNetwork.html # @since vCloud API version 5.1 def post_create_org_vdc_network(vdc_id, name, options={}) body = Fog::Generators::Compute::VcloudDirector::OrgVdcNetwork.new(options.merge(:name => name)).generate_xml request( :body => body, :expects => 201, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.orgVdcNetwork+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "admin/vdc/#{vdc_id}/networks" ) end end class Mock def post_create_org_vdc_network(vdc_id, name, options={}) unless data[:vdcs][vdc_id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.vdc:#{vdc_id})\"." ) end type = 'network' id = uuid # Description # Configuration # IpScopes # IpScope # IsInherited # Gateway # Netmask # Dns1 # Dns2 # DnsSuffix # IsEnabled # IpRanges # IpRange # StartAddress # EndAddress # FenceMode # EdgeGateway # IsShared network_body = { :name => name, :vdc => vdc_id, } [:Description, :IsShared].each do |key| network_body[key] = options[key] if options.key?(key) end if options.key?(:EdgeGateway) network_body[:EdgeGateway] = options[:EdgeGateway][:href].split('/').last end if configuration = options[:Configuration] if ip_scopes = configuration[:IpScopes] if ip_scope = ip_scopes[:IpScope] [:IsInherited, :Gateway, :Netmask, :Dns1, :Dns2, :DnsSuffix, :IsEnabled].each do |key| network_body[key] = ip_scope[key] if ip_scope.key?(key) end if ip_ranges = ip_scope[:IpRanges] network_body[:IpRanges] = [] ip_ranges.each do |ipr| network_body[:IpRanges] << { :StartAddress => ipr[:IpRange][:StartAddress], :EndAddress => ipr[:IpRange][:EndAddress] } end end end end network_body[:FenceMode] = configuration[:FenceMode] if ip_scope.key?(:FenceMode) end owner = { :href => make_href("#{type}/#{id}"), :type => "application/vnd.vmware.vcloud.#{type}+xml" } task_id = enqueue_task( "Adding #{type} #{name} (#{id})", 'CreateOrgVdcNetwork', owner, :on_success => lambda do data[:networks][id] = network_body end ) body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location, :href => make_href("admin/network/#{id}"), :name => name, :id => "urn:vcloud:network:#{id}", :type => "application/vnd.vmware.vcloud.orgVdcNetwork+xml", :Link => [ {:rel=>"up", :type=>"application/vnd.vmware.vcloud.vdc+xml", :href=>make_href("vdc/#{vdc_id}")}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.metadata+xml", :href=>make_href("admin/network/#{id}/metadata")}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.allocatedNetworkAddress+xml", :href=>make_href("admin/network/#{id}/allocatedAddresses/")}, ], }.merge(options) body[:Tasks] = { :Task => task_body(task_id) } Excon::Response.new( :status => 201, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vms_in_lease_from_query.rb0000644000004100000410000001117012261242552030545 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves a list of VMs in lease by using REST API general # QueryHandler. # # @param [Hash] options # @option options [String] :sortAsc (Sorted by database ID) Sort # results by attribute-name in ascending order. attribute-name cannot # include metadata. # @option options [String] :sortDesc (Sorted by database ID) Sort # results by attribute-name in descending order. attribute-name # cannot include metadata. # @option options [Integer] :page (1) If the query results span # multiple pages, return this page. # @option options [Integer] :pageSize (25) Number of results per page, # to a maximum of 128. # @option options [String] :format (records) One of the following # types: # - *references* Returns a reference to each object, including its # :name, :type, and :href attributes. # - *records* Returns all database records for each object, with each # record as an attribute. # - *idrecords* Identical to the records format, except that object # references are returned in :id format rather than :href format. # @option options [Array] :fields (all static attribute names) # List of attribute names or metadata key names to return. # @option options [Integer] :offset (0) Integer value specifying the # first record to return. Record numbers < offset are not returned. # @option options [String] :filter (none) Filter expression. # @return [Excon::Response] # * hash<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :name<~String> - Query name that generated this result set. # * :page<~String> - Page of the result set that this container # holds. The first page is page number 1. # * :pageSize<~String> - Page size, as a number of records or # references. # * :total<~String> - Total number of records or references in the # container. # * :Link<~Array>: # * :href<~String> - Contains the URI to the entity. # * :type<~String> - Contains the type of the entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # * :VMRecord<~Array>: # * TODO # * :firstPage<~Integer> - First page in the result set. # * :previousPage<~Integer> - Previous page in the result set. # * :nextPage<~Integer> - Next page in the result set. # * :lastPage<~Integer> - Last page in the result set. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VMsInLeaseFromQuery.html # @since vCloud API version 1.5 def get_vms_in_lease_from_query(options={}) query = [] query << "sortAsc=#{options[:sortAsc]}" if options[:sortAsc] query << "sortDesc=#{options[:sortDesc]}" if options[:sortDesc] query << "page=#{options[:page]}" if options[:page] query << "pageSize=#{options[:pageSize]}" if options[:pageSize] query << "format=#{options[:format]}" if options[:format] query << "fields=#{Array(options[:fields]).join(',')}" if options[:fields] query << "offset=#{options[:offset]}" if options[:offset] query << "filter=#{options[:filter]}" if options[:filter] response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'vms/query', :query => query.map {|q| URI.escape(q)}.join('&') ) ensure_list! response.body, :Link ensure_list! response.body, response.body[:type] == 'application/vnd.vmware.vcloud.query.references+xml' ? :VMReference : :VMRecord %w[firstPage previousPage nextPage lastPage].each do |rel| if link = response.body[:Link].detect {|l| l[:rel] == rel} href = Nokogiri::XML.fragment(link[:href]) query = CGI.parse(URI.parse(href.text).query) response.body[rel.to_sym] = query['page'].first.to_i response.body[:pageSize] ||= query['pageSize'].first.to_i end end response end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_exit_maintenance_mode.rb0000644000004100000410000000121112261242552030351 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Take the vApp out of maintenance mode. # # @param [String] id Object identifier of the vApp. # @return [Excon::Response] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-ExitMaintenanceMode.html # @since vCloud API version 1.5 def post_exit_maintenance_mode(id) request( :expects => 204, :method => 'POST', :path => "vApp/#{id}/action/exitMaintenanceMode" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vapp_template.rb0000644000004100000410000000133112261242552026470 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a vApp template. # # @param [String] id Object identifier of the vApp template. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VAppTemplate.html # @since vCloud API version 0.9 def get_vapp_template(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_consolidate_vm_vapp_template.rb0000644000004100000410000000153712261242552031774 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Consolidate VM snapshots. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-ConsolidateVm-vAppTemplate.html # @since vCloud API version 1.5 def post_consolidate_vm_vapp_template(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/action/consolidate" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_execute_query.rb0000644000004100000410000006602112261242552026525 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # REST API General queries handler. # # @param [String] type The type of the query. Type names are # case-sensitive. You can retrieve a summary list of all typed # queries types accessible to the currently authenticated user by # making a request with type=nil. # @param [Hash] options # @option options [String] :sortAsc (Sorted by database ID) Sort # results by attribute-name in ascending order. attribute-name cannot # include metadata. # @option options [String] :sortDesc (Sorted by database ID) Sort # results by attribute-name in descending order. attribute-name # cannot include metadata. # @option options [Integer] :page (1) If the query results span # multiple pages, return this page. # @option options [Integer] :pageSize (25) Number of results per page, # to a maximum of 128. # @option options [String] :format (records) One of the following # types: # - *references* Returns a reference to each object, including its # :name, :type, and :href attributes. # - *records* Returns all database records for each object, with each # record as an attribute. # - *idrecords* Identical to the records format, except that object # references are returned in :id format rather than :href format. # @option options [Array] :fields (all static attribute names) # List of attribute names or metadata key names to return. # @option options [Integer] :offset (0) Integer value specifying the # first record to return. Record numbers < offset are not returned. # @option options [String] :filter (none) Filter expression. # @return [Excon::Response] if type is specified. # * hash<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :name<~String> - Query name that generated this result set. # * :page<~String> - Page of the result set that this container # holds. The first page is page number 1. # * :pageSize<~String> - Page size, as a number of records or # references. # * :total<~String> - Total number of records or references in the # container. # * :Link<~Array>: # * :href<~String> - Contains the URI to the entity. # * :type<~String> - Contains the type of the entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # * :Record<~Array> - The name and content of this item # varies according to the type and format of the query. # * :firstPage<~Integer> - First page in the result set. # * :previousPage<~Integer> - Previous page in the result set. # * :nextPage<~Integer> - Next page in the result set. # * :lastPage<~Integer> - Last page in the result set. # @return [Excon::Response] if type is nil. # * hash<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :Link<~Array>: # * :href<~String> - Contains the URI to the entity. # * :name<~String> - Contains the name of the entity. # * :type<~String> - Contains the type of the entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # # @see http://pubs.vmware.com/vcd-55/topic/com.vmware.vcloud.api.reference.doc_55/doc/operations/GET-ExecuteQuery.html # @since vCloud API version 1.5 def get_execute_query(type=nil, options={}) if type.nil? response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'query' ) else query = ["type=#{type}"] query << "sortAsc=#{options[:sortAsc]}" if options[:sortAsc] query << "sortDesc=#{options[:sortDesc]}" if options[:sortDesc] query << "page=#{options[:page]}" if options[:page] query << "pageSize=#{options[:pageSize]}" if options[:pageSize] query << "format=#{options[:format]}" if options[:format] query << "fields=#{Array(options[:fields]).join(',')}" if options[:fields] query << "offset=#{options[:offset]}" if options[:offset] query << "filter=#{options[:filter]}" if options[:filter] response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'query', :query => query.map {|q| URI.escape(q)}.join('&') ) ensure_list! response.body, :Link # TODO: figure out the right key (this isn't it) #ensure_list! response.body, # response.body[:type] == 'application/vnd.vmware.vcloud.query.references+xml' ? # "#{response.body[:name]}Reference".to_sym : # "#{response.body[:name]}Record".to_sym %w[firstPage previousPage nextPage lastPage].each do |rel| if link = response.body[:Link].detect {|l| l[:rel] == rel} href = Nokogiri::XML.fragment(link[:href]) query = CGI.parse(URI.parse(href.text).query) response.body[rel.to_sym] = query['page'].first.to_i response.body[:pageSize] ||= query['pageSize'].first.to_i end end response end end end class Mock def get_execute_query(type=nil, options={}) unless options[:fields].nil? Fog::Mock.not_implemented("Fields are not yet implemented in get_execute_query Mock for #{type}") end unless options[:format].nil? || options[:format] == 'records' Fog::Mock.not_implemented("Formats #{options[:format]} is not yet implemented in get_execute_query Mock for #{type}") end # NB: default is to sort by 'Database ID' (uuid?). Does this matter? unless options[:sortAsc].nil? && options[:sortDesc].nil? Fog::Mock.not_implemented("Sorting by field is not yet implemented in get_execute_query Mock for #{type}") end # NB: default offset is 0 unless options[:offset].nil? Fog::Mock.not_implemented("Offset results are not yet implemented in get_execute_query Mock for #{type}") end # NB: default page is 1 if options.key?(:page) && options[:page].to_i != 1 Fog::Mock.not_implemented("Paginated results are not yet implemented in get_execute_query Mock for #{type}") end # NB: default pageSize is 25 unless options[:pageSize].nil? Fog::Mock.not_implemented("Paginated results are not yet implemented in get_execute_query Mock for #{type}") end if type.nil? body = all_types else body = fetch_items(type, options) end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end private def fetch_items(type, opts) if opts.key?(:filter) && opts[:filter] =~ /^name==([^;,]+)$/ name = $1 elsif opts.key?(:filter) Fog::Mock.not_implemented("Complex filters are not yet implemented in get_execute_query Mock for #{type}: #{opts[:filter]}") end body = { :xmlns=>xmlns, :xmlns_xsi=>xmlns_xsi, :href=>make_href('query'), :name=>type, :type=>"application/vnd.vmware.vcloud.query.records+xml", :xsi_schemaLocation=>xsi_schema_location, } if type == 'orgVdcNetwork' record_type = :OrgVdcNetworkRecords data_type = :networks records = [] data[data_type].each do |id, dr| r = {} if name.nil? || dr[:name] == name vdc_id = dr[:vdc] if data[:vdcs][vdc_id] && data[:vdcs][vdc_id].key?(:name) r[:vdcName] = data[:vdcs][vdc_id][:name] end r[:name] = dr[:name] r[:vdc] = make_href("vdc/#{vdc_id}") if vdc_id r[:href] = make_href("admin/network/#{id}") mapping = { :description => :Description, :netmask => :Netmask, :linkType => :LinkType, :dns1 => :Dns1, :dns2 => :Dns2, :dnsSuffix => :DnsSuffix, :defaultGateway => :Gateway, :isShared => :IsShared, :isBusy => :IsBusy, :isIpScopeInherited => :IsIpScopeInherited, } mapping.each do |k,v| r[k] = dr[v] if dr.key?(v) end records << r end end body[:page] = 1.to_s # TODO: Support pagination body[:pageSize] = records.size.to_s # TODO: Support pagination body[:total] = records.size.to_s body[record_type] = records else Fog::Mock.not_implemented("No 'get by name' get_execute_query Mock for #{type} (#{name})") end body end def all_types {:xmlns=>xmlns, :xmlns_xsi=>xmlns_xsi, :type=>"application/vnd.vmware.vcloud.query.queryList+xml", :href=>make_href('query'), :xsi_schemaLocation=>xsi_schema_location, :Link=> [{:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"organization", :href=>make_href('query?type=organization&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"organization", :href=>make_href('query?type=organization&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"organization", :href=>make_href('query?type=organization&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"orgVdc", :href=>make_href('query?type=orgVdc&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"orgVdc", :href=>make_href('query?type=orgVdc&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"orgVdc", :href=>make_href('query?type=orgVdc&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"media", :href=>make_href('query?type=media&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"media", :href=>make_href('query?type=media&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"media", :href=>make_href('query?type=media&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"vAppTemplate", :href=>make_href('query?type=vAppTemplate&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"vAppTemplate", :href=>make_href('query?type=vAppTemplate&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"vAppTemplate", :href=>make_href('query?type=vAppTemplate&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"vApp", :href=>make_href('query?type=vApp&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"vApp", :href=>make_href('query?type=vApp&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"vApp", :href=>make_href('query?type=vApp&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"vm", :href=>make_href('query?type=vm&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"vm", :href=>make_href('query?type=vm&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"vm", :href=>make_href('query?type=vm&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"orgNetwork", :href=>make_href('query?type=orgNetwork&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"orgNetwork", :href=>make_href('query?type=orgNetwork&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"orgNetwork", :href=>make_href('query?type=orgNetwork&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"vAppNetwork", :href=>make_href('query?type=vAppNetwork&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"vAppNetwork", :href=>make_href('query?type=vAppNetwork&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"vAppNetwork", :href=>make_href('query?type=vAppNetwork&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"catalog", :href=>make_href('query?type=catalog&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"catalog", :href=>make_href('query?type=catalog&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"catalog", :href=>make_href('query?type=catalog&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"group", :href=>make_href('query?type=group&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"group", :href=>make_href('query?type=group&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"group", :href=>make_href('query?type=group&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"user", :href=>make_href('query?type=user&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"user", :href=>make_href('query?type=user&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"user", :href=>make_href('query?type=user&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"strandedUser", :href=>make_href('query?type=strandedUser&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"strandedUser", :href=>make_href('query?type=strandedUser&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"strandedUser", :href=>make_href('query?type=strandedUser&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"role", :href=>make_href('query?type=role&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"role", :href=>make_href('query?type=role&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"role", :href=>make_href('query?type=role&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"allocatedExternalAddress", :href=>make_href('query?type=allocatedExternalAddress&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"allocatedExternalAddress", :href=>make_href('query?type=allocatedExternalAddress&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"event", :href=>make_href('query?type=event&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"event", :href=>make_href('query?type=event&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"right", :href=>make_href('query?type=right&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"right", :href=>make_href('query?type=right&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"right", :href=>make_href('query?type=right&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"vAppOrgNetworkRelation", :href=>make_href('query?type=vAppOrgNetworkRelation&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"vAppOrgNetworkRelation", :href=>make_href('query?type=vAppOrgNetworkRelation&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"vAppOrgNetworkRelation", :href=>make_href('query?type=vAppOrgNetworkRelation&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"catalogItem", :href=>make_href('query?type=catalogItem&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"catalogItem", :href=>make_href('query?type=catalogItem&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"catalogItem", :href=>make_href('query?type=catalogItem&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"task", :href=>make_href('query?type=task&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"task", :href=>make_href('query?type=task&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"task", :href=>make_href('query?type=task&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"disk", :href=>make_href('query?type=disk&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"disk", :href=>make_href('query?type=disk&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"disk", :href=>make_href('query?type=disk&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"vmDiskRelation", :href=>make_href('query?type=vmDiskRelation&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"vmDiskRelation", :href=>make_href('query?type=vmDiskRelation&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"service", :href=>make_href('query?type=service&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"service", :href=>make_href('query?type=service&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"service", :href=>make_href('query?type=service&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"orgVdcStorageProfile", :href=>make_href('query?type=orgVdcStorageProfile&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"orgVdcStorageProfile", :href=>make_href('query?type=orgVdcStorageProfile&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"orgVdcStorageProfile", :href=>make_href('query?type=orgVdcStorageProfile&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"apiDefinition", :href=>make_href('query?type=apiDefinition&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"apiDefinition", :href=>make_href('query?type=apiDefinition&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"apiDefinition", :href=>make_href('query?type=apiDefinition&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"fileDescriptor", :href=>make_href('query?type=fileDescriptor&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"fileDescriptor", :href=>make_href('query?type=fileDescriptor&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"edgeGateway", :href=>make_href('query?type=edgeGateway&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"edgeGateway", :href=>make_href('query?type=edgeGateway&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"edgeGateway", :href=>make_href('query?type=edgeGateway&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"orgVdcNetwork", :href=>make_href('query?type=orgVdcNetwork&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"orgVdcNetwork", :href=>make_href('query?type=orgVdcNetwork&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"orgVdcNetwork", :href=>make_href('query?type=orgVdcNetwork&format=idrecords')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.references+xml", :name=>"vAppOrgVdcNetworkRelation", :href=>make_href('query?type=vAppOrgVdcNetworkRelation&format=references')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.records+xml", :name=>"vAppOrgVdcNetworkRelation", :href=>make_href('query?type=vAppOrgVdcNetworkRelation&format=records')}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :name=>"vAppOrgVdcNetworkRelation", :href=>make_href('query?type=vAppOrgVdcNetworkRelation&format=idrecords')} ] } end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_network_section_vapp.rb0000644000004100000410000000137012261242552030075 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the network section of a vApp. # # @param [String] id The object identifier of the vApp. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-NetworkSection-vApp.html # @since vCloud API version 0.9 def get_network_section_vapp(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/networkSection/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/put_media_metadata_item_metadata.rb0000644000004100000410000000353312261242552031463 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Set the value for the specified metadata key to the value provided, # overwriting any existing value. # # @param [String] id Object identifier of the media object. # @param [String] key Key of the metadata item. # @param [Boolean,DateTime,Fixnum,String] value Value of the metadata # item. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/PUT-MediaMetadataItem-metadata.html # @since vCloud API version 1.5 def put_media_metadata_item_metadata(id, key, value) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance' } MetadataValue(attrs) { if api_version.to_f < 5.1 Value value else type = case value when TrueClass, FalseClass then 'MetadataBooleanValue'; when DateTime then 'MetadataDateTimeValue'; when Fixnum then 'MetadataNumberValue'; else 'MetadataStringValue' end TypedValue('xsi:type' => type) { Value value } end } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.metadata.value+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "media/#{id}/metadata/#{URI.escape(key)}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vapps_in_lease_from_query.rb0000644000004100000410000001116412261242552031074 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves a list of vApps by using REST API general QueryHandler. # # @param [Hash] options # @option options [String] :sortAsc (Sorted by database ID) Sort # results by attribute-name in ascending order. attribute-name cannot # include metadata. # @option options [String] :sortDesc (Sorted by database ID) Sort # results by attribute-name in descending order. attribute-name # cannot include metadata. # @option options [Integer] :page (1) If the query results span # multiple pages, return this page. # @option options [Integer] :pageSize (25) Number of results per page, # to a maximum of 128. # @option options [String] :format (records) One of the following # types: # - *references* Returns a reference to each object, including its # :name, :type, and :href attributes. # - *records* Returns all database records for each object, with each # record as an attribute. # - *idrecords* Identical to the records format, except that object # references are returned in :id format rather than :href format. # @option options [Array] :fields (all static attribute names) # List of attribute names or metadata key names to return. # @option options [Integer] :offset (0) Integer value specifying the # first record to return. Record numbers < offset are not returned. # @option options [String] :filter (none) Filter expression. # @return [Excon::Response] # * hash<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :name<~String> - Query name that generated this result set. # * :page<~String> - Page of the result set that this container # holds. The first page is page number 1. # * :pageSize<~String> - Page size, as a number of records or # references. # * :total<~String> - Total number of records or references in the # container. # * :Link<~Array>: # * :href<~String> - Contains the URI to the entity. # * :type<~String> - Contains the type of the entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # * :VAppRecord<~Array>: # * TODO # * :firstPage<~Integer> - First page in the result set. # * :previousPage<~Integer> - Previous page in the result set. # * :nextPage<~Integer> - Next page in the result set. # * :lastPage<~Integer> - Last page in the result set. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VAppsInLeaseFromQuery.html # @since vCloud API version 1.5 def get_vapps_in_lease_from_query(options={}) query = [] query << "sortAsc=#{options[:sortAsc]}" if options[:sortAsc] query << "sortDesc=#{options[:sortDesc]}" if options[:sortDesc] query << "page=#{options[:page]}" if options[:page] query << "pageSize=#{options[:pageSize]}" if options[:pageSize] query << "format=#{options[:format]}" if options[:format] query << "fields=#{Array(options[:fields]).join(',')}" if options[:fields] query << "offset=#{options[:offset]}" if options[:offset] query << "filter=#{options[:filter]}" if options[:filter] response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'vApps/query', :query => query.map {|q| URI.escape(q)}.join('&') ) ensure_list! response.body, :Link ensure_list! response.body, response.body[:type] == 'application/vnd.vmware.vcloud.query.references+xml' ? :VAppReference : :VAppRecord %w[firstPage previousPage nextPage lastPage].each do |rel| if link = response.body[:Link].detect {|l| l[:rel] == rel} href = Nokogiri::XML.fragment(link[:href]) query = CGI.parse(URI.parse(href.text).query) response.body[rel.to_sym] = query['page'].first.to_i response.body[:pageSize] ||= query['pageSize'].first.to_i end end response end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_request.rb0000644000004100000410000000057012261242552025323 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # This is used for manual testing. # # @api private def get_request(uri) request( :expects => 200, :idempotent => true, :method => 'GET', :path => uri ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/put_vm_capabilities.rb0000644000004100000410000000306712261242552027023 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Update VM's capabilities. # # @param [String] id Object identifier of the VM. # @param [Hash] options # @option options [Boolean] :MemoryHotAddEnabled True if the virtual # machine supports addition of memory while powered on. # @option options [Boolean] :CpuHotAddEnabled True if the virtual # machine supports addition of virtual CPUs while powered on. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/PUT-VmCapabilities.html def put_vm_capabilities(id, options={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5' } VmCapabilities(attrs) { if options.key?(:MemoryHotAddEnabled) MemoryHotAddEnabled options[:MemoryHotAddEnabled] end if options.key?(:CpuHotAddEnabled) MemoryHotAddEnabled options[:CpuHotAddEnabled] end } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.vmCapabilitiesSection+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/vmCapabilities" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_snapshot_section.rb0000644000004100000410000000137512261242552027222 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve SnapshotSection element for a vApp or VM. # # @param [String] id Object identifier of the vApp or VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-SnapshotSection.html # @since vCloud API version 5.1 def get_snapshot_section(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/snapshotSection" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_current_session.rb0000644000004100000410000000631512261242552027063 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a representation of the current session. # # A Session object contains one or more URLs from which you can begin # browsing, as well as links to the query service and entity resolver. # The list of URLs in the Session object is based on the role and # privileges of the authenticated user. # # A Session object expires after a configurable interval of client # inactivity. # # @return [Excon::Response] # * body<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :org<~String> - The name of the user's organization. # * :user<~String> - The name of the user that owns the session # * :Link<~Array]: # * :href<~String> - Contains the URI to the linked entity. # * :name<~String> - Contains the name of the linked entity. # * :type<~String> - Contains the type of the linked entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-CurrentSession.html # @since vCloud API version 1.5 def get_current_session request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'session' ) end end class Mock def get_current_session body = {:href => make_href('session/'), :type => 'application/vnd.vmware.vcloud.session+xml', :org => data[:org][:name], :user => user_name, :Link => [{:href => make_href('org/'), :type => 'application/vnd.vmware.vcloud.orgList+xml', :rel => 'down'}, {:href => make_href('admin/'), :type => 'application/vnd.vmware.admin.vcloud+xml', :rel => 'down'}, {:href => make_href("org/#{data[:org][:uuid]}"), :name => data[:org][:name], :type => 'application/vnd.vmware.vcloud.org+xml', :rel => 'down'}, {:href => make_href('query'), :type => 'application/vnd.vmware.vcloud.query.queryList+xml', :rel => 'down'}, {:href => make_href('entity/'), :type => 'application/vnd.vmware.vcloud.entity+xml', :rel => 'entityResolver'}]} if @api_version.to_f >= 5.1 body[:Link] << { :href => make_href('extensibility'), :type => 'application/vnd.vmware.vcloud.apiextensibility+xml', :rel => 'down:extensibility' } end Excon::Response.new( :body => body, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :status => 200 ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vdc_storage_class_metadata_item_metadata.rb0000644000004100000410000000154512261242552034041 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve metadata associated with the vDC storage profile. # # @param [String] id Object identifier of the vDC storage profile. # @param [String] key Key of the metadata. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VdcStorageClassMetadataItem-metadata.html def get_vdc_storage_class_metadata_item_metadata(id, key) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vdcStorageProfile/#{id}/metadata/#{URI.escape(key)})" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_update_disk_metadata.rb0000644000004100000410000000354512261242552030202 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Merge the metadata provided in the request with existing metadata. # # @param [String] id Object identifier of the disk. # @param [Hash{String=>Boolean,DateTime,Fixnum,String}] metadata # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-UpdateDiskMetadata.html # @since vCloud API version 5.1 def post_update_disk_metadata(id, metadata={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance' } Metadata(attrs) { metadata.each do |key, value| MetadataEntry { Key key if api_version.to_f < 5.1 Value value else type = case value when TrueClass, FalseClass then 'MetadataBooleanValue'; when DateTime then 'MetadataDateTimeValue'; when Fixnum then 'MetadataNumberValue'; else 'MetadataStringValue' end TypedValue('xsi:type' => type) { Value value } end } end } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.metadata+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "disk/#{id}/metadata/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_entity.rb0000644000004100000410000000271512261242552025152 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Redirects to the URL of an entity with the given VCD ID. # # @param [String] id # @return [Excon:Response] # * body<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :id<~String> - The entity identifier, expressed in URN format. # The value of this attribute uniquely identifies the entity, # persists for the life of the entity, and is never reused. # * :name<~String> - The name of the entity. # * :Link<~Array]: # * :href<~String> - Contains the URI to the linked entity. # * :type<~String> - Contains the type of the linked entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-Entity.html # @since vCloud API version 1.5 def get_entity(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "entity/#{id}" ) ensure_list! response.body, :Link response end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/put_metadata_value.rb0000644000004100000410000000163312261242552026641 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # deprecated Use {#put_vapp_metadata_item_metadata} instead. def put_metadata_value(vm_id, metadata_key, metadata_value) Fog::Logger.deprecation("#{self} => ##{put_metadata_value} is deprecated, use ##{put_vapp_metadata_item_metadata} instead [light_black](#{caller.first})[/]") body=" #{metadata_value} " request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.metadata.value+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "vApp/#{vm_id}/metadata/#{URI.escape(metadata_key)}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/delete_vapp_template.rb0000644000004100000410000000147612261242552027165 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Delete a vApp template. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the vApp template. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/DELETE-VAppTemplate.html # @since vCloud API version 0.9 def delete_vapp_template(id) request( :expects => 202, :method => 'DELETE', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vms_by_metadata.rb0000644000004100000410000000110012261242552026760 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/parsers/compute/vms_by_metadata' # @see #get_vms_in_lease_by_query def get_vms_by_metadata(key,value) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Compute::VcloudDirector::VmsByMetadata.new, :path => "vms/query?format=records&filter=metadata:#{key}==STRING:#{value}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vm_customization.rb0000644000004100000410000000202012261242552027235 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/parsers/compute/vm_customization' # Retrieves the guest customization section of a VM. # # @deprecated Use {#get_guest_customization_system_section_vapp} # instead. # @todo Log deprecation warning. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-GuestCustomizationSystemSection-vApp.html # @since vCloud API version 1.0 def get_vm_customization(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Compute::VcloudDirector::VmCustomization.new, :path => "vApp/#{id}/guestCustomizationSection" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_network.rb0000644000004100000410000000366012261242552025327 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/parsers/compute/network' # Retrieve an organization network. # # @param [String] id Object identifier of the network. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-Network.html # @since vCloud API version 0.9 def get_network(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Compute::VcloudDirector::Network.new, :path => "network/#{id}" ) end end class Mock def get_network(id) unless network = data[:networks][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end body = {:name=>network[:name], :href=>make_href("network/#{id}"), :type=>"application/vnd.vmware.vcloud.orgNetwork+xml", :id=>id, :description=>nil, :is_inherited=>network[:IsInherited], :gateway=>network[:Gateway], :netmask=>network[:Netmask], :dns1=>network[:Dns1], :dns2=>network[:Dns2], :dns_suffix=>network[:DnsSuffix]} body[:ip_ranges] = network[:IpRanges].map do |ip_range| {:start_address=>ip_range[:StartAddress], :end_address=>ip_range[:EndAddress]} end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_capture_vapp.rb0000644000004100000410000000320112261242552026524 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Create a vApp template from a vApp. # # The response includes a Task element. You can monitor the task to to # track the creation of the vApp template. # # @param [String] vdc_id Object identifier of the vDC. # @param [String] name Name of the vApp template. # @param [String] source_id Object identifier of the vApp to capture. # @param [Hash] options # @option options [String] :Description Optional description. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-CaptureVApp.html # @since vCloud API version 0.9 def post_capture_vapp(vdc_id, name, source_id, options={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', :name => name } CaptureVAppParams(attrs) { if options.key?(:Description) Description options[:Description] end Source(:href => "#{end_point}vApp/#{source_id}") } end.to_xml request( :body => body, :expects => 201, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.captureVAppParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vdc/#{vdc_id}/action/captureVApp" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_deploy_vapp.rb0000644000004100000410000000411412261242552026361 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Deploy a vApp or VM. # # Deployment allocates all resources for the vApp and the virtual # machines it contains. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the vApp. # @param [Hash] options # @option options [Integer] :deploymentLeaseSeconds Lease in seconds # for deployment. A value of 0 is replaced by the organization # default deploymentLeaseSeconds value. # @option options [Boolean] :forceCustomization Used to specify whether # to force customization on deployment, if not set default value is # false. # @option options [Boolean] :powerOn Used to specify whether to power # on vApp on deployment, if not set default value is true. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-DeployVApp.html # @since vCloud API version 0.9 def post_deploy_vapp(id, options={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5' } attr[:deploymentLeaseSeconds] = options[:deploymentLeaseSeconds] if options.key?(:deploymentLeaseSeconds) attr[:forceCustomization] = options[:forceCustomization] if options.key?(:forceCustomization) attr[:powerOn] = options[:powerOn] if options.key?(:powerOn) DeployVAppParams(attrs) end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.deployVAppParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/action/deploy" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_power_off_vapp.rb0000644000004100000410000000225212261242552027054 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :post_vm_poweroff, :post_power_off_vapp # Power off a vApp or VM. # # If used on a vApp, powers off all VMs in the vApp. If used on a VM, # powers off the VM. This operation is available only for a vApp or VM # that is powered on. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the vApp or VM. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::BadRequest] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-PowerOffVApp.html # @since vCloud API version 0.9 def post_power_off_vapp(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/power/action/powerOff" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vapp_templates_from_query.rb0000644000004100000410000001124312261242552031126 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves a list of vAppTemplates using REST API general # QueryHandler. # # @param [Hash] options # @option options [String] :sortAsc (Sorted by database ID) Sort # results by attribute-name in ascending order. attribute-name cannot # include metadata. # @option options [String] :sortDesc (Sorted by database ID) Sort # results by attribute-name in descending order. attribute-name # cannot include metadata. # @option options [Integer] :page (1) If the query results span # multiple pages, return this page. # @option options [Integer] :pageSize (25) Number of results per page, # to a maximum of 128. # @option options [String] :format (records) One of the following # types: # - *references* Returns a reference to each object, including its # :name, :type, and :href attributes. # - *records* Returns all database records for each object, with each # record as an attribute. # - *idrecords* Identical to the records format, except that object # references are returned in :id format rather than :href format. # @option options [Array] :fields (all static attribute names) # List of attribute names or metadata key names to return. # @option options [Integer] :offset (0) Integer value specifying the # first record to return. Record numbers < offset are not returned. # @option options [String] :filter (none) Filter expression. # @return [Excon::Response] # * hash<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :name<~String> - Query name that generated this result set. # * :page<~String> - Page of the result set that this container # holds. The first page is page number 1. # * :pageSize<~String> - Page size, as a number of records or # references. # * :total<~String> - Total number of records or references in the # container. # * :Link<~Array>: # * :href<~String> - Contains the URI to the entity. # * :type<~String> - Contains the type of the entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # * :VAppTemplateRecord<~Array>: # * TODO # * :firstPage<~Integer> - First page in the result set. # * :previousPage<~Integer> - Previous page in the result set. # * :nextPage<~Integer> - Next page in the result set. # * :lastPage<~Integer> - Last page in the result set. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VAppTemplatesFromQuery.html # @since vCloud API version 1.5 def get_vapp_templates_from_query(options={}) query = [] query << "sortAsc=#{options[:sortAsc]}" if options[:sortAsc] query << "sortDesc=#{options[:sortDesc]}" if options[:sortDesc] query << "page=#{options[:page]}" if options[:page] query << "pageSize=#{options[:pageSize]}" if options[:pageSize] query << "format=#{options[:format]}" if options[:format] query << "fields=#{Array(options[:fields]).join(',')}" if options[:fields] query << "offset=#{options[:offset]}" if options[:offset] query << "filter=#{options[:filter]}" if options[:filter] response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'vAppTemplates/query', :query => query.map {|q| URI.escape(q)}.join('&') ) ensure_list! response.body, :Link ensure_list! response.body, response.body[:type] == 'application/vnd.vmware.vcloud.query.references+xml' ? :VAppTemplateReference : :VAppTemplateRecord %w[firstPage previousPage nextPage lastPage].each do |rel| if link = response.body[:Link].detect {|l| l[:rel] == rel} href = Nokogiri::XML.fragment(link[:href]) query = CGI.parse(URI.parse(href.text).query) response.body[rel.to_sym] = query['page'].first.to_i response.body[:pageSize] ||= query['pageSize'].first.to_i end end response end end end end end ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootfog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vapp_template_customization_system_section.rbfog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vapp_template_customization_system_section.r0000644000004100000410000000150312261242552034447 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves the customization section of a vApp template. # # @param [String] id Object identifier of the vApp template. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VAppTemplateCustomizationSystemSection.html # @since vCloud API version 1.0 def get_vapp_template_customization_system_section(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/customizationSection" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_users_from_query.rb0000644000004100000410000001124312261242552027243 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves a list of users for organization the org admin belongs to # by using REST API general QueryHandler. # # @param [Hash] options # @option options [String] :sortAsc (Sorted by database ID) Sort # results by attribute-name in ascending order. attribute-name cannot # include metadata. # @option options [String] :sortDesc (Sorted by database ID) Sort # results by attribute-name in descending order. attribute-name # cannot include metadata. # @option options [Integer] :page (1) If the query results span # multiple pages, return this page. # @option options [Integer] :pageSize (25) Number of results per page, # to a maximum of 128. # @option options [String] :format (records) One of the following # types: # - *references* Returns a reference to each object, including its # :name, :type, and :href attributes. # - *records* Returns all database records for each object, with each # record as an attribute. # - *idrecords* Identical to the records format, except that object # references are returned in :id format rather than :href format. # @option options [Array] :fields (all static attribute names) # List of attribute names or metadata key names to return. # @option options [Integer] :offset (0) Integer value specifying the # first record to return. Record numbers < offset are not returned. # @option options [String] :filter (none) Filter expression. # @return [Excon::Response] # * hash<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :name<~String> - Query name that generated this result set. # * :page<~String> - Page of the result set that this container # holds. The first page is page number 1. # * :pageSize<~String> - Page size, as a number of records or # references. # * :total<~String> - Total number of records or references in the # container. # * :Link<~Array>: # * :href<~String> - Contains the URI to the entity. # * :type<~String> - Contains the type of the entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # * :UserRecord<~Array>: # * TODO # * :firstPage<~Integer> - First page in the result set. # * :previousPage<~Integer> - Previous page in the result set. # * :nextPage<~Integer> - Next page in the result set. # * :lastPage<~Integer> - Last page in the result set. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-UsersFromQuery-query.html # @since vCloud API version 1.5 def get_users_from_query(options={}) query = [] query << "sortAsc=#{options[:sortAsc]}" if options[:sortAsc] query << "sortDesc=#{options[:sortDesc]}" if options[:sortDesc] query << "page=#{options[:page]}" if options[:page] query << "pageSize=#{options[:pageSize]}" if options[:pageSize] query << "format=#{options[:format]}" if options[:format] query << "fields=#{Array(options[:fields]).join(',')}" if options[:fields] query << "offset=#{options[:offset]}" if options[:offset] query << "filter=#{options[:filter]}" if options[:filter] response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'admin/users/query', :query => query.map {|q| URI.escape(q)}.join('&') ) ensure_list! response.body, :Link ensure_list! response.body, response.body[:type] == 'application/vnd.vmware.vcloud.query.references+xml' ? :UserReference : :UserRecord %w[firstPage previousPage nextPage lastPage].each do |rel| if link = response.body[:Link].detect {|l| l[:rel] == rel} href = Nokogiri::XML.fragment(link[:href]) query = CGI.parse(URI.parse(href.text).query) response.body[rel.to_sym] = query['page'].first.to_i response.body[:pageSize] ||= query['pageSize'].first.to_i end end response end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_upgrade_hw_version.rb0000644000004100000410000000167212261242552027737 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Upgrade the virtual hardware version of a VM to the highest supported # virtual hardware version of the vDC that contains it. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-UpgradeHwVersion.html # @since vCloud API version 5.1 def post_upgrade_hw_version(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/action/upgradeHardwareVersion" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vcloud.rb0000644000004100000410000000606212261242552025131 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve an administrative view of a cloud. # # The VCloud element provides access to cloud-wide namespace of objects # that an administrator can view and, in most cases, modify. # # @return [Excon:Response] # * body<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :name<~String> - The name of the entity. # * :Description<~String> - Optional description. # * :OrganizationReferences: # * :OrganizationReference<~Array>: # * :href<~String> - Contains the URI to the entity. # * :name<~String> - Contains the name of the entity. # * :type<~String> - Contains the type of the entity. # * :ProviderVdcReferences<~Hash>: # * :ProviderVdcReferences<~Array>: # * :RightReferences<~Hash>: # * :RightReferences<~Array>: # * :RoleReferences<~Hash>: # * :RoleReferences<~Array>: # * :Networks<~Hash>: # * :Network<~Array>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-Vcloud.html # @since vCloud API version 0.9 def get_vcloud response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'admin/' ) ensure_list! response.body, :OrganizationReferences, :OrganizationReference ensure_list! response.body, :ProviderVdcReferences, :ProviderVdcReference ensure_list! response.body, :RightReferences, :RightReference ensure_list! response.body, :RoleReferences, :RoleReference ensure_list! response.body, :Networks, :Network response end end class Mock def get_vcloud body = {:href=>make_href('admin/'), :type=>"application/vnd.vmware.admin.vcloud+xml", :name=>'VMware vCloud Director', :Description=>'5.1.2.1377223 Tue Oct 15 20:56:05 GMT 2013', :Tasks=>{:Task=>[]}, :OrganizationReferences=> {:OrganizationReference=> [{:type=>"application/vnd.vmware.admin.organization+xml", :name=>data[:org][:name], :href=>make_href("api/admin/org/#{data[:org][:uuid]}")}]}, :ProviderVdcReferences=>{:ProviderVdcReference=>[]}, :RightReferences=>{:RightReference=>[]}, :RoleReferences=>{:RoleReference=>[]}, :Networks=>{:Network=>[]}} Excon::Response.new( :body => body, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :status => 200 ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_update_vapp_metadata.rb0000644000004100000410000000355312261242552030215 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Merge the metadata provided in the request with existing metadata. # # @param [String] id Object identifier of the vApp or VM. # @param [Hash{String=>Boolean,DateTime,Fixnum,String}] metadata # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-UpdateVAppMetadata.html # @since vCloud API version 1.5 def post_update_vapp_metadata(id, metadata={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance' } Metadata(attrs) { metadata.each do |key, value| MetadataEntry { Key key if api_version.to_f < 5.1 Value value else type = case value when TrueClass, FalseClass then 'MetadataBooleanValue'; when DateTime then 'MetadataDateTimeValue'; when Fixnum then 'MetadataNumberValue'; else 'MetadataStringValue' end TypedValue('xsi:type' => type) { Value value } end } end } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.metadata+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/metadata/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_attach_disk.rb0000644000004100000410000000361512261242552026322 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Attach a disk to a VM. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @param [String] disk_id Object identifier of the disk. # @param [Hash] options # @option options [Integer] :BusNumber Bus number on which to place the # disk controller. If empty or missing, the system assigns a bus # number and a unit number on that bus. # @option options [Integer] :BusNumber Unit number (slot) on the bus # specified by :BusNumber. Ignored if :BusNumber is empty or missing. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-AttachDisk.html # @since vCloud API version 5.1 def post_attach_disk(id, disk_id, options={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5' } DiskAttachOrDetachParams(attrs) { Disk(:href => "#{end_point}disk/#{disk_id}") if options.key?(:BusNumber) BusNumber options[:BusNumber] end if options.key?(:UnitNumber) BusNumber options[:UnitNumber] end } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.diskAttachOrDetachParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/disk/action/attach" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_startup_section.rb0000644000004100000410000000135112261242552027057 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the startup section of a vApp. # # @param [String] id Object identifier of the vApp. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-StartupSection.html # @since vCloud API version 0.9 def get_startup_section(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/startupSection" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_network_metadata_item_metadata.rb0000644000004100000410000000155712261242552032050 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the value of the specified key from network metadata. # # @param [String] id Object identifier of the network. # @param [String] key Key of the metadata. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-NetworkMetadataItem-metadata.html # @since vCloud API version 1.5 def get_network_metadata_item_metadata(id, key) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "admin/network/#{id}/metadata/#{URI.escape(key)})" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_network_config_section_vapp_template.rb0000644000004100000410000000147512261242552033323 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the network config section of a vApp template. # # @param [String] id The object identifier of the vApp template. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-NetworkConfigSection-vAppTemplate.html # @since vCloud API version 0.9 def get_network_config_section_vapp_template(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/networkConfigSection/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_disk_metadata.rb0000644000004100000410000000134312261242552026424 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve metadata associated with the disk. # # @param [String] id Object identifier of the disk. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-DiskMetadata.html # @since vCloud API version 5.1 def get_disk_metadata(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "disk/#{id}/metadata" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vapp_metadata_item_metadata.rb0000644000004100000410000000154612261242552031323 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the value of the specified key from vApp or VM metadata. # # @param [String] id Object identifier of the vApp or VM. # @param [String] key Key of the metadata. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VAppMetadataItem-metadata.html # @since vCloud API version 1.5 def get_vapp_metadata_item_metadata(id, key) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/metadata/#{URI.escape(key)})" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_network_cards_items_list.rb0000644000004100000410000000145212261242552030734 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve all RASD items that specify network card properties of a VM. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-NetworkCardsItemsList.html # @since vCloud API version 0.9 def get_network_cards_items_list(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/virtualHardwareSection/networkCards" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vm_pending_question.rb0000644000004100000410000000226412261242552027712 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a question being asked by a VM. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :Question<~String> - Question text. # * :QuestionId<~String> - Question ID of this question. # * Choices<~Array>: # * Id<~String> - Choice ID of the answer. # * Text<~String> - Answer text. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VmPendingQuestion.html # @since vCloud API version 0.9 def get_vm_pending_question(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/question" ) ensure_list! response.body, :Choices response end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vdcs_from_query.rb0000644000004100000410000001114112261242552027036 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves a list of vdcs in the organization. # # @param [Hash] options # @option options [String] :sortAsc (Sorted by database ID) Sort # results by attribute-name in ascending order. attribute-name cannot # include metadata. # @option options [String] :sortDesc (Sorted by database ID) Sort # results by attribute-name in descending order. attribute-name # cannot include metadata. # @option options [Integer] :page (1) If the query results span # multiple pages, return this page. # @option options [Integer] :pageSize (25) Number of results per page, # to a maximum of 128. # @option options [String] :format (records) One of the following # types: # - *references* Returns a reference to each object, including its # :name, :type, and :href attributes. # - *records* Returns all database records for each object, with each # record as an attribute. # - *idrecords* Identical to the records format, except that object # references are returned in :id format rather than :href format. # @option options [Array] :fields (all static attribute names) # List of attribute names or metadata key names to return. # @option options [Integer] :offset (0) Integer value specifying the # first record to return. Record numbers < offset are not returned. # @option options [String] :filter (none) Filter expression. # @return [Excon::Response] # * hash<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :name<~String> - Query name that generated this result set. # * :page<~String> - Page of the result set that this container # holds. The first page is page number 1. # * :pageSize<~String> - Page size, as a number of records or # references. # * :total<~String> - Total number of records or references in the # container. # * :Link<~Array>: # * :href<~String> - Contains the URI to the entity. # * :type<~String> - Contains the type of the entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # * :OrgVdcRecord<~Array>: # * TODO # * :firstPage<~Integer> - First page in the result set. # * :previousPage<~Integer> - Previous page in the result set. # * :nextPage<~Integer> - Next page in the result set. # * :lastPage<~Integer> - Last page in the result set. # # @see http://pubs.vmware.com/vcd-55/topic/com.vmware.vcloud.api.reference.doc_55/doc/operations/GET-RightsFromQuery-query.html # @since vCloud API version 1.5 def get_vdcs_from_query(options={}) query = [] query << "sortAsc=#{options[:sortAsc]}" if options[:sortAsc] query << "sortDesc=#{options[:sortDesc]}" if options[:sortDesc] query << "page=#{options[:page]}" if options[:page] query << "pageSize=#{options[:pageSize]}" if options[:pageSize] query << "format=#{options[:format]}" if options[:format] query << "fields=#{Array(options[:fields]).join(',')}" if options[:fields] query << "offset=#{options[:offset]}" if options[:offset] query << "filter=#{options[:filter]}" if options[:filter] response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'admin/vdcs/query', :query => query.map {|q| URI.escape(q)}.join('&') ) ensure_list! response.body, :Link ensure_list! response.body, response.body[:type] == 'application/vnd.vmware.vcloud.query.references+xml' ? :OrgVdcReference : :OrgVdcRecord %w[firstPage previousPage nextPage lastPage].each do |rel| if link = response.body[:Link].detect {|l| l[:rel] == rel} href = Nokogiri::XML.fragment(link[:href]) query = CGI.parse(URI.parse(href.text).query) response.body[rel.to_sym] = query['page'].first.to_i response.body[:pageSize] ||= query['pageSize'].first.to_i end end response end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/delete_disk.rb0000644000004100000410000000333712261242552025254 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Delete a disk. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the disk. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/DELETE-Disk.html # @since vCloud API version 5.1 def delete_disk(id) request( :expects => 202, :method => 'DELETE', :parser => Fog::ToHashDocument.new, :path => "disk/#{id}" ) end end class Mock def delete_disk(id) unless data[:disks][id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.disk:#{id})\"" ) end owner = { :href => make_href("disk/#{id}"), :type => 'application/vnd.vmware.vcloud.disk+xml' } task_id = enqueue_task( "Deleting Disk(#{id})", 'vdcDeleteDisk', owner, :on_success => lambda do data[:disks].delete(id) end ) body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location, }.merge(task_body(task_id)) Excon::Response.new( :status => 202, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_enable_nested_hv.rb0000644000004100000410000000155112261242552027326 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Expose hardware-assisted CPU virtualization to guest OS. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-EnableNestedHv.html # @since vCloud API version 5.1 def post_enable_nested_hv(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/action/enableNestedHypervisor" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vm_capabilities.rb0000644000004100000410000000211512261242552026763 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Gets capabilities for the VM identified by id. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :MemoryHotAddEnabled<~String> - True if the virtual machine # supports addition of memory while powered on. # * :CpuHotAddEnabled<~String> - True if the virtual machine # supports addition of virtual CPUs while powered on. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VmCapabilities.html def get_vm_capabilities(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/vmCapabilities" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_catalogs_from_query.rb0000644000004100000410000001117012261242552027676 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves a list of Catalogs by using REST API general QueryHandler. # # @param [Hash] options # @option options [String] :sortAsc (Sorted by database ID) Sort # results by attribute-name in ascending order. attribute-name cannot # include metadata. # @option options [String] :sortDesc (Sorted by database ID) Sort # results by attribute-name in descending order. attribute-name # cannot include metadata. # @option options [Integer] :page (1) If the query results span # multiple pages, return this page. # @option options [Integer] :pageSize (25) Number of results per page, # to a maximum of 128. # @option options [String] :format (records) One of the following # types: # - *references* Returns a reference to each object, including its # :name, :type, and :href attributes. # - *records* Returns all database records for each object, with each # record as an attribute. # - *idrecords* Identical to the records format, except that object # references are returned in :id format rather than :href format. # @option options [Array] :fields (all static attribute names) # List of attribute names or metadata key names to return. # @option options [Integer] :offset (0) Integer value specifying the # first record to return. Record numbers < offset are not returned. # @option options [String] :filter (none) Filter expression. # @return [Excon::Response] # * hash<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :name<~String> - Query name that generated this result set. # * :page<~String> - Page of the result set that this container # holds. The first page is page number 1. # * :pageSize<~String> - Page size, as a number of records or # references. # * :total<~String> - Total number of records or references in the # container. # * :Link<~Array>: # * :href<~String> - Contains the URI to the entity. # * :type<~String> - Contains the type of the entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # * :CatalogRecord<~Array>: # * TODO # * :firstPage<~Integer> - First page in the result set. # * :previousPage<~Integer> - Previous page in the result set. # * :nextPage<~Integer> - Next page in the result set. # * :lastPage<~Integer> - Last page in the result set. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-CatalogsFromQuery.html # @since vCloud API version 1.5 def get_catalogs_from_query(options={}) query = [] query << "sortAsc=#{options[:sortAsc]}" if options[:sortAsc] query << "sortDesc=#{options[:sortDesc]}" if options[:sortDesc] query << "page=#{options[:page]}" if options[:page] query << "pageSize=#{options[:pageSize]}" if options[:pageSize] query << "format=#{options[:format]}" if options[:format] query << "fields=#{Array(options[:fields]).join(',')}" if options[:fields] query << "offset=#{options[:offset]}" if options[:offset] query << "filter=#{options[:filter]}" if options[:filter] response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'catalogs/query', :query => query.map {|q| URI.escape(q)}.join('&') ) ensure_list! response.body, :Link ensure_list! response.body, response.body[:type] == 'application/vnd.vmware.vcloud.query.references+xml' ? :CatalogReference : :CatalogRecord %w[firstPage previousPage nextPage lastPage].each do |rel| if link = response.body[:Link].detect {|l| l[:rel] == rel} href = Nokogiri::XML.fragment(link[:href]) query = CGI.parse(URI.parse(href.text).query) response.body[rel.to_sym] = query['page'].first.to_i response.body[:pageSize] ||= query['pageSize'].first.to_i end end response end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_login_session.rb0000644000004100000410000000302112261242552026706 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Log in and create a Session object. # # @return [Excon::Response] # * body<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :org<~String> - The name of the user's organization. # * :user<~String> - The name of the user that owns the session # * :Link<~Array]: # * :href<~String> - Contains the URI to the linked entity. # * :name<~String> - Contains the name of the linked entity. # * :type<~String> - Contains the type of the linked entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-Login-sessions.html # @since vCloud API version 1.5 def post_login_session headers = { 'Accept' => "application/*+xml;version=#{@api_version}", 'Authorization' => "Basic #{Base64.encode64("#{@vcloud_director_username}:#{@vcloud_director_password}").delete("\r\n")}" } @connection.request( :expects => 200, :headers => headers, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "#{@path}/sessions" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_supported_versions.rb0000644000004100000410000021240412261242552027611 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # List all supported versions. # # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-55/topic/com.vmware.vcloud.api.reference.doc_55/doc/operations/GET-SupportedVersions.html # @since vCloud API version 0.9 def get_supported_versions @connection.request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "#{@path}/versions" ) end end class Mock def get_supported_versions body = {:xmlns=>"http://www.vmware.com/vcloud/versions", :xmlns_xsi=>xmlns_xsi, :xsi_schemaLocation=>xsi_schema_location, :VersionInfo=> [{:Version=>"1.5", :LoginUrl=>make_href("sessions"), :MediaTypeMapping=> [{:MediaType=> "application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml", :ComplexTypeName=>"InstantiateVAppTemplateParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwProviderVdcReferences+xml", :ComplexTypeName=>"VMWProviderVdcReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.customizationSection+xml", :ComplexTypeName=>"CustomizationSectionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.prepareHostParams+xml", :ComplexTypeName=>"PrepareHostParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.relocateVmParams+xml", :ComplexTypeName=>"RelocateParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.org+xml", :ComplexTypeName=>"OrgType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.vmwExternalNetworkReferences+xml", :ComplexTypeName=>"VMWExternalNetworkReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.vcloud.networkConnectionSection+xml", :ComplexTypeName=>"NetworkConnectionSectionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.host+xml", :ComplexTypeName=>"HostType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.catalogItem+xml", :ComplexTypeName=>"CatalogItemType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.owner+xml", :ComplexTypeName=>"OwnerType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vdc+xml", :ComplexTypeName=>"VdcType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vdc+xml", :ComplexTypeName=>"AdminVdcType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.catalog+xml", :ComplexTypeName=>"AdminCatalogType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.recomposeVAppParams+xml", :ComplexTypeName=>"RecomposeVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.importVmIntoExistingVAppParams+xml", :ComplexTypeName=>"ImportVmIntoExistingVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.admin.taskExtensionRequestUpdateProgressOperationParams+xml", :ComplexTypeName=>"TaskExtensionRequestUpdateProgressParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.catalog+xml", :ComplexTypeName=>"CatalogType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.cloneVAppTemplateParams+xml", :ComplexTypeName=>"CloneVAppTemplateParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.providervdc+xml", :ComplexTypeName=>"ProviderVdcType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmsObjectRefsList+xml", :ComplexTypeName=>"VmObjectRefsListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.undeployVAppParams+xml", :ComplexTypeName=>"UndeployVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vdcReferences+xml", :ComplexTypeName=>"VdcReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.systemPasswordPolicySettings+xml", :ComplexTypeName=>"SystemPasswordPolicySettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vApp+xml", :ComplexTypeName=>"VAppType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.taskExtensionRequest+xml", :ComplexTypeName=>"TaskExtensionRequestType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vimServerNetworks+xml", :ComplexTypeName=>"VimObjectRefListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwprovidervdc+xml", :ComplexTypeName=>"VMWProviderVdcType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.orgSettings+xml", :ComplexTypeName=>"OrgSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.captureVAppParams+xml", :ComplexTypeName=>"CaptureVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.screenTicket+xml", :ComplexTypeName=>"ScreenTicketType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.runtimeInfoSection+xml", :ComplexTypeName=>"RuntimeInfoSectionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.tasksList+xml", :ComplexTypeName=>"TasksListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.amqpSettingsTest+xml", :ComplexTypeName=>"AmqpSettingsTestType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.extensionSettings+xml", :ComplexTypeName=>"TaskExtensionSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.admin.importVmAsVAppTemplateParams+xml", :ComplexTypeName=>"ImportVmAsVAppTemplateParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.admin.organizationGeneralSettings+xml", :ComplexTypeName=>"OrgGeneralSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.registerVimServerParams+xml", :ComplexTypeName=>"RegisterVimServerParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.network+xml", :ComplexTypeName=>"OrgNetworkType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.vcloud.uploadVAppTemplateParams+xml", :ComplexTypeName=>"UploadVAppTemplateParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.datastore+xml", :ComplexTypeName=>"DatastoreType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.metadata+xml", :ComplexTypeName=>"MetadataType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.licensingReportList+xml", :ComplexTypeName=>"LicensingReportListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwNetworkPool+xml", :ComplexTypeName=>"VMWNetworkPoolType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.systemSettings+xml", :ComplexTypeName=>"SystemSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwHostReferences+xml", :ComplexTypeName=>"VMWHostReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.admin.taskExtensionRequestOperationParams+xml", :ComplexTypeName=>"TaskExtensionRequestOperationParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.metadata.value+xml", :ComplexTypeName=>"MetadataValueType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.taskOperationList+xml", :ComplexTypeName=>"TaskOperationListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.media+xml", :ComplexTypeName=>"MediaType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.productSections+xml", :ComplexTypeName=>"ProductSectionListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.amqpSettings+xml", :ComplexTypeName=>"AmqpSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vAppTemplate+xml", :ComplexTypeName=>"VAppTemplateType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.deployVAppParams+xml", :ComplexTypeName=>"DeployVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.importVmIntoExistingVAppTemplateParams+xml", :ComplexTypeName=>"ImportVmIntoExistingVAppTemplateParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.resourcePoolList+xml", :ComplexTypeName=>"ResourcePoolListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.networkConfigSection+xml", :ComplexTypeName=>"NetworkConfigSectionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.OrganizationVdcResourcePoolSet+xml", :ComplexTypeName=>"OrganizationResourcePoolSetType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.admin.organizationPasswordPolicySettings+xml", :ComplexTypeName=>"OrgPasswordPolicySettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.publishCatalogParams+xml", :ComplexTypeName=>"PublishCatalogParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwExtension+xml", :ComplexTypeName=>"VMWExtensionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.vcloud.mediaInsertOrEjectParams+xml", :ComplexTypeName=>"MediaInsertOrEjectParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vmPendingQuestion+xml", :ComplexTypeName=>"VmPendingQuestionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.notificationsSettings+xml", :ComplexTypeName=>"NotificationsSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.ldapUserSettings+xml", :ComplexTypeName=>"LdapUserAttributesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.right+xml", :ComplexTypeName=>"RightType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.ldapSettings+xml", :ComplexTypeName=>"LdapSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.organization+xml", :ComplexTypeName=>"AdminOrgType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.orgList+xml", :ComplexTypeName=>"OrgListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.vAppTemplateLeaseSettings+xml", :ComplexTypeName=>"OrgVAppTemplateLeaseSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwVimServerReferences+xml", :ComplexTypeName=>"VMWVimServerReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwexternalnet+xml", :ComplexTypeName=>"VMWExternalNetworkType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.entity+xml", :ComplexTypeName=>"EntityType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.cloneMediaParams+xml", :ComplexTypeName=>"CloneMediaParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.licensingReport+xml", :ComplexTypeName=>"LicensingReportType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.importMediaParams+xml", :ComplexTypeName=>"ImportMediaParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.admin.resourcePoolSetUpdateParams+xml", :ComplexTypeName=>"UpdateResourcePoolSetParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.taskExtensionRequestList+xml", :ComplexTypeName=>"ReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vmPendingAnswer+xml", :ComplexTypeName=>"VmQuestionAnswerType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.rasdItemsList+xml", :ComplexTypeName=>"RasdItemsListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.generalSettings+xml", :ComplexTypeName=>"GeneralSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwNetworkPoolReferences+xml", :ComplexTypeName=>"VMWNetworkPoolReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.group+xml", :ComplexTypeName=>"GroupType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.controlAccess+xml", :ComplexTypeName=>"ControlAccessParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.ldapGroupSettings+xml", :ComplexTypeName=>"LdapGroupAttributesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.user+xml", :ComplexTypeName=>"UserType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vcloud+xml", :ComplexTypeName=>"VCloudType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.uberAdminSettings+xml", :ComplexTypeName=>"UberAdminSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwvirtualcenter+xml", :ComplexTypeName=>"VimServerType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.leaseSettingsSection+xml", :ComplexTypeName=>"LeaseSettingsSectionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.composeVAppParams+xml", :ComplexTypeName=>"ComposeVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.organizationEmailSettings+xml", :ComplexTypeName=>"OrgEmailSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vm+xml", :ComplexTypeName=>"VmType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.vmwProviderVdcResourcePoolSet+xml", :ComplexTypeName=>"VMWProviderVdcResourcePoolSetType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.cloneVAppParams+xml", :ComplexTypeName=>"CloneVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.vcloud.guestCustomizationSection+xml", :ComplexTypeName=>"GuestCustomizationSectionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.task+xml", :ComplexTypeName=>"TaskType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.session+xml", :ComplexTypeName=>"SessionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vAppLeaseSettings+xml", :ComplexTypeName=>"OrgLeaseSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.importVmAsVAppParams+xml", :ComplexTypeName=>"ImportVmAsVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.role+xml", :ComplexTypeName=>"RoleType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.rasdItem+xml", :ComplexTypeName=>"RASD_Type", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.startupSection+xml", :ComplexTypeName=>"StartupSection_Type", :SchemaLocation=> "http://schemas.dmtf.org/ovf/envelope/1/dsp8023_1.1.0.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.virtualHardwareSection+xml", :ComplexTypeName=>"VirtualHardwareSection_Type", :SchemaLocation=> "http://schemas.dmtf.org/ovf/envelope/1/dsp8023_1.1.0.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.operatingSystemSection+xml", :ComplexTypeName=>"OperatingSystemSection_Type", :SchemaLocation=> "http://schemas.dmtf.org/ovf/envelope/1/dsp8023_1.1.0.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.networkSection+xml", :ComplexTypeName=>"NetworkSection_Type", :SchemaLocation=> "http://schemas.dmtf.org/ovf/envelope/1/dsp8023_1.1.0.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vAppNetwork+xml", :ComplexTypeName=>"VAppNetworkType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.network+xml", :ComplexTypeName=>"NetworkType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.orgNetwork+xml", :ComplexTypeName=>"OrgNetworkType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwexternalnet+xml", :ComplexTypeName=>"VMWExternalNetworkType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}]}, {:Version=>"5.1", :LoginUrl=>make_href("sessions"), :MediaTypeMapping=> [{:MediaType=> "application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml", :ComplexTypeName=>"InstantiateVAppTemplateParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwprovidervdc+xml", :ComplexTypeName=>"MergeParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.admin.organizationFederationSettings+xml", :ComplexTypeName=>"OrgFederationSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.emailSettings+xml", :ComplexTypeName=>"EmailSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.prepareHostParams+xml", :ComplexTypeName=>"PrepareHostParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.org+xml", :ComplexTypeName=>"OrgType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.aclRule+xml", :ComplexTypeName=>"AclRuleType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.organizationLdapSettings+xml", :ComplexTypeName=>"OrgLdapSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.vcloud.networkConnectionSection+xml", :ComplexTypeName=>"NetworkConnectionSectionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.owner+xml", :ComplexTypeName=>"OwnerType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vdc+xml", :ComplexTypeName=>"AdminVdcType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.importVmIntoExistingVAppParams+xml", :ComplexTypeName=>"ImportVmIntoExistingVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.catalog+xml", :ComplexTypeName=>"CatalogType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.cloneVAppTemplateParams+xml", :ComplexTypeName=>"CloneVAppTemplateParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.createVdcParams+xml", :ComplexTypeName=>"CreateVdcParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmsObjectRefsList+xml", :ComplexTypeName=>"VmObjectRefsListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.undeployVAppParams+xml", :ComplexTypeName=>"UndeployVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.createSnapshotParams+xml", :ComplexTypeName=>"CreateSnapshotParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.blockingTask+xml", :ComplexTypeName=>"BlockingTaskType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwPvdcStorageProfile+xml", :ComplexTypeName=>"VMWProviderVdcStorageProfileType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.allocatedNetworkAddress+xml", :ComplexTypeName=>"AllocatedIpAddressesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vimServerNetworks+xml", :ComplexTypeName=>"VimObjectRefListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.admin.blockingTaskOperationParams+xml", :ComplexTypeName=>"BlockingTaskOperationParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.admin.updateProviderVdcStorageProfiles+xml", :ComplexTypeName=>"UpdateProviderVdcStorageProfilesParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.bundleUploadSocket+xml", :ComplexTypeName=>"BundleUploadSocketType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.gateway+xml", :ComplexTypeName=>"GatewayType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.screenTicket+xml", :ComplexTypeName=>"ScreenTicketType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.resourceClassAction+xml", :ComplexTypeName=>"ResourceClassActionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.event+xml", :ComplexTypeName=>"EventType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.tasksList+xml", :ComplexTypeName=>"TasksListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.migrateVmParams+xml", :ComplexTypeName=>"MigrateParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.diskCreateParams+xml", :ComplexTypeName=>"DiskCreateParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.registerVAppParams+xml", :ComplexTypeName=>"RegisterVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.organizationGeneralSettings+xml", :ComplexTypeName=>"OrgGeneralSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.registerVimServerParams+xml", :ComplexTypeName=>"RegisterVimServerParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.datastore+xml", :ComplexTypeName=>"DatastoreType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.vcloud.diskAttachOrDetachParams+xml", :ComplexTypeName=>"DiskAttachOrDetachParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.updateRightsParams+xml", :ComplexTypeName=>"UpdateRightsParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.metadata+xml", :ComplexTypeName=>"MetadataType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vdcStorageProfile+xml", :ComplexTypeName=>"AdminVdcStorageProfileType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.systemSettings+xml", :ComplexTypeName=>"SystemSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwHostReferences+xml", :ComplexTypeName=>"VMWHostReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.userEntityRights+xml", :ComplexTypeName=>"UserEntityRightsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.metadata.value+xml", :ComplexTypeName=>"MetadataValueType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.media+xml", :ComplexTypeName=>"MediaType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.brandingSettings+xml", :ComplexTypeName=>"BrandingSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.updateVdcStorageProfiles+xml", :ComplexTypeName=>"UpdateVdcStorageProfilesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.amqpSettings+xml", :ComplexTypeName=>"AmqpSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.resourceClass+xml", :ComplexTypeName=>"ResourceClassType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.deployVAppParams+xml", :ComplexTypeName=>"DeployVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.resourcePoolList+xml", :ComplexTypeName=>"ResourcePoolListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vdcStorageProfile+xml", :ComplexTypeName=>"VdcStorageProfileType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.networkConfigSection+xml", :ComplexTypeName=>"NetworkConfigSectionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.OrganizationVdcResourcePoolSet+xml", :ComplexTypeName=>"OrganizationResourcePoolSetType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.createProviderVdcParams+xml", :ComplexTypeName=>"VMWProviderVdcParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.publishCatalogParams+xml", :ComplexTypeName=>"PublishCatalogParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwExtension+xml", :ComplexTypeName=>"VMWExtensionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.notificationsSettings+xml", :ComplexTypeName=>"NotificationsSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.right+xml", :ComplexTypeName=>"RightType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.supportedSystemsInfo+xml", :ComplexTypeName=>"SupportedOperatingSystemsInfoType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vm.complianceResult+xml", :ComplexTypeName=>"ComplianceResultType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.orgList+xml", :ComplexTypeName=>"OrgListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwVimServerReferences+xml", :ComplexTypeName=>"VMWVimServerReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwexternalnet+xml", :ComplexTypeName=>"VMWExternalNetworkType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.entity+xml", :ComplexTypeName=>"EntityType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.cloneMediaParams+xml", :ComplexTypeName=>"CloneMediaParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.licensingReport+xml", :ComplexTypeName=>"LicensingReportType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.apiDefinition+xml", :ComplexTypeName=>"ApiDefinitionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vshieldmanager+xml", :ComplexTypeName=>"ShieldManagerType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.blockingTaskList+xml", :ComplexTypeName=>"ReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vmPendingAnswer+xml", :ComplexTypeName=>"VmQuestionAnswerType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.rasdItemsList+xml", :ComplexTypeName=>"RasdItemsListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.generalSettings+xml", :ComplexTypeName=>"GeneralSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.group+xml", :ComplexTypeName=>"GroupType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.controlAccess+xml", :ComplexTypeName=>"ControlAccessParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.user+xml", :ComplexTypeName=>"UserType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwvirtualcenter+xml", :ComplexTypeName=>"VimServerType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.strandedItem+xml", :ComplexTypeName=>"StrandedItemType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.leaseSettingsSection+xml", :ComplexTypeName=>"LeaseSettingsSectionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.organizationEmailSettings+xml", :ComplexTypeName=>"OrgEmailSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.cloneVAppParams+xml", :ComplexTypeName=>"CloneVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.task+xml", :ComplexTypeName=>"TaskType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vAppLeaseSettings+xml", :ComplexTypeName=>"OrgLeaseSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.role+xml", :ComplexTypeName=>"RoleType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwProviderVdcReferences+xml", :ComplexTypeName=>"VMWProviderVdcReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.customizationSection+xml", :ComplexTypeName=>"CustomizationSectionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.service+xml", :ComplexTypeName=>"ServiceType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.relocateVmParams+xml", :ComplexTypeName=>"RelocateParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.rights+xml", :ComplexTypeName=>"RightRefsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.admin.vmwExternalNetworkReferences+xml", :ComplexTypeName=>"VMWExternalNetworkReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.disk+xml", :ComplexTypeName=>"DiskType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.kerberosSettings+xml", :ComplexTypeName=>"KerberosSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.operationLimitsSettings+xml", :ComplexTypeName=>"OrgOperationLimitsSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.host+xml", :ComplexTypeName=>"HostType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.catalogItem+xml", :ComplexTypeName=>"CatalogItemType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.entityReferences+xml", :ComplexTypeName=>"EntityReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vdc+xml", :ComplexTypeName=>"VdcType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.catalog+xml", :ComplexTypeName=>"AdminCatalogType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.recomposeVAppParams+xml", :ComplexTypeName=>"RecomposeVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.orgVdcNetwork+xml", :ComplexTypeName=>"OrgVdcNetworkType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.providervdc+xml", :ComplexTypeName=>"ProviderVdcType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.blockingTaskUpdateProgressOperationParams+xml", :ComplexTypeName=>"BlockingTaskUpdateProgressParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vdcReferences+xml", :ComplexTypeName=>"VdcReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.systemPasswordPolicySettings+xml", :ComplexTypeName=>"SystemPasswordPolicySettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vApp+xml", :ComplexTypeName=>"VAppType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwprovidervdc+xml", :ComplexTypeName=>"VMWProviderVdcType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vms+xml", :ComplexTypeName=>"VmsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.orgSettings+xml", :ComplexTypeName=>"OrgSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.apiFilter+xml", :ComplexTypeName=>"ApiFilterType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.captureVAppParams+xml", :ComplexTypeName=>"CaptureVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vmCapabilitiesSection+xml", :ComplexTypeName=>"VmCapabilitiesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.runtimeInfoSection+xml", :ComplexTypeName=>"RuntimeInfoSectionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.amqpSettingsTest+xml", :ComplexTypeName=>"AmqpSettingsTestType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.admin.importVmAsVAppTemplateParams+xml", :ComplexTypeName=>"ImportVmAsVAppTemplateParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.admin.guestPersonalizationSettings+xml", :ComplexTypeName=>"OrgGuestPersonalizationSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.orgNetwork+xml", :ComplexTypeName=>"OrgNetworkType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.fileDescriptor+xml", :ComplexTypeName=>"FileDescriptorType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.vcloud.uploadVAppTemplateParams+xml", :ComplexTypeName=>"UploadVAppTemplateParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.licensingReportList+xml", :ComplexTypeName=>"LicensingReportListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwNetworkPool+xml", :ComplexTypeName=>"VMWNetworkPoolType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.taskOperationList+xml", :ComplexTypeName=>"TaskOperationListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vSphereWebClientUrl+xml", :ComplexTypeName=>"VSphereWebClientUrlType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.productSections+xml", :ComplexTypeName=>"ProductSectionListType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.blockingTaskSettings+xml", :ComplexTypeName=>"BlockingTaskSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vAppTemplate+xml", :ComplexTypeName=>"VAppTemplateType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.organizationPasswordPolicySettings+xml", :ComplexTypeName=>"OrgPasswordPolicySettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.vcloud.mediaInsertOrEjectParams+xml", :ComplexTypeName=>"MediaInsertOrEjectParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vmPendingQuestion+xml", :ComplexTypeName=>"VmPendingQuestionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.organization+xml", :ComplexTypeName=>"AdminOrgType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.ldapSettings+xml", :ComplexTypeName=>"LdapSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.snapshotSection+xml", :ComplexTypeName=>"SnapshotSectionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.vAppTemplateLeaseSettings+xml", :ComplexTypeName=>"OrgVAppTemplateLeaseSettingsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.importMediaParams+xml", :ComplexTypeName=>"ImportMediaParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=> "application/vnd.vmware.admin.resourcePoolSetUpdateParams+xml", :ComplexTypeName=>"UpdateResourcePoolSetParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.licenseSettings+xml", :ComplexTypeName=>"LicenseType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.bundleUploadParams+xml", :ComplexTypeName=>"BundleUploadParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwNetworkPoolReferences+xml", :ComplexTypeName=>"VMWNetworkPoolReferencesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vcloud+xml", :ComplexTypeName=>"VCloudType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.serviceResource+xml", :ComplexTypeName=>"ServiceResourceType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.composeVAppParams+xml", :ComplexTypeName=>"ComposeVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.admin.vmwProviderVdcResourcePool+xml", :ComplexTypeName=>"VMWProviderVdcResourcePoolSetType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vm+xml", :ComplexTypeName=>"VmType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=> "application/vnd.vmware.vcloud.guestCustomizationSection+xml", :ComplexTypeName=>"GuestCustomizationSectionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.session+xml", :ComplexTypeName=>"SessionType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.pvdcStorageProfile+xml", :ComplexTypeName=>"ProviderVdcStorageProfileType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwStorageProfiles+xml", :ComplexTypeName=>"VMWStorageProfilesType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.importVmAsVAppParams+xml", :ComplexTypeName=>"ImportVmAsVAppParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.admin.serviceLink+xml", :ComplexTypeName=>"ServiceLinkType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.enableDownloadParams+xml", :ComplexTypeName=>"EnableDownloadParamsType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.rasdItem+xml", :ComplexTypeName=>"RASD_Type", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.startupSection+xml", :ComplexTypeName=>"StartupSection_Type", :SchemaLocation=> "http://schemas.dmtf.org/ovf/envelope/1/dsp8023_1.1.0.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.virtualHardwareSection+xml", :ComplexTypeName=>"VirtualHardwareSection_Type", :SchemaLocation=> "http://schemas.dmtf.org/ovf/envelope/1/dsp8023_1.1.0.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.operatingSystemSection+xml", :ComplexTypeName=>"OperatingSystemSection_Type", :SchemaLocation=> "http://schemas.dmtf.org/ovf/envelope/1/dsp8023_1.1.0.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.networkSection+xml", :ComplexTypeName=>"NetworkSection_Type", :SchemaLocation=> "http://schemas.dmtf.org/ovf/envelope/1/dsp8023_1.1.0.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.vAppNetwork+xml", :ComplexTypeName=>"VAppNetworkType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.network+xml", :ComplexTypeName=>"NetworkType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.vcloud.orgNetwork+xml", :ComplexTypeName=>"OrgNetworkType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/master.xsd"}, {:MediaType=>"application/vnd.vmware.admin.vmwexternalnet+xml", :ComplexTypeName=>"VMWExternalNetworkType", :SchemaLocation=> "http://#{@host}#{@path}/v1.5/schema/vmwextensions.xsd"}]}]} Excon::Response.new( :body => body, :headers => {'Content-Type' => 'text/xml'}, :status => 200 ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_cancel_task.rb0000644000004100000410000000231212261242552026304 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :post_task_cancel, :post_cancel_task # Cancel a task. # # @param [String] id Object identifier of the task. # @return [Excon::Response] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-CancelTask.html # @since vCloud API version 1.5 def post_cancel_task(id) request( :expects => 204, :method => 'POST', :path => "task/#{id}/action/cancel" ) end end class Mock def post_cancel_task(id) unless task = data[:tasks][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'No access to entity "com.vmware.vcloud.entity.task:%s"' % id ) end # @note Tasks don't actually get cancelled (confirmed VCloud Director # bug) so we'll emulate that. Set the flag and we're done! task[:cancel_requested] = true Excon::Response.new( :status => 204 ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/put_disks.rb0000644000004100000410000000247212261242552025004 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :put_vm_disks, :put_disks require 'fog/vcloud_director/generators/compute/disks' # Update all RASD items that specify hard disk and hard disk controller # properties of a VM. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @param [Array] disks # * disks is the body of #get_vm_disks # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/PUT-Disks.html # @since vCloud API version 0.9 def put_disks(id, disks=[]) data = Fog::Generators::Compute::VcloudDirector::Disks.new(disks) request( :body => data.generate_xml, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.rasdItemsList+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/virtualHardwareSection/disks" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vdc.rb0000644000004100000410000001440712261242552024413 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a vDC. # # @param [String] id Object identifier of the vDC. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-Vdc.html # @since vCloud API version 0.9 def get_vdc(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vdc/#{id}" ) ensure_list! response.body, :ResourceEntities, :ResourceEntity ensure_list! response.body, :AvailableNetworks, :Network ensure_list! response.body, :VdcStorageProfiles, :VdcStorageProfile response end end class Mock def get_vdc(vdc_id) response = Excon::Response.new unless vdc = data[:vdcs][vdc_id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"com.vmware.vcloud.entity.vdc:#{vdc_id}\"." ) end body = {:xmlns=>xmlns, :xmlns_xsi=>xmlns_xsi, :status=>"1", :name=>vdc[:name], :id=>"urn:vcloud:vdc:#{vdc_id}", :type=>"application/vnd.vmware.vcloud.vdc+xml", :href=>make_href("vdc/#{vdc_id}"), :xsi_schemaLocation=>xsi_schema_location, :Link=> [{:rel=>"up", :type=>"application/vnd.vmware.vcloud.org+xml", :href=>make_href("org/#{data[:org][:uuid]}")}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.metadata+xml", :href=>make_href("vdc/#{vdc_id}/metadata")}, {:rel=>"add", :type=>"application/vnd.vmware.vcloud.uploadVAppTemplateParams+xml", :href=> make_href("vdc/#{vdc_id}/action/uploadVAppTemplate")}, {:rel=>"add", :type=>"application/vnd.vmware.vcloud.media+xml", :href=>make_href("vdc/#{vdc_id}/media")}, {:rel=>"add", :type=> "application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml", :href=> make_href("vdc/#{vdc_id}/action/instantiateVAppTemplate")}, {:rel=>"add", :type=>"application/vnd.vmware.vcloud.cloneVAppParams+xml", :href=>make_href("vdc/#{vdc_id}/action/cloneVApp")}, {:rel=>"add", :type=>"application/vnd.vmware.vcloud.cloneVAppTemplateParams+xml", :href=> make_href("vdc/#{vdc_id}/action/cloneVAppTemplate")}, {:rel=>"add", :type=>"application/vnd.vmware.vcloud.cloneMediaParams+xml", :href=>make_href("vdc/#{vdc_id}/action/cloneMedia")}, {:rel=>"add", :type=>"application/vnd.vmware.vcloud.captureVAppParams+xml", :href=>make_href("vdc/#{vdc_id}/action/captureVApp")}, {:rel=>"add", :type=>"application/vnd.vmware.vcloud.composeVAppParams+xml", :href=>make_href("vdc/#{vdc_id}/action/composeVApp")}, {:rel=>"add", :type=>"application/vnd.vmware.vcloud.diskCreateParams+xml", :href=>make_href("vdc/#{vdc_id}/disk")}, {:rel=>"edgeGateways", :type=>"application/vnd.vmware.vcloud.query.records+xml", :href=>make_href("admin/vdc/#{vdc_id}/edgeGateways")}, {:rel=>"add", :type=>"application/vnd.vmware.vcloud.orgVdcNetwork+xml", :href=>make_href("admin/vdc/#{vdc_id}/networks")}, {:rel=>"orgVdcNetworks", :type=>"application/vnd.vmware.vcloud.query.records+xml", :href=>make_href("admin/vdc/#{vdc_id}/networks")}], :Description=>vdc[:description]||'', :AllocationModel=>"AllocationVApp", :ComputeCapacity=> {:Cpu=> {:Units=>"MHz", :Allocated=>"0", :Limit=>"0", :Reserved=>"0", :Used=>"0", :Overhead=>"0"}, :Memory=> {:Units=>"MB", :Allocated=>"0", :Limit=>"0", :Reserved=>"0", :Used=>"0", :Overhead=>"0"}}, :ResourceEntities => {}, :AvailableNetworks => {}, :Capabilities=> {:SupportedHardwareVersions=> {:SupportedHardwareVersion=>"vmx-08"}}, :NicQuota=>"0", :NetworkQuota=>"20", :UsedNetworkCount=>"0", :VmQuota=>"100", :IsEnabled=>"true"} body[:ResourceEntities][:ResourceEntity] = data[:catalog_items].map do |id, item| {:type=>"application/vnd.vmware.vcloud.#{item[:type]}+xml", :name=>item[:name], :href=>make_href("#{item[:type]}/#{item[:type]}-#{id}")} end body[:AvailableNetworks][:Network] = data[:networks].map do |id, network| {:type=>"application/vnd.vmware.vcloud.network+xml", :name=>network[:name], :href=>make_href("network/#{id}")} end if api_version.to_f >= 5.1 body[:VdcStorageProfiles] = {} body[:VdcStorageProfiles][:VdcStorageProfile] = data[:vdc_storage_classes].select do |id, storage_class| storage_class[:vdc] == vdc_id end.map do |id, storage_class| {:type => 'application/vnd.vmware.vcloud.vdcStorageProfile+xml', :name => storage_class[:name], :href => make_href("vdcStorageProfile/#{id}")} end end response.status = 200 response.headers = {'Content-Type' => "#{body[:type]};version=#{api_version}"} response.body = body response end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_thumbnail.rb0000644000004100000410000000156012261242552025616 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves a thumbnail image of a VM console. # # The content type of the response can be any of `image/png`, # `image/gif`. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~String> - the thumbnail image. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-Thumbnail.html # @since vCloud API version 0.9 def get_thumbnail(id) request( :expects => 200, :headers => {'Accept' => "image/*;version=#{@api_version}"}, :idempotent => true, :method => 'GET', :path => "vApp/#{id}/screen" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_instantiate_vapp_template.rb0000644000004100000410000001404612261242552031310 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Create a vApp from a vApp template. # # The response includes a Task element. You can monitor the task to to # track the creation of the vApp. # # @note This may not work at all or may work only under certain # circumstances. # # @param [String] id Object identifier of the vDC. # @param [String] vapp_template_id Object identifier of the vApp # template. # @param [String] name # @param [Hash] options # @option options [Boolean] :deploy True if the vApp should be deployed # at instantiation. Defaults to true. # @option options [Boolean] :powerOn True if the vApp should be # powered-on at instantiation. Defaults to true. # @option options [String] :Description Optional description. # @option options [Hash] :InstantiationParams Instantiation parameters # for the composed vApp. # * :LeaseSettingsSection<~Hasn>: # * :DeploymentLeaseTimeInSeconds<~Integer> - Deployment lease in # seconds. # * :StorageLeaseTimeInSeconds<~Integer> - Storage lease in # seconds. # * :DeploymentLeaseExpiration<~Integer> - Expiration date/time of # deployment lease. # * :StorageLeaseExpiration<~Integer> - Expiration date/time of # storage lease. # * :NetworkConfigSection<~Hash>: # * :NetworkConfig<~Hash>: # * :networkName<~String> - The name of the vApp network. # * :Configuration<~Hash>: # * :ParentNetwork<~Hash>: # * :href<~String> - # * :FenceMode<~String> - Isolation type of the network. # @option options [Boolean] :IsSourceDelete Set to true to delete the # source object after the operation completes. # @option options [Boolean] :AllEULAsAccepted True confirms acceptance # of all EULAs in a vApp template. # @return [Excon::Response] # * body<~Hash>: # # @raise Fog::Compute::VcloudDirector::DuplicateName # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-InstantiateVAppTemplate.html # @since vCloud API version 0.9 def post_instantiate_vapp_template(id, vapp_template_id, name, options={}) body = Nokogiri::XML::Builder.new do attrs = { 'xmlns' => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1', :name => name } attrs[:deploy] = options[:deploy] if options.key?(:deploy) attrs[:powerOn] = options[:powerOn] if options.key?(:powerOn) InstantiateVAppTemplateParams(attrs) { if options.key?(:Description) Description options[:Description] end if instantiation_params = options[:InstantiationParams] InstantiationParams { if section = instantiation_params[:LeaseSettingsSection] LeaseSettingsSection { self['ovf'].Info 'Lease settings section' if section.key?(:DeploymentLeaseInSeconds) DeploymentLeaseInSeconds section[:DeploymentLeaseInSeconds] end if section.key?(:StorageLeaseInSeconds) StorageLeaseInSeconds section[:StorageLeaseInSeconds] end if section.key?(:DeploymentLeaseExpiration) DeploymentLeaseExpiration section[:DeploymentLeaseExpiration].strftime('%Y-%m-%dT%H:%M:%S%z') end if section.key?(:StorageLeaseExpiration) StorageLeaseExpiration section[:StorageLeaseExpiration].strftime('%Y-%m-%dT%H:%M:%S%z') end } end if section = instantiation_params[:NetworkConfigSection] NetworkConfigSection { self['ovf'].Info 'Configuration parameters for logical networks' if network_configs = section[:NetworkConfig] network_configs = [network_configs] if network_configs.is_a?(Hash) network_configs.each do |network_config| NetworkConfig(:networkName => network_config[:networkName]) { if configuration = network_config[:Configuration] Configuration { ParentNetwork(configuration[:ParentNetwork]) FenceMode configuration[:FenceMode] } end } end end } end } end Source(:href => "#{end_point}vAppTemplate/#{vapp_template_id}") if options.key?(:IsSourceDelete) IsSourceDelete options[:IsSourceDelete] end if options.key?(:AllEULAsAccepted) AllEULAsAccepted options[:AllEULAsAccepted] end } end.to_xml begin request( :body => body, :expects => 201, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vdc/#{id}/action/instantiateVAppTemplate" ) rescue Fog::Compute::VcloudDirector::BadRequest => e if e.minor_error_code == 'DUPLICATE_NAME' raise Fog::Compute::VcloudDirector::DuplicateName.new(e.message) end raise end end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_shadow_vm.rb0000644000004100000410000000124112261242552025616 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a shadow VM. # # @param [String] id The object identifier of the shadow VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-ShadowVm.html def get_shadow_vm(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "shadowVm/#{id}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_catalog_metadata_item_metadata.rb0000644000004100000410000000155112261242552031763 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the value of the specified key from catalog metadata. # # @param [String] id Object identifier of the catalog. # @param [String] key Key of the metadata. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-CatalogMetadataItem-metadata.html # @since vCloud API version 1.5 def get_catalog_metadata_item_metadata(id, key) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "catalog/#{id}/metadata/#{URI.escape(key)})" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_disks_from_query.rb0000644000004100000410000001113712261242552027221 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves a disk list by using REST API general QueryHandler. # # @param [Hash] options # @option options [String] :sortAsc (Sorted by database ID) Sort # results by attribute-name in ascending order. attribute-name cannot # include metadata. # @option options [String] :sortDesc (Sorted by database ID) Sort # results by attribute-name in descending order. attribute-name # cannot include metadata. # @option options [Integer] :page (1) If the query results span # multiple pages, return this page. # @option options [Integer] :pageSize (25) Number of results per page, # to a maximum of 128. # @option options [String] :format (records) One of the following # types: # - *references* Returns a reference to each object, including its # :name, :type, and :href attributes. # - *records* Returns all database records for each object, with each # record as an attribute. # - *idrecords* Identical to the records format, except that object # references are returned in :id format rather than :href format. # @option options [Array] :fields (all static attribute names) # List of attribute names or metadata key names to return. # @option options [Integer] :offset (0) Integer value specifying the # first record to return. Record numbers < offset are not returned. # @option options [String] :filter (none) Filter expression. # @return [Excon::Response] # * hash<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :name<~String> - Query name that generated this result set. # * :page<~String> - Page of the result set that this container # holds. The first page is page number 1. # * :pageSize<~String> - Page size, as a number of records or # references. # * :total<~String> - Total number of records or references in the # container. # * :Link<~Array>: # * :href<~String> - Contains the URI to the entity. # * :type<~String> - Contains the type of the entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # * :DiskRecord<~Array>: # * TODO # * :firstPage<~Integer> - First page in the result set. # * :previousPage<~Integer> - Previous page in the result set. # * :nextPage<~Integer> - Next page in the result set. # * :lastPage<~Integer> - Last page in the result set. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-DisksFromQuery.html # @since vCloud API version 1.5 def get_disks_from_query(options={}) query = [] query << "sortAsc=#{options[:sortAsc]}" if options[:sortAsc] query << "sortDesc=#{options[:sortDesc]}" if options[:sortDesc] query << "page=#{options[:page]}" if options[:page] query << "pageSize=#{options[:pageSize]}" if options[:pageSize] query << "format=#{options[:format]}" if options[:format] query << "fields=#{Array(options[:fields]).join(',')}" if options[:fields] query << "offset=#{options[:offset]}" if options[:offset] query << "filter=#{options[:filter]}" if options[:filter] response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'disks/query', :query => query.map {|q| URI.escape(q)}.join('&') ) ensure_list! response.body, :Link ensure_list! response.body, response.body[:type] == 'application/vnd.vmware.vcloud.query.references+xml' ? :DiskReference : :DiskRecord %w[firstPage previousPage nextPage lastPage].each do |rel| if link = response.body[:Link].detect {|l| l[:rel] == rel} href = Nokogiri::XML.fragment(link[:href]) query = CGI.parse(URI.parse(href.text).query) response.body[rel.to_sym] = query['page'].first.to_i response.body[:pageSize] ||= query['pageSize'].first.to_i end end response end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_check_vm_compliance.rb0000644000004100000410000000163512261242552030015 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Perform storage profile compliance check on a VM. # # This operation is asynchronous and return a task. When the task # completes, the compliance check on the VM has been completed and the # results can be retrieved. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-CheckVmCompliance.html # @since vCloud API version 5.1 def post_check_vm_compliance(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/action/checkCompliance" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vapp_template_owner.rb0000644000004100000410000000136712261242552027713 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the owner of a vApp template. # # @param [String] id Object identifier of the vApp template. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VAppTemplateOwner.html # @since vCloud API version 1.5 def get_vapp_template_owner(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/owner" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_install_vmware_tools.rb0000644000004100000410000000153212261242552030307 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Install VMware Tools on a running VM. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-InstallVMwareTools.html # @since vCloud API version 1.5 def post_install_vmware_tools(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/action/installVMwareTools" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_media.rb0000644000004100000410000000671112261242552024715 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a media object. # # @param [String] id Object identifier of the media object. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-Media.html # @since vCloud API version 0.9 def get_media(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "media/#{id}" ) ensure_list! response.body, :Files, :File response end end class Mock def get_media(id) unless data[:medias][id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.media:#{id})\"." ) end body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location }.merge(media_body(id)) Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=>#{@api_version}"}, :body => body ) end private def media_body(id) media = data[:medias][id] body = { :size => media[:size].to_s, :imageType => media[:image_type], :status => media[:status].to_s, :name => media[:name], :id => "urn:vcloud:media:#{id}", :type => 'application/vnd.vmware.vcloud.media+xml', :href => make_href("media/#{id}"), :Link => { :href => make_href("vdc/#{media[:vdc_id]}"), :type => 'application/vnd.vmware.vcloud.vdc+xml', :rel => 'up' }, :Description => media[:description] || '', :Tasks => { # FIXME: there's only one for now :Task => media[:tasks].map {|task_id| task_body(task_id)}.first }, :Files => { :File => [] }, :Owner => { :type => 'application/vnd.vmware.vcloud.owner+xml', :User => { :href => make_href("admin/user/#{user_uuid}"), :name => user_uuid, :type => 'application/vnd.vmware.admin.user+xml', } } } if media[:status] == 0 body[:Files][:File] << { :size => media[:size].to_s, :bytesTransferred => media[:file][:bytes_transferred].to_s, :name => 'file', :Link=> { :href => make_href("transfer/#{media[:file][:uuid]}/file"), :rel => 'upload:default' } } end if api_version.to_f >= 5.1 storage_class_id = media[:vdc_storage_class] body[:VdcStorageProfile] = { :href => make_href("vdcStorageProfile/#{storage_class_id}"), :name => data[:vdc_storage_classes][storage_class_id][:name], :type => 'application/vnd.vmware.vcloud.vdcStorageProfile+xml', } end body end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_medias_from_query.rb0000644000004100000410000001115112261242552027342 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves a media list by using REST API general QueryHandler. # # @param [Hash] options # @option options [String] :sortAsc (Sorted by database ID) Sort # results by attribute-name in ascending order. attribute-name cannot # include metadata. # @option options [String] :sortDesc (Sorted by database ID) Sort # results by attribute-name in descending order. attribute-name # cannot include metadata. # @option options [Integer] :page (1) If the query results span # multiple pages, return this page. # @option options [Integer] :pageSize (25) Number of results per page, # to a maximum of 128. # @option options [String] :format (records) One of the following # types: # - *references* Returns a reference to each object, including its # :name, :type, and :href attributes. # - *records* Returns all database records for each object, with each # record as an attribute. # - *idrecords* Identical to the records format, except that object # references are returned in :id format rather than :href format. # @option options [Array] :fields (all static attribute names) # List of attribute names or metadata key names to return. # @option options [Integer] :offset (0) Integer value specifying the # first record to return. Record numbers < offset are not returned. # @option options [String] :filter (none) Filter expression. # @return [Excon::Response] # * hash<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :name<~String> - Query name that generated this result set. # * :page<~String> - Page of the result set that this container # holds. The first page is page number 1. # * :pageSize<~String> - Page size, as a number of records or # references. # * :total<~String> - Total number of records or references in the # container. # * :Link<~Array>: # * :href<~String> - Contains the URI to the entity. # * :type<~String> - Contains the type of the entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # * :MediaRecord<~Array>: # * TODO # * :firstPage<~Integer> - First page in the result set. # * :previousPage<~Integer> - Previous page in the result set. # * :nextPage<~Integer> - Next page in the result set. # * :lastPage<~Integer> - Last page in the result set. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-MediasFromQuery.html # @since vCloud API version 1.5 def get_medias_from_query(options={}) query = [] query << "sortAsc=#{options[:sortAsc]}" if options[:sortAsc] query << "sortDesc=#{options[:sortDesc]}" if options[:sortDesc] query << "page=#{options[:page]}" if options[:page] query << "pageSize=#{options[:pageSize]}" if options[:pageSize] query << "format=#{options[:format]}" if options[:format] query << "fields=#{Array(options[:fields]).join(',')}" if options[:fields] query << "offset=#{options[:offset]}" if options[:offset] query << "filter=#{options[:filter]}" if options[:filter] response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'mediaList/query', :query => query.map {|q| URI.escape(q)}.join('&') ) ensure_list! response.body, :Link ensure_list! response.body, response.body[:type] == 'application/vnd.vmware.vcloud.query.references+xml' ? :MediaReference : :MediaRecord %w[firstPage previousPage nextPage lastPage].each do |rel| if link = response.body[:Link].detect {|l| l[:rel] == rel} href = Nokogiri::XML.fragment(link[:href]) query = CGI.parse(URI.parse(href.text).query) response.body[rel.to_sym] = query['page'].first.to_i response.body[:pageSize] ||= query['pageSize'].first.to_i end end response end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/put_catalog_item_metadata_item_metadata.rb0000644000004100000410000000355612261242552033041 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Set the metadata value for the specified key to the value provided, # overwriting any existing value. # # @param [String] id Object identifier of the catalog item. # @param [String] key Key of the metadata item. # @param [Boolean,DateTime,Fixnum,String] value Value of the metadata # item. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/PUT-CatalogItemMetadataItem-metadata.html # @since vCloud API version 1.5 def put_catalog_item_metadata_item_metadata(id, key, value) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance' } MetadataValue(attrs) { if api_version.to_f < 5.1 Value value else type = case value when TrueClass, FalseClass then 'MetadataBooleanValue'; when DateTime then 'MetadataDateTimeValue'; when Fixnum then 'MetadataNumberValue'; else 'MetadataStringValue' end TypedValue('xsi:type' => type) { Value value } end } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.metadata.value+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "catalogItem/#{id}/metadata/#{URI.escape(key)}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_upload_vapp_template.rb0000644000004100000410000000331612261242552030247 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Upload an OVF package to create a vApp template # # The response includes an upload link for the OVF descriptor. # # @param [String] vdc_id Object identifier of the vDC. # @param [String] name The name of the vApp template. # @param [Hash] options # @option options [Boolean] :manifestRequired True if an OVF manifest # is included in the upload. Default value is false. # @option options [String] :Description Optional description. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-UploadVAppTemplate.html # @since vCloud API version 0.9 def post_upload_vapp_template(vdc_id, name, options={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', :name => name } attrs[:manifestRequired] = options[:manifestRequired] if options.key?(:manifestRequired) UploadVAppTemplateParams(attrs) { if options.key?(:Description) Description options[:Description] end } end.to_xml request( :body => body, :expects => 201, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.vAppTemplateParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vdc/#{vdc_id}/action/uploadVAppTemplate" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_shutdown_vapp.rb0000644000004100000410000000211612261242552026740 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Shut down a vApp or VM. # # If used on a vApp, shuts down all VMs in the vApp. If used on a VM, # shuts down the VM. This operation is available only for a vApp or VM # that is powered on. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the vApp or VM. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::BadRequest] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-ShutdownVApp.html # @since vCloud API version 0.9 def post_shutdown_vapp(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/power/action/shutdown" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/put_cpu.rb0000644000004100000410000000454112261242552024455 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :put_vm_cpu, :put_cpu # Update the RASD item that specifies CPU properties of a VM. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @param [Integer] num_cpus # @return [Excon:Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/PUT-Cpu.html # @since vCloud API version 0.9 def put_cpu(id, num_cpus) data = < hertz * 10^6 Number of Virtual CPUs #{num_cpus} virtual CPU(s) 4 0 3 #{num_cpus} 0 EOF request( :body => data, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.rasdItem+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/virtualHardwareSection/cpu" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_eject_cd_rom.rb0000644000004100000410000000246212261242552026460 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Eject virtual media. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @param [String] media_id Object identifier of the media object. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-EjectCdRom.html # @since vCloud API version 0.9 def post_eject_cd_rom(id, media_id) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5' } MediaInsertOrEjectParams(attrs) { Media(:href => "#{end_point}media/#{media_id}") } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.mediaInsertOrEjectParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/media/action/ejectMedia" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/put_guest_customization_section_vapp.rb0000644000004100000410000001401012261242552032547 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :put_vm_customization, :put_guest_customization_section_vapp # Updates the guest customization section of a VM. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @param [Hash] options # @option options [Boolean] :Enabled True if guest customization is # enabled. # @option options [Boolean] :ChangeSid True if customization can change # the Windows SID of this virtual machine. # @option options [Boolean] :JoinDomainEnabled True if this virtual # machine can join a Windows Domain. # @option options [Boolean] :UseOrgSettings True if customization # should use organization settings (OrgGuestPersonalizationSettings) # when joining a Windows Domain. # @option options [String] :DomainName The name of the Windows Domain # to join. # @option options [String] :DomainUserName User name to specify when # joining a Windows Domain. # @option options [String] :DomainUserPassword Password to use with # :DomainUserName. # @option options [String] :MachineObjectOU The name of the Windows # Domain Organizational Unit (OU) in which the computer account for # this virtual machine will be created. # @option options [Boolean] :AdminPassword_enabled True if guest # customization can modify administrator password settings for this # virtual machine. # @option options [Boolean] :AdminPassword_auto True if the # administrator password for this virtual machine should be # automatically generated. # @option options [String] :AdminPassword True if the administrator # password for this virtual machine should be set to this string. # (:AdminPasswordAuto must be false.) # @option options [Boolean] :ResetPasswordRequired True if the # administrator password for this virtual machine must be reset after # first use. # @option customization [String] :CustomizationScript Script to run on # guest customization. The entire script must appear in this element. # @option customization [String] :ComputerName Computer name to assign # to this virtual machine. # @return [Excon::Response] # * body<~Hash>: # * :Tasks<~Hash>: # * :Task<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/PUT-GuestCustomizationSection-vApp.html # @since vCloud API version 1.0 def put_guest_customization_section_vapp(id, options={}) options = options.dup # Mutate options to new format. deprecated = { :enabled => :Enabled, :change_sid => :ChangeSid, :join_domain_enabled => :JoinDomainEnabled, :use_org_settings => :UseOrgSettings, :admin_password => :AdminPassword, :admin_password_enabled => :AdminPasswordEnabled, :admin_password_auto => :AdminPasswordAuto, :reset_password_required => :ResetPasswordRequired, :customization_script => :CustomizationScript, :computer_name => :ComputerName } deprecated.each do |from, to| options[to] = options.delete(from) if options.key?(from) end body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1' } GuestCustomizationSection(attrs) { self['ovf'].Info 'Specifies Guest OS Customization Settings' if options.key?(:Enabled) Enabled options[:Enabled] end if options.key?(:ChangeSid) ChangeSid options[:ChangeSid] end if options.key?(:JoinDomainEnabled) JoinDomainEnabled options[:JoinDomainEnabled] end if options.key?(:UseOrgSettings) UseOrgSettings options[:UseOrgSettings] end if options.key?(:DomainName) DomainName options[:DomainName] end if options.key?(:DomainUser) DomainUser options[:DomainUser] end if options.key?(:DomainUserPassword) DomainUserPassword options[:DomainUserPassword] end if options.key?(:MachineObjectOU) MachineObjectOU options[:MachineObjectOU] end if options.key?(:AdminPasswordEnabled) AdminPasswordEnabled options[:AdminPasswordEnabled] end if options.key?(:AdminPasswordAuto) AdminPasswordAuto options[:AdminPasswordAuto] end if options.key?(:AdminPassword) AdminPassword options[:AdminPassword] end if options.key?(:ResetPasswordRequired) ResetPasswordRequired options[:ResetPasswordRequired] end if options.key?(:CustomizationScript) CustomizationScript options[:CustomizationScript] end if options.key?(:ComputerName) ComputerName options[:ComputerName] end } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.guestCustomizationSection+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/guestCustomizationSection" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_catalog.rb0000644000004100000410000000235212261242552025245 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a catalog. # # @param [String] id Object identifier of the catalog. # @return [Excon::Response] # * hash<~Hash>: # # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-Catalog.html # @since vCloud API version 0.9 def get_catalog(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "catalog/#{id}" ) ensure_list! response.body, :CatalogItems, :CatalogItem response end end class Mock def get_catalog(id) unless catalog = data[:catalogs][id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.catalog:#{id})\"." ) end Fog::Mock.not_implemented catalog.is_used_here # avoid warning from syntax checker end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vms_disk_attached_to.rb0000644000004100000410000000220712261242552030010 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a list of all VMs attached to a disk. # # @param [String] id Object identifier of the disk. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VmsDisksAttachedTo.html # @since vCloud API version 5.1 def get_vms_disk_attached_to(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "disk/#{id}/attachedVms" ) ensure_list! response.body, :VmReference response end end class Mock def get_vms_disk_attached_to(id) unless data[:disks][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'No access to entity "com.vmware.vcloud.entity.disk:%s".' % id ) end Fog::Mock.not_implemented end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vapp_template_metadata.rb0000644000004100000410000000143312261242552030333 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve metadata associated with the vApp template or VM. # # @param [String] id Object identifier of the vApp template or VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VAppTemplateMetadata.html # @since vCloud API version 1.5 def get_vapp_template_metadata(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/metadata/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/delete_logout.rb0000644000004100000410000000066212261242552025631 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # @return [Excon::Response] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/DELETE-Logout.html def delete_logout request( :expects => 204, :method => 'DELETE', :path => 'session' ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_suspend_vapp.rb0000644000004100000410000000210512261242552026544 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Suspend a vApp or VM. # # If used on a vApp, suspends all VMs in the vApp. If used on a VM, # suspends the VM. This operation is available only for a vApp or VM # that is powered on. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the vApp or VM. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::BadRequest] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-SuspendVApp.html # @since vCloud API version 0.9 def post_suspend_vapp(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/power/action/suspend" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vapp_ovf_descriptor.rb0000644000004100000410000000132012261242552027703 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the OVF descriptor of a vApp directly. # # @param [String] id Object identifier of the vApp. # @return [Excon::Response] # * body<~String> - the OVF descriptor. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VAppOvfDescriptor.html # @since vCloud API version 5.1 def get_vapp_ovf_descriptor(id) request( :expects => 200, :idempotent => true, :method => 'GET', :path => "vApp/#{id}/ovf" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_product_sections_vapp.rb0000644000004100000410000000142212261242552030245 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a list of ProductSection elements from a vApp or VM. # # @param [String] id Object identifier of the vApp or VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-ProductSections-vApp.html # @since vCloud API version 1.5 def get_product_sections_vapp(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/productSections" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_undeploy_vapp.rb0000644000004100000410000000523612261242552026732 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Undeploy a vApp/VM. # # Undeployment deallocates all resources used by the vApp and the VMs # it contains. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the vApp. # @param [Hash] options # @option options [String] :UndeployPowerAction The specified action is # applied to all virtual machines in the vApp. All values other than # default ignore actions, order, and delay specified in the # StartupSection. One of: # - powerOff (Power off the virtual machines. This is the default # action if this attribute is missing or empty) # - suspend (Suspend the virtual machines) # - shutdown (Shut down the virtual machines) # - force (Attempt to power off the virtual machines. Failures in # undeploying the virtual machine or associated networks are # ignored. All references to the vApp and its virtual machines are # removed from the database) # - default (Use the actions, order, and delay specified in the # StartupSection). # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::BadRequest] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-UndeployVApp.html # @since vCloud API version 0.9 def post_undeploy_vapp(id, options={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5' } UndeployVAppParams(attrs) { if options[:UndeployPowerAction] UndeployPowerAction options[:UndeployPowerAction] end } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.undeployVAppParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/action/undeploy" ) end # @deprecated Use {#post_undeploy_vapp} instead. def undeploy(id) Fog::Logger.deprecation("#{self} => ##{undeploy} is deprecated, use ##{post_undeploy_vapp} instead [light_black](#{caller.first})[/]") post_undeploy_vapp(id, :UndeployPowerAction => 'shutdown') end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_disk.rb0000644000004100000410000001041112261242552024560 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a disk. # # @param [String] id Object identifier of the disk. # @return [Excon::Response] # * body<~Hash>: # * :href<~String> - The URI of the disk. # * :type<~String> - The MIME type of the disk. # * :id<~String> - The disk identifier, expressed in URN format. # * :name<~String> - The name of the disk. # * :status<~String> - Creation status of the disk. # * :busSubType<~String> - Disk bus sub type. # * :busType<~String> - Disk bus type. # * :size<~String> - Size of the disk. # * :Description<~String> - Optional description. # * :Tasks<~Hash> - A list of queued, running, or recently # completed tasks associated with this disk. # * :StorageProfile<~Hash> - Storage profile of the disk. # * :Owner<~Hash> - Disk owner. # # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-Disk.html # @since vCloud API version 5.1 def get_disk(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "disk/#{id}" ) ensure_list! response.body, :Link ensure_list! response.body, :Tasks, :Task ensure_list! response.body, :Files, :File response end end class Mock def get_disk(id) unless data[:disks][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'No access to entity "com.vmware.vcloud.entity.disk:%s".' % id ) end body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location }.merge(disk_body(id)) Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{@version}"}, :body => body ) end private def disk_body(id) disk = data[:disks][id] storage_class_id = disk[:vdc_storage_class] body = { :href => make_href("disk/#{id}"), :type => 'application/vnd.vmware.vcloud.disk+xml', :id => "urn:vcloud:disk:#{id}", :name => disk[:name], :status => disk[:status].to_s, :busSubType => disk[:bus_sub_type], :busType => disk[:bus_type], :size => disk[:size].to_s, :Link => [ { :href => make_href("vdc/#{disk[:vdc_id]}"), :rel => 'up', :type => 'application/vnd.vmware.vcloud.vdc+xml' } ], :Description => disk[:description], :Tasks => { # FIXME: there's only one for now :Task => disk[:tasks].map {|task_id| task_body(task_id)}.first }, :Files => { :File => [] }, :StorageProfile => { :href => make_href("vdcStorageProfile/#{storage_class_id}"), :name => data[:vdc_storage_classes][storage_class_id][:name], :type => 'application/vnd.vmware.vcloud.vdcStorageProfile+xml', }, :Owner => { :type => 'application/vnd.vmware.vcloud.owner+xml', :User => { :href => make_href("admin/user/#{user_uuid}"), :name => user_name, :type => 'application/vnd.vmware.admin.user+xml', } } } if api_version.to_f >= 5.1 storage_class_id = disk[:vdc_storage_class] body[:VdcStorageProfile] = { :href => make_href("vdcStorageProfile/#{storage_class_id}"), :name => data[:vdc_storage_classes][storage_class_id][:name], :type => 'application/vnd.vmware.vcloud.vdcStorageProfile+xml', } end body end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/delete_catalog_item.rb0000644000004100000410000000114212261242552026742 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Delete a catalog item. # # @param [String] id Object identifier of the catalog item. # @return [Excon::Response] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/DELETE-CatalogItem.html # @since vCloud API version 0.9 def delete_catalog_item(id) request( :expects => 204, :method => 'DELETE', :path => "catalogItem/#{id}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vms.rb0000644000004100000410000000130312261242552024433 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/parsers/compute/vms' # Retrieve a vApp or VM. # # @note This should probably be deprecated. # # @param [String] id Object identifier of the vApp or VM. # @return [Excon::Response] # * body<~Hash>: # # @see #get_vapp def get_vms(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Compute::VcloudDirector::Vms.new, :path => "vApp/#{id}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_enable_vapp_template_download.rb0000644000004100000410000000134312261242552032076 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Enable a vApp template for download. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-EnableVAppTemplateDownload.html # @since vCloud API version 0.9 def post_enable_vapp_template_download(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/action/enableDownload" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/put_network_connection_system_section_vapp.rb0000644000004100000410000001242212261242552033751 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :put_vm_network, :put_network_connection_system_section_vapp # Update the network connection section of a VM. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @param [Hash] options Container for the network connections of this # virtual machine. # @option options [Integer] :PrimaryNetworkConnectionIndex (0) # Virtual slot number associated with the NIC that should be # considered this virtual machine's primary network connection. # Defaults to slot 0. # @option options [Array] :NetworkConnection # * :needsCustomization<~Boolean> - True if this NIC needs # customization. # * :network<~String> - Name of the network to which this NIC is # connected. # * :NetworkConnectionIndex<~Integer> - Virtual slot number # associated with this NIC. First slot number is 0. # * :IpAddress<~String> - IP address assigned to this NIC. # * :IsConnected<~Boolean> - If the virtual machine is undeployed, # this value specifies whether the NIC should be connected upon # deployment. If the virtual machine is deployed, this value # reports the current status of this NIC's connection, and can be # updated to change that connection status. # * :MACAddress<~String> - MAC address associated with the NIC. # * :IpAddressAllocationMode<~String> - IP address allocation mode # for this connection. One of: # - POOL (A static IP address is allocated automatically from a # pool of addresses.) # - DHCP (The IP address is obtained from a DHCP service.) # - MANUAL (The IP address is assigned manually in the :IpAddress # element.) # - NONE (No IP addressing mode specified.) # @return [Excon::Response] # * body<~Hash>: # * :Tasks<~Hash>: # * :Task<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/PUT-NetworkConnectionSystemSection-vApp.html # @since vCloud API version 0.9 def put_network_connection_system_section_vapp(id, options={}) options = options.dup # Mutate options to new format. deprecated = { :needs_customization => :needsCustomization, :network => :network, :network_connection_index => :NetworkConnectionIndex, :ip_address => :IpAddress, :is_connected => :IsConnected, :mac_address => :MACAddress, :ip_address_allocation_mode => :IpAddressAllocationMode } option = options.delete(:primary_network_connection_index) options[:PrimaryNetworkConnectionIndex] ||= option unless option.nil? unless options.key?(:NetworkConnection) deprecated.each do |from, to| if options.key?(from) options[:NetworkConnection] ||= [{}] options[:NetworkConnection].first[to] = options.delete(from) end end end options[:NetworkConnection] = [options[:NetworkConnection]] if options[:NetworkConnection].is_a?(Hash) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1' } NetworkConnectionSection(attrs) { self[:ovf].Info 'Specifies the available VM network connections' if options.key?(:PrimaryNetworkConnectionIndex) PrimaryNetworkConnectionIndex options[:PrimaryNetworkConnectionIndex] end if network_connection = options[:NetworkConnection] network_connection.each do |nic| attrs = { :network => nic[:network] } if nic.key?(:needsCustomization) attrs[:needsCustomization] = nic[:needsCustomization] end NetworkConnection(attrs) { NetworkConnectionIndex nic[:NetworkConnectionIndex] if nic.key?(:IpAddress) IpAddress nic[:IpAddress] end IsConnected nic[:IsConnected] if nic.key?(:MACAddress) MACAddress nic[:MACAddress] end IpAddressAllocationMode nic[:IpAddressAllocationMode] } end end } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.networkConnectionSection+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/networkConnectionSection/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_network_section_vapp_template.rb0000644000004100000410000000144312261242552031771 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the network section of a vApp template. # # @param [String] id The object identifier of the vApp template. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-NetworkSection-vAppTemplate.html # @since vCloud API version 0.9 def get_network_section_vapp_template(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/networkSection/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_supported_systems_info.rb0000644000004100000410000002446312261242552030471 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # List operating systems available for use on virtual machines owned by # this organization. # # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-SupportedSystemsInfo.html # @since vCloud API version 5.1 def get_supported_systems_info request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'supportedSystemsInfo' ) end end class Mock def get_supported_systems_info body = # this is a subset of the full list {:xmlns=>xmlns, :xmlns_xsi=>xmlns_xsi, :type=>"application/vnd.vmware.vcloud.supportedSystemsInfo+xml", :href=>make_href('supportedSystemsInfo/'), :xsi_schemaLocation=>xsi_schema_location, :OperatingSystemFamilyInfo=> [{:Name=>"Microsoft Windows", :OperatingSystemFamilyId=>"1", :OperatingSystem=> [{:OperatingSystemId=>"85", :DefaultHardDiskAdapterType=>"4", :MinimumHardDiskSizeGigabytes=>"40", :MinimumMemoryMegabytes=>"512", :Name=>"Microsoft Windows Server 2012 (64-bit)", :InternalName=>"windows8Server64Guest", :Supported=>"true", :x64=>"true", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"8", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"true", :SupportsMemHotAdd=>"true", :cimOsId=>"74", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"3", :DefaultHardDiskAdapterType=>"4", :MinimumHardDiskSizeGigabytes=>"40", :MinimumMemoryMegabytes=>"512", :Name=>"Microsoft Windows Server 2008 R2 (64-bit)", :InternalName=>"windows7Server64Guest", :Supported=>"true", :x64=>"true", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"true", :SupportsMemHotAdd=>"true", :cimOsId=>"102", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"4", :DefaultHardDiskAdapterType=>"4", :MinimumHardDiskSizeGigabytes=>"40", :MinimumMemoryMegabytes=>"512", :Name=>"Microsoft Windows Server 2008 (32-bit)", :InternalName=>"winLonghornGuest", :Supported=>"true", :x64=>"false", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"true", :SupportsMemHotAdd=>"true", :cimOsId=>"73", :CimVersion=>"0", :SupportedForCreate=>"true"}]}, {:Name=>"Linux", :OperatingSystemFamilyId=>"2", :OperatingSystem=> [{:OperatingSystemId=>"48", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"64", :Name=>"Ubuntu Linux (64-bit)", :InternalName=>"ubuntu64Guest", :Supported=>"true", :x64=>"true", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"true", :cimOsId=>"94", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"47", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"64", :Name=>"Ubuntu Linux (32-bit)", :InternalName=>"ubuntuGuest", :Supported=>"true", :x64=>"false", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"true", :cimOsId=>"93", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"50", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"32", :Name=>"Other 2.6.x Linux (64-bit)", :InternalName=>"other26xLinux64Guest", :Supported=>"true", :x64=>"true", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"7", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"true", :cimOsId=>"100", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"49", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"32", :Name=>"Other 2.6.x Linux (32-bit)", :InternalName=>"other26xLinuxGuest", :Supported=>"true", :x64=>"false", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"7", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"true", :cimOsId=>"99", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"54", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"32", :Name=>"Other Linux (64-bit)", :InternalName=>"otherLinux64Guest", :Supported=>"true", :x64=>"true", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"false", :cimOsId=>"101", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"53", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"32", :Name=>"Other Linux (32-bit)", :InternalName=>"otherLinuxGuest", :Supported=>"true", :x64=>"false", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"false", :cimOsId=>"36", :CimVersion=>"0", :SupportedForCreate=>"true"}]}, {:Name=>"Other", :OperatingSystemFamilyId=>"3", :OperatingSystem=> [{:OperatingSystemId=>"68", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"32", :Name=>"Other (64-bit)", :InternalName=>"otherGuest64", :Supported=>"true", :x64=>"true", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"false", :PersonalizationAuto=>"false", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"true", :cimOsId=>"102", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"67", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"32", :Name=>"Other (32-bit)", :InternalName=>"otherGuest", :Supported=>"true", :x64=>"false", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"false", :PersonalizationAuto=>"false", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"true", :cimOsId=>"1", :CimVersion=>"0", :SupportedForCreate=>"true"}]}]} Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_media_metadata_item_metadata.rb0000644000004100000410000000155512261242552031434 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the value of the specified key from media object metadata. # # @param [String] id Object identifier of the media object. # @param [String] key Key of the metadata. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-MediaMetadataItem-metadata.html # @since vCloud API version 1.5 def get_media_metadata_item_metadata(id, key) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "media/#{id}/metadata/#{URI.escape(key)})" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vapp.rb0000644000004100000410000000141512261242552024600 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a vApp or VM. # # @param [String] id Object identifier of the vApp or VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VApp.html # @since vCloud API version 0.9 def get_vapp(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}" ) ensure_list! response.body, :Children, :Vm response end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_upload_disk.rb0000644000004100000410000001236712261242552026346 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Create a disk. # # @param [String] id Object identifier of the vDC. # @param [String] name The name of the disk. # @param [Integer] size Size of the disk. For modify operation this is # required only for the XSD validation it could not be changed. # @param [Hash] options # @option options [String] :operationKey Optional unique identifier to # support idempotent semantics for create and delete operations. # @option options [Integer] :busSubType Disk bus sub type. # @option options [Integer] :busType Disk bus type. # @option options [String] :Description Optional description. # @return [Excon::Response] # * body<~Hash>: # * :href<~String> - The URI of the disk. # * :type<~String> - The MIME type of the disk. # * :id<~String> - The disk identifier, expressed in URN format. # * :operationKey<~String> - Optional unique identifier to support # idempotent semantics for create and delete operations. # * :name<~String> - The name of the disk. # * :status<~String> - Creation status of the disk. # * :busSubType<~String> - Disk bus sub type. # * :busType<~String> - Disk bus type. # * :size<~String> - Size of the disk. # * :Link: # * :Description<~String> - Optional description. # * :Tasks<~Hash>: # * :StorageProfile<~Hash> - Storage profile of the disk. # * :href<~String> - Contains the URI to the entity. # * :name<~String> - Contains the name of the entity. # * :type<~String> - Contains the type of the entity. # * :Owner<~Hash> - Disk owner. # * :type<~String> - The MIME type of the entity. # * :User<~Hash> - Reference to the user who is the owner of this # disk. # * :href<~String> - Contains the URI to the entity. # * :name<~String> - Contains the name of the entity. # * :type<~String> - Contains the type of the entity. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-CreateDisk.html # @since vCloud API version 5.1 def post_upload_disk(id, name, size, options={}) body = Nokogiri::XML::Builder.new do DiskCreateParams(:xmlns => 'http://www.vmware.com/vcloud/v1.5') { attrs = { :name => name, :size => size } attrs[:operationKey] = options[:operationKey] if options.key?(:operationKey) attrs[:busSubType] = options[:busSubType] if options.key?(:busSubType) attrs[:busType] = options[:busType] if options.key?(:busType) Disk(attrs) { if options.key?(:Description) Description options[:Description] end if options.key?(:StorageProfile) attrs = { :href => options[:StorageProfile][:href] } StorageProfile(attrs) end } } end.to_xml request( :body => body, :expects => 201, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.diskCreateParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vdc/#{id}/disk" ) end end class Mock def post_upload_disk(id, name, size, options={}) unless size.to_s =~ /^\d+$/ raise Fog::Compute::VcloudDirector::BadRequest.new( "validation error on field 'diskSpec.sizeBytes': must be greater than or equal to 0" ) end unless data[:vdcs][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'No access to entity "(com.vmware.vcloud.entity.vdc:%s)".' % id ) end disk_id = uuid owner = { :href => make_href("disk/#{disk_id}"), :type => 'application/vnd.vmware.vcloud.disk+xml' } task_id = enqueue_task( "Creating Disk #{name}(#{disk_id})", 'vdcCreateDisk', owner, :on_success => lambda do data[:disks][disk_id][:status] = 1 end ) disk = { :description => options[:Description], :name => name, :size => size.to_i, :status => 0, :tasks => [task_id], :vdc_id => id, :vdc_storage_class => data[:vdc_storage_classes].detect {|k,v| v[:default]}.first } data[:disks][disk_id] = disk body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location }.merge(disk_body(disk_id)) Excon::Response.new( :status => 201, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vapp_metadata.rb0000644000004100000410000000150312261242552026436 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve metadata associated with the vApp or VM. # # @param [String] id Object identifier of the vApp or VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VAppMetadata.html # @since vCloud API version 1.5 def get_vapp_metadata(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/metadata/" ) ensure_list! response.body, :MetadataEntry response end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_organizations.rb0000644000004100000410000000334112261242552026521 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a list of organizations accessible to you. # # The system administrator has access to all organizations. # # @return [Excon::Response] # * body<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :Org<~Array]: # * :href<~String> - Contains the URI to the linked entity. # * :name<~String> - Contains the name of the linked entity. # * :type<~String> - Contains the type of the linked entity. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-Organizations.html # @since vCloud API version 0.9 def get_organizations response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'org' ) ensure_list! response.body, :Org response end end class Mock def get_organizations body = {:href=>make_href('org/'), :type=>"application/vnd.vmware.vcloud.orgList+xml", :Org=> [{:href=>make_href("org/#{data[:org][:uuid]}"), :name=>data[:org][:name], :type=>"application/vnd.vmware.vcloud.org+xml"}]} Excon::Response.new( :body => body, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :status => 200 ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/instantiate_vapp_template.rb0000644000004100000410000000706412261242552030245 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Create a vApp from a vApp template. # # The response includes a Task element. You can monitor the task to to # track the creation of the vApp. # # @param [String] vapp_name # @param [String] template_id # @param [Hash] options # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-InstantiateVAppTemplate.html # @since vCloud API version 0.9 def instantiate_vapp_template(vapp_name, template_id, options={}) params = populate_uris(options.merge(:vapp_name => vapp_name, :template_id => template_id)) # @todo Move all the logic to a generator. data = generate_instantiate_vapp_template_request(params) request( :body => data, :expects => 201, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vdc/#{params[:vdc_id]}/action/instantiateVAppTemplate" ) end private def populate_uris(options = {}) options[:vdc_id] || raise("vdc_id option is required") options[:vdc_uri] = vdc_end_point(options[:vdc_id]) options[:network_id] || raise("network_id option is required") options[:network_uri] = network_end_point(options[:network_id]) options[:template_uri] = vapp_template_end_point(options[:template_id]) || raise("template_id option is required") options end def generate_instantiate_vapp_template_request(options ={}) xml = Builder::XmlMarkup.new xml.InstantiateVAppTemplateParams(xmlns.merge!(:name => options[:vapp_name], :"xml:lang" => "en")) { xml.Description(options[:description]) xml.InstantiationParams { # This options are fully ignored if options[:network_uri] xml.NetworkConfigSection { xml.tag!("ovf:Info"){ "Configuration parameters for logical networks" } xml.NetworkConfig("networkName" => options[:network_name]) { xml.Configuration { xml.ParentNetwork(:href => options[:network_uri]) xml.FenceMode("bridged") } } } end } # The template xml.Source(:href => options[:template_uri]) xml.AllEULAsAccepted("true") } end def xmlns { 'xmlns' => "http://www.vmware.com/vcloud/v1.5", "xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1", "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", "xmlns:xsd" => "http://www.w3.org/2001/XMLSchema" } end def vdc_end_point(vdc_id = nil) end_point + ( vdc_id ? "vdc/#{vdc_id}" : "vdc" ) end def network_end_point(network_id = nil) end_point + ( network_id ? "network/#{network_id}" : "network" ) end def vapp_template_end_point(vapp_template_id = nil) end_point + ( vapp_template_id ? "vAppTemplate/#{vapp_template_id}" : "vAppTemplate" ) end def endpoint end_point end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_insert_cd_rom.rb0000644000004100000410000000246612261242552026676 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Insert virtual media. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @param [String] media_id Object identifier of the media object. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-InsertCdRom.html # @since vCloud API version 0.9 def post_insert_cd_rom(id, media_id) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5' } MediaInsertOrEjectParams(attrs) { Media(:href => "#{end_point}media/#{media_id}") } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.mediaInsertOrEjectParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/media/action/insertMedia" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_detach_disk.rb0000644000004100000410000000244312261242552026304 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Detach a disk from a VM. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @param [String] disk_id Object identifier of the disk. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-DetachDisk.html # @since vCloud API version 5.1 def post_detach_disk(id, disk_id) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5' } DiskAttachOrDetachParams(attrs) { Disk(:href => "#{end_point}disk/#{disk_id}") } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.diskAttachOrDetachParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/disk/action/detach" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_consolidate_vm_vapp.rb0000644000004100000410000000150612261242552030075 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Consolidate VM snapshots. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-ConsolidateVm-vApp.html # @since vCloud API version 1.5 def post_consolidate_vm_vapp(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/action/consolidate" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vdc_storage_class.rb0000644000004100000410000000665012261242552027325 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :get_vdc_storage_profile, :get_vdc_storage_class # Returns storage class referred by the Id. All properties of the # storage classes are visible to vcloud user, except for VDC Storage # Class reference. # # @param [String] id Object identifier of the vDC storage profile. # @return [Excon::Response] # * body<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :id<~String> - The entity identifier, expressed in URN format. # The value of this attribute uniquely identifies the entity, # persists for the life of the entity, and is never reused. # * :name<~String> - The name of the entity. # * :Description<~String> - Optional description. # * :Enabled<~String> - True if this storage profile is enabled for # use in the vDC. # * :Units<~String> - Units used to define :Limit. # * :Limit<~String> - Maximum number of :Units allocated for this # storage profile. # * :Default<~String> - True if this is default storage profile for # this vDC. The default storage profile is used when an object # that can specify a storage profile is created with no storage # profile specified. # # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VdcStorageClass.html def get_vdc_storage_class(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vdcStorageProfile/#{id}" ) end end class Mock def get_vdc_storage_class(id) unless vdc_storage_class = data[:vdc_storage_classes][id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.vdcstorageProfile:#{id})\"." ) end body = {:xmlns=>xmlns, :xmlns_xsi=>xmlns_xsi, :name=>vdc_storage_class[:name], :id=>"urn:vcloud:vdcstorageProfile:#{id}", :type=>"application/vnd.vmware.vcloud.vdcStorageProfile+xml", :href=>make_href("api/vdcStorageProfile/#{id}"), :xsi_schemaLocation=>xsi_schema_location, :Link=> [{:rel=>"up", :type=>"application/vnd.vmware.vcloud.vdc+xml", :href=>make_href("vdc/#{vdc_storage_class[:vdc]}")}, {:rel=>"down", :type=>"application/vnd.vmware.vcloud.metadata+xml", :href=>make_href("vdcStorageProfile/#{id}/metadata")}], :Enabled=>vdc_storage_class[:enabled].to_s, :Units=>vdc_storage_class[:units], :Limit=>vdc_storage_class[:limit].to_s, :Default=>vdc_storage_class[:default].to_s} Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_runtime_info_section_type.rb0000644000004100000410000000140012261242552031107 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the runtime info section of a VM. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-RuntimeInfoSectionType.html # @since vCloud API version 1.5 def get_runtime_info_section_type(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/runtimeInfoSection" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/delete_network.rb0000644000004100000410000000354312261242552026012 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Delete an OrgVdcNetwork # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the OrgVdcNetwork. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::BadRequest] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/DELETE-Network.html # @since vCloud API version 0.9 def delete_network(id) request( :expects => 202, :method => 'DELETE', :parser => Fog::ToHashDocument.new, :path => "admin/network/#{id}" ) end end class Mock def delete_network(id) unless data[:networks][id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.orgVdcNetwork:#{id})\"" ) end owner = { :href => make_href("network/#{id}"), :type => 'application/vnd.vmware.vcloud.network+xml' } task_id = enqueue_task( "Deleting Network(#{id})", 'DeleteNetwork', owner, :on_success => lambda do data[:networks].delete(id) end ) body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location, }.merge(task_body(task_id)) Excon::Response.new( :status => 202, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_disk_metadata_item_metadata.rb0000644000004100000410000000153212261242552031302 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the value of the specified key from disk metadata. # # @param [String] id Object identifier of the disk. # @param [String] key Key of the metadata. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-DiskMetadataItem-metadata.html # @since vCloud API version 5.1 def get_disk_metadata_item_metadata(id, key) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "disk/#{id}/metadata/#{URI.escape(key)})" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vapp_template_metadata_item_metadata.rb0000644000004100000410000000163312261242552033213 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the value of the specified key from vApp template or VM # metadata. # # @param [String] id Object identifier of the vApp template or VM. # @param [String] key Key of the metadata. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VAppTemplateMetadataItem-metadata.html # @since vCloud API version 1.5 def get_vapp_template_metadata_item_metadata(id, key) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/metadata/#{URI.escape(key)})" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_metadata.rb0000644000004100000410000000166412261242552025420 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve metadata associated with the vApp or VM. # # @deprecated Use {#get_vapp_metadata} instead. # @todo Log deprecation warning. # # @param [String] id Object identifier of the vApp or VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VAppMetadata.html # @since vCloud API version 1.5 def get_metadata(id) require 'fog/vcloud_director/parsers/compute/metadata' request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Compute::VcloudDirector::Metadata.new, :path => "vApp/#{id}/metadata/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_network_metadata.rb0000644000004100000410000000136212261242552027164 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve metadata associated with the network. # # @param [String] id Object identifier of the network. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-NetworkMetadata.html # @since vCloud API version 1.5 def get_network_metadata(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "network/#{id}/metadata" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_clone_vapp_template.rb0000644000004100000410000000367312261242552030071 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Create a copy of a vApp template. # # The response includes a Task element. You can monitor the task to to # track the creation of the vApp template. # # @param [String] vdc_id Object identifier of the vDC. # @param [String] name Name of the new vApp template. # @param [String] source_id Object identifier of the source vApp # template. # @param [Hash] options # @option options [String] :Description Optional description. # @option options [Boolean] :IsSourceDelete Set to true to delete the # source object after the operation completes. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-CloneVAppTemplate.html # @since vCloud API version 0.9 def post_clone_vapp_template(vdc_id, name, source_id, options={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', :name => name } CloneVAppTemplateParams(attrs) { if options.key?(:Description) Description options[:Description] end Source(:href => "#{end_point}vAppTemplate/#{source_id}") if options.key?(:IsSourceDelete) IsSourceDelete options[:IsSourceDelete] end } end.to_xml request( :body => body, :expects => 201, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.cloneVAppTemplateParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vdc/#{vdc_id}/action/cloneVAppTemplate" ) end end end end end ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootfog-1.19.0/lib/fog/vcloud_director/requests/compute/get_network_connection_system_section_vapp_template.rbfog-1.19.0/lib/fog/vcloud_director/requests/compute/get_network_connection_system_section_vapp_templ0000644000004100000410000000150412261242552034516 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the network connection section of a VM. # # @param [String] id The object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-NetworkConnectionSystemSection-vAppTemplate.html # @since vCloud API version 0.9 def get_network_connection_system_section_vapp_template(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/networkConnectionSection/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_groups_from_query.rb0000644000004100000410000001124412261242552027422 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves a list of groups for organization the org admin belongs to # by using REST API general QueryHandler. # # @param [Hash] options # @option options [String] :sortAsc (Sorted by database ID) Sort # results by attribute-name in ascending order. attribute-name cannot # include metadata. # @option options [String] :sortDesc (Sorted by database ID) Sort # results by attribute-name in descending order. attribute-name # cannot include metadata. # @option options [Integer] :page (1) If the query results span # multiple pages, return this page. # @option options [Integer] :pageSize (25) Number of results per page, # to a maximum of 128. # @option options [String] :format (records) One of the following # types: # - *references* Returns a reference to each object, including its # :name, :type, and :href attributes. # - *records* Returns all database records for each object, with each # record as an attribute. # - *idrecords* Identical to the records format, except that object # references are returned in :id format rather than :href format. # @option options [Array] :fields (all static attribute names) # List of attribute names or metadata key names to return. # @option options [Integer] :offset (0) Integer value specifying the # first record to return. Record numbers < offset are not returned. # @option options [String] :filter (none) Filter expression. # @return [Excon::Response] # * hash<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :name<~String> - Query name that generated this result set. # * :page<~String> - Page of the result set that this container # holds. The first page is page number 1. # * :pageSize<~String> - Page size, as a number of records or # references. # * :total<~String> - Total number of records or references in the # container. # * :Link<~Array>: # * :href<~String> - Contains the URI to the entity. # * :type<~String> - Contains the type of the entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # * :GroupRecord<~Array>: # * TODO # * :firstPage<~Integer> - First page in the result set. # * :previousPage<~Integer> - Previous page in the result set. # * :nextPage<~Integer> - Next page in the result set. # * :lastPage<~Integer> - Last page in the result set. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-GroupsFromQuery.html # @since vCloud API version 1.5 def get_groups_from_query(options={}) query = [] query << "sortAsc=#{options[:sortAsc]}" if options[:sortAsc] query << "sortDesc=#{options[:sortDesc]}" if options[:sortDesc] query << "page=#{options[:page]}" if options[:page] query << "pageSize=#{options[:pageSize]}" if options[:pageSize] query << "format=#{options[:format]}" if options[:format] query << "fields=#{Array(options[:fields]).join(',')}" if options[:fields] query << "offset=#{options[:offset]}" if options[:offset] query << "filter=#{options[:filter]}" if options[:filter] response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'admin/groups/query', :query => query.map {|q| URI.escape(q)}.join('&') ) ensure_list! response.body, :Link ensure_list! response.body, response.body[:type] == 'application/vnd.vmware.vcloud.query.references+xml' ? :GroupReference : :GroupRecord %w[firstPage previousPage nextPage lastPage].each do |rel| if link = response.body[:Link].detect {|l| l[:rel] == rel} href = Nokogiri::XML.fragment(link[:href]) query = CGI.parse(URI.parse(href.text).query) response.body[rel.to_sym] = query['page'].first.to_i response.body[:pageSize] ||= query['pageSize'].first.to_i end end response end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_control_access_params_catalog.rb0000644000004100000410000000156312261242552031674 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve access control information for a catalog. # # @param [String] id Object identifier of the organization. # @param [String] catalog_id Object identifier of the catalog. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-ControlAccessParams-vApp.html # @since vCloud API 0.9 def get_control_access_params_catalog(id, catalog_id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "org/#{id}/catalog/#{catalog_id}/controlAccess" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_org_settings.rb0000644000004100000410000000254612261242552026347 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve settings for this organization. # # Organization settings are divided into categories. This request # retrieves all categories of organization settings. # # @param [String] id Object identitifier of the organization. # @return [Excon:Response] # * body<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :OrgGeneralSettings<~Hash>: # * :VAppLeaseSettings<~Hash>: # * :VAppTemplateLeaseSettings<~Hash>: # * :OrgLdapSettings<~Hash>: # * :OrgEmailSettings<~Hash>: # * :OrgPasswordPolicySettings<~Hash>: # * :OrgOperationLimitsSettings<~Hash>: # * :OrgFederationSettings<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-OrgSettings.html # @since vCloud API version 0.9 def get_org_settings(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "admin/org/#{id}/settings" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_catalog_metadata.rb0000644000004100000410000000134212261242552027103 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve all catalog metadata. # # @param [String] id Object identifier of the catalog. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-CatalogMetadata.html # @since vCloud API version 1.5 def get_catalog_metadata(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "catalog/#{id}/metadata" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_lease_settings_section_vapp.rb0000644000004100000410000000141612261242552031416 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves the lease settings section of a vApp. # # @param [String] id Object identifier of the vApp. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-LeaseSettingsSection-vApp.html # @since vCloud API version 1.0 def get_lease_settings_section_vapp(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/leaseSettingsSection" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_media_drives_rasd_items_list.rb0000644000004100000410000000153212261242552031532 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve all RASD items that specify CD-ROM, DVD, and floppy disk # device and controller properties of a VM. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-MediaDrivesRasdItemsList.html # @since vCloud API version 0.9 def get_media_drives_rasd_items_list(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/virtualHardwareSection/media" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_organizations_from_query.rb0000644000004100000410000001124212261242552030770 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves a list of organizations by using REST API general # QueryHandler. # # @param [Hash] options # @option options [String] :sortAsc (Sorted by database ID) Sort # results by attribute-name in ascending order. attribute-name cannot # include metadata. # @option options [String] :sortDesc (Sorted by database ID) Sort # results by attribute-name in descending order. attribute-name # cannot include metadata. # @option options [Integer] :page (1) If the query results span # multiple pages, return this page. # @option options [Integer] :pageSize (25) Number of results per page, # to a maximum of 128. # @option options [String] :format (records) One of the following # types: # - *references* Returns a reference to each object, including its # :name, :type, and :href attributes. # - *records* Returns all database records for each object, with each # record as an attribute. # - *idrecords* Identical to the records format, except that object # references are returned in :id format rather than :href format. # @option options [Array] :fields (all static attribute names) # List of attribute names or metadata key names to return. # @option options [Integer] :offset (0) Integer value specifying the # first record to return. Record numbers < offset are not returned. # @option options [String] :filter (none) Filter expression. # @return [Excon::Response] # * hash<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :name<~String> - Query name that generated this result set. # * :page<~String> - Page of the result set that this container # holds. The first page is page number 1. # * :pageSize<~String> - Page size, as a number of records or # references. # * :total<~String> - Total number of records or references in the # container. # * :Link<~Array>: # * :href<~String> - Contains the URI to the entity. # * :type<~String> - Contains the type of the entity. # * :rel<~String> - Defines the relationship of the link to the # object that contains it. # * :OrganizationRecord<~Array>: # * TODO # * :firstPage<~Integer> - First page in the result set. # * :previousPage<~Integer> - Previous page in the result set. # * :nextPage<~Integer> - Next page in the result set. # * :lastPage<~Integer> - Last page in the result set. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-OrganizationsFromQuery.html # @since vCloud API version 1.5 def get_organizations_from_query(options={}) query = [] query << "sortAsc=#{options[:sortAsc]}" if options[:sortAsc] query << "sortDesc=#{options[:sortDesc]}" if options[:sortDesc] query << "page=#{options[:page]}" if options[:page] query << "pageSize=#{options[:pageSize]}" if options[:pageSize] query << "format=#{options[:format]}" if options[:format] query << "fields=#{Array(options[:fields]).join(',')}" if options[:fields] query << "offset=#{options[:offset]}" if options[:offset] query << "filter=#{options[:filter]}" if options[:filter] response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'admin/orgs/query', :query => query.map {|q| URI.escape(q)}.join('&') ) ensure_list! response.body, :Link ensure_list! response.body, response.body[:type] == 'application/vnd.vmware.vcloud.query.references+xml' ? :OrganizationReference : :OrganizationRecord %w[firstPage previousPage nextPage lastPage].each do |rel| if link = response.body[:Link].detect {|l| l[:rel] == rel} href = Nokogiri::XML.fragment(link[:href]) query = CGI.parse(URI.parse(href.text).query) response.body[rel.to_sym] = query['page'].first.to_i response.body[:pageSize] ||= query['pageSize'].first.to_i end end response end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vapp_template_ovf_descriptor.rb0000644000004100000410000000136112261242552031603 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the OVF descriptor of a vApp template. # # @param [String] id Object identifier of the vAppTemplate. # @return [Excon::Response] # * body<~String> - the OVF descriptor. # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VAppTemplateOvfDescriptor.html # @since vCloud API version 0.9 def get_vapp_template_ovf_descriptor(id) request( :expects => 200, :idempotent => true, :method => 'GET', :path => "vAppTemplate/#{id}/ovf" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_update_catalog_item_metadata.rb0000644000004100000410000000362012261242552031672 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Merge the metadata provided in the request with existing catalog item metadata. # # @param [String] id Object identifier of the catalog item. # @param [Hash{String=>Boolean,DateTime,Fixnum,String}] metadata # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-UpdateCatalogItemMetadata.html # @since vCloud API version 1.5 def post_update_catalog_item_metadata(id, metadata={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance' } Metadata(attrs) { metadata.each do |key, value| MetadataEntry { Key key if api_version.to_f < 5.1 Value value else type = case value when TrueClass, FalseClass then 'MetadataBooleanValue'; when DateTime then 'MetadataDateTimeValue'; when Fixnum then 'MetadataNumberValue'; else 'MetadataStringValue' end TypedValue('xsi:type' => type) { Value value } end } end } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.metadata+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "catalogItem/#{id}/metadata/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vm_compliance_results.rb0000644000004100000410000000132012261242552030222 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the results of a compliance check. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VmComplianceResults.html def get_vm_compliance_results(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/complianceResult" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/put_vm.rb0000644000004100000410000000255512261242552024313 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/generators/compute/vm' # Update the name, description and storage profile for VM. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @param [String] name of the VM. # @param [Hash] options # * :Description<~String>: - description to be assigned. # * :StorageProfile<~Hash>: - storage profile to be assigned. # * :name<~String> # * :href<~String> # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/PUT-Vm.html # @since vCloud API version 0.9 def put_vm(id, name, options) body = Fog::Generators::Compute::VcloudDirector::Vm.new(options.merge(:name => name)).generate_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.vm+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_catalog_item_metadata_item_metadata.rb0000644000004100000410000000160012261242552032774 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the value of the specified key from catalog item metadata. # # @param [String] id Object identifier of the catalog item. # @param [String] key Key of the metadata. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-CatalogItemMetadataItem-metadata.html # @since vCloud API version 1.5 def get_catalog_item_metadata_item_metadata(id, key) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "catalogItem/#{id}/metadata/#{URI.escape(key)})" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_organization_metadata.rb0000644000004100000410000000140212261242552030172 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve metadata associated with the organization. # # @param [String] id Object identifier of the organization. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-OrganizationMetadata.html # @since vCloud API version 1.5 def get_organization_metadata(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "org/#{id}/metadata" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_clone_vapp.rb0000644000004100000410000000466412261242552026177 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Create a copy of a vApp. # # The response includes a Task element. You can monitor the task to to # track the creation of the vApp template. # # @param [String] vdc_id Object identifier of the vDC. # @param [String] name Name of the new vApp. # @param [String] source_id Object identifier of the source vApp. # @param [Hash] options # @option options [Boolean] :deploy True if the vApp should be deployed # at instantiation. Defaults to true. # @option options [Boolean] :powerOn True if the vApp should be # powered-on at instantiation. Defaults to true. # @option options [String] :Description Optional description. # @option options [Hash] :InstantiationParams Instantiation parameters # for the composed vApp. # @option options [Boolean] :IsSourceDelete Set to true to delete the # source object after the operation completes. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-CloneVApp.html # @since vCloud API version 0.9 def post_clone_vapp(vdc_id, name, source_id, options={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', :name => name } attrs[:deploy] = options[:deploy] if options.key?(:deploy) attrs[:powerOn] = options[:powerOn] if options.key?(:powerOn) CloneVAppParams(attrs) { if options.key?(:Description) Description options[:Description] end InstantiationParams { # TODO } Source(:href => "#{end_point}vApp/#{source_id}") if options.key?(:IsSourceDelete) IsSourceDelete options[:IsSourceDelete] end } end.to_xml request( :body => body, :expects => 201, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.cloneVAppParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vdc/#{vdc_id}/action/cloneVApp" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_network_connection_system_section_vapp.rb0000644000004100000410000000145312261242552033722 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the network connection section of a VM. # # @param [String] id The object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-NetworkConnectionSystemSection-vApp.html # @since vCloud API version 0.9 def get_network_connection_system_section_vapp(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/networkConnectionSection/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_guest_customization_system_section_vapp.rb0000644000004100000410000000145312261242552034131 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieves the guest customization section of a VM. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-GuestCustomizationSystemSection-vApp.html # @since vCloud API version 1.0 def get_guest_customization_system_section_vapp(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/guestCustomizationSection" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_organization_metadata_item_metadata.rb0000644000004100000410000000173312261242552033057 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the value of the specified key in the specified domain from # organization metadata. # # @param [String] id Object identifier of the network. # @param [String] domain # @param [String] key Key of the metadata. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-OrganizationMetadataItem-metadata.html # @since vCloud API version 5.1 def get_organization_metadata_item_metadata(id, domain, key) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "admin/org/#{id}/metadata/#{URI.escape(domain)}/#{URI.escape(key)})" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_disable_nested_hv.rb0000644000004100000410000000155412261242552027506 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Hide hardware-assisted CPU virtualization from guest OS. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-DisableNestedHv.html # @since vCloud API version 5.1 def post_disable_nested_hv(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/action/disableNestedHypervisor" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/put_vapp_name_and_description.rb0000644000004100000410000000242512261242552031060 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/generators/compute/vapp' # Modify the name or description of a vApp. # # This operation is asynchronous and returns a task that you can monitor # to track the progress of the request. # # # @param [String] id Object identifier of the vApp. # @param [String] name of the vApp. # @param [Hash] options # * :Description<~String>: - description to be assigned (optional) # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-55/topic/com.vmware.vcloud.api.reference.doc_55/doc/operations/PUT-VAppNameAndDescription.html # @since vCloud API version 0.9 def put_vapp_name_and_description(id, name, options={}) body = Fog::Generators::Compute::VcloudDirector::Vapp.new(name, options).generate_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.vApp+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/delete_shadow_vm.rb0000644000004100000410000000164012261242552026304 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Deletes shadow VM. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @deprecated Since vCloud API version 5.1 this operation may be # removed in a future release. # # @param [String] id Object identifier of the vApp. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/DELETE-ShadowVm.html # @since vCloud API version 1.5 def delete_shadow_vm(id) request( :expects => 202, :method => 'DELETE', :parser => Fog::ToHashDocument.new, :path => "shadowVm/#{id}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_acquire_ticket.rb0000644000004100000410000000154512261242552027040 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a screen ticket that you can use with the VMRC browser # plug-in to gain access to the console of a running VM. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::Conflict] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-AcquireTicket.html # @since vCloud API version 0.9 def post_acquire_ticket(id) request( :expects => 200, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/screen/action/acquireTicket" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vdc_metadata.rb0000644000004100000410000000133512261242552026247 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve metadata associated with a vDC. # # @param [String] id Object identifier of the vDC. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VdcMetadata.html # @since vCloud API version 1.5 def get_vdc_metadata(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vdc/#{id}/metadata/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_power_on_vapp.rb0000644000004100000410000000224412261242552026717 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :post_vm_poweron, :post_power_on_vapp # Power on a vApp or VM. # # If used on a vApp, powers on all VMs in the vApp. If used on a VM, # powers on the VM. This operation is available only for a vApp or VM # that is powered off. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the vApp or VM. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::BadRequest] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-PowerOnVApp.html # @since vCloud API version 0.9 def post_power_on_vapp(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/power/action/powerOn" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_disable_vapp_template_download.rb0000644000004100000410000000134712261242552032257 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Disable a vApp template for download. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-DisableVAppTemplateDownload.html # @since vCloud API version 0.9 def post_disable_vapp_template_download(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/action/disableDownload" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vm_network.rb0000644000004100000410000000177212261242552026033 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/parsers/compute/vm_network' # Retrieve the network connection section of a VM. # # @deprecated Use {#get_network_connection_system_section_vapp} # instead. # @todo Log deprecation warning. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-NetworkConnectionSystemSection-vApp.html # @since vCloud API version 0.9 def get_vm_network(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Compute::VcloudDirector::VmNetwork.new, :path => "vApp/#{id}/networkConnectionSection/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/delete_media_metadata_item_metadata.rb0000644000004100000410000000151412261242552032112 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Delete the specified key and its value from media object metadata. # # @param [String] id Object identifier of the media object. # @param [String] key Key of the metadata item. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/DELETE-MediaMetadataItem-metadata.html # @since vCloud API version 1.5 def delete_media_metadata_item_metadata(id, key) request( :expects => 202, :method => 'DELETE', :parser => Fog::ToHashDocument.new, :path => "media/#{id}/metadata/#{URI.escape(key)}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/delete_vapp.rb0000644000004100000410000000153712261242552025270 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Delete a vApp or VM. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the vApp. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::BadRequest] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/DELETE-VApp.html # @since vCloud API version 0.9 def delete_vapp(id) request( :expects => 202, :method => 'DELETE', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_update_vapp_template_metadata.rb0000644000004100000410000000360712261242552032110 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Merge the metadata provided in the request with existing metadata. # # @param [String] id Object identifier of the vApp template. # @param [Hash{String=>Boolean,DateTime,Fixnum,String}] metadata # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-UpdateVAppTemplateMetadata.html # @since vCloud API version 1.5 def post_update_vapp_template_metadata(id, metadata={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance' } Metadata(attrs) { metadata.each do |key, value| MetadataEntry { Key key if api_version.to_f < 5.1 Value value else type = case value when TrueClass, FalseClass then 'MetadataBooleanValue'; when DateTime then 'MetadataDateTimeValue'; when Fixnum then 'MetadataNumberValue'; else 'MetadataStringValue' end TypedValue('xsi:type' => type) { Value value } end } end } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.metadata+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vAppTemplate/#{id}/metadata/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_configure_edge_gateway_services.rb0000644000004100000410000000533712261242552032440 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/generators/compute/edge_gateway_service_configuration' # Configure edge gateway services like firewall, nat and load balancer. # # The response includes a Task element. You can monitor the task to # track the configuration of edge gateway services. # # @param [String] id Object identifier of the edge gateway. # @param [Hash] configuration # @configuration firewall_service [Hash] - configurations for firewall service. # @configuration nat_service [Hash] - configurations for NAT network service. # @configuration load_balancer_service [Hash] - configurations for load balancer service # @return [Excon::Response] # * body<~Hash>: # @see https://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-ConfigureEdgeGatewayServices.html # vCloud API Documentaion # @since vCloud API version 5.1 def post_configure_edge_gateway_services(id, configuration) body = Fog::Generators::Compute::VcloudDirector::EdgeGatewayServiceConfiguration.new(configuration).generate_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.admin.edgeGatewayServiceConfiguration+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "admin/edgeGateway/#{id}/action/configureServices" ) end end class Mock def post_configure_edge_gateway_services(id, configuration) unless data[:edge_gateways][id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.edgegateway:#{id})\"." ) end owner = {:href => '', :name => nil, :type => nil} #known-bug: admin-api does not return owner. task_id = enqueue_task( "Configuring edgegateway(#{id})", 'networkConfigureEdgeGatewayServices', owner, :on_success => lambda do data[:edge_gateways][id][:Configuration][:EdgeGatewayServiceConfiguration] = configuration end ) body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location, }.merge(task_body(task_id)) Excon::Response.new( :status => 202, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/delete_disk_metadata_item_metadata.rb0000644000004100000410000000147112261242552031767 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Delete the specified key and its value from disk metadata. # # @param [String] id Object identifier of the disk. # @param [String] key Key of the metadata item. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/DELETE-DiskMetadataItem-metadata.html # @since vCloud API version 5.1 def delete_disk_metadata_item_metadata(id, key) request( :expects => 202, :method => 'DELETE', :parser => Fog::ToHashDocument.new, :path => "disk/#{id}/metadata/#{URI.escape(key)}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/delete_media.rb0000644000004100000410000001316212261242552025376 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Delete a media object. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the media object. # @return [Excon::Response] # * body<~Hash>: # * :href<~String> - The URI of the entity. # * :type<~String> - The MIME type of the entity. # * :id<~String> - The entity identifier, expressed in URN format. # The value of this attribute uniquely identifies the entity, # persists for the life of the entity, and is never reused. # * :operationKey<~String> - Optional unique identifier to support # idempotent semantics for create and delete operations. # * :name<~String> - The name of the entity. # * :cancelRequested<~String> - Whether user has requested this # processing to be canceled. # * :endTime<~String> - The date and time that processing of the # task was completed. May not be present if the task is still # being executed. # * :expiryTime<~String> - The date and time at which the task # resource will be destroyed and no longer available for # retrieval. May not be present if the task has not been executed # or is still being executed. # * :operation<~String> - A message describing the operation that # is tracked by this task. # * :operationName<~String> - The short name of the operation that # is tracked by this task. # * :serviceNamespace<~String> - Identifier of the service that # created the task. # * :startTime<~String> - The date and time the system started # executing the task. May not be present if the task has not been # executed yet. # * :status<~String> - The execution status of the task. # * :Link<~Array>: # * :Description<~String> - Optional description. # * :Owner<~Hash> - Reference to the owner of the task. This is # typically the object that the task is creating or updating. # * :href<~String> - Contains the URI to the entity. # * :name<~String> - Contains the name of the entity. # * :type<~String> - Contains the type of the entity. # * :Error<~Hash> - Represents error information from a failed # task. # * :majorErrorCode<~String> - The class of the error. Matches # the HTTP status code. # * :message<~String> - An one line, human-readable message # describing the error that occurred. # * :minorErrorCode<~String> - Resource-specific error code. # * :stackTrace<~String> - The stack trace of the exception. # * :vendorSpecificErrorCode<~String> - A vendor- or # implementation-specific error code that can reference # specific modules or source lines for diagnostic purposes. # * :User<~Hash> - The user who started the task. # * :href<~String> - Contains the URI to the entity. # * :name<~String> - Contains the name of the entity. # * :type<~String> - Contains the type of the entity. # * :Organization<~Hash> - The organization to which the :User # belongs. # * :href<~String> - Contains the URI to the entity. # * :name<~String> - Contains the name of the entity. # * :type<~String> - Contains the type of the entity. # * :Progress<~String> - Read-only indicator of task progress as # an approximate percentage between 0 and 100. Not available # for all tasks. # * :Params # * :Details<~String> - Detailed message about the task. Also # contained by the :Owner entity when task status is # preRunning. # # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/DELETE-Media.html # @since vCloud API version 0.9 def delete_media(id) request( :expects => 202, :method => 'DELETE', :parser => Fog::ToHashDocument.new, :path => "media/#{id}" ) end end class Mock def delete_media(id) unless media = data[:medias][id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.media:#{id})\"" ) end owner = { :href => make_href("media/#{id}"), :type => 'application/vnd.vmware.vcloud.media+xml' } task_id = enqueue_task( "Deleting Media File(#{media[:file][:uuid]})", 'vdcDeleteMedia', owner, :on_success => lambda do data[:medias].delete(id) end ) body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location, }.merge(task_body(task_id)) Excon::Response.new( :status => 202, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_memory_rasd_item.rb0000644000004100000410000000155112261242552027172 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :get_vm_memory, :get_memory_rasd_item # Retrieve the RASD item that specifies memory properties of a VM. # # @param [String] id Object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-MemoryRasdItem.html # @since vCloud API version 0.9 def get_memory_rasd_item(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/virtualHardwareSection/memory" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_operating_system_section.rb0000644000004100000410000000141412261242552030751 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the operating system section of a VM. # # @param [String] id The object identifier of the VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-OperatingSystemSection.html # @since vCloud API version 0.9 def get_operating_system_section(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/operatingSystemSection/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_revert_snapshot.rb0000644000004100000410000000161012261242552027263 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Reverts a vApp or virtual machine to the current snapshot, if any. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the vApp or virtual machine. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-RevertSnapshot.html # @since vCloud API version 5.1 def post_revert_snapshot(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/action/revertToCurrentSnapshot" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_discard_vapp_state.rb0000644000004100000410000000174012261242552027700 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Discard suspended state of a vApp or VM. # # Discarding the suspended state of a vApp discards the suspended state # of all VMs it contains. # # This operation is asynchronous and returns a task that you can # monitor to track the progress of the request. # # @param [String] id Object identifier of the vApp or VM. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-DiscardVAppState.html # @since vCloud API version 0.9 def post_discard_vapp_state(id) request( :expects => 202, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/action/discardSuspendedState" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_disk_owner.rb0000644000004100000410000000436112261242552026001 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve the owner of a disk. # # @param [String] id Object identifier of the disk. # @return [Excon::Response] # * body<~Hash>: # * :href<~String> - The URI of the disk. # * :type<~String> - The MIME type of the disk. # * :Link<~Hash>: # * :href<~String> - # * :type<~String> - # * :rel<~String> - # * :User<~Hash> - Reference to the user who is the owner of this # disk. # * :href<~String> - The URI of the user. # * :name<~String> - The name of the user. # * :type<~String> - The MIME type of the user. # # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-DiskOwner.html # @since vCloud API version 5.1 def get_disk_owner(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "disk/#{id}/owner" ) end end class Mock def get_disk_owner(id) unless data[:disks][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'No access to entity "com.vmware.vcloud.entity.disk:%s".' % id ) end body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location, :Link => { :href => make_href("disk/#{id}"), :type => 'application/vnd.vmware.vcloud.disk+xml', :rel => 'up' }, :User => { :href => make_href("admin/user/#{user_uuid}"), :name => user_name, :type => 'application/vnd.vmware.admin.user+xml', } } Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{@version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_edge_gateway.rb0000644000004100000410000001070512261242552026261 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve an edge gateway. # # @param [String] id Object identifier of the edge gateway. # @return [Excon::Response] # * body<~Hash>: # # @raise [Fog::Compute::VcloudDirector::Forbidden] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-EdgeGateway.html # @since vCloud API version 5.1 def get_edge_gateway(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "admin/edgeGateway/#{id}" ) ensure_list! response.body[:Configuration], :GatewayInterfaces, :GatewayInterface edge_gateway_service_configuration = response.body[:Configuration][:EdgeGatewayServiceConfiguration] ensure_list! edge_gateway_service_configuration[:FirewallService], :FirewallRule if edge_gateway_service_configuration[:FirewallService] ensure_list! edge_gateway_service_configuration[:NatService], :NatRule if edge_gateway_service_configuration[:NatService] if edge_gateway_service_configuration[:LoadBalancerService] ensure_list! edge_gateway_service_configuration[:LoadBalancerService], :Pool edge_gateway_service_configuration[:LoadBalancerService][:Pool].each do |pool| ensure_list! pool, :ServicePort ensure_list! pool, :Member pool[:Member].each do |member| ensure_list! member, :ServicePort end end ensure_list! edge_gateway_service_configuration[:LoadBalancerService], :VirtualServer edge_gateway_service_configuration[:LoadBalancerService][:VirtualServer].each do |virtual_server| ensure_list! virtual_server, :ServiceProfile end end response end end class Mock def get_edge_gateway(id) unless edge_gateway = data[:edge_gateways][id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.gateway:#{id})\"" ) end vdc_id = edge_gateway[:vdc] body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :status => "1", :name => edge_gateway[:name], :id => "urn:vcloud:gateway:#{id}", :type => "application/vnd.vmware.admin.edgeGateway+xml", :href => make_href("admin/edgeGateway/#{id}"), :xsi_schemaLocation => xsi_schema_location, :Link =>[{:rel => "up", :type => "application/vnd.vmware.vcloud.vdc+xml", :href => make_href("vdc/#{vdc_id}")}, {:rel => "edgeGateway:redeploy", :href => make_href("admin/edgeGateway/#{id}/action/redeploy")}, {:rel => "edgeGateway:configureServices", :type => "application/vnd.vmware.admin.edgeGatewayServiceConfiguration+xml", :href => make_href("admin/edgeGateway/#{id}/action/configureServices")}, {:rel => "edgeGateway:reapplyServices", :href => make_href("admin/edgeGateway/#{id}/action/reapplyServices")}, {:rel => "edgeGateway:syncSyslogSettings", :href => make_href("admin/edgeGateway/#{id}/action/syncSyslogServerSettings")}], :Description => "vCloud CI (nft00052i2)", :Configuration => edge_gateway[:Configuration].dup } body[:Configuration][:GatewayInterfaces][:GatewayInterface] += edge_gateway[:networks].map do |network| extras = { :Network => { :type => "application/vnd.vmware.admin.network+xml", :name => "anything", :href => make_href("admin/network/#{network}") }, :Name => data[:networks][network][:name], :DisplayName => data[:networks][network][:name] } data[:networks][network].merge extras end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_vdc_storage_class_metadata.rb0000644000004100000410000000156512261242552031165 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real extend Fog::Deprecation deprecate :get_vdc_storage_profile_metadata, :get_vdc_storage_class_metadata # Retrieve metadata associated with the vDC storage profile. # # @param [String] id Object identifier of the vDC storage profile. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-VdcStorageClassMetadata.html def get_vdc_storage_class_metadata(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "vdcStorageProfile/#{id}/metadata/" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/post_enter_maintenance_mode.rb0000644000004100000410000000156712261242552030533 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Place the vApp in maintenance mode. # # When a vApp is in maintenance mode, it is read-only to users. Only a # system administrator can modify it. User-initiated tasks that are # running when the vApp enters maintenance mode continue to run. # # @param [String] id Object identifier of the vApp. # @return [Excon::Response] # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-EnterMaintenanceMode.html # @since vCloud API version 1.5 def post_enter_maintenance_mode(id) request( :expects => 204, :method => 'POST', :path => "vApp/#{id}/action/enterMaintenanceMode" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/put_vapp_template_metadata_item_metadata.rb0000644000004100000410000000356212261242552033247 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Set the value for the specified metadata key to the value provided, # overwriting any existing value. # # @param [String] id Object identifier of the vApp template. # @param [String] key Key of the metadata item. # @param [Boolean,DateTime,Fixnum,String] value Value of the metadata # item. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/PUT-VAppTemplateMetadataItem-metadata.html # @since vCloud API version 1.5 def put_vapp_template_metadata_item_metadata(id, key, value) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance' } MetadataValue(attrs) { if api_version.to_f < 5.1 Value value else type = case value when TrueClass, FalseClass then 'MetadataBooleanValue'; when DateTime then 'MetadataDateTimeValue'; when Fixnum then 'MetadataNumberValue'; else 'MetadataStringValue' end TypedValue('xsi:type' => type) { Value value } end } end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.metadata.value+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "vappTemplate/#{id}/metadata/#{URI.escape(key)}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/delete_catalog_item_metadata_item_metadata.rb0000644000004100000410000000153712261242552033470 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Delete the specified key and its value from catalog item metadata. # # @param [String] id Object identifier of the catalog item. # @param [String] key Key of the metadata item. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/DELETE-CatalogItemMetadataItem-metadata.html # @since vCloud API version 1.5 def delete_catalog_item_metadata_item_metadata(id, key) request( :expects => 202, :method => 'DELETE', :parser => Fog::ToHashDocument.new, :path => "catalogItem/#{id}/metadata/#{URI.escape(key)}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/requests/compute/get_catalog_item.rb0000644000004100000410000000132412261242552026261 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Retrieve a catalog item. # # @param [String] id Object identifier of the catalog item. # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-CatalogItem.html # @since vCloud API version 0.9 def get_catalog_item(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "catalogItem/#{id}" ) end end end end end fog-1.19.0/lib/fog/vcloud_director/parsers/0000755000004100000410000000000012261242552020575 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud_director/parsers/compute/0000755000004100000410000000000012261242552022251 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud_director/parsers/compute/metadata.rb0000644000004100000410000000661212261242552024363 0ustar www-datawww-datamodule Fog module Parsers module Compute module VcloudDirector # # # # # # # # # buenas si # no tanto ya # # # # # # hola # adios # # # # {:metadata=>{"buenas si"=>"no tanto ya", "hola"=>"adios"}, # :type=>"application/vnd.vmware.vcloud.metadata+xml", # :href=> # "https://example.com/api/vApp/vm-18545e82-d919-4071-ae7e-d1300d9d8112/metadata", # :id=>"vm-18545e82-d919-4071-ae7e-d1300d9d8112"} # class Metadata < VcloudDirectorParser def reset @response = { :metadata => {} } end def start_element(name, attributes) super case name when 'Metadata' metadata = extract_attributes(attributes) @response[:type] = metadata[:type] @response[:href] = metadata[:href] @response[:id] = @response[:href].split('/')[-2] end end def end_element(name) case name when 'Key' @key = value when 'Value' @val = value when 'MetadataEntry' @response[:metadata].merge!(Hash[@key, @val]) end end end end end end end fog-1.19.0/lib/fog/vcloud_director/parsers/compute/network.rb0000644000004100000410000001103712261242552024271 0ustar www-datawww-datamodule Fog module Parsers module Compute module VcloudDirector # #{:xmlns=>"http://www.vmware.com/vcloud/v1.5", # :xmlns_xsi=>"http://www.w3.org/2001/XMLSchema-instance", # :name=>"DevOps - Dev Network Connection", # :id=>"urn:vcloud:network:d5f47bbf-de27-4cf5-aaaa-56772f2ccd17", # :type=>"application/vnd.vmware.vcloud.orgNetwork+xml", # :href=> # "https://example.com/api/network/d5f47bbf-de27-4cf5-aaaa-56772f2ccd17", # :xsi_schemaLocation=> # "http://www.vmware.com/vcloud/v1.5 http://10.194.1.65/api/v1.5/schema/master.xsd", # :Link=> # [{:rel=>"up", # :type=>"application/vnd.vmware.vcloud.org+xml", # :name=>"DevOps", # :href=> # "https://example.com/api/org/c6a4c623-c158-41cf-a87a-dbc1637ad55a"}, # {:rel=>"down", # :type=>"application/vnd.vmware.vcloud.metadata+xml", # :href=> # "https://example.com/api/network/d5f47bbf-de27-4cf5-aaaa-56772f2ccd17/metadata"}], # :Description=>"", # :Configuration=> # {:IpScope=> # {:IsInherited=>"true", # :Gateway=>"10.192.0.1", # :Netmask=>"255.255.252.0", # :Dns1=>"10.192.0.11", # :Dns2=>"10.192.0.12", # :DnsSuffix=>"dev.ad.mdsol.com", # :IpRanges=> # {:IpRange=> # {:StartAddress=>"10.192.0.100", :EndAddress=>"10.192.3.254"}}}, # :FenceMode=>"bridged", # :RetainNetInfoAcrossDeployments=>"false"}} # # # # # # # # # true # 10.192.0.1 # 255.255.252.0 # 10.192.0.11 # 10.192.0.12 # dev.ad.mdsol.com # # # 10.192.0.100 # 10.192.3.254 # # # # bridged # false # # # class Network < VcloudDirectorParser def reset @response = { :ip_ranges => [] } @ip_range = {} end def start_element(name, attributes) super case name when 'OrgNetwork', 'OrgVdcNetwork' # OrgVdcNetwork belongs to 5.1 network = extract_attributes(attributes) @response.merge!(network.reject {|key,value| ![:href, :name, :type].include?(key)}) @response[:id] = @response[:href].split('/').last when 'Description', @response[:description] = value end end def end_element(name) case name when 'IsInherited' @response[:is_inherited] = (value == "true") when 'Gateway', 'Netmask', 'Dns1', 'Dns2' @response[name.downcase.to_sym] = value when 'DnsSuffix' @response[:dns_suffix] = value when 'StartAddress' @ip_range[:start_address] = value when 'EndAddress' @ip_range[:end_address] = value when 'IpRange' @response[:ip_ranges] << @ip_range @ip_range = {} end end end end end end end fog-1.19.0/lib/fog/vcloud_director/parsers/compute/vms_by_metadata.rb0000644000004100000410000000276212261242552025744 0ustar www-datawww-datamodule Fog module Parsers module Compute module VcloudDirector class VmsByMetadata < VcloudDirectorParser def reset @response = { :vm_records => [] } end def start_element(name, attributes) super case name when 'QueryResultRecords' results = extract_attributes(attributes) @response[:type] = results[:type] @response[:href] = results[:href] @response[:total] = results[:total].to_i # href "https://devlab.mdsol.com/api/vms/query?page=1&pageSize=25&format=records&filter=metadata:unoo==STRING:janderr&fields=name,containerName" key = @response[:href].scan(/filter=metadata:(.*)==STRING/).flatten.first value = @response[:href].scan(/STRING:(.*)&?/).flatten.first @response[:id] = "#{key}:#{value}" when 'VMRecord' results = extract_attributes(attributes) results[:id] = results[:href].split('/').last results[:vapp_name] = results.delete(:containerName) results[:vapp_id] = results.delete(:container).split('/').last results[:cpu] = results.delete(:numberOfCpus) results[:memory] = results.delete(:memoryMB) results[:type] = "application/vnd.vmware.vcloud.vm+xml" @response[:vm_records] << results end end end end end end end fog-1.19.0/lib/fog/vcloud_director/parsers/compute/vm_customization.rb0000644000004100000410000000375612261242552026223 0ustar www-datawww-datamodule Fog module Parsers module Compute module VcloudDirector class VmCustomization < VcloudDirectorParser def reset @response = { } end def start_element(name, attributes) super case name when 'GuestCustomizationSection' customizations = extract_attributes(attributes) @response[:href] = customizations[:href] @response[:type] = customizations[:type] # href looks like this: # "https://example.com/api/vApp/vm-2bbbf556-55dc-4974-82e6-aa6e814f0b64/guestCustomizationSection/" @response[:id] = @response[:href].split('/')[-2] end end def end_element(name) case name when 'Enabled' @response[:enabled] = (value == "true") when 'ChangeSid' @response[:change_sid] = (value == "true") when 'JoinDomainEnabled' @response[:join_domain_enabled] = (value == "true") when 'UseOrgSettings' @response[:use_org_settings] = (value == "true") when 'AdminPassword' @response[:admin_password] = value when 'AdminPasswordEnabled' @response[:admin_password_enabled] = (value == "true") when 'AdminPasswordAuto' @response[:admin_password_auto] = (value == "true") when 'ResetPasswordRequired' @response[:reset_password_required] = (value == "true") when 'VirtualMachineId' @response[:virtual_machine_id] = value when 'ComputerName' @response[:computer_name] = value when 'CustomizationScript' @response[:has_customization_script] = !value.empty? @response[:customization_script] = CGI::unescapeHTML(value) if @response[:has_customization_script] end end end end end end end fog-1.19.0/lib/fog/vcloud_director/parsers/compute/vm_network.rb0000644000004100000410000001145612261242552025000 0ustar www-datawww-datamodule Fog module Parsers module Compute module VcloudDirector # #{:xmlns=>"http://www.vmware.com/vcloud/v1.5", # :xmlns_xsi=>"http://www.w3.org/2001/XMLSchema-instance", # :name=>"DevOps - Dev Network Connection", # :id=>"urn:vcloud:network:d5f47bbf-de27-4cf5-aaaa-56772f2ccd17", # :type=>"application/vnd.vmware.vcloud.orgNetwork+xml", # :href=> # "https://example.com/api/network/d5f47bbf-de27-4cf5-aaaa-56772f2ccd17", # :xsi_schemaLocation=> # "http://www.vmware.com/vcloud/v1.5 http://10.194.1.65/api/v1.5/schema/master.xsd", # :Link=> # [{:rel=>"up", # :type=>"application/vnd.vmware.vcloud.org+xml", # :name=>"DevOps", # :href=> # "https://example.com/api/org/c6a4c623-c158-41cf-a87a-dbc1637ad55a"}, # {:rel=>"down", # :type=>"application/vnd.vmware.vcloud.metadata+xml", # :href=> # "https://example.com/api/network/d5f47bbf-de27-4cf5-aaaa-56772f2ccd17/metadata"}], # :Description=>"", # :Configuration=> # {:IpScope=> # {:IsInherited=>"true", # :Gateway=>"10.192.0.1", # :Netmask=>"255.255.252.0", # :Dns1=>"10.192.0.11", # :Dns2=>"10.192.0.12", # :DnsSuffix=>"dev.ad.mdsol.com", # :IpRanges=> # {:IpRange=> # {:StartAddress=>"10.192.0.100", :EndAddress=>"10.192.3.254"}}}, # :FenceMode=>"bridged", # :RetainNetInfoAcrossDeployments=>"false"}} # # # # # # # # # true # 10.192.0.1 # 255.255.252.0 # 10.192.0.11 # 10.192.0.12 # dev.ad.mdsol.com # # # 10.192.0.100 # 10.192.3.254 # # # # bridged # false # # # class VmNetwork < VcloudDirectorParser def reset @response = { } end def start_element(name, attributes) super case name when 'NetworkConnectionSection' network_connection_section = extract_attributes(attributes) @response[:type] = network_connection_section[:type] @response[:href] = network_connection_section[:href] @response[:id] = @response[:href].split('/')[-2] when 'NetworkConnection' network_connection = extract_attributes(attributes) @response[:network] = network_connection[:network] @response[:needs_customization] = ( network_connection[:needsCustomization] == "true" ) end end def end_element(name) case name when 'Info' @response[:info] = value when 'PrimaryNetworkConnectionIndex' @response[:primary_network_connection_index] = value.to_i when 'NetworkConnectionIndex' @response[:network_connection_index] = value.to_i when 'IpAddress' @response[:ip_address] = value when 'IsConnected' @response[:is_connected] = (value == "true") when 'MACAddress' @response[:mac_address] = value when 'IpAddressAllocationMode' @response[:ip_address_allocation_mode] = value end end end end end end end fog-1.19.0/lib/fog/vcloud_director/parsers/compute/vm.rb0000644000004100000410000000453512261242552023227 0ustar www-datawww-datamodule Fog module Parsers module Compute module VcloudDirector class Vm < VcloudDirectorParser def reset @in_operating_system = false @in_children = false @resource_type = nil @response = { :vm => { :ip_address => '' } } @links = [] end def start_element(name, attributes) super case name when 'OperatingSystemSection' @in_operating_system = true when 'Vm' vm_attrs = extract_attributes(attributes) @response[:vm].merge!(vm_attrs.reject {|key,value| ![:href, :name, :status, :type].include?(key)}) @response[:vm][:id] = @response[:vm][:href].split('/').last @response[:vm][:status] = human_status(@response[:vm][:status]) when 'HostResource' @current_host_resource = extract_attributes(attributes) when 'Link' @links << extract_attributes(attributes) end end def end_element(name) case name when 'IpAddress' @response[:vm][:ip_address] = value when 'Description' if @in_operating_system @response[:vm][:operating_system] = value @in_operating_system = false end when 'ResourceType' @resource_type = value when 'VirtualQuantity' case @resource_type when '3' @response[:vm][:cpu] = value when '4' @response[:vm][:memory] = value end when 'ElementName' @element_name = value when 'Item' if @resource_type == '17' # disk @response[:vm][:disks] ||= [] @response[:vm][:disks] << { @element_name => @current_host_resource[:capacity].to_i } end when 'Link' @response[:vm][:links] = @links end end def human_status(status) case status when '0', 0 'creating' when '8', 8 'off' when '4', 4 'on' else 'unknown' end end end end end end end fog-1.19.0/lib/fog/vcloud_director/parsers/compute/disks.rb0000644000004100000410000000302712261242552023715 0ustar www-datawww-datamodule Fog module Parsers module Compute module VcloudDirector class Disks < VcloudDirectorParser def reset @disk = {} @response = { :disks => [] } @host_resource = nil end def start_element(name, attributes) super case name when 'HostResource' @host_resource = extract_attributes(attributes) end end def end_element(name) case name when 'Address' @disk[:address] = value.to_i when 'AddressOnParent' @disk[:address_on_parent] = value.to_i when 'Description' @disk[:description] = value when 'ElementName' @disk[:name] = value when 'InstanceID' @disk[:id] = value.to_i when 'ResourceSubType' @disk[:resource_sub_type] = value when 'Parent' @disk[:parent] = value.to_i when 'ResourceType' @disk[:resource_type] = value.to_i when 'Item' if @host_resource @disk[:capacity] = @host_resource[:capacity].to_i @disk[:bus_sub_type] = @host_resource[:busSubType] @disk[:bus_type] = @host_resource[:busType].to_i end @response[:disks] << @disk @host_resource = nil @disk = {} end end end end end end end fog-1.19.0/lib/fog/vcloud_director/parsers/compute/vms.rb0000644000004100000410000000547112261242552023412 0ustar www-datawww-datamodule Fog module Parsers module Compute module VcloudDirector class Vms < VcloudDirectorParser def reset @vm = { :ip_address => '' } @in_operating_system = false @in_children = false @resource_type = nil @response = { :vms => [] } @links = [] end def start_element(name, attributes) super case name when 'OperatingSystemSection' @in_operating_system = true when 'VApp' vapp = extract_attributes(attributes) @response.merge!(vapp.reject {|key,value| ![:href, :name, :size, :status, :type].include?(key)}) @response[:id] = @response[:href].split('/').last when 'Vm' vapp = extract_attributes(attributes) @vm.merge!(vapp.reject {|key,value| ![:href, :name, :status, :type].include?(key)}) @vm[:id] = @vm[:href].split('/').last @vm[:vapp_id] = @response[:id] @vm[:vapp_name] = @response[:name] @vm[:status] = human_status(@vm[:status]) when 'Children' @in_children = true when 'HostResource' @current_host_resource = extract_attributes(attributes) when 'Link' @links << extract_attributes(attributes) end end def end_element(name) if @in_children case name when 'IpAddress' @vm[:ip_address] = value when 'Description' if @in_operating_system @vm[:operating_system] = value @in_operating_system = false end when 'ResourceType' @resource_type = value when 'VirtualQuantity' case @resource_type when '3' @vm[:cpu] = value when '4' @vm[:memory] = value end when 'ElementName' @element_name = value when 'Item' if @resource_type == '17' # disk @vm[:disks] ||= [] @vm[:disks] << { @element_name => @current_host_resource[:capacity].to_i } end when 'Link' @vm[:links] = @links when 'Vm' @response[:vms] << @vm @vm = {} end end end def human_status(status) case status when '0', 0 'creating' when '8', 8 'off' when '4', 4 'on' else 'unknown' end end end end end end end fog-1.19.0/lib/fog/vcloud_director/generators/0000755000004100000410000000000012261242552021267 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud_director/generators/compute/0000755000004100000410000000000012261242552022743 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud_director/generators/compute/metadata.rb0000644000004100000410000000643712261242552025062 0ustar www-datawww-datamodule Fog module Generators module Compute module VcloudDirector # {:metadata=> # {"buenas si"=>"no tanto ya", # "hola"=>"adios"}, # :type=>"application/vnd.vmware.vcloud.metadata+xml", # :href=> # "https://example.com/api/vApp/vm-18545e82-d919-4071-ae7e-d1300d9d8112/metadata", # :id=>"vm-18545e82-d919-4071-ae7e-d1300d9d8112"} # # This is what it generates: # # # # buenas si # no tanto ya # # # hola # adios # # # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/types/MetadataType.html class MetadataBase attr_reader :attrs def initialize(attrs={}) @attrs = attrs end def generate_xml output = "" output << header attrs[:metadata].each_pair do |k,v| output << metadata_entry(k,v) end output << tail output end def add_item(k,v) @attrs[:metadata].merge!(Hash[k,v]) end # 1.5 def header <<-END END end def metadata_entry raise "This is an abstract class. Use the appropriate subclass" end # 5.1 #def header # '' #end def tail <<-END END end end class MetadataV51 < MetadataBase def metadata_entry(key, value) <<-END #{key} #{value} END end end class MetadataV15 < MetadataBase def metadata_entry(key, value) <<-END #{key} #{value} END end end end end end end fog-1.19.0/lib/fog/vcloud_director/generators/compute/vm_network.rb0000644000004100000410000001135212261242552025465 0ustar www-datawww-datamodule Fog module Generators module Compute module VcloudDirector # This is the data structure it accepts, this is the output of # #get_vm_network # # {:type=>"application/vnd.vmware.vcloud.networkConnectionSection+xml", # :href=> # "https://example.com/api/vApp/vm-8b74d95a-ee91-4f46-88d8-fc92be0dbaae/networkConnectionSection/", # :id=>"vm-8b74d95a-ee91-4f46-88d8-fc92be0dbaae", # :primary_network_connection_index=>0, # :network=>"DevOps - Dev Network Connection", # :needs_customization=>true, # :network_connection_index=>0, # :ip_address=>"10.192.0.130", # :is_connected=>true, # :mac_address=>"00:50:56:01:00:8d", # :ip_address_allocation_mode=>"POOL"} # # This is what it generates: # # # Specifies the available VM network connections # 0 # # 0 # 10.192.0.130 # true # 00:50:56:01:00:8d # POOL # # # # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/types/NetworkConnectionSectionType.html class VmNetwork attr_reader :attrs def initialize(attrs={}) @attrs = attrs end def generate_xml output = "" output << header output << body(@attrs) output << tail output end def network @attrs[:network] end def network=(new_network_name) @attrs[:network] = new_network_name end def ip_address @attrs[:ip_address] end def ip_address=(new_ip_address) @attrs[:ip_address] = new_ip_address end def is_connected @attrs[:is_connected] end def is_connected=(new_is_connected) @attrs[:is_connected] = new_is_connected end def ip_address_allocation_mode @attrs[:ip_address_allocation_mode] end def ip_address_allocation_mode=(new_ip_address_allocation_mode) @attrs[:ip_address_allocation_mode] = new_ip_address_allocation_mode end private def header <<-END END end def body(opts={}) <<-END #{opts[:info]} #{opts[:primary_network_connection_index]} #{opts[:network_connection_index]} #{opts[:ip_address]} #{opts[:is_connected]} #{opts[:mac_address]} #{opts[:ip_address_allocation_mode]} END end def tail <<-END END end end end end end end fog-1.19.0/lib/fog/vcloud_director/generators/compute/org_vdc_network.rb0000644000004100000410000000730712261242552026473 0ustar www-datawww-datamodule Fog module Generators module Compute module VcloudDirector # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/types/OrgVdcNetworkType.html class OrgVdcNetwork attr_reader :options def initialize(options={}) @options = options end def generate_xml body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', :name => options[:name] } OrgVdcNetwork(attrs) { Description options[:Description] if options.key?(:Description) if configuration = options[:Configuration] Configuration { if ip_scopes = configuration[:IpScopes] IpScopes { if ip_scope = ip_scopes[:IpScope] IpScope { IsInherited ip_scope[:IsInherited] if ip_scope.key?(:IsInherited) Gateway ip_scope[:Gateway] if ip_scope.key?(:Gateway) Netmask ip_scope[:Netmask] if ip_scope.key?(:Netmask) Dns1 ip_scope[:Dns1] if ip_scope.key?(:Dns1) Dns2 ip_scope[:Dns2] if ip_scope.key?(:Dns2) DnsSuffix ip_scope[:DnsSuffix] if ip_scope.key?(:DnsSuffix) IsEnabled ip_scope[:IsEnabled] if ip_scope.key?(:IsEnabled) if ip_ranges = ip_scope[:IpRanges] IpRanges { ip_ranges.each do |h| if h.key?(:IpRange) IpRange { StartAddress h[:IpRange][:StartAddress] EndAddress h[:IpRange][:EndAddress] } end end } end } end } end FenceMode configuration[:FenceMode] if router_info = configuration[:RouterInfo] RouterInfoType { ExternalIp router_info[:ExternalIp] } end } end # Configuration if edgegw = options[:EdgeGateway] and configuration[:FenceMode] != 'isolated' EdgeGateway(edgegw) elsif options[:Configuration] && options[:Configuration][:FenceMode] == 'isolated' # isolated networks can specify ServiceConfig if sc = options[:ServiceConfig] ServiceConfig { if dhcp = sc[:GatewayDhcpService] IsEnabled dhcp[:IsEnabled] if dhcp[:IsEnabled] if pool = dhcp[:Pool] IsEnabled pool[:IsEnabled] DefaultLeaseTime pool[:DefaultLeaseTime] MaxLeaseTime pool[:MaxLeaseTime] LowIpAddress pool[:LowIpAddress] HighIpAddress pool[:HighIpAddress] end end } end end IsShared options[:IsShared] if options.key?(:IsShared) } end.to_xml end end end end end end fog-1.19.0/lib/fog/vcloud_director/generators/compute/vm.rb0000644000004100000410000000174712261242552023723 0ustar www-datawww-datamodule Fog module Generators module Compute module VcloudDirector # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/types/VmType.html class Vm attr_reader :attrs def initialize(attrs={}) @attrs = attrs end def generate_xml attrs = @attrs Nokogiri::XML::Builder.new do Vm('xmlns' => 'http://www.vmware.com/vcloud/v1.5', 'name' => attrs[:name]) { Description attrs[:Description] if attrs.key?(:Description) if attrs.key?(:StorageProfile) StorageProfile( 'type' => 'application/vnd.vmware.vcloud.vdcStorageProfile+xml', 'name' => attrs[:StorageProfile][:name], 'href' => attrs[:StorageProfile][:href] ) end } end.to_xml end end end end end end fog-1.19.0/lib/fog/vcloud_director/generators/compute/edge_gateway_service_configuration.rb0000644000004100000410000001571612261242552032376 0ustar www-datawww-datamodule Fog module Generators module Compute module VcloudDirector class EdgeGatewayServiceConfiguration def initialize(configuration={}) @configuration = configuration end def generate_xml Nokogiri::XML::Builder.new do |xml| xml.EdgeGatewayServiceConfiguration('xmlns' => "http://www.vmware.com/vcloud/v1.5"){ build_firewall_service(xml) build_nat_service(xml) build_load_balancer_service(xml) } end.to_xml end private def build_load_balancer_service(xml) lb_config = @configuration[:LoadBalancerService] return unless lb_config xml.LoadBalancerService { xml.IsEnabled lb_config[:IsEnabled] if lb_config.key?(:IsEnabled) lb_config[:Pool].each do |pool| xml.Pool { xml.Name pool[:Name] xml.Description pool[:Description] if pool.key?(:Description) pool[:ServicePort].each do |service_port| xml.ServicePort { xml.IsEnabled service_port[:IsEnabled] xml.Protocol service_port[:Protocol] xml.Algorithm service_port[:Algorithm] xml.Port service_port[:Port] xml.HealthCheckPort service_port[:HealthCheckPort] xml.HealthCheck { xml.Mode service_port[:HealthCheck][:Mode] xml.Uri service_port[:HealthCheck][:Uri] xml.HealthThreshold service_port[:HealthCheck][:HealthThreshold] xml.UnhealthThreshold service_port[:HealthCheck][:UnhealthThreshold] xml.Interval service_port[:HealthCheck][:Interval] xml.Timeout service_port[:HealthCheck][:Timeout] } } end pool[:Member].each do |member| xml.Member { xml.IpAddress member[:IpAddress] xml.Weight member[:Weight] member[:ServicePort].each do |member_service_port| xml.ServicePort { xml.Protocol member_service_port[:Protocol] xml.Port member_service_port[:Port] xml.HealthCheckPort member_service_port[:HealthCheckPort] } end } end } end lb_config[:VirtualServer].each do |virtual_server| xml.VirtualServer { xml.IsEnabled virtual_server[:IsEnabled] xml.Name virtual_server[:Name] xml.Description virtual_server[:Description] xml.Interface(:href => virtual_server[:Interface][:href], :name => virtual_server[:Interface][:name]) xml.IpAddress virtual_server[:IpAddress] virtual_server[:ServiceProfile].each do |service_profile| xml.ServiceProfile { xml.IsEnabled service_profile[:IsEnabled] xml.Protocol service_profile[:Protocol] xml.Port service_profile[:Port] xml.Persistence { xml.Method service_profile[:Persistence][:method] if service_profile[:Persistence][:Method] == 'COOKIE' xml.CookieName service_profile[:Persistence][:CookieName] xml.CookieMode service_profile[:Persistence][:CookieMode] end } } end xml.Logging virtual_server[:Logging] xml.Pool virtual_server[:Pool] } end } end def build_nat_service(xml) nat_config = @configuration[:NatService] return unless nat_config xml.NatService { xml.IsEnabled nat_config[:IsEnabled] nat_config[:NatRule].each do |rule| xml.NatRule { xml.RuleType rule[:RuleType] xml.IsEnabled rule[:IsEnabled] xml.Id rule[:Id] gateway_nat_rule = rule[:GatewayNatRule] xml.GatewayNatRule { xml.Interface(:name => gateway_nat_rule[:Interface][:name], :href => gateway_nat_rule[:Interface][:href]) xml.OriginalIp gateway_nat_rule[:OriginalIp] xml.OriginalPort gateway_nat_rule[:OriginalPort] if gateway_nat_rule.key?(:OriginalPort) xml.TranslatedIp gateway_nat_rule[:TranslatedIp] xml.TranslatedPort gateway_nat_rule[:TranslatedPort] if gateway_nat_rule.key?(:TranslatedPort) xml.Protocol gateway_nat_rule[:Protocol] if rule[:RuleType] == "DNAT" } } end } end def build_firewall_service(xml) firewall_config = @configuration[:FirewallService] return unless firewall_config xml.FirewallService { xml.IsEnabled firewall_config[:IsEnabled] xml.DefaultAction firewall_config[:DefaultAction] if firewall_config.key?(:DefaultAction) xml.LogDefaultAction firewall_config[:LogDefaultAction] if firewall_config.key?(:LogDefaultAction) firewall_config[:FirewallRule].each do |rule| xml.FirewallRule { xml.Id rule[:Id] xml.IsEnabled rule[:IsEnabled] if rule.key?(:IsEnabled) xml.MatchOnTranslate rule[:MatchOnTranslate] if rule.key?(:MatchOnTranslate) xml.Description rule[:Description] if rule.key?(:Description) xml.Policy rule[:Policy] if rule.key?(:Policy) xml.Protocols { rule[:Protocols].each do |key, value| xml.send(key.to_s.capitalize, value) end } xml.IcmpSubType rule[:IcmpSubType] if rule.key?(:IcmpSubType) xml.Port rule[:Port] if rule.key?(:Port) xml.DestinationPortRange rule[:DestinationPortRange] xml.DestinationIp rule[:DestinationIp] xml.SourcePort rule[:SourcePort] if rule.key?(:SourcePort) xml.SourcePortRange rule[:SourcePortRange] xml.SourceIp rule[:SourceIp] xml.Direction rule[:Direction] if rule.key?(:Direction) #Firewall rule direction is allowed only in backward compatibility mode. xml.EnableLogging rule[:EnableLogging] if rule.key?(:EnableLogging) } end } end end end end end end fog-1.19.0/lib/fog/vcloud_director/generators/compute/disks.rb0000644000004100000410000001611212261242552024406 0ustar www-datawww-datamodule Fog module Generators module Compute module VcloudDirector # This is the data structure it accepts, this is the output of # #get_vm_disks: # # {:disks=> # [{:address=>0, # :description=>"SCSI Controller", # :name=>"SCSI Controller 0", # :id=>2, # :resource_sub_type=>"VirtualSCSI", # :resource_type=>6}, # {:address_on_parent=>0, # :description=>"Hard disk", # :name=>"Hard disk 1", # :id=>2000, # :parent=>2, # :resource_type=>17, # :capacity=>16384, # :bus_sub_type=>"VirtualSCSI", # :bus_type=>6}, # {:address=>0, # :description=>"IDE Controller", # :name=>"IDE Controller 0", # :id=>3, # :resource_type=>5}]} # # This is what it generates: # # # # 0 # SCSI Controller # SCSI Controller 0 # 2 # VirtualSCSI # 6 # # # 0 # Hard disk # Hard disk 1 # # 2000 # 2 # 17 # # # 0 # IDE Controller # IDE Controller 0 # 3 # 5 # # # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/types/RasdItemsListType.html class Disks def initialize(items=[]) @items = items[:disks] end def modify_hard_disk_size(disk_number, new_size) found = false @items.each do |item| if item[:resource_type] == 17 if item[:name] == "Hard disk #{disk_number}" found = true raise "Hard disk size can't be reduced" if item[:capacity].to_i > new_size.to_i item[:capacity] = new_size end end end raise "Hard disk #{disk_number} not found" unless found true end def add_hard_disk(size) new_hard_disk = last_hard_disk.dup new_hard_disk[:capacity] = size new_hard_disk[:name] = increase_hard_disk_name(new_hard_disk[:name]) new_hard_disk[:address_on_parent] += 1 new_hard_disk[:id] += 1 @items << new_hard_disk end def delete_hard_disk(disk_number) @items.delete_if {|item| item[:resource_type] == 17 && item[:name] =~ /#{disk_number}$/ } end def disks { :disks => @items } end def generate_xml output = "" output << header @items.each do |item| output << case item[:resource_type] when 6 scsi_controller(item) when 17 hard_disk_item(item) when 5 ide_controller_item(item) end end output << tail output end def header <<-END END end def tail <<-END END end def hard_disk_item(opts={}) <<-END #{opts[:address_on_parent]} #{opts[:description]} #{opts[:name]} #{opts[:id]} #{opts[:parent]} 17 END end def ide_controller_item(opts={}) <<-END #{opts[:address]} #{opts[:description]} #{opts[:name]} #{opts[:id]} 5 END end def scsi_controller(opts={}) <<-END #{opts[:address]} #{opts[:description]} #{opts[:name]} #{opts[:id]} #{opts[:resource_sub_type]} 6 END end # helpers def last_hard_disk hard_disks = @items.select{|item| item[:resource_type] == 17} names = hard_disks.map{|item| item[:name] } only_numbers = names.map{|b| b.scan(/\d+/).first.to_i} # extract numbers last_number = only_numbers.sort.last # get the last number hard_disks.detect{|hard_disk| hard_disk[:name] =~ /#{last_number}$/ } end def increase_hard_disk_name(hard_disk_name) hard_disk_name.gsub(/(\d+)$/) { $1.to_i + 1 } end end end end end end fog-1.19.0/lib/fog/vcloud_director/generators/compute/vapp.rb0000644000004100000410000000136612261242552024244 0ustar www-datawww-datamodule Fog module Generators module Compute module VcloudDirector # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/types/VAppType.html class Vapp attr_reader :name, :options def initialize(name, options={}) @name = name @options = options end def generate_xml attrs = @attrs Nokogiri::XML::Builder.new do VApp('xmlns' => 'http://www.vmware.com/vcloud/v1.5', 'name' => name ) { Description options[:Description] if options.key?(:Description) } end.to_xml end end end end end end fog-1.19.0/lib/fog/vcloud_director/generators/compute/customization.rb0000644000004100000410000001102412261242552026176 0ustar www-datawww-datamodule Fog module Generators module Compute module VcloudDirector # This is the data structure it accepts, this is the output of # #get_vm_customization: # # {:type=>"application/vnd.vmware.vcloud.guestCustomizationSection+xml", # :href=> # "https://example.com/api/vApp/vm-2bbbf556-55dc-4974-82e6-aa6e814f0b64/guestCustomizationSection/", # :id=>"vm-2bbbf556-55dc-4974-82e6-aa6e814f0b64", # :enabled=>false, # :change_sid=>false, # :virtual_machine_id=>"2bbbf556-55dc-4974-82e6-aa6e814f0b64", # :join_domain_enabled=>false, # :use_org_settings=>false, # :admin_password_enabled=>false, # :admin_password_auto=>true, # :reset_password_required=>false, # :customization_script=>"hola\nmundo", # :has_customization_script=>true, # :computer_name=>"DEVWEB-001"} # # This is what it generates: # # # Specifies Guest OS Customization Settings # true # true # 55cc91f2-7e12-48d4-ad90-6f637a51fd88 # false # false # true # true # false # DEVWEB-001 # # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/types/GuestCustomizationSectionType.html class Customization def initialize(attrs={}) @attrs = attrs end def generate_xml output = "" output << header output << body(@attrs) output << tail output end private def header <<-END END end # The order matters: http://communities.vmware.com/thread/448760?start=0&tstart=0 # # CustomizationScript: Script to run on guest customization. You # could use XML escape sequence to make multiple lines script. # The script could contain any UNICODE symbol by specifying its # number in format &#xxxx; where xxxx is the number. The predefined # symbols in the XML are: # * & & # * < < # * > > # * " " # * ' ' def body(opts={}) <<-END Specifies Guest OS Customization Settings #{opts[:enabled]} #{opts[:change_sid]} #{opts[:virtual_machine_id]} #{opts[:join_domain_enabled]} #{opts[:use_org_settings]} #{opts[:admin_password_enabled]} #{opts[:admin_password_auto]} #{opts[:reset_password_required]} #{CGI::escapeHTML(opts[:customization_script]).gsub(/\r/, " ")} #{opts[:computer_name]} END end def tail <<-END END end end end end end end fog-1.19.0/lib/fog/vcloud_director/models/0000755000004100000410000000000012261242552020401 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud_director/models/compute/0000755000004100000410000000000012261242552022055 5ustar www-datawww-datafog-1.19.0/lib/fog/vcloud_director/models/compute/media.rb0000644000004100000410000000113612261242552023462 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class VcloudDirector class Media < Model identity :id attribute :href attribute :type attribute :name attribute :status, :type => :integer attribute :image_type, :aliases => :imageType attribute :size, :type => :integer attribute :description, :aliases => :Description # @return [Boolean] def destroy requires :id response = service.delete_media(id) service.process_task(response.body) end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/task.rb0000644000004100000410000000333112261242552023344 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class VcloudDirector class Task < Fog::Model identity :id attribute :href attribute :type attribute :name attribute :end_time, :aliases => :endTime, :type => :time attribute :expiry_time, :aliases => :expiryTime, :type => :time attribute :operation attribute :operation_name, :aliases => :operationName attribute :start_time, :aliases => :startTime, :type => :time attribute :status attribute :description, :aliases => :Description attribute :error, :aliases => :Error attribute :progress, :aliases => :Progress, :type => :integer # Since 5.1 attribute :operation_key, :aliases => :operationKey attribute :cancel_requested, :aliases => :cancelRequested, :type => :boolean attribute :service_namespace, :aliases => :serviceNamespace attribute :details, :aliases => :Details def ready? status == 'success' end def success? status == 'success' end def non_running? if @service.show_progress? && (@last_progress ||= 0) < 100 if status == 'running' Formatador.redisplay_progressbar(progress, 100, :label => operation_name, :started_at => start_time) @last_progress = progress elsif status == 'success' Formatador.redisplay_progressbar(100, 100, :label => operation_name, :started_at => start_time) @last_progress = 100 end end status != 'running' end def cancel service.post_cancel_task(id) end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/medias.rb0000644000004100000410000000447712261242552023660 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/media' module Fog module Compute class VcloudDirector class Medias < Collection model Fog::Compute::VcloudDirector::Media attribute :vdc # @param [String] name The name of the entity. # @param [#read] io The input object to read from. # @param [String] image_type Media image type. One of: iso, floppy. # @return [Media] def create(name, io, image_type='iso') requires :vdc response = service.post_upload_media(vdc.id, name, image_type, io.size) service.add_id_from_href!(response.body) media = new(response.body) # Perhaps this would be better implemented as media#upload. file = response.body[:Files][:File].first file[:Link] = [file[:Link]] if file[:Link].is_a?(Hash) link = file[:Link].detect {|l| l[:rel] == 'upload:default'} headers = { 'Content-Length' => io.size, 'Content-Type' => 'application/octet-stream', 'x-vcloud-authorization' => service.vcloud_token } chunker = lambda do # to_s will convert the nil received after everything is read to # the final empty chunk. io.read(Excon.defaults[:chunk_size]).to_s end Excon.put( link[:href], :expects => 200, :headers => headers, :request_block => chunker) service.process_task(response.body[:Tasks][:Task]) media.reload media end private # @param [String] item_id # @return [Media] def get_by_id(item_id) item = service.get_media(item_id).body %w(:Link).each {|key_to_delete| item.delete(key_to_delete)} service.add_id_from_href!(item) item end # @return [Array] def item_list data = service.get_vdc(vdc.id).body return [] if data[:ResourceEntities].empty? items = data[:ResourceEntities][:ResourceEntity].select do |resource| resource[:type] == 'application/vnd.vmware.vcloud.media+xml' end items.each {|item| service.add_id_from_href!(item)} items end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/organization.rb0000644000004100000410000000137212261242552025111 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class VcloudDirector class Organization < Model identity :id attribute :name attribute :type attribute :href attribute :description, :aliases => :Description attribute :full_name, :aliases => :FullName def vdcs requires :id service.vdcs(:organization => self) end def catalogs requires :id service.catalogs(:organization => self) end def networks requires :id service.networks(:organization => self) end def tasks requires :id service.tasks(:organization => self) end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/vdc.rb0000644000004100000410000000220012261242552023150 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class VcloudDirector class Vdc < Model identity :id attribute :name attribute :type attribute :href attribute :description, :aliases => :Description attribute :available_networks, :aliases => :AvailableNetworks, :squash => :Network attribute :compute_capacity, :aliases => :ComputeCapacity attribute :storage_capacity , :aliases => :StorageCapacity attribute :allocation_model, :aliases => :AllocationModel attribute :capabilities, :aliases => :Capabilities, :squash => :SupportedHardwareVersions attribute :nic_quota, :aliases => :NicQuota, :type => :integer attribute :network_quota ,:aliases => :NetworkQuota, :type => :integer attribute :vm_quota ,:aliases => :VmQuota, :type => :integer attribute :is_enabled ,:aliases => :IsEnabled, :type => :boolean def medias requires :id service.medias(:vdc => self) end def vapps requires :id service.vapps(:vdc => self) end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/catalogs.rb0000644000004100000410000000147012261242552024201 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/catalog' module Fog module Compute class VcloudDirector class Catalogs < Collection model Fog::Compute::VcloudDirector::Catalog attribute :organization private def get_by_id(item_id) item = service.get_catalog(item_id).body %w(:CatalogItems :Link).each {|key_to_delete| item.delete(key_to_delete) } service.add_id_from_href!(item) item end def item_list data = service.get_organization(organization.id).body items = data[:Link].select { |link| link[:type] == "application/vnd.vmware.vcloud.catalog+xml" } items.each{|item| service.add_id_from_href!(item) } items end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/network.rb0000644000004100000410000000073212261242552024075 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class VcloudDirector class Network < Model identity :id attribute :name attribute :type attribute :href attribute :description attribute :is_inherited attribute :gateway attribute :netmask attribute :dns1 attribute :dns2 attribute :dns_suffix attribute :ip_ranges, :type => :array end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/vm_customizations.rb0000644000004100000410000000045512261242552026203 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/vm_customization' module Fog module Compute class VcloudDirector class VmCustomizations < Collection model Fog::Compute::VcloudDirector::VmCustomization attribute :vm end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/catalog.rb0000644000004100000410000000073712261242552024023 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class VcloudDirector class Catalog < Model identity :id attribute :name attribute :type attribute :href attribute :description, :aliases => :Description attribute :is_published, :aliases => :IsPublished, :type => :boolean def catalog_items requires :id service.catalog_items(:catalog => self) end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/vm_customization.rb0000644000004100000410000000210312261242552026010 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class VcloudDirector class VmCustomization < Model identity :id attribute :type attribute :href attribute :enabled attribute :change_sid attribute :join_domain_enabled attribute :use_org_settings attribute :admin_password_auto attribute :admin_password attribute :admin_password_enabled attribute :reset_password_required attribute :virtual_machine_id attribute :computer_name attribute :has_customization_script # bug: for some reason if the customization_script has /r, is showed # here as /n. Looks likes is something in excon def script attributes[:customization_script] end def script=(new_script) attributes[:customization_script] = new_script end def save response = service.put_guest_customization_section_vapp(id, attributes) service.process_task(response.body) end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/vm_network.rb0000644000004100000410000000123612261242552024577 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class VcloudDirector class VmNetwork < Model identity :id attribute :type attribute :href attribute :info attribute :primary_network_connection_index attribute :network attribute :needs_customization attribute :network_connection_index attribute :is_connected attribute :mac_address attribute :ip_address_allocation_mode def save response = service.put_network_connection_system_section_vapp(id, attributes) service.process_task(response.body) end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/vm_networks.rb0000644000004100000410000000060112261242552024755 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/vm_network' module Fog module Compute class VcloudDirector class VmNetworks < Collection model Fog::Compute::VcloudDirector::VmNetwork attribute :vm def get(id) data = service.get_vm_network(id).body new(data) end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/vm.rb0000644000004100000410000001137212261242552023030 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/vcloud_director/models/compute/vm_customization' module Fog module Compute class VcloudDirector class Vm < Model identity :id attribute :vapp_id attribute :vapp_name attribute :name attribute :type attribute :href attribute :status attribute :operating_system attribute :ip_address attribute :cpu, :type => :integer attribute :memory, :type => :integer attribute :hard_disks, :aliases => :disks def reload # when collection.vapp is nil, it means it's fatherless, # vms from different vapps are loaded in the same collection. # This situation comes from a "query" result collection.vapp.nil? ? reload_single_vm : super end def reload_single_vm return unless data = begin collection.get_single_vm(identity) rescue Excon::Errors::SocketError nil end # these two attributes don't exists in the get_single_vm response # that's why i use the old attributes data.attributes[:vapp_id] = attributes[:vapp_id] data.attributes[:vapp_name] = attributes[:vapp_name] new_attributes = data.attributes merge_attributes(new_attributes) self end # Power off the VM. def power_off requires :id begin response = service.post_power_off_vapp(id) rescue Fog::Compute::VcloudDirector::BadRequest => ex Fog::Logger.debug(ex.message) return false end service.process_task(response.body) end # Power on the VM. def power_on requires :id begin response = service.post_power_on_vapp(id) rescue Fog::Compute::VcloudDirector::BadRequest => ex Fog::Logger.debug(ex.message) return false end service.process_task(response.body) end # Reboot the VM. def reboot requires :id begin response = service.post_reboot_vapp(id) rescue Fog::Compute::VcloudDirector::BadRequest => ex Fog::Logger.debug(ex.message) return false end service.process_task(response.body) end # Reset the VM. def reset requires :id begin response = service.post_reset_vapp(id) rescue Fog::Compute::VcloudDirector::BadRequest => ex Fog::Logger.debug(ex.message) return false end service.process_task(response.body) end # Shut down the VM. def shutdown requires :id begin response = service.post_shutdown_vapp(id) rescue Fog::Compute::VcloudDirector::BadRequest => ex Fog::Logger.debug(ex.message) return false end service.process_task(response.body) end # Suspend the VM. def suspend requires :id begin response = service.post_suspend_vapp(id) rescue Fog::Compute::VcloudDirector::BadRequest => ex Fog::Logger.debug(ex.message) return false end service.process_task(response.body) end def tags requires :id service.tags(:vm => self) end def customization requires :id data = service.get_vm_customization(id).body service.vm_customizations.new(data) end def network requires :id data = service.get_vm_network(id).body service.vm_networks.new(data) end def disks requires :id service.disks(:vm => self) end def memory=(new_memory) has_changed = ( memory != new_memory.to_i ) not_first_set = !memory.nil? attributes[:memory] = new_memory.to_i if not_first_set && has_changed response = service.put_memory(id, memory) service.process_task(response.body) end end def cpu=(new_cpu) has_changed = ( cpu != new_cpu.to_i ) not_first_set = !cpu.nil? attributes[:cpu] = new_cpu.to_i if not_first_set && has_changed response = service.put_cpu(id, cpu) service.process_task(response.body) end end def ready? reload status == 'on' end def vapp # get_by_metadata returns a vm collection where every vapp parent is orpahn collection.vapp ||= service.vapps.get(vapp_id) end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/tag.rb0000644000004100000410000000134712261242552023162 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class VcloudDirector class Tag < Model identity :id attribute :value def value=(new_value) has_changed = ( value != new_value ) not_first_set = !value.nil? attributes[:value] = new_value if not_first_set && has_changed response = service.put_vapp_metadata_item_metadata(vm.id, id, value) service.process_task(response.body) end end def destroy response = service.delete_vapp_metadata_item_metadata(vm.id, id) service.process_task(response.body) end def vm attributes[:vm] end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/tags.rb0000644000004100000410000000165612261242552023350 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/tag' module Fog module Compute class VcloudDirector class Tags < Collection model Fog::Compute::VcloudDirector::Tag attribute :vm def get_by_name(tag_name) get(tag_name) end def get_by_id(item_id) item_list unless @items @items.detect{ |i| i[:id] == item_id} end def create(key,value) response = service.post_update_vapp_metadata(vm.id, { key => value} ) service.process_task(response.body) end def hash_items @tags = service.get_metadata(vm.id).body @tags[:metadata] end private def item_list @items =[] hash_items.each_pair{ |k,v| @items << {:id => k, :value => v }.merge(:vm => vm) } @items end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/catalog_items.rb0000644000004100000410000000166012261242552025220 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/catalog_item' module Fog module Compute class VcloudDirector class CatalogItems < Collection model Fog::Compute::VcloudDirector::CatalogItem attribute :catalog private def item_list data = service.get_catalog(catalog.id).body items = data[:CatalogItems][:CatalogItem].select do |link| link[:type] == 'application/vnd.vmware.vcloud.catalogItem+xml' end items.each {|item| service.add_id_from_href!(item)} items end def get_by_id(item_id) item = service.get_catalog_item(item_id).body item[:vapp_template_id] = item[:Entity][:href].split('/').last %w(:Link :Entity).each {|key_to_delete| item.delete(key_to_delete) } service.add_id_from_href!(item) item end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/disks.rb0000644000004100000410000000172512261242552023524 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/disk' module Fog module Compute class VcloudDirector class Disks < Collection model Fog::Compute::VcloudDirector::Disk attribute :vm def create(size) item_list unless @disks data = Fog::Generators::Compute::VcloudDirector::Disks.new(@disks) data.add_hard_disk(size) response = service.put_disks(vm.id, data.disks) service.process_task(response.body) end def get_by_id(item_id) item = item_list.detect{ |i| i[:id] == item_id} item.merge!(:all_disks => @disks, :vm => vm) if item item end def item_list @disks = service.get_vm_disks(vm.id).body items = @disks[:disks] items.each do |disk| disk[:all_disks] = @disks disk[:vm] = vm end items end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/vapp.rb0000644000004100000410000001067512261242552023361 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class VcloudDirector class Vapp < Model identity :id attribute :name attribute :type attribute :href attribute :description, :aliases => :Description attribute :deployed, :type => :boolean attribute :status attribute :lease_settings, :aliases => :LeaseSettingsSection attribute :network_section, :aliases => :"ovf:NetworkSection", :squash => :"ovf:Network" attribute :network_config, :aliases => :NetworkConfigSection, :squash => :NetworkConfig attribute :owner, :aliases => :Owner, :squash => :User attribute :InMaintenanceMode, :type => :boolean def vms requires :id service.vms(:vapp => self) end def tags requires :id service.tags(:vm => self) end # @param [String] action The specified action is applied to all virtual # machines in the vApp. All values other than **default** ignore # actions, order, and delay specified in the StartupSection. One of: # * powerOff (Power off the virtual machines. This is the default # action if this attribute is missing or empty) # * suspend (Suspend the virtual machines) # * shutdown (Shut down the virtual machines) # * force (Attempt to power off the virtual machines. Failures in # undeploying the virtual machine or associated networks are ignored. # All references to the vApp and its virtual machines are removed # from the database) # * default (Use the actions, order, and delay specified in the # StartupSection) def undeploy(action='powerOff') begin response = service.post_undeploy_vapp(id, :UndeployPowerAction => action) rescue Fog::Compute::VcloudDirector::BadRequest => ex Fog::Logger.debug(ex.message) return false end service.process_task(response.body) end # Power off all VMs in the vApp. def power_off requires :id begin response = service.post_power_off_vapp(id) rescue Fog::Compute::VcloudDirector::BadRequest => ex Fog::Logger.debug(ex.message) return false end service.process_task(response.body) end # Power on all VMs in the vApp. def power_on requires :id begin response = service.post_power_on_vapp(id) rescue Fog::Compute::VcloudDirector::BadRequest => ex Fog::Logger.debug(ex.message) return false end service.process_task(response.body) end # Reboot all VMs in the vApp. def reboot requires :id begin response = service.post_reboot_vapp(id) rescue Fog::Compute::VcloudDirector::BadRequest => ex Fog::Logger.debug(ex.message) return false end service.process_task(response.body) end # Reset all VMs in the vApp. def reset requires :id begin response = service.post_reset_vapp(id) rescue Fog::Compute::VcloudDirector::BadRequest => ex Fog::Logger.debug(ex.message) return false end service.process_task(response.body) end # Shut down all VMs in the vApp. def shutdown requires :id begin response = service.post_shutdown_vapp(id) rescue Fog::Compute::VcloudDirector::BadRequest => ex Fog::Logger.debug(ex.message) return false end service.process_task(response.body) end # Suspend all VMs in the vApp. def suspend requires :id begin response = service.post_suspend_vapp(id) rescue Fog::Compute::VcloudDirector::BadRequest => ex Fog::Logger.debug(ex.message) return false end service.process_task(response.body) end def destroy requires :id begin response = service.delete_vapp(id) rescue Fog::Compute::VcloudDirector::BadRequest => ex Fog::Logger.debug(ex.message) return false end service.process_task(response.body) end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/catalog_item.rb0000644000004100000410000000121312261242552025027 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class VcloudDirector class CatalogItem < Model identity :id attribute :name attribute :type attribute :href attribute :description, :aliases => :Description attribute :vapp_template_id def instantiate(vapp_name, options={}) response = service.instantiate_vapp_template(vapp_name, vapp_template_id, options) service.process_task(response.body[:Tasks][:Task]) response.body[:href].split('/').last # returns the vapp_id if it was instantiated successfully . end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/vms.rb0000644000004100000410000000153312261242552023211 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/vm' module Fog module Compute class VcloudDirector class Vms < Collection model Fog::Compute::VcloudDirector::Vm attribute :vapp def get_by_metadata(key, value) data = service.get_vms_by_metadata(key, value).body items = data[:vm_records] load(items) end def get_single_vm(vm_id) item = service.get_vm(vm_id).body return nil unless item new(item[:vm]) end private def get_by_id(item_id) item = item_list.detect{ |vm| vm[:id] == item_id } item end def item_list data = service.get_vms(vapp.id).body # vapp.id items = data[:vms] items end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/vdcs.rb0000644000004100000410000000146212261242552023344 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/vdc' module Fog module Compute class VcloudDirector class Vdcs < Collection model Fog::Compute::VcloudDirector::Vdc attribute :organization private def get_by_id(item_id) item = service.get_vdc(item_id).body %w(:VdcItems :Link :ResourceEntities).each {|key_to_delete| item.delete(key_to_delete) } service.add_id_from_href!(item) item end def item_list data = service.get_organization(organization.id).body items = data[:Link].select { |link| link[:type] == "application/vnd.vmware.vcloud.vdc+xml" } items.each{|item| service.add_id_from_href!(item) } items end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/vapps.rb0000644000004100000410000000160312261242552023533 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/vapp' module Fog module Compute class VcloudDirector class Vapps < Collection model Fog::Compute::VcloudDirector::Vapp attribute :vdc private def get_by_id(item_id) item = service.get_vapp(item_id).body %w(:Link).each {|key_to_delete| item.delete(key_to_delete) } service.add_id_from_href!(item) item end def item_list data = service.get_vdc(vdc.id).body return [] if data[:ResourceEntities].empty? resource_entities = data[:ResourceEntities][:ResourceEntity] items = resource_entities.select { |link| link[:type] == "application/vnd.vmware.vcloud.vApp+xml" } items.each{|item| service.add_id_from_href!(item) } items end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/disk.rb0000644000004100000410000000304712261242552023340 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class VcloudDirector class Disk < Model # there is no lazy_load in disks identity :id attribute :address attribute :description attribute :name attribute :resource_sub_type attribute :resource_type attribute :address_on_parent attribute :parent attribute :capacity attribute :bus_sub_type attribute :bus_type # TODO Virtual machine disk sizes may only be increased, not decreased. def capacity=(new_capacity) has_changed = ( capacity != new_capacity.to_i ) not_first_set = !capacity.nil? attributes[:capacity] = new_capacity.to_i if not_first_set && has_changed data = Fog::Generators::Compute::VcloudDirector::Disks.new(all_disks) num_disk = name.scan(/\d+/).first.to_i data.modify_hard_disk_size(num_disk, new_capacity) response = service.put_disks(attributes[:vm].id, data.disks) service.process_task(response.body) end end def all_disks attributes[:all_disks] # this is passed at instantiation time end def destroy num_disk = name.scan(/\d+/).first.to_i data = Fog::Generators::Compute::VcloudDirector::Disks.new(all_disks) data.delete_hard_disk(num_disk) response = service.put_disks(attributes[:vm].id, data.disks) service.process_task(response.body) end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/organizations.rb0000644000004100000410000000121212261242552025265 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/organization' module Fog module Compute class VcloudDirector class Organizations < Collection model Fog::Compute::VcloudDirector::Organization private def get_by_id(org_id) org = service.get_organization(org_id).body org.delete(:Link) service.add_id_from_href!(org) org end def item_list data = service.get_organizations.body orgs = data[:Org] orgs.each {|org| service.add_id_from_href!(org)} orgs end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/tasks.rb0000644000004100000410000000117512261242552023533 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/task' module Fog module Compute class VcloudDirector class Tasks < Collection model Fog::Compute::VcloudDirector::Task attribute :organization def get(id) data = service.get_task(id).body return nil unless data data[:id] = data[:href].split('/').last new(data) end private def item_list data = service.get_task_list(organization.id).body data[:Task].each {|task| service.add_id_from_href!(task)} end end end end end fog-1.19.0/lib/fog/vcloud_director/models/compute/networks.rb0000644000004100000410000000134612261242552024262 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/network' module Fog module Compute class VcloudDirector class Networks < Collection model Fog::Compute::VcloudDirector::Network attribute :organization private def get_by_id(item_id) item = service.get_network(item_id).body service.add_id_from_href!(item) item end def item_list data = service.get_organization(organization.id).body items = data[:Link].select { |link| link[:type] == "application/vnd.vmware.vcloud.orgNetwork+xml" } items.each{|item| service.add_id_from_href!(item) } items end end end end end fog-1.19.0/lib/fog/vcloud_director/README.md0000644000004100000410000006524412261242552020410 0ustar www-datawww-data# VMware vCloud Director 5.1 API client ## Introduction Collection and Model representation in vcloud_director fog provider. ```no-highlight organizations organization vdcs -> vdc -> vapps -> vapp -> vms -> vm -> customizations -> script -> network -> disks -> disk -> tags -> tag -> power_on networks -> network catalogs -> catalog -> catalog_items -> catalog_item -> instantiate_vapp medias -> media ``` ### Actions Every collection supports the following methods: Method Name | Lazy Load ----------------- | --------- get(id) | false get_by_name(name) | false all | true all(false) | false ### Lazy Loading When listing a collection (eg: `vdc.vapps`), lazy load will be used by default to improve the performance, otherwise it will make as many requests as items are in the collection. You can disable lazy load using the explict caller and passing a *false* option: `vdc.vapps.all(false)`. Attributes showing the value **NonLoaded** will be populated when accessing the value, if there are more than one **NonLoaded** values the first time accessing on any of those values will populate the others. You can explicitly load those attributes with the `reload` method: ```ruby org = vcloud.organizations.first org.reload ``` Lazy load isn't used with `get` and `get_by_name` methods are used. ## Initialization ```ruby vcloud = Fog::Compute::VcloudDirector.new( :vcloud_director_username => "@", :vcloud_director_password => "", :vcloud_director_host => 'api.example.com', :vcloud_director_show_progress => false, # task progress bar on/off ) ``` ## Organizations ### List Organizations Note that when listing, by default only the attributes `id`, `name`, `type`, and `href` are loaded. To disable lazy loading, and load all attributes, just specify `false`. Another option is to reload a specific item: `vcloud.organizations.first.reload` ```ruby vcloud.organizations ``` ``` ] > ``` ### Retrieve an Organization by Id ```ruby org = vcloud.organizations.get("c6a4c623-c158-41cf-a87a-dbc1637ad55a") ``` ### Retrieve an Organization by Name ```ruby org = vcloud.organizations.get_by_name("DevOps") ``` ## vDCs It shows the Organization's vDCs. ### List vDCs ```ruby org = vcloud.organizations.first org.vdcs ``` ```ruby [ ] > ``` ### Retrieve a vDC ```ruby org = vcloud.organizations.first org.vdcs.get_by_name("DevOps - VDC") ``` ```ruby "application/vnd.vmware.vcloud.network+xml", :name=>"DevOps - Dev Network Connection", :href=>"https://example.com/api/network/d5f47bbf-de27-4cf5-aaaa-56772f2ccd17"}, compute_capacity_cpu=NonLoaded, compute_capacity_memory={:Units=>"MB", :Allocated=>"0", :Limit=>"0", :Used=>"3584", :Overhead=>"65"}, storage_capacity={:Units=>"MB", :Allocated=>"1048320", :Limit=>"1048320", :Used=>"903168", :Overhead=>"0"}, allocation_model="AllocationVApp", capabilities={:SupportedHardwareVersion=>"vmx-09"}, nic_quota=0, network_quota=1024, vm_quota=0, is_enabled=true > ``` ## vApps ### List vApps ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vdc.vapps ``` ```ruby [ , ] > ``` ### Retrieve a vApp ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vdc.vapps.get_by_name("segundo") ``` ```ruby "0", :ovf_stopAction=>"powerOff", :ovf_startDelay=>"0", :ovf_startAction=>"powerOn", :ovf_order=>"0", :ovf_id=>"DEVWEB"}, network_section={:ovf_name=>"DevOps - Dev Network Connection", :"ovf:Description"=>""}, network_config={:networkName=>"DevOps - Dev Network Connection", :Link=>{:rel=>"repair", :href=>"https://example.com/api/admin/network/82a07044-4dda-4a3e-a53d-8981cf0d5baa/action/reset"}, :Description=>"", :Configuration=>{:IpScope=>{:IsInherited=>"true", :Gateway=>"10.192.0.1", :Netmask=>"255.255.252.0", :Dns1=>"10.192.0.11", :Dns2=>"10.192.0.12", :DnsSuffix=>"dev.ad.mdsol.com", :IpRanges=>{:IpRange=>{:StartAddress=>"10.192.0.100", :EndAddress=>"10.192.3.254"}}}, :ParentNetwork=>{:name=>"DevOps - Dev Network Connection", :id=>"d5f47bbf-de27-4cf5-aaaa-56772f2ccd17", :href=>"https://example.com/api/admin/network/d5f47bbf-de27-4cf5-aaaa-56772f2ccd17"}, :FenceMode=>"bridged", :RetainNetInfoAcrossDeployments=>"false"}, :IsDeployed=>"false"}, owner={:type=>"application/vnd.vmware.admin.user+xml", :name=>"restebanez", :href=>"https://example.com/api/admin/user/c3ca7b97-ddea-425f-8bdb-1fdb946f7349"}, InMaintenanceMode=false > ``` ## VMs ### List VMs ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vapp.vms ``` ```ruby "0", :ovf_stopAction=>"powerOff", :ovf_startDelay=>"0", :ovf_startAction=>"powerOn", :ovf_order=>"0", :ovf_id=>"DEVWEB"}, network_section={:ovf_name=>"DevOps - Dev Network Connection", :"ovf:Description"=>""}, network_config={:networkName=>"DevOps - Dev Network Connection", :Link=>{:rel=>"repair", :href=>"https://example.com/api/admin/network/82a07044-4dda-4a3e-a53d-8981cf0d5baa/action/reset"}, :Description=>"", :Configuration=>{:IpScope=>{:IsInherited=>"true", :Gateway=>"10.192.0.1", :Netmask=>"255.255.252.0", :Dns1=>"10.192.0.11", :Dns2=>"10.192.0.12", :DnsSuffix=>"dev.ad.mdsol.com", :IpRanges=>{:IpRange=>{:StartAddress=>"10.192.0.100", :EndAddress=>"10.192.3.254"}}}, :ParentNetwork=>{:name=>"DevOps - Dev Network Connection", :id=>"d5f47bbf-de27-4cf5-aaaa-56772f2ccd17", :href=>"https://example.com/api/admin/network/d5f47bbf-de27-4cf5-aaaa-56772f2ccd17"}, :FenceMode=>"bridged", :RetainNetInfoAcrossDeployments=>"false"}, :IsDeployed=>"false"}, owner={:type=>"application/vnd.vmware.admin.user+xml", :name=>"restebanez", :href=>"https://example.com/api/admin/user/c3ca7b97-ddea-425f-8bdb-1fdb946f7349"}, InMaintenanceMode=false > [ 163840}] > ] > ``` ### Retrieve a VM ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vapp.vms.get_by_name("DEVWEB") ``` ```ruby 163840}] > ``` ### Modify CPU ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") vm.cpu = 4 ``` ```no-highlight 4 ``` ### Modify Memory ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") vm.memory = 4096 ``` ```no-highlight 4096 ``` ### Power On a VM ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") vm.power_on ``` ```no-highlight true ``` ## VM Customization ### Retrieve VM Customization ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") vm.customization ``` ```ruby ``` ### Modify VM Customization Customization attributes model requires to `save` it after setting the attributes. ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") customization = vm.customization customization.compute_name = "NEWNAME" customization.enabled = false customization.script = "new userdata script" customization.save ``` ```no-highlight true ``` ## VM Network ### Show VM Networks ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") vm.network ``` ```ruby ``` ### Modify one or more attributes Network attributes model requires to `save` it after setting the attributes. ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") network = vm.network network.is_connected = false network.ip_address_allocation_mode = "DHCP" network.save ``` ```no-highlight true ``` ## VM Disk ### List VM Disks ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") vm.disks ``` ```ruby 163840}] > [ , , ] > ``` ### Create a New Disk ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") vm.disks.create(1024) ``` ```no-highlight true ``` The new disk should show up. ```ruby >> vm.disks 163840}] > [ , , , ] > ``` ### Modify the Hard Disk Size ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") disk = vm.disks.get_by_name("Hard disk 2") disk.capacity = 2048 ``` ```no-highlight true ``` ### Destroy a Hard Disk ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") disk = vm.disks.get_by_name("Hard disk 2") disk.destroy ``` ```no-highlight true ``` ## VM Tags ### List VM Tags ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") vm.tags ``` ```ruby 163840}] > [ , , , ] > ``` ### Create a Tag ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") vm.tags.create('this_is_a_key', 'this_is_a_value') ``` ```no-highlight true ``` ### Retrieve a Tag ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") vm.tags.get_by_name('this_is_a_key') ``` ```ruby ``` ### Modify a Tag ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") vm.tags.get_by_name('this_is_a_key').value = 'new_value' ``` ```no-highlight "new_value" ``` ### Destroy a Tag ```ruby org = vcloud.organizations.first vdc = org.vdcs.first vapp = vdc.vapps.get_by_name("segundo") vm = vapp.vms.get_by_name("DEVWEB") vm.tags.get_by_name('this_is_a_key').destroy ``` ```no-highlight true ``` ## Networks It shows the Organization's Networks. ### List Networks ```ruby org = vcloud.organizations.first org.networks ``` ```ruby [ ] > ``` ### Retrieve a Network ```ruby org = vcloud.organizations.first org.networks.get_by_name("DevOps - Dev Network Connection") ``` ```ruby "10.192.0.100", :end_address=>"10.192.3.254"}] > ``` ## Catalogs It shows the Organization's Catalogs. ### List Catalogs ```ruby org = vcloud.organizations.first org.catalogs ``` ```ruby [ , ] > ``` ### Retrieve a Catalog ```ruby org = vcloud.organizations.first org.catalogs.get("4ee720e5-173a-41ac-824b-6f4908bac975") # or get_by_name("Public VM Templates") ``` ```ruby ``` ## Catalog Items ### List Catalog Items ```ruby org = vcloud.organizations.first catalog = org.catalogs.first catalog.catalog_items ``` ```ruby [ , , ] > ``` ### Retrieve a Catalog Item ```ruby org = vcloud.organizations.first catalog = org.catalogs.first catalog.catalog_items.get_by_name('DEVAPP') ``` ```ruby ``` ### Instantiate a vApp Template It creates a Vapp from a CatalogItem. ```ruby org = vcloud.organizations.first catalog = org.catalogs.first template = catalog.catalog_items.get_by_name('DEVAPP') template.instantiate('webserver') ``` It there were more than one vDC or/and network you'd have to specify it as a second param: ```ruby template.instantiate('webserver', { vdc_id: "9a06a16b-12c6-44dc-aee1-06aa52262ea3", network_id: "d5f47bbf-de27-4cf5-aaaa-56772f2ccd17" } ``` fog-1.19.0/lib/fog/vcloud_director/compute.rb0000644000004100000410000006535712261242552021137 0ustar www-datawww-datarequire 'fog/vcloud_director' require 'fog/compute' class VcloudDirectorParser < Fog::Parsers::Base def extract_attributes(attributes_xml) attributes = {} until attributes_xml.empty? if attributes_xml.first.is_a?(Array) until attributes_xml.first.empty? attribute = attributes_xml.first.shift attributes[attribute.localname.to_sym] = attribute.value end else attribute = attributes_xml.shift attributes[attribute.localname.to_sym] = attribute.value end end attributes end end class NonLoaded end module Fog module Compute class VcloudDirector < Fog::Service module Defaults PATH = '/api' PORT = 443 SCHEME = 'https' API_VERSION = '5.1' end class ServiceError < Fog::VcloudDirector::Errors::ServiceError; end class BadRequest < Fog::VcloudDirector::Errors::BadRequest; end class Unauthorized < Fog::VcloudDirector::Errors::Unauthorized; end class Forbidden < Fog::VcloudDirector::Errors::Forbidden; end class Conflict < Fog::VcloudDirector::Errors::Conflict; end class DuplicateName < Fog::VcloudDirector::Errors::DuplicateName; end class TaskError < Fog::VcloudDirector::Errors::TaskError; end requires :vcloud_director_username, :vcloud_director_password, :vcloud_director_host recognizes :vcloud_director_api_version, :vcloud_director_show_progress secrets :vcloud_director_password model_path 'fog/vcloud_director/models/compute' model :catalog collection :catalogs model :organization collection :organizations model :catalog_item collection :catalog_items model :vdc collection :vdcs model :vapp collection :vapps model :task collection :tasks model :vm collection :vms model :vm_customization collection :vm_customizations model :network collection :networks model :disk collection :disks model :vm_network collection :vm_networks model :tag # this is called metadata in vcloud collection :tags model :media collection :medias # sic request_path 'fog/vcloud_director/requests/compute' request :delete_catalog_item request :delete_catalog_item_metadata_item_metadata request :delete_disk request :delete_disk_metadata_item_metadata request :delete_logout request :delete_media request :delete_media_metadata_item_metadata request :delete_network request :delete_shadow_vm request :delete_vapp request :delete_vapp_metadata_item_metadata request :delete_vapp_template request :delete_vapp_template_metadata_item_metadata request :get_allocated_ip_addresses request :get_catalog request :get_catalog_item request :get_catalog_item_metadata request :get_catalog_item_metadata_item_metadata request :get_catalog_metadata request :get_catalog_metadata_item_metadata request :get_catalogs_from_query request :get_control_access_params_catalog request :get_control_access_params_vapp request :get_cpu_rasd_item request :get_current_session request :get_disk request :get_disk_metadata request :get_disk_metadata_item_metadata request :get_disk_owner request :get_disks_from_query request :get_disks_rasd_items_list request :get_edge_gateway request :get_entity request :get_execute_query request :get_groups_from_query request :get_guest_customization_system_section_vapp request :get_guest_customization_system_section_vapp_template request :get_href # this is used for manual testing request :get_lease_settings_section_vapp request :get_lease_settings_section_vapp_template request :get_media request :get_media_drives_rasd_items_list request :get_media_metadata request :get_media_metadata_item_metadata request :get_media_owner request :get_medias_from_query request :get_memory_rasd_item request :get_metadata request :get_network request :get_network_cards_items_list request :get_network_config_section_vapp request :get_network_config_section_vapp_template request :get_network_connection_system_section_vapp request :get_network_connection_system_section_vapp_template request :get_network_metadata request :get_network_metadata_item_metadata request :get_network_section_vapp request :get_network_section_vapp_template request :get_operating_system_section request :get_org_settings request :get_org_vdc_gateways request :get_organization request :get_organization_metadata request :get_organization_metadata_item_metadata request :get_organizations request :get_organizations_from_query request :get_product_sections_vapp request :get_product_sections_vapp_template request :get_request # this is used for manual testing request :get_runtime_info_section_type request :get_serial_ports_items_list request :get_shadow_vm request :get_snapshot_section request :get_startup_section request :get_supported_systems_info request :get_supported_versions request :get_task request :get_task_list request :get_thumbnail request :get_users_from_query request :get_vapp request :get_vapp_metadata request :get_vapp_metadata_item_metadata request :get_vapp_ovf_descriptor request :get_vapp_owner request :get_vapp_template request :get_vapp_template_customization_system_section request :get_vapp_template_metadata request :get_vapp_template_metadata_item_metadata request :get_vapp_template_ovf_descriptor request :get_vapp_template_owner request :get_vapp_templates_from_query request :get_vapps_in_lease_from_query request :get_vcloud request :get_vdc request :get_vdc_metadata request :get_vdc_metadata_item_metadata request :get_vdc_storage_class request :get_vdc_storage_class_metadata request :get_vdc_storage_class_metadata_item_metadata request :get_vdcs_from_query request :get_virtual_hardware_section request :get_vm request :get_vm_capabilities request :get_vm_compliance_results request :get_vm_customization request :get_vm_disks request :get_vm_network request :get_vm_pending_question request :get_vms request :get_vms_by_metadata request :get_vms_disk_attached_to request :get_vms_in_lease_from_query request :instantiate_vapp_template # to be deprecated request :post_acquire_ticket request :post_answer_vm_pending_question request :post_attach_disk request :post_cancel_task request :post_capture_vapp request :post_check_vm_compliance request :post_clone_media request :post_clone_vapp request :post_clone_vapp_template request :post_configure_edge_gateway_services request :post_consolidate_vm_vapp request :post_consolidate_vm_vapp_template request :post_create_org_vdc_network request :post_deploy_vapp request :post_detach_disk request :post_disable_nested_hv request :post_disable_vapp_template_download request :post_discard_vapp_state request :post_eject_cd_rom request :post_enable_nested_hv request :post_enable_vapp_template_download request :post_enter_maintenance_mode request :post_exit_maintenance_mode request :post_insert_cd_rom request :post_install_vmware_tools request :post_instantiate_vapp_template request :post_login_session request :post_power_off_vapp request :post_power_on_vapp request :post_reboot_vapp request :post_remove_all_snapshots request :post_reset_vapp request :post_revert_snapshot request :post_shutdown_vapp request :post_suspend_vapp request :post_undeploy_vapp request :post_update_catalog_item_metadata request :post_update_disk_metadata request :post_update_media_metadata request :post_update_vapp_metadata request :post_update_vapp_template_metadata request :post_upgrade_hw_version request :post_upload_disk request :post_upload_media request :post_upload_vapp_template request :put_catalog_item_metadata_item_metadata request :put_cpu request :put_disk_metadata_item_metadata request :put_disks request :put_guest_customization_section_vapp request :put_media_metadata_item_metadata request :put_memory request :put_metadata_value # deprecated request :put_network_connection_system_section_vapp request :put_vapp_metadata_item_metadata request :put_vapp_name_and_description request :put_vapp_template_metadata_item_metadata request :put_vm request :put_vm_capabilities class Model < Fog::Model def initialize(attrs={}) super(attrs) lazy_load_attrs.each do |attr| attributes[attr]= NonLoaded if attributes[attr].nil? make_lazy_load_method(attr) end self.class.attributes.each {|attr| make_attr_loaded_method(attr)} end def lazy_load_attrs @lazy_load_attrs ||= self.class.attributes - attributes.keys end def make_lazy_load_method(attr) self.class.instance_eval do define_method(attr) do reload if attributes[attr] == NonLoaded and !@inspecting attributes[attr] end end end # it adds an attr_loaded? method to know if the value has been loaded # yet or not: ie description_loaded? def make_attr_loaded_method(attr) self.class.instance_eval do define_method("#{attr}_loaded?") do attributes[attr] != NonLoaded end end end def inspect @inspecting = true out = super @inspecting = false out end end class Collection < Fog::Collection def all(lazy_load=true) lazy_load ? index : get_everyone end def get(item_id) item = get_by_id(item_id) return nil unless item new(item) end def get_by_name(item_name) item_found = item_list.detect {|item| item[:name] == item_name} return nil unless item_found get(item_found[:id]) end def index load(item_list) end def get_everyone items = item_list.map {|item| get_by_id(item[:id])} load(items) end end class Real extend Fog::Deprecation deprecate :auth_token, :vcloud_token attr_reader :end_point, :api_version, :show_progress alias_method :show_progress?, :show_progress def initialize(options={}) @vcloud_director_password = options[:vcloud_director_password] @vcloud_director_username = options[:vcloud_director_username] @connection_options = options[:connection_options] || {} @host = options[:vcloud_director_host] @path = options[:path] || Fog::Compute::VcloudDirector::Defaults::PATH @persistent = options[:persistent] || false @port = options[:port] || Fog::Compute::VcloudDirector::Defaults::PORT @scheme = options[:scheme] || Fog::Compute::VcloudDirector::Defaults::SCHEME @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) @end_point = "#{@scheme}://#{@host}#{@path}/" @api_version = options[:vcloud_director_api_version] || Fog::Compute::VcloudDirector::Defaults::API_VERSION @show_progress = options[:vcloud_director_show_progress] @show_progress = $stdin.tty? if @show_progress.nil? end def vcloud_token login if @vcloud_token.nil? @vcloud_token end def org_name login if @org_name.nil? @org_name end def user_name login if @user_name.nil? @user_name end def reload @connection.reset end def request(params) begin do_request(params) # this is to know if Excon::Errors::Unauthorized really happens #rescue Excon::Errors::Unauthorized # login # do_request(params) end end # @api private def do_request(params) headers = { 'Accept' => "application/*+xml;version=#{@api_version}", 'x-vcloud-authorization' => vcloud_token } if params[:path] if params[:override_path] == true path = params[:path] else path = "#{@path}/#{params[:path]}" end else path = "#{@path}" end @connection.request({ :body => params[:body], :expects => params[:expects], :headers => headers.merge!(params[:headers] || {}), :idempotent => params[:idempotent], :method => params[:method], :parser => params[:parser], :path => path, :query => params[:query] }) rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::BadRequest then BadRequest.slurp(error); when Excon::Errors::Unauthorized then Unauthorized.slurp(error); when Excon::Errors::Forbidden then Forbidden.slurp(error); when Excon::Errors::Conflict then Conflict.slurp(error); else ServiceError.slurp(error) end end def process_task(response_body) task = make_task_object(response_body) wait_and_raise_unless_success(task) true end def make_task_object(task_response) task_response[:id] = task_response[:href].split('/').last tasks.new(task_response) end def wait_and_raise_unless_success(task) task.wait_for { non_running? } raise TaskError.new "status: #{task.status}, error: #{task.error}" unless task.success? end def add_id_from_href!(data={}) data[:id] = data[:href].split('/').last end # Compensate for Fog::ToHashDocument shortcomings. # @api private # @param [Hash] hash # @param [String,Symbol] key1 # @param [String,Symbol] key2 # @return [Hash] def ensure_list!(hash, key1, key2=nil) if key2.nil? hash[key1] ||= [] hash[key1] = [hash[key1]] if hash[key1].is_a?(Hash) else hash[key1] ||= {key2 => []} hash[key1] = {key2 => []} if hash[key1].empty? hash[key1][key2] = [hash[key1][key2]] if hash[key1][key2].is_a?(Hash) end hash end private def login response = post_login_session x_vcloud_authorization = response.headers.keys.detect do |key| key.downcase == 'x-vcloud-authorization' end @vcloud_token = response.headers[x_vcloud_authorization] @org_name = response.body[:org] @user_name = response.body[:user] end # @note This isn't needed. def logout delete_logout @vcloud_token = nil @org_name = nil end end class Mock attr_reader :end_point, :api_version def data @@data ||= Hash.new do |hash, key| vdc1_uuid = uuid vdc2_uuid = uuid default_network_uuid = uuid uplink_network_uuid = uuid isolated_vdc1_network_uuid = uuid isolated_vdc2_network_uuid = uuid hash[key] = { :catalogs => { uuid => { :name => 'Default Catalog' } }, :catalog_items => { uuid => { :type => 'vAppTemplate', :name => 'vAppTemplate 1' } }, :disks => {}, :edge_gateways => { uuid => { :name => 'MockEdgeGateway', :networks => [uplink_network_uuid, default_network_uuid], :vdc => vdc1_uuid, :Configuration => { :GatewayBackingConfig => "compact", :GatewayInterfaces => { :GatewayInterface => []}, :EdgeGatewayServiceConfiguration => { :FirewallService => { :IsEnabled => "true", :DefaultAction => "drop", :LogDefaultAction => "false", :FirewallRule => [] }, :NatService => {:IsEnabled => "true"}}, :HaEnabled => "false", :UseDefaultRouteForDnsRelay => "false" } } }, :medias => {}, :networks => { default_network_uuid => { :IsShared => true, :vdc => vdc1_uuid, :FenceMode => 'natRouted', :ApplyRateLimit => "false", :Description => 'Org Network for mocking', :Dns1 => '8.8.8.8', :Dns2 => '8.8.4.4', :DnsSuffix => 'example.com', :Gateway => '192.168.1.1', :InterfaceType => "internal", :IpRanges => [{ :StartAddress=>'192.168.1.2', :EndAddress=>'192.168.1.254' }], :IsInherited => false, :Netmask => '255.255.255.0', :name => 'Default Network', :SubnetParticipation => { :Gateway => "192.168.1.0", :Netmask => "255.255.0.0", :IpAddress => "192.168.1.0" }, :UseForDefaultRoute => "false" }, isolated_vdc1_network_uuid => { :IsShared => false, :vdc => vdc1_uuid, :ApplyRateLimit => "false", :FenceMode => 'isolated', :Description => 'Org Network for mocking', :Dns1 => '8.8.8.8', :Dns2 => '8.8.4.4', :DnsSuffix => 'example.com', :InterfaceType => "internal", :IpRanges => [{ :StartAddress=>'10.1.0.100', :EndAddress=>'10.1.0.200' }], :IsInherited => false, :Netmask => '255.255.255.0', :name => 'vDC1 backend network', :SubnetParticipation => { :Gateway => "192.168.1.0", :Netmask => "255.255.0.0", :IpAddress => "192.168.1.0" }, :UseForDefaultRoute => "false" }, isolated_vdc2_network_uuid => { :IsShared => false, :vdc => vdc2_uuid, :ApplyRateLimit => "false", :Description => 'Org Network for mocking', :Dns1 => '8.8.8.8', :Dns2 => '8.8.4.4', :DnsSuffix => 'example.com', :InterfaceType => "internal", :IpRanges => [{ :StartAddress=>'10.2.0.100', :EndAddress=>'10.2.0.200' }], :IsInherited => false, :Netmask => '255.255.255.0', :name => 'vDC2 backend network', :SubnetParticipation => { :Gateway => "192.168.1.0", :Netmask => "255.255.0.0", :IpAddress => "192.168.1.0" }, :UseForDefaultRoute => "false" }, uplink_network_uuid => { :IsShared => false, :vdc => vdc1_uuid, :ApplyRateLimit => "false", :FenceMode => 'bridged', :Description => 'Uplink Network for mocking', :Dns1 => '8.8.8.8', :Dns2 => '8.8.4.4', :DnsSuffix => 'example.com', :Gateway => '198.51.100.1', :InterfaceType => "uplink", :IpRanges => [{ :StartAddress=>'198.51.100.2', :EndAddress=>'198.51.100.254' }], :IsInherited => false, :Netmask => '255.255.255.0', :name => 'uplink Network', :SubnetParticipation => { :Gateway => "198.51.100.81", :Netmask => "255.255.255.248", :IpAddress => "198.51.100.83", :IpRanges => { :IpRange => { :StartAddress => "198.51.100.84", :EndAddress => "198.51.100.86" } } }, :UseForDefaultRoute => "true" } }, :org => { :description => 'Organization for mocking', :full_name => 'Mock Organization', :name => org_name, :uuid => uuid }, :tasks => {}, :vdc_storage_classes => { uuid => { :default => true, :enabled => true, :limit => 2 * 1024 * 1024, :name => 'DefaultMockStorageClass', :units => 'MB', :vdc => vdc1_uuid, } }, :vdcs => { vdc1_uuid => { :description => 'vDC1 for mocking', :name => 'MockVDC 1' }, vdc2_uuid => { :description => 'vDC2 for mocking', :name => 'MockVDC 2' }, } } end[@vcloud_director_username] end def initialize(options={}) @vcloud_director_password = options[:vcloud_director_password] @vcloud_director_username = options[:vcloud_director_username] #@connection_options = options[:connection_options] || {} @host = options[:vcloud_director_host] @path = options[:path] || Fog::Compute::VcloudDirector::Defaults::PATH @persistent = options[:persistent] || false @port = options[:port] || Fog::Compute::VcloudDirector::Defaults::PORT @scheme = options[:scheme] || Fog::Compute::VcloudDirector::Defaults::SCHEME #@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) @end_point = "#{@scheme}://#{@host}#{@path}/" @api_version = options[:vcloud_director_api_version] || Fog::Compute::VcloudDirector::Defaults::API_VERSION end def vcloud_token @vcloud_token || Fog::Mock.random_base64(32) end def org_name @org_name ||= begin username = @vcloud_director_username.split('@') if username.size >= 2 # may be 'email_address@org_name' username.last else Fog::Logger.warning('vcloud_director_username should be in the form user@org_name') 'vcd_org_name' end end end def user_name @user_name ||= @vcloud_director_username.split('@').first end def user_uuid @user_uuid ||= uuid end def uuid [8,4,4,4,12].map {|i| Fog::Mock.random_hex(i)}.join('-') end # Create a task. # # @param [String] operation A message describing the operation that is # tracked by this task. # @param [String] operation_name The short name of the operation that # is tracked by this task. # @param [Hash] owner Reference to the owner of the task. This is # typically the object that the task is creating or updating. # * :href<~String> - Contains the URI to the entity. # * :type<~String> - Contains the MIME type of the entity. # @return [String] Object identifier of the task. def enqueue_task(operation, operation_name, owner, options={}) task_id = uuid now = DateTime.now data[:tasks][task_id] = { :cancel_requested => false, :details => '', :expiry_time => now + 86400, # in 24 hours :name => 'task', :progress => 1, :service_namespace => 'com.vmware.vcloud', :start_time => now, :status => 'running', }.merge(options).merge( :operation => operation, :operation_name => operation_name, :owner => owner ) task_id end # @note As far as this method is concerned, the only possible task # states are 'running' and 'success'. # # @param [Hash] response_body # @return [Boolean] def process_task(response_body) task_id = response_body[:href].split('/').last task = data[:tasks][task_id] if task[:status] == 'running' task[:end_time] = DateTime.now task[:progress] = 100 task[:status] = 'success' if task[:on_success] task[:on_success].call task.delete(:on_success) end end return true if task[:status] == 'success' raise TaskError.new "status: #{task[:status]}, error: #{task[:Error]}" end def add_id_from_href!(data={}) data[:id] = data[:href].split('/').last end private def make_href(path) "#{@end_point}#{path}" end def xmlns 'http://www.vmware.com/vcloud/v1.5' end def xmlns_xsi 'http://www.w3.org/2001/XMLSchema-instance' end def xsi_schema_location "http://www.vmware.com/vcloud/v1.5 http://#{@host}#{@path}/v1.5/schema/master.xsd" end end end end end fog-1.19.0/lib/fog/ecloud/0000755000004100000410000000000012261242551015201 5ustar www-datawww-datafog-1.19.0/lib/fog/ecloud/model.rb0000644000004100000410000000050712261242551016630 0ustar www-datawww-datamodule Fog module Ecloud class Model < Fog::Model attr_accessor :loaded alias_method :loaded?, :loaded def reload instance = super @loaded = true instance end def load_unless_loaded! unless @loaded reload end end end end end fog-1.19.0/lib/fog/ecloud/requests/0000755000004100000410000000000012261242551017054 5ustar www-datawww-datafog-1.19.0/lib/fog/ecloud/requests/compute/0000755000004100000410000000000012261242551020530 5ustar www-datawww-datafog-1.19.0/lib/fog/ecloud/requests/compute/get_organization.rb0000644000004100000410000000115312261242551024420 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_organization end class Mock def get_organization(uri) organization_id = id_from_uri(uri) organization = self.data[:organizations][organization_id] body = { :xmlns_i => "http://www.w3.org/2001/XMLSchema-instance", :href => "/cloudapi/ecloud/organizations/", :type => "application/vnd.tmrk.cloud.organization; type=collection" }.merge(organization) response(:body => body) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/virtual_machine_edit_hardware_configuration.rb0000644000004100000410000000454712261242551032052 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real def virtual_machine_edit_hardware_configuration(vm_uri, data) validate_data([:cpus, :memory, :disks, :nics], data) body = build_request_body_edit_hardware_configuration(data) request( :expects => 202, :method => 'PUT', :headers => {}, :body => body, :uri => vm_uri, :parse => true ) end def build_request_body_edit_hardware_configuration(data) xml = Builder::XmlMarkup.new xml.HardwareConfiguration do xml.ProcessorCount data[:cpus] xml.Memory do xml.Unit "MB" xml.Value data[:memory] end xml.Disks do data[:disks].each do |disk| xml.Disk do xml.Index disk[:Index] xml.Size do xml.Unit "GB" xml.Value disk[:Size][:Value] end end end end xml.Nics do data[:nics].each do |nic| xml.Nic do xml.UnitNumber nic[:UnitNumber] xml.MacAddress nic[:MacAddress] xml.Network(:href => nic[:Network][:href], :name => nic[:Network][:name], :type => "application/vnd.tmrk.cloud.network") do end end end end end end end class Mock def virtual_machine_edit_hardware_configuration(vm_uri, data) server_id = vm_uri.match(/(\d+)/)[1] server = self.data[:servers][server_id.to_i] task_id = Fog::Mock.random_numbers(10) task = { :id => task_id, :href => "/cloudapi/ecloud/tasks/#{task_id}", :type => "application/vnd.tmrk.cloud.task", :Operation => "Configure Server", :Status => "Complete", :ImpactedItem => Fog::Ecloud.keep(server, :name, :href, :type), :StartTime => Time.now.iso8601, :CompletedTime => Time.now.iso8601, :InitiatedBy => {}, } self.data[:tasks][task_id] = task response(:body => task) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_location.rb0000644000004100000410000000020112261242551023515 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_location end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/node_service_delete.rb0000644000004100000410000000177712261242551025060 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :node_service_delete, 202, 'DELETE' end class Mock def node_service_delete(uri) service_id = id_from_uri(uri) service = self.data[:node_services][service_id].dup self.data[:node_services].delete(service_id) task_id = Fog::Mock.random_numbers(10).to_i task = { :id => task_id, :href => "/cloudapi/ecloud/tasks/#{task_id}", :type => "application/vnd.tmrk.cloud.task", :Operation => "Delete Node Service", :Status => "Complete", :ImpactedItem => Fog::Ecloud.keep(service, :name, :href, :type), :StartTime => Time.now.iso8601, :CompletedTime => Time.now.iso8601, :InitiatedBy => {}, } self.data[:tasks][task_id] = task response(:body => task) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/virtual_machine_edit_assigned_ips.rb0000644000004100000410000000515512261242551027772 0ustar www-datawww-datamodule Fog module Compute class Ecloud module Shared def build_request_body_edit_assigned_ips(networks) xml = Builder::XmlMarkup.new xml.AssignedIpAddresses do xml.Networks do networks.each do |network| xml.Network(:href => network[:href], :type => network[:type]) do xml.IpAddresses do network[:ips].each do |ip| xml.IpAddress ip end end end end end end end end class Real def virtual_machine_edit_assigned_ips(href, options) body = build_request_body_edit_assigned_ips(options) request( :expects => 202, :method => 'PUT', :headers => {}, :body => body, :uri => href, :parse => true ) end end class Mock def virtual_machine_edit_assigned_ips(href, options) server_id = href.match(/(\d+)/)[1].to_i server = self.data[:servers][server_id] options.each do |network| network_id = id_from_uri(network[:href]) network = self.data[:networks][network_id] options.each.each do |net| net[:ips].each do |ip| ip = network[:IpAddresses][:IpAddress].detect { |iph| iph[:name] == ip } ip[:Host] = { :href => "/clouapi/ecloud/networkhosts/#{server_id}", :name => server[:name], :type => "application/vnd.tmrk.cloud.networkHost" } ip[:DetectedOn] = { :href => "/clouapi/ecloud/networkhosts/#{server_id}", :name => server[:name], :type => "application/vnd.tmrk.cloud.networkHost" } end end end task_id = Fog::Mock.random_numbers(10) task = { :id => task_id, :href => "/cloudapi/ecloud/tasks/#{task_id}", :type => "application/vnd.tmrk.cloud.task", :Operation => "Delete Server", :Status => "Complete", :ImpactedItem => Fog::Ecloud.keep(server, :name, :href, :type), :StartTime => Time.now.iso8601, :CompletedTime => Time.now.iso8601, :InitiatedBy => {}, } self.data[:tasks][task_id] = task response(:body => task) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_catalog_configuration.rb0000644000004100000410000000021512261242551026253 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_catalog_configuration end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_process.rb0000644000004100000410000000017712261242551023377 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_process end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/virtual_machine_import.rb0000644000004100000410000001462112261242551025625 0ustar www-datawww-datamodule Fog module Compute class Ecloud module Shared def validate_import_server_options(template_uri, options) required_opts = [:name, :cpus, :memory, :row, :group, :network_uri, :catalog_network_name] unless required_opts.all? { |opt| options.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(required_opts - options.keys).map(&:inspect).join(", ")}") end options[:network_uri] = [*options[:network_uri]] options[:template_uri] = template_uri options end def build_request_body_import(options) xml = Builder::XmlMarkup.new xml.ImportVirtualMachine(:name => options[:name]) do xml.ProcessorCount options[:cpus] xml.Memory do xml.Unit "MB" xml.Value options[:memory] end xml.Layout do xml.NewRow options[:row] xml.NewGroup options[:group] end xml.Description options[:description] if options[:tags] xml.Tags do options[:tags].each do |tag| xml.Tag tag end end end xml.CatalogEntry(:href => options[:template_uri]) xml.NetworkMappings do xml.NetworkMapping(:name => options[:catalog_network_name]) do xml.Network(:href => options[:network_uri][0]) end end if options[:operating_system] xml.OperatingSystem(:href => options[:operating_system][:href], :name => options[:operating_system][:name], :type => "application/vnd.tmrk.cloud.operatingSystem") end end end end class Real def virtual_machine_import(template_uri, options) options = validate_import_server_options(template_uri, options) request( :expects => 201, :method => 'POST', :body => build_request_body_import(options), :uri => options[:uri], :parse => true ) end end class Mock def virtual_machine_import(template_uri, options) options = validate_import_server_options(template_uri, options) compute_pool_id = options[:uri].match(/computePools\/(\d+)/)[1].to_i compute_pool = self.data[:compute_pools][compute_pool_id].dup environment = self.data[:environments][compute_pool[:environment_id]] networks = options[:network_uri].map{|nuri| self.data[:networks][id_from_uri(nuri)].dup} server_id = Fog::Mock.random_numbers(6).to_i row_id = Fog::Mock.random_numbers(6).to_i group_id = Fog::Mock.random_numbers(6).to_i nics = networks.each_with_index.map do |network, i| { :UnitNumber => i.to_s, :Name => "Network adapter #{i}", :MacAddress => Fog::Ecloud.mac_address, :Network => Fog::Ecloud.keep(network, :name, :href, :type) } end links = [Fog::Ecloud.keep(compute_pool, :name, :href, :type), Fog::Ecloud.keep(environment, :name, :href, :type)] networks.each{|network| links << Fog::Ecloud.keep(network, :name, :href, :type)} server = { :href => "/cloudapi/ecloud/virtualmachines/#{server_id}", :name => options[:name], :type => "application/vnd.tmrk.cloud.virtualMachine", :Description => options[:description], :Status => "Deployed", :PoweredOn => "false", :HardwareConfiguration => { :href => "/cloudapi/ecloud/virtualmachines/#{server_id}/hardwareconfiguration", :type => "application/vnd.tmrk.cloud.virtualMachineHardware", :Links => { :Link => { :href => "/cloudapi/ecloud/virtualmachines/#{server_id}", :name => options[:name], :type => "application/vnd.tmrk.cloud.virtualMachine", :rel => "up" } }, :ProcessorCount => options[:cpus], :Memory => { :Unit => "MB", :Value => options[:memory], }, :Disks => { # Default drive :Disk => [{ :Index => "0", :Name => "Hard Disk 1", :Size => { :Unit => "GB", :Value => "25" }, }], }, :Nics => { :Nic => nics, }, }, :Links => { :Link => links }, } row = { :id => row_id, :name => options[:row], :href => "/cloudapi/ecloud/layoutrows/#{row_id}", :type => "application/vnd.tmrk.cloud.layoutRow", :Links => { :Link => [ Fog::Ecloud.keep(environment, :name, :href, :type) ], }, :Index => 0, :Groups => { :Group => [ ], }, :environment_id => environment[:id], } group = { :id => group_id, :name => options[:group], :href => "/cloudapi/ecloud/layoutgroups/#{group_id}", :type => "application/vnd.tmrk.cloud.layoutGroup", :Links => { :Link => [ Fog::Ecloud.keep(row, :name, :href, :type), ], }, :Index => 0, :VirtualMachines => { :VirtualMachine => [ server, ], }, :row_id => row_id, } row[:Groups][:Group].push(group) layout[:Rows][:Row].push(row) server.merge!(:OperatingSystem => options[:operating_system].merge(:type => "application/vnd.tmrk.cloud.operatingSystem")) if options[:operating_system] server_response = response(:body => server) server.merge!(:compute_pool_id => compute_pool_id) self.data[:servers][server_id] = server self.data[:rows][row_id] = row self.data[:groups][group_id] = group server_response end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_api_key.rb0000644000004100000410000000017712261242551023342 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_api_key end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/virtual_machine_attach_disk.rb0000644000004100000410000000430212261242551026564 0ustar www-datawww-datamodule Fog module Compute class Ecloud module Shared def build_request_body_attach_disk(options) xml = Builder::XmlMarkup.new xml.AttachDisks(:name => options[:name]) do xml.DetachedDisks do xml.DetachedDisk(:href => options[:href], :name => options[:name], :type => "application/vnd.tmrk.cloud.detachedDisk") end end end end class Real def virtual_machine_attach_disk(href, options) body = build_request_body_attach_disk(options) request( :expects => 202, :method => 'POST', :headers => {}, :body => body, :uri => href, :parse => true ) end end class Mock def virtual_machine_attach_disk(href, options) server_id = href.match(/(\d+)/)[1].to_i server = self.data[:servers][server_id] compute_pool_id = server[:compute_pool_id] compute_pool = self.data[:compute_pools][compute_pool_id] detached_disk_id = options[:href].match(/(\d+)/)[1].to_i detached_disk = self.data[:detached_disks][detached_disk_id] new_index = (server[:HardwareConfiguration][:Disks][:Disk].map { |h| h[:Index].to_i }.sort.last + 1).to_s detached_disk[:Index] = new_index server[:HardwareConfiguration][:Disks][:Disk] << Fog::Ecloud.keep(detached_disk, :Index, :Size, :Name) self.data[:detached_disks].delete(detached_disk_id) task_id = Fog::Mock.random_numbers(10).to_i task = { :id => task_id, :href => "/cloudapi/ecloud/tasks/#{task_id}", :type => "application/vnd.tmrk.cloud.task", :Operation => "Attach Disk", :Status => "Complete", :ImpactedItem => Fog::Ecloud.keep(server, :href, :type), :StartTime => Time.now.iso8601, :CompletedTime => Time.now.iso8601, :InitiatedBy => {}, } self.data[:tasks][task_id] = task response(:body => task) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_admin_organization.rb0000644000004100000410000000105212261242551025566 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_admin_organization end class Mock def get_admin_organization(uri) organization_id = id_from_uri(uri) admin_organization = self.data[:admin_organizations][organization_id] if admin_organization body = Fog::Ecloud.slice(admin_organization, :id, :organization_id) response(:body => body) else response(:status => 404) # ? end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/node_service_edit.rb0000644000004100000410000000214712261242551024533 0ustar www-datawww-datamodule Fog module Compute class Ecloud module Shared def validate_edit_node_service_options(options) required_opts = [:name, :enabled] unless required_opts.all? { |opt| options.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(required_opts - options.keys).map(&:inspect).join(", ")}") end end def build_node_service_body_edit(options) xml = Builder::XmlMarkup.new xml.NodeService(:name => options[:name]) do xml.Enabled options[:enabled] if options[:description] xml.Description options[:description] end end end end class Real def node_service_edit(options) validate_edit_node_service_options(options) body = build_node_service_body_edit(options) request( :expects => 202, :method => 'PUT', :headers => {}, :body => body, :uri => options[:uri], :parse => true ) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_storage_usage_detail.rb0000644000004100000410000000021412261242551026063 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_storage_usage_detail end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_task.rb0000644000004100000410000000027312261242551022660 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_task end class Mock def get_task(uri) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_internet_services.rb0000644000004100000410000000061312261242551025447 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_internet_services end class Mock def get_internet_services(uri) public_ip_id = id_from_uri(uri) public_ip = self.data[:public_ips][public_ip_id] response(:body => Fog::Ecloud.slice(public_ip, :environment_id)) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_user.rb0000644000004100000410000000017412261242551022674 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_user end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_support_ticket.rb0000644000004100000410000000020612261242551024771 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_support_ticket end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/internet_service_edit.rb0000644000004100000410000000433612261242551025440 0ustar www-datawww-datamodule Fog module Compute class Ecloud module Shared def validate_edit_internet_service_options(options) required_opts = [:name, :enabled, :persistence] unless required_opts.all? { |opt| options.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(required_opts - options.keys).map(&:inspect).join(", ")}") end raise ArgumentError.new("Required data missing: #{:persistence[:type]}") unless options[:persistence][:type] end def build_node_service_body_edit(options) xml = Builder::XmlMarkup.new xml.InternetService(:name => options[:name]) do xml.Enabled options[:enabled] if options[:description] xml.Description options[:description] end xml.Persistence do xml.Type options[:persistence][:type] if options[:persistence][:timeout] xml.Timeout options[:persistence][:timeout] end end if options[:redirect_url] xml.RedirectUrl options[:redirect_url] end if options[:trusted_network_group] xml.TrustedNetworkGroup(:href => options[:trusted_network_group][:href], :name => service_data[:trusted_network_group][:name], :type => 'application/vnd.tmrk.cloud.trustedNetworkGroup') end if options[:backup_internet_service] xml.BackupInternetService(:href => options[:backup_internet_service][:href], :name => service_data[:backup_internet_service][:name], :type => 'application/vnd.tmrk.cloud.backupInternetService') end if options[:load_balancing_method] xml.LoadBalancingMethod options[:load_balancing_method] end end end end class Real def node_service_edit(options) validate_edit_node_service_options(options) body = build_node_service_body_edit(options) request( :expects => 202, :method => 'PUT', :headers => {}, :body => body, :uri => options[:uri], :parse => true ) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_physical_device.rb0000644000004100000410000000020712261242551025046 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_physical_device end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_associations.rb0000644000004100000410000000020412261242551024407 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_associations end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/virtual_machine_upload_file.rb0000644000004100000410000000200712261242551026571 0ustar www-datawww-datamodule Fog module Compute class Ecloud module Shared def validate_upload_file_options(options) required_opts = [:file, :path, :credentials] unless required_opts.all? { |opt| options.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(required_opts - options.keys).map(&:inspect).join(", ")}") end end end class Real def virtual_machine_upload_file(vm_uri, options) validate_upload_file_options(options) request( :expects => 204, :method => 'POST', :headers => {'Content-Type' => 'application/octet-stream', 'X-Guest-User' => options[:credentials][:user], 'X-Guest-Password' => options[:credentials][:password], 'Content-Range' => "0-#{options[:file].bytesize - 1}/#{options[:file].bytesize}"}, :body => options[:file], :uri => vm_uri + "?path=#{options[:path]}", :parse => true ) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_ip_address.rb0000644000004100000410000000107412261242551024033 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_ip_address end class Mock def get_ip_address(uri) network_id, ip_address_id = uri.match(/\/networks\/(\d+)\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/).captures ip_address = self.data[:networks][network_id.to_i][:IpAddresses][:IpAddress].detect{|ip| ip[:name] == ip_address_id }.dup if ip_address response(:body => ip_address) else response(:status => 404) # ? end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/public_ip_activate.rb0000644000004100000410000000022312261242551024700 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :public_ip_activate, 201, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_physical_devices.rb0000644000004100000410000000021012261242551025223 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_physical_devices end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/admin_disable_support_access.rb0000644000004100000410000000023312261242551026743 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :admin_disable_support_access, 204, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/rnat_associations_create_device.rb0000644000004100000410000000145012261242551027442 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def rnat_associations_create_device(data) validate_data([:host_ip_href, :public_ip_href], data) request( :body => generate_rnat_associations_create_device_request(data), :expects => 201, :method => "POST", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_rnat_associations_create_device_request(data) xml = Builder::XmlMarkup.new xml.CreateRnatAssociation do xml.PublicIp(:href => data[:public_ip_href]) xml.IpAddress(:href => data[:host_ip_href]) end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/node_service_create.rb0000644000004100000410000000633112261242551025050 0ustar www-datawww-datamodule Fog module Compute class Ecloud module Shared def validate_node_service_data(service_data) required_opts = [:name, :port, :enabled, :ip_address] unless required_opts.all? { |opt| service_data.has_key?(opt) } raise ArgumentError.new("Required Internet Service data missing: #{(required_opts - service_data.keys).map(&:inspect).join(", ")}") end end end class Real include Shared def node_service_create(service_data) validate_node_service_data(service_data) request( :body => generate_node_service_request(service_data), :expects => 201, :method => "POST", :headers => {}, :uri => service_data[:uri], :parse => true ) end private def generate_node_service_request(service_data) xml = Builder::XmlMarkup.new xml.CreateNodeService(:name => service_data[:name]) do xml.IpAddress(:href => service_data[:ip_address], :name => service_data[:ip_address].scan(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)[0]) xml.Port service_data[:port] xml.Enabled service_data[:enabled] if service_data[:description] xml.Description service_data[:description] end end end end class Mock def node_service_create(service_data) validate_node_service_data(service_data) internet_service_id = service_data[:uri].match(/(\d+)/)[1] internet_service = self.data[:internet_services][internet_service_id.to_i].dup network_id, ip_address_name = service_data[:ip_address].match(/\/(\d+)\/(.*)$/).captures network = self.data[:networks][network_id.to_i] ip_addresses = network[:IpAddresses][:IpAddress] ip_addresses = ip_addresses.is_a?(Array) ? ip_addresses : [ip_addresses] ip_address = ip_addresses.detect { |ip| ip[:name] == ip_address_name } service_id = Fog::Mock.random_numbers(6).to_i service = { :href => "/cloudapi/ecloud/nodeservices/#{service_id}", :name => service_data[:name], :type => "application/vnd.tmrk.cloud.nodeService", :Links => { :Link => [ Fog::Ecloud.keep(internet_service, :href, :name, :type), ], }, :Protocol => service_data[:protocol], :Port => service_data[:port], :Enabled => service_data[:enabled], :Description => service_data[:description], :IpAddress => { :href => ip_address[:href], :name => ip_address[:name], :type => ip_address[:type], :Network => { :href => network[:href], :name => network[:name], :type => network[:type], }, }, } node_service_response = response(:body => service) service.merge!(:internet_service => internet_service) self.data[:node_services][service_id] = service node_service_response end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_environment.rb0000644000004100000410000000153112261242551024260 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_environment end class Mock def get_environment(uri) environment_id = id_from_uri(uri) organizations = self.data[:organizations].values environment = nil catch(:found) do organizations.each do |organization| organization[:Locations][:Location].each do |location| environment = location[:Environments][:Environment].find{|e| e[:id] == environment_id} throw :found if environment end end end if environment body = environment.dup body.delete(:id) response(:body => body) else response(:status => 404) # ? end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/trusted_network_groups_create.rb0000644000004100000410000000257712261242551027255 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def trusted_network_groups_create(data) validate_data([:name], data) unless (data[:hosts] || data[:networks]) raise ArgumentError.new("Required data missing: Either hosts or networks must be present") end request( :body => generate_create_trusted_network_groups_request(data), :expects => 201, :method => "POST", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_create_trusted_network_groups_request(data) xml = Builder::XmlMarkup.new xml.CreateTrustedNetworkGroup(:name => data[:name]) do if data[:hosts] xml.Hosts do data[:hosts].each do |ip| xml.IpAddress ip end end end if data[:networks] xml.Networks do data[:networks].each do |network| address, subnet = network.split('/') xml.Network do xml.Address address xml.Size subnet end end end end end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_support_tickets.rb0000644000004100000410000000020712261242551025155 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_support_tickets end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_monitors.rb0000644000004100000410000000020012261242551023556 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_monitors end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/monitors_create_http.rb0000644000004100000410000000227712261242551025321 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def monitors_create_http(data) validate_data([:interval, :response_timeout, :retries, :downtime, :enabled, :request_uri, :response_codes], data) request( :body => generate_http_monitor_request(data), :expects => 201, :method => "POST", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_http_monitor_request(data) xml = Builder::XmlMarkup.new xml.CreateHttpMonitor do xml.Interval data[:interval] xml.ResponseTimeout data[:response_timeout] xml.Retries data[:retries] xml.Downtime data[:downtime] xml.Enabled data[:enabled] xml.RequestUri data[:request_uri] if data[:http_headers] xml.HttpHeaders data[:http_headers] end xml.ResponseCodes do data[:response_codes].each do |c| xml.ResponseCode c end end end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/monitors_edit_http.rb0000644000004100000410000000225412261242551024776 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def monitors_edit_http(data) validate_data([:interval, :response_timeout, :retries, :downtime, :enabled, :request_uri, :response_codes], data) request( :body => generate_edit_http_request(data), :expects => 200, :method => "PUT", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_edit_http_request(data) xml = Builder::XmlMarkup.new xml.HttpMonitor do xml.Interval data[:interval] xml.ResponseTimeout data[:response_timeout] xml.Retries data[:retries] xml.Downtime data[:downtime] xml.Enabled data[:enabled] xml.RequestUri data[:request_uri] if xml[:httpheaders] xml.HttpHeaders xml[:http_headers] end xml.ResponseCodes do xml[:response_codes].each do |c| xml.ResponseCode c end end end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_server.rb0000644000004100000410000000077012261242551023226 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_server end class Mock def get_server(uri) server_id = uri.match(/(\d+)/) server_id = server_id.nil? ? nil : server_id[1].to_i server = self.data[:servers][server_id] if server response(:body => Fog::Ecloud.slice(server, :id, :compute_pool_id)) else raise Fog::Errors::NotFound end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_processes.rb0000644000004100000410000000020112261242551023713 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_processes end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_memory_usage_detail_summary.rb0000644000004100000410000000022312261242551027504 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_memory_usage_detail_summary end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/rows_create.rb0000644000004100000410000000112712261242551023373 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def rows_create(data) validate_data([:name], data) request( :body => generate_rows_create_request(data), :expects => 201, :method => "POST", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_rows_create_request(data) xml = Builder::XmlMarkup.new xml.CreateLayoutRow(:name => data[:name]) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/rows_delete.rb0000644000004100000410000000073112261242551023372 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :rows_delete, 204, 'DELETE' end class Mock def rows_delete(uri) row_id = id_from_uri(uri) self.data[:rows].delete(row_id) self.data[:layouts].values.each do |layout| layout[:Rows][:Row].delete_if { |r| r[:id] == row_id } end response(:body => nil, :status => 204) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_server_configuration_option.rb0000644000004100000410000000022312261242551027536 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_server_configuration_option end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_node.rb0000644000004100000410000000074412261242551022646 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_node end class Mock def get_node(uri) node_service_id = id_from_uri(uri) node_service = self.data[:node_services][node_service_id.to_i] if node_service response(:body => Fog::Ecloud.slice(node_service, :id, :internet_service_id)) else raise Fog::Errors::NotFound end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/firewall_acls_create.rb0000644000004100000410000000551512261242551025215 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def firewall_acls_create(data) validate_data([:permission, :protocol, :source, :destination], data) raise ArgumentError.new("Required data missing: source[:type] is required") unless data[:source][:type] raise ArgumentError.new("Required data missing: destination[:type] is required") unless data[:destination][:type] request( :body => generate_create_firewall_acls_request(data), :expects => 201, :method => "POST", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_create_firewall_acls_request(data) xml = Builder::XmlMarkup.new xml.CreateFirewallAcl do xml.Permission data[:permission] xml.Protocol data[:protocol] xml.Source do xml.Type data[:source][:type] if data[:source][:external_ip_address] xml.ExternalIpAddress data[:external_ip_address] end if data[:source][:external_network] xml.ExternalNetwork do xml.Address data[:source][:external_network][:address] xml.Size data[:source][:external_network][:size] end end if data[:source][:ip_address] xml.IpAddress(:href => data[:source][:ip_address]) end if data[:source][:network] xml.Network(:href => data[:source][:network][:href], :name => data[:source][:network][:name]) end end xml.Destination do xml.Type data[:destination][:type] if data[:destination][:external_ip_address] xml.ExternalIpAddress data[:external_ip_address] end if data[:destination][:external_network] xml.ExternalNetwork do xml.Address data[:destination][:external_network][:address] xml.Size data[:destination][:external_network][:size] end end if data[:destination][:ip_address] xml.IpAddress(:href => data[:destination][:ip_address]) end if data[:destination][:network] xml.Network(:href => data[:destination][:network][:href], :name => data[:destination][:network][:name]) end end xml.PortRange do if data[:port_range][:start] xml.Start data[:port_range][:start] end if data[:port_range][:end] xml.End data[:port_range][:end] end end end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_servers.rb0000644000004100000410000000274512261242551023415 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_servers end class Mock def get_servers(uri) if uri =~ /layoutgroups/i group_id = id_from_uri(uri) group = self.data[:groups][group_id] servers = group[:VirtualMachines][:VirtualMachine] compute_pool_id = servers.first[:compute_pool_id] unless servers.empty? compute_pool = self.data[:compute_pools][compute_pool_id] unless compute_pool_id.nil? elsif uri =~ /computepool/i compute_pool_id = id_from_uri(uri) compute_pool = self.data[:compute_pools][compute_pool_id] servers = self.data[:servers].values.select{|cp| cp[:compute_pool_id] == compute_pool_id} servers = servers.map{|server| Fog::Ecloud.slice(server, :id, :compute_pool_id)} end links = if compute_pool.nil? [] else [Fog::Ecloud.keep(compute_pool, :name, :href, :type),] end server_response = {:VirtualMachine => (servers.size > 1 ? servers : servers.first)} # GAH body = { :href => uri, :type => "application/vnd.tmrk.cloud.virtualMachine; type=collection", :Links => { :Link => links } }.merge(server_response) response(:body => body) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_operating_system.rb0000644000004100000410000000140512261242551025310 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_operating_system end class Mock def get_operating_system(uri) os_name, compute_pool_id = uri.match(/operatingsystems\/(.*)\/computepools\/(\d+)$/).captures compute_pool_id = compute_pool_id.to_i operating_systems = self.data[:operating_systems].values.select{|os| os[:compute_pool_id] == compute_pool_id} operating_system = operating_systems.find{|os| os[:short_name] == os_name} if operating_system response(:body => Fog::Ecloud.slice(operating_system, :id, :compute_pool_id, :short_name)) else response(:status => 404) # ? end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/power_off.rb0000644000004100000410000000021212261242551023036 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :power_off, 202, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/admin_edit_authentication_levels.rb0000644000004100000410000000145712261242551027632 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real def authentication_levels_edit(data) validate_data([:basic, :sha1, :sha256, :sha512], data) body = build_authentication_levels_edit(data) request( :expects => 202, :method => 'PUT', :headers => {}, :body => body, :uri => data[:uri], :parse => true ) end private def build_authentication_levels_edit(data) xml = Builder::XmlMarkup.new xml.AuthenticationLevels do xml.BasicEnabled data[:basic] xml.SHA1Enabled data[:sha1] xml.SHA256Enabled data[:sha256] xml.SHA512Enabled data[:sha512] end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/virtual_machine_detach_disk.rb0000644000004100000410000000443612261242551026560 0ustar www-datawww-datamodule Fog module Compute class Ecloud module Shared def build_request_body_detach_disk(options) xml = Builder::XmlMarkup.new xml.DetachDisk(:name => options[:name]) do xml.Description options[:description] xml.Disk do xml.Index options[:disk][:Index] end end end end class Real def virtual_machine_detach_disk(href, options) body = build_request_body_detach_disk(options) request( :expects => 201, :method => 'POST', :headers => {}, :body => body, :uri => href, :parse => true ) end end class Mock def virtual_machine_detach_disk(href, options) server_id = href.match(/(\d+)/)[1].to_i server = self.data[:servers][server_id] compute_pool_id = server[:compute_pool_id] compute_pool = self.data[:compute_pools][compute_pool_id] detached_disk_id = Fog::Mock.random_numbers(6).to_i detached_disk = { :id => detached_disk_id, :href => "/cloudapi/ecloud/detacheddisks/#{detached_disk_id}", :name => options[:name], :type => "application/vnd.tmrk.cloud.detachedDisk", :Links => { :Link => [ Fog::Ecloud.keep(compute_pool, :href, :name, :type), ], }, :Description => options[:description], :LastKnownVirtualMachineConfiguration => Fog::Ecloud.keep(server, :name, :ProcessorCount, :Memory, :OperatingSystem), :Type => "Data", :Size => { :Unit => "GB", :Value => options[:disk][:Size][:Value], }, :Status => "Available", } server[:HardwareConfiguration][:Disks][:Disk].delete_if { |disk| disk[:Index] == options[:disk][:Index] } detached_disk_response = response(:body => detached_disk) detached_disk.merge!(:compute_pool_id => compute_pool_id) self.data[:detached_disks][detached_disk_id] = detached_disk detached_disk_response end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_backup_internet_services.rb0000644000004100000410000000022012261242551026766 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_backup_internet_services end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_guest_processes.rb0000644000004100000410000000020712261242551025130 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_guest_processes end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/monitors_edit_ecv.rb0000644000004100000410000000211212261242551024565 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def monitors_edit_ecv(data) validate_data([:interval, :response_timeout, :retries, :downtime, :enabled, :send_string, :receive_string], data) request( :body => generate_edit_ecv_request(data), :expects => 200, :method => "PUT", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_edit_ecv_request(data) xml = Builder::XmlMarkup.new xml.EcvMonitor do xml.Interval data[:interval] xml.ResponseTimeout data[:response_timeout] xml.Retries data[:retries] xml.Downtime data[:downtime] xml.Enabled data[:enabled] xml.SendString data[:send_string] if data[:http_headers] xml.HttpHeaders data[:http_headers] end xml.ReceiveString data[:receive_string] end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_public_ip.rb0000644000004100000410000000072112261242551023662 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_public_ip end class Mock def get_public_ip(uri) public_ip_id = id_from_uri(uri) public_ip = self.data[:public_ips][public_ip_id] if public_ip response(:body => Fog::Ecloud.slice(public_ip, :id, :environment_id)) else raise Fog::Errors::NotFound end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_users.rb0000644000004100000410000000017512261242551023060 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_users end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/admin_edit_password_complexity_rules.rb0000644000004100000410000000647612261242551030600 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real def password_complexity_rules_edit(data) validate_data([:rule_type], data) if data[:rule_type] == "Custom" raise ArgumentError.new("Required data missing: custom_rules") unless data[:custom_rules] end validate_data([:minimum_characters, :minimum_uppercase_characters, :minimum_lowercase_characters, :minimum_numeric_characters, :minimum_special_characters, :maximum_consecutive_characters_from_prior_passwords, :minimum_lifetime_restriction, :minimum_generations_before_reuse], data[:custom_rules]) body = build_password_complexity_rules_edit(data) request( :expects => 202, :method => 'PUT', :headers => {}, :body => body, :uri => data[:uri], :parse => true ) end private def build_password_complexity_rules_edit(data) xml = Builder::XmlMarkup.new xml.PasswordComplexityRules do xml.RuleType data[:rule_type] if data[:rule_type] == "Custom" xml.CustomRules do xml.MinimumCharacters do xml.Enabled data[:custom_rules][:minimum_characters][:enabled] xml.Value data[:custom_rules][:minimum_characters][:value] end xml.MinimumUpperCaseCharacters do xml.Enabled data[:custom_rules][:minimum_uppercase_characters][:enabled] xml.Value data[:custom_rules][:minimum_uppercase_characters][:value] end xml.MinimumLowerCaseCharacters do xml.Enabled data[:custom_rules][:minimum_lowercase_characters][:enabled] xml.Value data[:custom_rules][:minimum_lowercase_characters][:value] end xml.MinimumNumericCharacters do xml.Enabled data[:custom_rules][:minimum_numeric_characters][:enabled] xml.Value data[:custom_rules][:minimum_numeric_characters][:value] end xml.MinimumSpecialCharacters do xml.Enabled data[:custom_rules][:minimum_special_characters][:enabled] xml.Value data[:custom_rules][:minimum_special_characters][:value] end xml.MaximumConsecutiveCharactersFromPriorPasswords do xml.Enabled data[:custom_rules][:maximum_consecutive_characters_from_prior_passwords][:enabled] xml.Value data[:custom_rules][:maximum_consecutive_characters_from_prior_passwords][:value] end xml.MinimumLifetimeRestriction do xml.Enabled data[:custom_rules][:minimum_lifetime_restriction][:enabled] xml.Value data[:custom_rules][:minimum_lifetime_restriction][:value] end xml.MinimumGenerationsBeforeReuse do xml.Enabled data[:custom_rules][:minimum_generations_before_reuse][:enabled] xml.Value data[:custom_rules][:minimum_generations_before_reuse][:value] end end end if data[:description] xml.Description data[:description] end end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_network.rb0000644000004100000410000000070712261242551023411 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_network end class Mock def get_network(uri) network_id = id_from_uri(uri) network = self.data[:networks][network_id].dup if network response(:body => Fog::Ecloud.slice(network, :id, :environment_id)) else response(:status => 404) # ? end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_rnats.rb0000644000004100000410000000017512261242551023046 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_rnats end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_environments.rb0000644000004100000410000000000012261242551024431 0ustar www-datawww-datafog-1.19.0/lib/fog/ecloud/requests/compute/get_compute_pool.rb0000644000004100000410000000074512261242551024427 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_compute_pool end class Mock def get_compute_pool(uri) compute_pool_id = id_from_uri(uri) compute_pool = self.data[:compute_pools][compute_pool_id] if compute_pool response(:body => Fog::Ecloud.slice(compute_pool, :id, :environment)) else response(:status => 404) # ? end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_authentication_level.rb0000644000004100000410000000021412261242551026117 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_authentication_level end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/monitors_edit_ping.rb0000644000004100000410000000155012261242551024752 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def monitors_edit_ping(data) validate_data([:interval, :response_timeout, :retries, :downtime, :enabled], data) request( :body => generate_edit_ping_request(data), :expects => 200, :method => "PUT", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_edit_ping_request(data) xml = Builder::XmlMarkup.new xml.PingMonitor do xml.Interval data[:interval] xml.ResponseTimeout data[:response_timeout] xml.Retries data[:retries] xml.Downtime data[:downtime] xml.Enabled data[:enabled] end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/power_shutdown.rb0000644000004100000410000000021712261242551024144 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :power_shutdown, 202, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/backup_internet_service_create.rb0000644000004100000410000000252212261242551027276 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def backup_internet_service_create(data) validate_data([:name, :protocol, :enabled, :persistence], data) unless data[:persistence][:type] raise ArgumentError.new("Required data missing: :persistence[:type]") end request( :body => generate_backup_internet_service_request(data), :expects => 201, :method => "POST", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_backup_internet_service_request(data) xml = Builder::XmlMarkup.new xml.CreateBackupInternetService(:name => data[:name]) do xml.Protocol data[:protocol] xml.Enabled data[:enabled] if data[:description] xml.Description data[:description] end xml.Persistence do xml.Type data[:persistence][:type] if data[:persistence][:timeout] xml.Timeout data[:persistence][:timeout] end end if data[:redirect_url] xml.RedirectUrl data[:redirect_url] end end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/compute_pool_edit.rb0000644000004100000410000000171212261242551024570 0ustar www-datawww-datamodule Fog module Compute class Ecloud module Shared def validate_edit_compute_pool_options(options) required_opts = [:name] unless required_opts.all? { |opt| options.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(required_opts - options.keys).map(&:inspect).join(", ")}") end end def build_compute_pool_body_edit(options) xml = Builder::XmlMarkup.new xml.ComputePool(:name => options[:name]) do end end end class Real def compute_pool_edit(options) validate_edit_compute_pool_options(options) body = build_compute_pool_body_edit(options) request( :expects => 200, :method => 'PUT', :headers => {}, :body => body, :uri => options[:uri], :parse => true ) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/groups_movedown.rb0000644000004100000410000000022012261242551024304 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :groups_movedown, 204, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_server_configuration_options.rb0000644000004100000410000000022412261242551027722 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_server_configuration_options end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_groups.rb0000644000004100000410000000046012261242551023233 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_groups end class Mock def get_groups(uri) row_id = id_from_uri(uri) row = self.data[:rows][row_id] response(:body => row) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/firewall_acls_delete.rb0000644000004100000410000000022712261242551025207 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :firewall_acls_delete, 202, 'DELETE' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/virtual_machine_copy.rb0000644000004100000410000001066612261242551025272 0ustar www-datawww-datamodule Fog module Compute class Ecloud module Shared def validate_create_server_options_copy(template_uri, options) required_opts = [:name, :cpus, :memory, :row, :group, :customization, :network_uri, :source] if options[:customization] == :windows required_opts.push(:windows_password) else required_opts.push(:ssh_key_uri) end unless required_opts.all? { |opt| options.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(required_opts - options.keys).map(&:inspect).join(", ")}") end options[:network_uri] = options[:network_uri].is_a?(String) ? [options[:network_uri]] : options[:network_uri] options[:network_uri].map! do |uri| network = get_network(uri).body if options[:ips] ip = options[:ips][options[:network_uri].index(uri)] end {:href => uri, :name => network[:name], :ip => ip} end options end def build_request_body_copy(options) xml = Builder::XmlMarkup.new xml.CopyVirtualMachine(:name => options[:name]) do xml.Source(:href => options[:source], :type => "application/vnd.tmrk.cloud.virtualMachine") xml.ProcessorCount options[:cpus] xml.Memory do xml.Unit "MB" xml.Value options[:memory] end xml.Layout do xml.NewRow options[:row] xml.NewGroup options[:group] end if options[:customization] == :windows xml.WindowsCustomization do xml.NetworkSettings do xml.NetworkAdapterSettings do options[:network_uri].each do |uri| xml.NetworkAdapter do xml.Network(:href => uri[:href], :name => uri[:name], :type => "application/vnd.tmrk.cloud.network") xml.IpAddress uri[:ip] end end end if options[:dns_settings] xml.DnsSettings do xml.PrimaryDns options[:dns_settings][:primary_dns] if options[:dns_settings][:secondary_dns] xml.SecondaryDns options[:dns_settings][:secondary_dns] end end end end xml.Password options[:windows_password] if options[:windows_license_key] xml.LicenseKey options[:windows_license_key] end end else xml.LinuxCustomization do xml.NetworkSettings do xml.NetworkAdapterSettings do options[:network_uri] = options[:network_uri].is_a?(String) ? [options[:network_uri]] : options[:network_uri] options[:network_uri].each do |uri| xml.NetworkAdapter do xml.Network(:href => uri[:href], :name => uri[:name], :type => "application/vnd.tmrk.cloud.network") xml.IpAddress uri[:ip] end end end if options[:dns_settings] xml.DnsSettings do xml.PrimaryDns options[:dns_settings][:primary_dns] if options[:dns_settings][:secondary_dns] xml.SecondaryDns options[:dns_settings][:secondary_dns] end end end end end xml.SshKey(:href => options[:ssh_key_uri]) end xml.Description options[:description] xml.Tags do options[:tags].each do |tag| xml.Tag tag end end xml.PoweredOn options[:powered_on] end end end class Real def virtual_machine_copy(template_uri, options) options = validate_create_server_options_copy(template_uri, options) body = build_request_body_copy(options) request( :expects => 201, :method => 'POST', :headers => {}, :body => body, :uri => template_uri, :parse => true ) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_layout.rb0000644000004100000410000000051112261242551023226 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_layout end class Mock def get_layout(uri) environment_id = id_from_uri(uri) layout = self.data[:layouts][environment_id] response(:body => layout) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/trusted_network_groups_delete.rb0000644000004100000410000000024012261242551027235 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :trusted_network_groups_delete, 202, 'DELETE' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/rnat_associations_edit_network.rb0000644000004100000410000000127312261242551027361 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def rnat_associations_edit_network(data) validate_data([:href], data) request( :body => generate_rnat_associations_edit_network_request(data), :expects => 202, :method => "PUT", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_rnat_associations_edit_network_request(data) xml = Builder::XmlMarkup.new xml.NetworkRnat do xml.Rnat(:href => data[:href]) end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_detached_disks.rb0000644000004100000410000000173212261242551024655 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_detached_disks end class Mock def get_detached_disks(uri) compute_pool_id = id_from_uri(uri) compute_pool = self.data[:compute_pools][compute_pool_id] detached_disks = self.data[:detached_disks].values.select{|cp| cp[:compute_pool_id] == compute_pool_id} detached_disks = detached_disks.map{|dd| Fog::Ecloud.slice(dd, :id, :compute_pool_id)} detached_disk_response = {:DetachedDisk => (detached_disks.size > 1 ? detached_disks : detached_disks.first)} # GAH body = { :href => uri, :type => "application/vnd.tmrk.cloud.detachedDisk; type=collection", :Links => { :Link => Fog::Ecloud.keep(compute_pool, :name, :href, :type), } }.merge(detached_disk_response) response(:body => body) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/groups_moveup.rb0000644000004100000410000000021612261242551023766 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :groups_moveup, 204, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/groups_delete.rb0000644000004100000410000000125212261242551023716 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :groups_delete, 204, 'DELETE' end class Mock def groups_delete(uri) group_id = id_from_uri(uri) self.data[:groups].delete(group_id) self.data[:rows].values.each do |row| row[:Groups][:Group].delete_if { |g| g[:id] == group_id } end self.data[:layouts].values.each do |layout| layout[:Rows][:Row].each do |row| row[:Groups][:Group].delete_if { |g| g[:id] == group_id } end end response(:body => nil, :status => 204) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_api_keys.rb0000644000004100000410000000020012261242551023510 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_api_keys end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_roles.rb0000644000004100000410000000017512261242551023043 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_roles end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_trusted_network_group.rb0000644000004100000410000000021512261242551026371 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_trusted_network_group end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_ssh_key.rb0000644000004100000410000000072112261242551023361 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_ssh_key end class Mock def get_ssh_key(uri) ssh_key_id = id_from_uri(uri).to_i ssh_key = self.data[:ssh_keys][ssh_key_id.to_i] if ssh_key response(:body => Fog::Ecloud.slice(ssh_key, :id, :admin_organization)) else response(:status => 404) # ? end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_row.rb0000644000004100000410000000045212261242551022524 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_row end class Mock def get_row(uri) row_id = id_from_uri(uri) row = self.data[:rows][row_id] response(:body => row) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/rows_movedown.rb0000644000004100000410000000021612261242551023764 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :rows_movedown, 204, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_public_ips.rb0000644000004100000410000000156712261242551024056 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_public_ips end class Mock def get_public_ips(uri) environment_id = id_from_uri(uri) environment = self.data[:environments][environment_id] public_ips = self.data[:public_ips].values.select{|cp| cp[:environment_id] == environment_id} public_ips = public_ips.map{|pi| Fog::Ecloud.slice(pi, :id, :environment_id)} public_ip_response = {:PublicIp => (public_ips.size > 1 ? public_ips : public_ips.first)} # GAH body = { :href => uri, :type => "application/vnd.tmrk.cloud.publicIp; type=collection", :Links => { :Link => environment, } }.merge(public_ip_response) response(:body => body) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_role.rb0000644000004100000410000000017412261242551022657 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_role end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_catalog_configurations.rb0000644000004100000410000000021612261242551026437 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_catalog_configurations end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_password_complexity_rules.rb0000644000004100000410000000022112261242551027240 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_password_complexity_rules end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_locations.rb0000644000004100000410000000020212261242551023701 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_locations end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_template.rb0000644000004100000410000000076312261242551023535 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_template end class Mock def get_template(uri) template_id, compute_pool_id = uri.match(/(\d+).*\/(\d+)$/).captures template = self.data[:templates][template_id.to_i] if template response(:body => Fog::Ecloud.slice(template, :id, :environment)) else response(:status => 404) # ? end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/monitors_create_ping.rb0000644000004100000410000000156712261242551025300 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def monitors_create_ping(data) validate_data([:interval, :response_timeout, :retries, :downtime, :enabled], data) request( :body => generate_ping_monitor_request(data), :expects => 201, :method => "POST", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_ping_monitor_request(data) xml = Builder::XmlMarkup.new xml.CreatePingMonitor do xml.Interval data[:interval] xml.ResponseTimeout data[:response_timeout] xml.Retries data[:retries] xml.Downtime data[:downtime] xml.Enabled data[:enabled] end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_operating_system_families.rb0000644000004100000410000000214412261242551027162 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_operating_system_families end class Mock def get_operating_system_families(uri) compute_pool_id = id_from_uri(uri) compute_pool = self.data[:compute_pools][compute_pool_id] operating_system_families = self.data[:operating_system_families].values.select{|osf| osf[:compute_pool_id] == compute_pool_id} operating_system_families = operating_system_families.map{|osf| Fog::Ecloud.slice(osf, :id, :compute_pool_id)}.map{|osf| osf[:OperatingSystemFamily]} operating_system_family_response = {:OperatingSystemFamily => (operating_system_families.size > 1 ? operating_system_families : operating_system_families.first)} # GAH body = { :href => uri, :type => "application/vnd.tmrk.cloud.operatingSystemFamily; type=collection", :Links => { :Link => compute_pool, } }.merge(operating_system_family_response) response(:body => body) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_trusted_network_groups.rb0000644000004100000410000000021612261242551026555 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_trusted_network_groups end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_templates.rb0000644000004100000410000000272512261242551023720 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_templates end class Mock def get_templates(uri) # /cloudapi/ecloud/computepools/compute_pools/534 compute_pool_id = id_from_uri(uri) compute_pool = self.data[:compute_pools][compute_pool_id] templates = self.data[:templates].values.select{|template| template[:compute_pool_id] == compute_pool_id} templates = templates.map{|template| Fog::Ecloud.slice(template, :id, :compute_pool)} template_response = {:Template => (templates.size > 1 ? templates : templates.first)} # GAH body = { :href => uri, :type => "application/vnd.tmrk.cloud.template; type=collection", :Links => { :Link => compute_pool, }, :Families => { :Family => { :Name => "Standard Templates", :Categories => { :Category => [ { :Name => "OS Only", :OperatingSystems => { :OperatingSystem => { :Name => "Linux", :Templates => template_response, } } } ] } } } } response(:body => body) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/rnat_associations_delete.rb0000644000004100000410000000023112261242551026116 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :rnat_associations_delete, 202, 'DELETE' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_storage_usage_detail_summary.rb0000644000004100000410000000022412261242551027641 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_storage_usage_detail_summary end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/backup_internet_service_delete.rb0000644000004100000410000000024112261242551027271 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :backup_internet_service_delete, 202, 'DELETE' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/groups_create.rb0000644000004100000410000000134512261242551023722 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def groups_create(data) validate_data([:name], data) request( :body => generate_groups_create_request(data), :expects => 201, :method => "POST", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_groups_create_request(data) xml = Builder::XmlMarkup.new xml.CreateLayoutGroup(:name => data[:name]) do xml.Row(:href => data[:href], :name => data[:row_name], :type => "application/vnd.tmrk.cloud.layoutRow") end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_detached_disk.rb0000644000004100000410000000076212261242551024474 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_detached_disk end class Mock def get_detached_disk(uri) detached_disk_id = id_from_uri(uri) detached_disk = self.data[:detached_disks][detached_disk_id] if detached_disk response(:body => Fog::Ecloud.slice(detached_disk, :id, :compute_pool_id)) else raise Fog::Errors::NotFound end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/internet_service_delete.rb0000644000004100000410000000201112261242551025741 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :internet_service_delete, 202, 'DELETE' end class Mock def internet_service_delete(uri) service_id = id_from_uri(uri) service = self.data[:internet_services][service_id].dup self.data[:internet_services].delete(service_id) task_id = Fog::Mock.random_numbers(10).to_i task = { :id => task_id, :href => "/cloudapi/ecloud/tasks/#{task_id}", :type => "application/vnd.tmrk.cloud.task", :Operation => "Delete Service", :Status => "Complete", :ImpactedItem => Fog::Ecloud.keep(service, :name, :href, :type), :StartTime => Time.now.iso8601, :CompletedTime => Time.now.iso8601, :InitiatedBy => {}, } self.data[:tasks][task_id] = task response(:body => task) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/power_reset.rb0000644000004100000410000000021412261242551023410 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :power_reset, 202, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_internet_service.rb0000644000004100000410000000101312261242551025257 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_internet_service end class Mock def get_internet_service(uri) internet_service_id = id_from_uri(uri) internet_service = self.data[:internet_services][internet_service_id.to_i] if internet_service response(:body => Fog::Ecloud.slice(internet_service, :id, :public_ip)) else raise Fog::Errors::NotFound end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/virtual_machine_edit.rb0000644000004100000410000000234312261242551025236 0ustar www-datawww-datamodule Fog module Compute class Ecloud module Shared def validate_edit_server_options(options) required_opts = [:name] unless required_opts.all? { |opt| options.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(required_opts - options.keys).map(&:inspect).join(", ")}") end end def build_request_body_edit(options) xml = Builder::XmlMarkup.new xml.VirtualMachine(:name => options[:name]) do if options[:description] xml.Description options[:description] end if options[:tags] xml.Tags do options[:tags].each do |tag| xml.Tag tag end end end end end end class Real def virtual_machine_edit(vm_uri, options) validate_edit_server_options(options) body = build_request_body_edit(options) request( :expects => [202,204], :method => 'PUT', :headers => {}, :body => body, :uri => vm_uri, :parse => true ) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/admin_edit_login_banner.rb0000644000004100000410000000125612261242551025673 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real def login_banner_edit(data) validate_data([:display], data) body = build_login_banner_edit(data) request( :expects => 200, :method => 'PUT', :headers => {}, :body => body, :uri => data[:uri], :parse => true ) end private def build_login_banner_edit(data) xml = Builder::XmlMarkup.new xml.LoginBanner do xml.Display data[:display] xml.Text data[:text] if data[:text] end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/internet_service_create.rb0000644000004100000410000001007612261242551025754 0ustar www-datawww-datamodule Fog module Compute class Ecloud module Shared def validate_internet_service_data(service_data) required_opts = [:name, :protocol, :port, :description, :enabled, :persistence] unless required_opts.all? { |opt| service_data.has_key?(opt) } raise ArgumentError.new("Required Internet Service data missing: #{(required_opts - service_data.keys).map(&:inspect).join(", ")}") end if service_data[:trusted_network_group] raise ArgumentError.new("Required Trusted Network Group data missing: #{([:name, :href] - service_data[:trusted_network_group].keys).map(&:inspect).join(", ")}") end if service_data[:backup_internet_service] raise ArgumentError.new("Required Backup Internet Service data missing: #{([:name, :href] - service_data[:backup_internet_service].keys).map(&:inspect).join(", ")}") end end end class Real include Shared def internet_service_create(service_data) validate_internet_service_data(service_data) request( :body => generate_internet_service_request(service_data), :expects => 201, :method => "POST", :headers => {}, :uri => service_data[:uri], :parse => true ) end private def generate_internet_service_request(service_data) xml = Builder::XmlMarkup.new xml.CreateInternetService(:name => service_data[:name]) do xml.Protocol service_data[:protocol] xml.Port service_data[:port] xml.Enabled service_data[:enabled] xml.Description service_data[:description] xml.Persistence do xml.Type service_data[:persistence][:type] if service_data[:persistence][:timeout] xml.Timeout service_data[:persistence][:timeout] end end if service_data[:redirect_url] xml.RedirectUrl service_data[:redirect_url] end if service_data[:trusted_network_group] xml.TrustedNetworkGroup(:href => service_data[:trusted_network_group][:href], :name => service_data[:trusted_network_group][:name], :type => 'application/vnd.tmrk.cloud.trustedNetworkGroup') end if service_data[:backup_internet_service] xml.BackupInternetService(:href => service_data[:backup_internet_service][:href], :name => service_data[:backup_internet_service][:name], :type => 'application/vnd.tmrk.cloud.backupInternetService') end if service_data[:load_balancing_method] xml.LoadBalancingMethod service_data[:load_balancing_method] end end end end class Mock def internet_service_create(service_data) validate_internet_service_data(service_data) public_ip_id = service_data[:uri].match(/(\d+)/)[1] public_ip = self.data[:public_ips][public_ip_id.to_i].dup service_id = Fog::Mock.random_numbers(6).to_i service = { :href => "/cloudapi/ecloud/internetServices/#{service_id}", :name => service_data[:name], :type => "application/vnd.tmrk.cloud.internetService", :Links => { :Link => [ Fog::Ecloud.keep(public_ip, :href, :name, :type), ], }, :Protocol => service_data[:protocol], :Port => service_data[:port], :Enabled => service_data[:enabled], :Description => service_data[:description], :PublicIp => Fog::Ecloud.keep(public_ip, :href, :name, :type), :Persistence => { :Type => service_data[:persistence][:type], }, } internet_service_response = response(:body => service) service.merge!(:public_ip => public_ip) self.data[:internet_services][service_id] = service internet_service_response end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_networks.rb0000644000004100000410000000151612261242551023573 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_networks end class Mock def get_networks(uri) environment_id = id_from_uri(uri) environment = self.data[:environments][environment_id] networks = self.data[:networks].values.select{|n| n[:environment_id] == environment_id}.dup networks = networks.map{|n| Fog::Ecloud.slice(n, :environment, :id)} body = { :href => uri, :type => "application/vnd.tmrk.cloud.network; type=collection", :Links => { :Link => Fog::Ecloud.keep(environment, :name, :href, :type) }, :Network => (networks.size > 1 ? networks : networks.first), } response(:body => body) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_catalog.rb0000644000004100000410000000017712261242551023333 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_catalog end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/trusted_network_groups_edit.rb0000644000004100000410000000256212261242551026731 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def trusted_network_groups_edit(data) validate_data([:name], data) unless (data[:hosts] || data[:networks]) raise ArgumentError.new("Required data missing: Either hosts or networks must be present") end request( :body => generate_edit_trusted_network_groups_request(data), :expects => 202, :method => "PUT", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_edit_trusted_network_groups_request(data) xml = Builder::XmlMarkup.new xml.TrustedNetworkGroup(:name => data[:name]) do if data[:hosts] xml.Hosts do data[:hosts].each do |ip| xml.IpAddress ip end end end if data[:networks] xml.Networks do data[:networks].each do |network| address, subnet = network.split('/') xml.Network do xml.Address address xml.Size subnet end end end end end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_nodes.rb0000644000004100000410000000056312261242551023030 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_nodes end class Mock def get_nodes(uri) internet_service_id = id_from_uri(uri) internet_service = self.data[:internet_services][internet_service_id] response(:body => internet_service) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_firewall_acls.rb0000644000004100000410000000020512261242551024520 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_firewall_acls end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_layouts.rb0000644000004100000410000000051312261242551023413 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_layouts end class Mock def get_layouts(uri) environment_id = id_from_uri(uri) layout = self.data[:layouts][environment_id] response(:body => layout) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_hardware_configurations.rb0000644000004100000410000000034312261242551026623 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_hardware_configurations end class Mock def get_hardware_configurations(uri) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_rows.rb0000644000004100000410000000022612261242551022706 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_rows end class Mock end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/monitors_disable.rb0000644000004100000410000000022112261242551024405 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :monitors_disable, 202, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/monitors_enable.rb0000644000004100000410000000022012261242551024227 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :monitors_enable, 202, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_organizations.rb0000644000004100000410000000126412261242551024606 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_organizations end # Real class Mock def get_organizations(uri) organizations = self.data[:organizations].values.dup organizations.each{|org| org.delete(:id)} body = { :xmlns_i => "http://www.w3.org/2001/XMLSchema-instance", :href => "/cloudapi/ecloud/organizations/", :type => "application/vnd.tmrk.cloud.organization; type=collection" }.merge(:Organization => (organizations.size > 1 ? organizations : organizations.first)) response(:body => body) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_guest_process.rb0000644000004100000410000000020512261242551024576 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_guest_process end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/monitors_create_ecv.rb0000644000004100000410000000213112261242551025104 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def monitors_create_ecv(data) validate_data([:interval, :response_timeout, :retries, :downtime, :enabled, :send_string, :receive_string], data) request( :body => generate_ecv_monitor_request(data), :expects => 201, :method => "POST", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_ecv_monitor_request(data) xml = Builder::XmlMarkup.new xml.CreateEcvMonitor do xml.Interval data[:interval] xml.ResponseTimeout data[:response_timeout] xml.Retries data[:retries] xml.Downtime data[:downtime] xml.Enabled data[:enabled] xml.SendString data[:send_string] if data[:http_headers] xml.HttpHeaders data[:http_headers] end xml.ReceiveString data[:receive_string] end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_compute_pools.rb0000644000004100000410000000171612261242551024611 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_compute_pools end class Mock def get_compute_pools(uri) # /cloudapi/ecloud/computepools/environments/534 environment_id = id_from_uri(uri) environment = self.data[:environments][environment_id] compute_pools = self.data[:compute_pools].values.select{|cp| cp[:environment_id] == environment_id} compute_pools = compute_pools.map{|cp| Fog::Ecloud.slice(cp, :id, :environment_id)} compute_pool_response = {:ComputePool => (compute_pools.size > 1 ? compute_pools : compute_pools.first)} # GAH body = { :href => uri, :type => "application/vnd.tmrk.cloud.computePool; type=collection", :Links => { :Link => environment, } }.merge(compute_pool_response) response(:body => body) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_login_banner.rb0000644000004100000410000000020412261242551024345 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_login_banner end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_password_complexity_rule.rb0000644000004100000410000000022012261242551027054 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_password_complexity_rule end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/virtual_machine_delete.rb0000644000004100000410000000304012261242551025546 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :virtual_machine_delete, 202, 'DELETE' end class Mock def virtual_machine_delete(uri) server_id = id_from_uri(uri) server = self.data[:servers][server_id] self.data[:servers].delete(server_id) self.data[:groups].values.each do |group| group[:VirtualMachines][:VirtualMachine].delete_if { |s| s[:name] == server[:name] } end self.data[:networks].values.each do |network| network[:IpAddresses][:IpAddress].each do |ip| unless ip[:Host].nil? ip[:Host] = nil if ip[:Host][:name] == server[:name] end unless ip[:DetectedOn].nil? ip[:DetectedOn] = nil if ip[:DetectedOn][:name] == server[:name] end end end task_id = Fog::Mock.random_numbers(10) task = { :id => task_id, :href => "/cloudapi/ecloud/tasks/#{task_id}", :type => "application/vnd.tmrk.cloud.task", :Operation => "Delete Server", :Status => "Complete", :ImpactedItem => Fog::Ecloud.keep(server, :name, :href, :type), :StartTime => Time.now.iso8601, :CompletedTime => Time.now.iso8601, :InitiatedBy => {}, } self.data[:tasks][task_id] = task response(:body => task) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_cpu_usage_detail_summary.rb0000644000004100000410000000022012261242551026760 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_cpu_usage_detail_summary end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/rows_moveup.rb0000644000004100000410000000021412261242551023437 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :rows_moveup, 204, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_tags.rb0000644000004100000410000000017412261242551022654 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_tags end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/groups_edit.rb0000644000004100000410000000112312261242551023376 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def groups_edit(data) validate_data([:name], data) request( :body => generate_groups_edit_request(data), :expects => 204, :method => "PUT", :headers => {}, :uri => data[:uri], :parse => false ) end private def generate_groups_edit_request(data) xml = Builder::XmlMarkup.new xml.LayoutGroup(:name => data[:name]) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_login_banners.rb0000644000004100000410000000020512261242551024531 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_login_banners end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_backup_internet_service.rb0000644000004100000410000000021712261242551026611 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_backup_internet_service end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_group.rb0000644000004100000410000000047012261242551023051 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_group end class Mock def get_group(uri) group_id = id_from_uri(uri) group = self.data[:groups][group_id] response(:body => group) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/virtual_machine_copy_identical.rb0000644000004100000410000000254312261242551027301 0ustar www-datawww-datamodule Fog module Compute class Ecloud module Shared def validate_create_server_options_identical(template_uri, options) required_opts = [:name, :row, :group, :source] unless required_opts.all? { |opt| options.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(required_opts - options.keys).map(&:inspect).join(", ")}") end options end def build_request_body_identical(options) xml = Builder::XmlMarkup.new xml.CopyIdenticalVirtualMachine(:name => options[:name]) do xml.Source(:href => options[:source], :type => "application/vnd.tmrk.cloud.virtualMachine") xml.Layout do xml.NewRow options[:row] xml.NewGroup options[:group] end xml.Description options[:description] end end end class Real def virtual_machine_copy_identical(template_uri, options) options = validate_create_server_options_identical(template_uri, options) body = build_request_body_identical(options) request( :expects => 201, :method => 'POST', :headers => {}, :body => body, :uri => template_uri, :parse => true ) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_hardware_configuration.rb0000644000004100000410000000170412261242551026442 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_hardware_configuration end class Mock def get_hardware_configuration(uri) server_id = uri.match(/(\d+)/)[1] server = self.data[:servers][server_id.to_i] server_hardware_configuration = server[:HardwareConfiguration] new_hardware_configuration = { :href => server_hardware_configuration[:href], :type => server_hardware_configuration[:type], :ProcessorCount => server_hardware_configuration[:ProcessorCount], :Memory => server_hardware_configuration[:Memory], :Disks => server_hardware_configuration[:Disks], :Nics => server_hardware_configuration[:Nics], } response(:body => {:HardwareConfiguration => new_hardware_configuration}) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_monitor.rb0000644000004100000410000000017712261242551023410 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_monitor end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_association.rb0000644000004100000410000000020312261242551024223 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_association end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_virtual_machine_assigned_ips.rb0000644000004100000410000000273012261242551027620 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real def get_virtual_machine_assigned_ips(virtual_machine_id) request( :uri => "#{base_path}/virtualmachines/#{virtual_machine_id}/assignedips", :parse => true ) end end class Mock def get_virtual_machine_assigned_ips(virtual_machine_id) server = self.data[:servers][virtual_machine_id.to_i] compute_pool = self.data[:compute_pools][server[:compute_pool_id]] environment_id = compute_pool[:environment_id] environment = self.data[:environments][environment_id] networks = self.data[:networks].values.select{|n| n[:environment_id] == environment_id} networks = networks.map{|n| deep_copy(Fog::Ecloud.slice(n, :environment, :id))} networks.each do |network| address = network[:IpAddresses][:IpAddress].map{|ia| ia[:name]} network[:IpAddresses][:IpAddress] = address.first end body = { :href => "/cloudapi/ecloud/virtualMachines/#{virtual_machine_id}/assignedIps", :type => "application/vnd.tmrk.cloud.network", :Links => { :Link => Fog::Ecloud.keep(environment, :name, :href, :type) }, :Networks => {:Network => (networks.size > 1 ? networks : networks.first)}, } response(:body => body) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/power_on.rb0000644000004100000410000000021112261242551022677 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :power_on, 202, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_authentication_levels.rb0000644000004100000410000000021512261242551026303 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_authentication_levels end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_memory_usage_detail.rb0000644000004100000410000000021312261242551025726 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_memory_usage_detail end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/backup_internet_service_edit.rb0000644000004100000410000000251112261242551026756 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def backup_internet_service_edit(data) validate_data([:name, :protocol, :enabled, :persistence], data) unless data[:persistence][:type] raise ArgumentError.new("Required data missing: :persistence[:type]") end request( :body => generate_backup_internet_service_request(data), :expects => 202, :method => "PUT", :headers => {}, :uri => data[:uri], :parse => true ) end private def generate_backup_internet_service_request(data) xml = Builder::XmlMarkup.new xml.BackupInternetService(:name => data[:name]) do xml.Protocol data[:protocol] xml.Enabled data[:enabled] if data[:description] xml.Description data[:description] end xml.Persistence do xml.Type data[:persistence][:type] if data[:persistence][:timeout] xml.Timeout data[:persistence][:timeout] end end if data[:redirect_url] xml.RedirectUrl data[:redirect_url] end end end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_firewall_acl.rb0000644000004100000410000000020412261242551024334 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_firewall_acl end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_tasks.rb0000644000004100000410000000017512261242551023044 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_tasks end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/monitors_create_loopback.rb0000644000004100000410000000023112261242551026120 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :monitors_create_loopback, 201, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/rows_edit.rb0000644000004100000410000000111312261242551023050 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real include Shared def rows_edit(data) validate_data([:name], data) request( :body => generate_rows_edit_request(data), :expects => 204, :method => "PUT", :headers => {}, :uri => data[:uri], :parse => false ) end private def generate_rows_edit_request(data) xml = Builder::XmlMarkup.new xml.LayoutRow(:name => data[:name]) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_cpu_usage_detail.rb0000644000004100000410000000021012261242551025202 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_cpu_usage_detail end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/virtual_machine_create_from_template.rb0000644000004100000410000002305112261242551030471 0ustar www-datawww-datamodule Fog module Compute class Ecloud module Shared def validate_create_server_options(template_uri, options) required_opts = [:name, :cpus, :memory, :row, :group, :customization, :network_uri] if options[:customization] == :windows required_opts.push(:windows_password) else required_opts.push(:ssh_key_uri) end unless required_opts.all? { |opt| options.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(required_opts - options.keys).map(&:inspect).join(", ")}") end options[:network_uri] = options[:network_uri].is_a?(String) ? [options[:network_uri]] : options[:network_uri] options[:network_uri].map! do |uri| network = get_network(uri).body if options[:ips] ip = options[:ips][options[:network_uri].index(uri)] end {:href => uri, :name => network[:name], :ip => ip} end options[:template_uri] = template_uri options end def build_request_body(options) xml = Builder::XmlMarkup.new xml.CreateVirtualMachine(:name => options[:name]) do xml.ProcessorCount options[:cpus] xml.Memory do xml.Unit "MB" xml.Value options[:memory] end xml.Layout do xml.NewRow options[:row] xml.NewGroup options[:group] end xml.Description options[:description] xml.Tags do options[:tags].each do |tag| xml.Tag tag end end if options[:customization] == :windows xml.WindowsCustomization do xml.NetworkSettings do xml.NetworkAdapterSettings do options[:network_uri].each do |uri| xml.NetworkAdapter do xml.Network(:href => uri[:href], :name => uri[:name], :type => "application/vnd.tmrk.cloud.network") xml.IpAddress uri[:ip] end end end if options[:dns_settings] xml.DnsSettings do xml.PrimaryDns options[:dns_settings][:primary_dns] if options[:dns_settings][:secondary_dns] xml.SecondaryDns options[:dns_settings][:secondary_dns] end end end end xml.Password options[:windows_password] if options[:windows_license_key] xml.LicenseKey options[:windows_license_key] end end else xml.LinuxCustomization do xml.NetworkSettings do xml.NetworkAdapterSettings do options[:network_uri] = options[:network_uri].is_a?(String) ? [options[:network_uri]] : options[:network_uri] options[:network_uri].each do |uri| xml.NetworkAdapter do xml.Network(:href => uri[:href], :name => uri[:name], :type => "application/vnd.tmrk.cloud.network") xml.IpAddress uri[:ip] end end end if options[:dns_settings] xml.DnsSettings do xml.PrimaryDns options[:dns_settings][:primary_dns] if options[:dns_settings][:secondary_dns] xml.SecondaryDns options[:dns_settings][:secondary_dns] end end end end xml.SshKey(:href => options[:ssh_key_uri]) end end xml.PoweredOn options[:powered_on] xml.Template(:href => options[:template_uri], :type => options[:template_type]) end end end class Real def virtual_machine_create_from_template(template_uri, options) options = validate_create_server_options(template_uri, options) request( :expects => 201, :method => 'POST', :body => build_request_body(options), :uri => options[:uri], :parse => true ) end end class Mock def virtual_machine_create_from_template(template_uri, options) options = validate_create_server_options(template_uri, options) server_id = Fog::Mock.random_numbers(7).to_i row_id = Fog::Mock.random_numbers(6).to_i group_id = Fog::Mock.random_numbers(6).to_i template_id, compute_pool_id = template_uri.match(/\/templates\/(\d+)\/computepools\/(\d+)$/).captures compute_pool = self.data[:compute_pools][compute_pool_id.to_i].dup environment = self.data[:environments][compute_pool[:environment_id]] layout = self.data[:layouts][environment[:id]] networks = options[:network_uri] nics = networks.each_with_index.map do |network, i| { :UnitNumber => i.to_s, :Name => "Network adapter #{i}", :MacAddress => Fog::Ecloud.mac_address, :Network => Fog::Ecloud.keep(network, :name, :href, :type), } end links = [Fog::Ecloud.keep(compute_pool, :name, :href, :type), Fog::Ecloud.keep(environment, :name, :href, :type)] networks.each do |network| links << Fog::Ecloud.keep(network, :name, :href, :type) network_id = id_from_uri(network[:href]) ip = self.data[:networks][network_id][:IpAddresses][:IpAddress].detect { |ip| ip[:id] = network[:ip] } ip[:DetectedOn] = {:href => "/cloudapi/ecloud/networkhosts/#{server_id}", :name => options[:name], :type => "application/vnd.tmrk.cloud.networkHost"} ip[:Host] = {:href => "/cloudapi/ecloud/networkhosts/#{server_id}", :name => options[:name], :type => "application/vnd.tmrk.cloud.networkHost"} end server = { :href => "/cloudapi/ecloud/virtualmachines/#{server_id}", :name => options[:name], :type => "application/vnd.tmrk.cloud.virtualMachine", :Description => options[:description], :Status => "Deployed", :HardwareConfiguration => { :href => "/cloudapi/ecloud/virtualmachines/#{server_id}/hardwareconfiguration", :type => "application/vnd.tmrk.cloud.virtualMachineHardware", :Links => { :Link => { :href => "/cloudapi/ecloud/virtualmachines/#{server_id}", :name => options[:name], :type => "application/vnd.tmrk.cloud.virtualMachine", :rel => "up", } }, :ProcessorCount => options[:cpus], :Memory => { :Unit => "MB", :Value => options[:memory], }, :Disks => { :Disk => [{ :Index => "0", :Name => "Hard Disk 1", :Size => { :Unit => "GB", :Value => "25", }, }], }, :Nics => { :Nic => nics, }, }, :IpAddresses => { :AssignedIpAddresses => { :Networks => { :Network => self.data[:networks].dup.values, } } }, :Links => { :Link => links }, } row = { :id => row_id, :name => options[:row], :href => "/cloudapi/ecloud/layoutrows/#{row_id}", :type => "application/vnd.tmrk.cloud.layoutRow", :Links => { :Link => [ Fog::Ecloud.keep(environment, :name, :href, :type) ], }, :Index => 0, :Groups => { :Group => [ ], }, :environment_id => environment[:id], } group = { :id => group_id, :name => options[:group], :href => "/cloudapi/ecloud/layoutgroups/#{group_id}", :type => "application/vnd.tmrk.cloud.layoutGroup", :Links => { :Link => [ Fog::Ecloud.keep(row, :name, :href, :type), ], }, :Index => 0, :VirtualMachines => { :VirtualMachine => [ server, ], }, :row_id => row_id, } row[:Groups][:Group].push(group) layout[:Rows][:Row].push(row) server.merge!(:OperatingSystem => options[:operating_system].merge(:type => "application/vnd.tmrk.cloud.operatingSystem")) if options[:operating_system] server_response = response(:body => server) server.merge!(:compute_pool_id => compute_pool[:id]) self.data[:servers][server_id] = server self.data[:rows][row_id] = row self.data[:groups][group_id] = group server_response end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_rnat.rb0000644000004100000410000000017412261242551022662 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_rnat end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_network_summary.rb0000644000004100000410000000020712261242551025161 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_network_summary end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_ssh_keys.rb0000644000004100000410000000165612261242551023554 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_ssh_keys end class Mock def get_ssh_keys(uri) organization_id = id_from_uri(uri) organization = self.data[:organizations][organization_id] ssh_keys = self.data[:ssh_keys].values.select{|key| key[:admin_organization_id] == organization_id} ssh_keys = ssh_keys.map{|key| Fog::Ecloud.slice(key, :id, :admin_organization)} ssh_key_response = {:SshKey => (ssh_keys.size > 1 ? ssh_keys : ssh_keys.first)} # GAH body = { :href => "/cloudapi/ecloud/admin/organizations/#{organization_id}/sshKeys", :type => "application/vnd.tmrk.cloud.sshKey; type=collection", :Links => { :Link => organization, }, }.merge(ssh_key_response) response(:body => body) end end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/admin_enable_support_access.rb0000644000004100000410000000023212261242551026565 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :admin_enable_support_access, 204, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_tag.rb0000644000004100000410000000017312261242551022470 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_tag end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/monitors_create_default.rb0000644000004100000410000000023012261242551025751 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :monitors_create_default, 201, 'POST' end end end end fog-1.19.0/lib/fog/ecloud/requests/compute/get_catalog_item.rb0000644000004100000410000000020412261242551024340 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Real basic_request :get_catalog_item end end end end fog-1.19.0/lib/fog/ecloud/mock_data_classes.rb0000644000004100000410000004026512261242551021174 0ustar www-datawww-datamodule Fog module Ecloud module MockDataClasses class Base < Hash def self.base_url=(url) @base_url = url end self.base_url = "http://vcloud.example.com" def self.base_url @base_url end def first raise "Don't do this" end def last raise "Don't do this" end def initialize(data = {}, parent = nil) @parent = parent replace(data) end def _parent @parent end def base_url Base.base_url end def href [base_url, self.class.name.split("::").last, object_id].join("/") end def inspect "<#{self.class.name} #{object_id} data=#{super}>" end end class MockData < Base def versions @versions ||= [] end def organizations @organizations ||= [] end def organization_collection_from_href(href) find_href_in(href, all_organizations) end def all_organizations organizations.map(&:environments).flatten end def organization_from_href(href) find_href_in(href, all_organizations) end def all_vdcs organizations.map(&:environments).flatten end def vdc_from_href(href) find_href_in(href, all_vdcs) end def all_catalogs all_vdcs.map(&:catalog).flatten end def catalog_from_href(href) find_href_in(href, all_catalogs) end def all_catalog_items all_catalogs.map(&:items).flatten end def catalog_item_from_href(href) find_href_in(href, all_catalog_items) end def all_virtual_machines all_vdcs.map(&:virtual_machines).flatten end def virtual_machine_from_href(href) find_href_prefixed_in(href, all_virtual_machines) end def all_networks all_vdcs.map(&:networks).flatten end def network_from_href(href) find_href_in(href, all_networks) end def all_network_extensions all_networks.map(&:extensions).flatten end def network_extension_from_href(href) find_href_in(href, all_network_extensions) end def all_vdc_internet_service_collections all_vdcs.map(&:internet_service_collection).flatten end def vdc_internet_service_collection_from_href(href) find_href_in(href, all_vdc_internet_service_collections) end def all_backup_internet_services all_vdc_internet_service_collections.map(&:backup_internet_services).flatten end def backup_internet_service_from_href(href) find_href_in(href, all_backup_internet_services) end def all_public_ip_collections all_vdcs.map {|v| v.public_ip_collection }.flatten end def public_ip_collection_from_href(href) find_href_in(href, all_public_ip_collections) end def all_public_ips all_public_ip_collections.map(&:items).flatten end def public_ip_from_href(href) find_href_in(href, all_public_ips) end def all_public_ip_internet_service_collections all_public_ips.map(&:internet_service_collection).flatten end def public_ip_internet_service_collection_from_href(href) find_href_in(href, all_public_ip_internet_service_collections) end def all_public_ip_internet_services all_public_ip_internet_service_collections.map(&:items).flatten end def public_ip_internet_service_from_href(href) find_href_in(href, all_public_ip_internet_services) end def all_public_ip_internet_service_node_collections all_public_ip_internet_services.map(&:node_collection).flatten end def public_ip_internet_service_node_collection_from_href(href) find_href_in(href, all_public_ip_internet_service_node_collections) end def all_public_ip_internet_service_nodes all_public_ip_internet_service_node_collections.map(&:items).flatten end def public_ip_internet_service_node_from_href(href) find_href_in(href, all_public_ip_internet_service_nodes) end def all_network_ip_collections all_networks.map(&:ip_collection) end def network_ip_collection_from_href(href) find_href_in(href, all_network_ip_collections) end def all_network_ips all_network_ip_collections.map {|c| c.items.values }.flatten end def network_ip_from_href(href) find_href_in(href, all_network_ips) end private def find_href_in(href, objects) objects.detect {|o| o.href == href } end def find_href_prefixed_in(href, objects) objects.detect {|o| href =~ %r{^#{o.href}($|/)} } end end class MockVersion < Base def version self[:version] end def supported !!self[:supported] end def login_url href end end class MockOrganization < Base def name self[:name] end def environments @vdcs ||= [] end end class MockVdc < Base def name self[:name] end def storage_allocated self[:storage_allocated] || 200 end def storage_used self[:storage_used] || 105 end def cpu_allocated self[:cpu_allocated] || 10000 end def memory_allocated self[:memory_allocated] || 20480 end def catalog @catalog ||= MockCatalog.new({}, self) end def networks @networks ||= [] end def virtual_machines @virtual_machines ||= [] end def task_list @task_list ||= MockTaskList.new({}, self) end # for TM eCloud, should probably be subclassed def public_ip_collection @public_ip_collection ||= MockPublicIps.new({}, self) end def internet_service_collection @internet_service_collection ||= MockVdcInternetServices.new({}, self) end def firewall_acls @firewall_acls ||= MockFirewallAcls.new({}, self) end end class MockTaskList < Base def name self[:name] || "Tasks List" end end class MockCatalog < Base def name self[:name] || "Catalog" end def items @items ||= [] end end class MockCatalogItem < Base def name self[:name] end def disks @disks ||= MockVirtualMachineDisks.new(self) end def customization @customization ||= MockCatalogItemCustomization.new({}, self) end def vapp_template @vapp_template ||= MockCatalogItemVappTemplate.new({ :name => name }, self) end end class MockCatalogItemCustomization < Base def name self[:name] || "Customization Options" end end class MockCatalogItemVappTemplate < Base def name self[:name] end end class MockNetwork < Base def name self[:name] || subnet end def subnet self[:subnet] end def gateway self[:gateway] || subnet_ips[1] end def netmask self[:netmask] || subnet_ipaddr.mask end def dns "8.8.8.8" end def features [ { :type => :FenceMode, :value => "isolated" } ] end def ip_collection @ip_collection ||= MockNetworkIps.new({}, self) end def extensions @extensions ||= MockNetworkExtensions.new({}, self) end def random_ip usable_subnet_ips[rand(usable_subnet_ips.length)] end # for TM eCloud. should probably be a subclass def rnat self[:rnat] end def usable_subnet_ips subnet_ips[3..-2] end def address subnet_ips.first end def broadcast subnet_ips.last end private def subnet_ipaddr @ipaddr ||= IPAddr.new(subnet) end def subnet_ips subnet_ipaddr.to_range.to_a.map(&:to_s) end end class MockNetworkIps < Base def items @items ||= _parent.usable_subnet_ips.inject({}) do |out, subnet_ip| out.update(subnet_ip => MockNetworkIp.new({ :ip => subnet_ip }, self)) end end def ordered_ips items.values.sort_by {|i| i.ip.split(".").map(&:to_i) } end def name "IP Addresses" end end class MockNetworkIp < Base def name self[:name] || ip end def ip self[:ip] end def used_by self[:used_by] || _parent._parent._parent.virtual_machines.detect {|v| v.ip == ip } end def status if used_by "Assigned" else "Available" end end def rnat self[:rnat] || _parent._parent.rnat end def rnat_set? !!self[:rnat] end end class MockNetworkExtensions < Base def name _parent.name end def gateway _parent.gateway end def broadcast _parent.broadcast end def address _parent.address end def rnat _parent.rnat end def type self[:type] || "DMZ" end def vlan object_id.to_s end def friendly_name "#{name} (#{type}_#{object_id})" end end class MockVirtualMachine < Base def name self[:name] end def ip self[:ip] end def cpus self[:cpus] || 1 end def memory self[:memory] || 1024 end def disks @disks ||= MockVirtualMachineDisks.new(self) end def status self[:status] || 2 end def power_off! self[:status] = 2 end def power_on! self[:status] = 4 end def size disks.inject(0) {|s, d| s + d.vcloud_size } end def network_ip if network = _parent.networks.detect {|n| n.ip_collection.items[ip] } network.ip_collection.items[ip] end end # from fog ecloud server's _compose_vapp_data def to_configure_vapp_hash { :name => name, :cpus => cpus, :memory => memory, :disks => disks.map {|d| { :number => d.address.to_s, :size => d.vcloud_size, :resource => d.vcloud_size.to_s } } } end def href(purpose = :base) case purpose when :base super() when :power_on super() + "/power/action/powerOn" when :power_off super() + "/power/action/powerOff" end end end class MockVirtualMachineDisks < Array def initialize(parent = nil) @parent = parent end def _parent @parent end def <<(disk) next_address = 0 disk_with_max_address = max {|a, b| a[:address] <=> b[:address] } disk_with_max_address && next_address = disk_with_max_address.address + 1 disk[:address] ||= next_address super(disk) if (addresses = map {|d| d.address }).uniq.size != size raise "Duplicate disk address in: #{addresses.inspect} (#{size})" end sort! {|a, b| a.address <=> b.address } self end def at_address(address) detect {|d| d.address == address } end end class MockVirtualMachineDisk < Base def size self[:size].to_i end def vcloud_size # kilobytes size * 1024 end def address self[:address].to_i end end # for Terremark eCloud class MockVdcInternetServices < Base def href _parent.href + "/internetServices" end def name "Internet Services" end def items public_ip_internet_services + backup_internet_services end def public_ip_internet_services _parent.public_ip_collection.items.inject([]) do |services, public_ip| services + public_ip.internet_service_collection.items end end def backup_internet_services @backup_internet_services ||= [] end end class MockBackupInternetService < Base def name self[:name] || "Backup Internet Service #{object_id}" end def protocol self[:protocol] end def port 0 end def enabled self[:enabled].to_s.downcase != "false" end def timeout self[:timeout] || 2 end def description self[:description] || "Description for Backup Service #{name}" end def redirect_url nil end def node_collection @node_collection ||= MockPublicIpInternetServiceNodes.new({}, self) end end class MockFirewallAcls < Base def name "Firewall Access List" end end class MockPublicIps < Base def name self[:name] || "Public IPs" end def items @items ||= [] end end class MockPublicIp < Base def name self[:name] end def internet_service_collection @internet_service_collection ||= MockPublicIpInternetServices.new({}, self) end end class MockPublicIpInternetServices < Base def href _parent.href + "/internetServices" end def items @items ||= [] end end class MockPublicIpInternetService < Base def name self[:name] || "Public IP Service #{object_id}" end def description self[:description] || "Description for Public IP Service #{name}" end def protocol self[:protocol] end def port self[:port] end def enabled !!self[:enabled] end def redirect_url self[:redirect_url] end def timeout self[:timeout] || 2 end def node_collection @node_collection ||= MockPublicIpInternetServiceNodes.new({}, self) end def monitor nil end def backup_service self[:backup_service] end end class MockPublicIpInternetServiceNodes < Base def href _parent.href + "/nodeServices" end def items @items ||= [].tap do |node_array| node_array.instance_variable_set("@default_port", _parent.port) def node_array.<<(node) node[:port] ||= @default_port super end end end end class MockPublicIpInternetServiceNode < Base def ip_address self[:ip_address] end def name self[:name] || "Public IP Service Node #{object_id}" end def description self[:description] || "Description for Public IP Service Node #{name}" end def port self[:port] end def enabled self[:enabled].to_s.downcase != "false" end def enabled=(new_value) self[:enabled] = new_value end end end end end fog-1.19.0/lib/fog/ecloud/generate_collection.rb0000644000004100000410000000627312261242551021543 0ustar www-datawww-datarequire 'optparse' class String def camelize self.split('_').map {|w| w.capitalize}.join end end options = {} OptionParser.new do |opts| opts.banner = "Usage: #{__FILE__} [options]" opts.on("-m", "--model-name NAME", "Model Name") { |v| options[:model] = v } opts.on("-c", "--collection-name NAME", "Collection Name") { |v| options[:collection] = v } opts.on("-M", "--methods a:href,b:href,c:href", Array, "List of methods to be defined and href to the method") { |v| options[:methods] = v.map { |a| a.split(':') } } opts.on("-a", "--attributes name:alias,other_name:other_alias", Array, "List of attributes to be defined") { |v| options[:attributes] = v.map { |a| a.split(':') } } end.parse! if options[:methods] methods = options[:methods].map do |m| m = < service, :href => "#{m[1]}") end METHOD end.join("\n ") end if options[:attributes] attributes = options[:attributes].map do |a| a = "attribute :#{a[0]}, :aliases => :#{a[1] || a[0].camelize}" end.join("\n ") end collection_file = "#{File.expand_path(File.dirname(__FILE__))}/models/compute/#{options[:collection]}.rb" model_file = "#{File.expand_path(File.dirname(__FILE__))}/models/compute/#{options[:model]}.rb" collection_request_file = "#{File.expand_path(File.dirname(__FILE__))}/requests/compute/get_#{options[:collection]}.rb" model_request_file = "#{File.expand_path(File.dirname(__FILE__))}/requests/compute/get_#{options[:model]}.rb" collection = < opts } if opts.is_a?(String) msg = ":href missing, call with a :href pointing to #{if opts[:message] opts[:message] elsif opts[:parent] "the #{opts[:parent]} whos #{self.class.to_s.split('::').last.downcase} you want to enumerate" else "the resource" end}" raise Fog::Errors::Error.new(msg) end end end end end fog-1.19.0/lib/fog/ecloud/ipaddr.rb0000644000004100000410000000007512261242551016773 0ustar www-datawww-dataclass IPAddr def mask _to_string(@mask_addr) end end fog-1.19.0/lib/fog/ecloud/models/0000755000004100000410000000000012261242551016464 5ustar www-datawww-datafog-1.19.0/lib/fog/ecloud/models/compute/0000755000004100000410000000000012261242551020140 5ustar www-datawww-datafog-1.19.0/lib/fog/ecloud/models/compute/task.rb0000644000004100000410000000125612261242551021433 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Task < Fog::Ecloud::Model identity :href attribute :type , :aliases => :Type attribute :operation, :aliases => :Operation attribute :status, :aliases => :Status attribute :impacted_item, :aliases => :ImpactedItem attribute :start_time, :aliases => :StartTime attribute :completed_time, :aliases => :CompletedTime attribute :notes, :aliases => :Notes attribute :error_message, :aliases => :ErrorMessage attribute :initiated_by, :aliases => :InitiatedBy def ready? !self.completed_time.nil? end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/location.rb0000644000004100000410000000110112261242551022266 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Location < Fog::Ecloud::Model identity :href ignore_attributes :xmlns, :xmlns_xsi, :xmlns_xsd, :xmlns_i attribute :name, :aliases => :Name attribute :type, :aliases => :Type def catalog(org_href) @catalog ||= Fog::Compute::Ecloud::Catalog.new(:service => service, :href => "#{service.base_path}/admin/catalog/organizations/#{org_href.scan(/\d+/)[0]}/locations/#{id}") end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/detached_disk.rb0000644000004100000410000000114512261242551023241 0ustar www-datawww-datamodule Fog module Compute class Ecloud class DetachedDisk < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :status, :aliases => :Status attribute :size, :aliases => :Size def ready? unless status =~ /AttachInProgress|DetachInProgress/ true else false end end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/password_complexity_rules.rb0000644000004100000410000000111112261242551026010 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/password_complexity_rule' module Fog module Compute class Ecloud class PasswordComplexityRules < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::PasswordComplexityRule def all data = service.get_password_complexity_rules(href).body load(data) end def get(uri) if data = service.get_password_complexity_rule(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/monitors.rb0000644000004100000410000000106512261242551022341 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/monitor' module Fog module Compute class Ecloud class Monitors < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::Monitor def all data = service.get_monitors(href).body load(data) end def get(uri) if data = service.get_monitor(uri) new(data.body) end rescue Fog::Errors::NotFound nil end def from_data(data) new(data) end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/ip_address.rb0000644000004100000410000000234512261242551022606 0ustar www-datawww-datamodule Fog module Compute class Ecloud class IpAddress < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links, :squash => :Link attribute :host, :aliases => :Host attribute :detected_on, :aliases => :DetectedOn attribute :rnat, :aliases => :RnatAddress attribute :reserved, :aliases => :Reserved, :type => :boolean def status (detected_on || host) ? "Assigned" : "Available" end def id href.match(/((\d+{1,3}\.){3}(\d+{1,3}))$/)[1] end def server @server ||= begin reload unless other_links server_link = other_links.find{|l| l[:type] == "application/vnd.tmrk.cloud.virtualMachine"} self.service.servers.get(server_link[:href]) end end def network reload if other_links.nil? network_href = other_links.detect { |l| l[:type] == "application/vnd.tmrk.cloud.network" }[:href] network = self.service.networks.get(network_href) end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/rnats.rb0000644000004100000410000000077012261242551021620 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/rnat' module Fog module Compute class Ecloud class Rnats < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::Rnat def all data = service.get_rnats(href).body[:Rnats][:Rnat] load(data) end def get(uri) if data = service.get_rnat(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/organization.rb0000644000004100000410000000575412261242551023204 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Organization < Fog::Ecloud::Model identity :href ignore_attributes :xmlns, :xmlns_xsi, :xmlns_xsd, :xmlns_i attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links, :squash => :Link def locations @locations ||= Fog::Compute::Ecloud::Locations.new( :service => service, :href => href ) end def environments @environments ||= self.service.environments(:href => href) end def tags @tags ||= self.service.tags(:href => "#{service.base_path}/deviceTags/organizations/#{id}") end def admin @admin ||= self.service.admin_organizations.new(:href => "#{service.base_path}/admin/organizations/#{id}") end def users @users ||= self.service.users(:href => "#{service.base_path}/admin/users/organizations/#{id}") end def support_tickets(type = :open) case type when :open @support_tickets ||= Fog::Compute::Ecloud::SupportTickets.new(:service => service, :href => "#{service.base_path}/admin/tickets/organizations/#{id}/active") when :closed @support_tickets ||= Fog::Compute::Ecloud::SupportTickets.new(:service => service, :href => "#{service.base_path}/admin/tickets/organizations/#{id}/closed") end end def edit_authentication_levels(options = {}) options[:uri] = "#{service.base_path}/admin/organizations/#{id}/authenticationLevels" data = service.admin_edit_authentication_levels(options).body level = Fog::Compute::Ecloud::AdminOrganizations.new(:service => service, :href => data[:href])[0] end def edit_password_complexity_rules(options = {}) options[:uri] = "#{service.base_path}/admin/organizations/#{id}/passwordComplexityRules" data = service.admin_edit_password_complexity_rules(options).body level = Fog::Compute::Ecloud::PasswordComplexityRules.new(:service => service, :href => data[:href])[0] end def edit_login_banner(options = {}) options[:uri] = "#{service.base_path}/admin/organizations/#{id}/loginBanner" data = service.admin_edit_login_banner(options).body banner = Fog::Compute::Ecloud::LoginBanners.new(:service => service, :href => data[:href])[0] end def enable_support_access(options = {}) options[:uri] = "#{service.base_path}/admin/organizations/#{id}/action/enableSupportAccess" service.admin_enable_support_access(options[:uri]) end def disable_support_access(options = {}) options[:uri] = "#{service.base_path}/admin/organizations/#{id}/action/disableSupportAccess" service.admin_disable_support_access(options[:uri]) end def id href.scan(/\d+/)[0] end alias :vdcs :environments end end end end fog-1.19.0/lib/fog/ecloud/models/compute/catalog_configurations.rb0000644000004100000410000000107412261242551025213 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/catalog_configuration' module Fog module Compute class Ecloud class CatalogConfigurations < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::CatalogConfiguration def all data = service.get_catalog_configurations(href).body load(data) end def get(uri) if data = service.get_catalog_configuration(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/guest_process.rb0000644000004100000410000000040712261242551023353 0ustar www-datawww-datamodule Fog module Compute class Ecloud class GuestProcess < Fog::Ecloud::Model identity :name attribute :process_id, :aliases => :ProcessId def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/servers.rb0000644000004100000410000000366112261242551022164 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/server' module Fog module Compute class Ecloud class Servers < Fog::Ecloud::Collection model Fog::Compute::Ecloud::Server identity :href def all data = service.get_servers(href).body if data.keys.include?(:VirtualMachines) data = data[:VirtualMachines][:VirtualMachine] elsif data[:VirtualMachine] data = data[:VirtualMachine] else data = [] end load(data) end def get(uri) data = service.get_server(uri).body new(data) rescue Fog::Errors::NotFound nil end def from_data(data) new(data) end def create( template_uri, options ) options[:cpus] ||= 1 options[:memory] ||= 512 options[:description] ||= "" options[:tags] ||= [] if template_uri =~ /\/templates\/\d+/ options[:uri] = href + "/action/createVirtualMachine" options[:customization] ||= :linux options[:powered_on] ||= false if options[:ips] options[:ips] = [*options[:ips]] else [*options[:network_uri]].each do |uri| index = options[:network_uri].index(uri) ip = self.service.ip_addresses(:href => uri).detect { |i| i.host == nil && i.detected_on.nil? }.name options[:ips] ||= [] options[:ips][index] = ip end end data = service.virtual_machine_create_from_template( template_uri, options ).body else options[:uri] = href + "/action/importVirtualMachine" data = service.virtual_machine_import( template_uri, options ).body end object = self.service.servers.new(data) object end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/memory_usage_detail_summary.rb0000644000004100000410000000115412261242551026261 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/memory_usage_detail' module Fog module Compute class Ecloud class MemoryUsageDetailSummary < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::MemoryUsageDetail def all data = service.get_memory_usage_detail_summary(href).body[:MemoryUsageDetailSummary][:MemoryUsageDetail] load(data) end def get(uri) if data = service.get_memory_usage_detail(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/hardware_configurations.rb0000644000004100000410000000106012261242551025371 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/hardware_configuration' module Fog module Compute class Ecloud class HardwareConfigurations < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::HardwareConfiguration def all data = service.get_server(href).body load(data) end def get(uri) if data = service.get_hardware_configuration(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/roles.rb0000644000004100000410000000160012261242551021606 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/role' module Fog module Compute class Ecloud class Roles < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::Role def all data = service.get_roles(href).body if data[:OrganizationRole] load(data[:OrganizationRole]) else r_data = [] data[:EnvironmentRoles][:EnvironmentRole].each do |d| d[:Environment][:EnvironmentName] = d[:Environment][:name] d[:Environment] = d[:Environment].merge(d[:Role]) if d[:Role] r_data << d[:Environment] end load(r_data) end end def get(uri) if data = service.get_role(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/cpu_usage_detail_summary.rb0000644000004100000410000000112712261242551025540 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/cpu_usage_detail' module Fog module Compute class Ecloud class CpuUsageDetailSummary < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::CpuUsageDetail def all data = service.get_cpu_usage_detail_summary(href).body[:CpuUsageDetailSummary][:CpuUsageDetail] load(data) end def get(uri) if data = service.get_cpu_usage_detail(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/trusted_network_group.rb0000644000004100000410000000171212261242551025145 0ustar www-datawww-datamodule Fog module Compute class Ecloud class TrustedNetworkGroup < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :hosts, :aliases => :Hosts def internet_services @internet_services ||= Fog::Compute::Ecloud::InternetServices.new(:service => service, :href => href) end def edit(options) options[:uri] = href data = service.trusted_network_groups_edit(options).body task = Fog::Compute::Ecloud::Tasks.new(:service => service, :href => data[:href])[0] end def delete data = service.trusted_network_groups_delete(href).body task = Fog::Compute::Ecloud::Tasks.new(:service => service, :href => data[:href])[0] end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/authentication_levels.rb0000644000004100000410000000106712261242551025062 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/authentication_level' module Fog module Compute class Ecloud class AuthenticationLevels < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::AuthenticationLevel def all data = service.get_authentication_levels(href).body load(data) end def get(uri) if data = service.get_authentication_level(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/memory_usage_detail.rb0000644000004100000410000000045612261242551024510 0ustar www-datawww-datamodule Fog module Compute class Ecloud class MemoryUsageDetail < Fog::Ecloud::Model identity :href attribute :time, :aliases => :Time attribute :value, :aliases => :Value def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/role.rb0000644000004100000410000000131312261242551021424 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Role < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :environment_name, :aliases => :EnvironmentName attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :role_type, :aliases => :RoleType attribute :active, :aliases => :Active, :type => :boolean attribute :category, :aliases => :Category attribute :is_admin, :aliases => :IsAdmin, :type => :boolean attribute :business_operations, :aliases => :BusinessOperations def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/guest_processes.rb0000644000004100000410000000104512261242551023702 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/guest_process' module Fog module Compute class Ecloud class GuestProcesses < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::GuestProcess def all data = service.get_guest_processes(href).body[:GuestProcess] load(data) end def get(uri) if data = service.get_guest_process(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/environments.rb0000644000004100000410000000164112261242551023216 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/environment' module Fog module Compute class Ecloud class Environments < Fog::Ecloud::Collection model Fog::Compute::Ecloud::Environment undef_method :create identity :href def all data = [] service.get_organization(href).body[:Locations][:Location].each do |d| environments = d[:Environments] next unless environments if environments[:Environment].is_a?(Array) environments[:Environment].each { |e| data << e } else data << environments[:Environment] end end load(data) end def get(uri) if data = service.get_environment(uri) new(data.body) end rescue Fog::Errors::NotFound nil end Vdcs = Environments end end end end fog-1.19.0/lib/fog/ecloud/models/compute/compute_pools.rb0000644000004100000410000000136012261242551023355 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/compute_pool' module Fog module Compute class Ecloud class ComputePools < Fog::Ecloud::Collection undef_method :create attribute :href, :aliases => :Href model Fog::Compute::Ecloud::ComputePool def all check_href!(:message => "the Compute Pool href of the Environment you want to enumerate") data = service.get_compute_pools(href).body[:ComputePool] load(data) end def get(uri) if data = service.get_compute_pool(uri) new(data.body) end rescue Fog::Errors::NotFound nil end def from_data(data) new(data) end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/password_complexity_rule.rb0000644000004100000410000000235112261242551025634 0ustar www-datawww-datamodule Fog module Compute class Ecloud class PasswordComplexityRule < Fog::Ecloud::Model identity :href attribute :rule_type, :aliases => :RuleType attribute :custom_rules, :aliases => :CustomRules attribute :description, :aliases => :Description def minimum_characters custom_rules[:MinimumCharacters] end def minimum_upper_case_characters custom_rules[:MinimumUpperCaseCharacters] end def minimum_lower_case_characters custom_rules[:MinimumLowerCaseCharacters] end def minimum_numeric_characters custom_rules[:MinimumNumericCharacters] end def minimum_special_characters custom_rules[:MinimumSpecialCharacters] end def maximum_consecutive_characters_from_prior_password custom_rules[:MaximumConsecutiveCharactersFromPriorPassword] end def minimum_lifetime_restriction custom_rules[:MinimumLifetimeRestriction] end def minimum_generations_before_reuse custom_rules[:MinimumGenerationsBeforeReuse] end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/network.rb0000644000004100000410000000300612261242551022155 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Network < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links, :squash => :Link attribute :address, :aliases => :Address attribute :network_type, :aliases => :NetworkType attribute :broadcast_address, :aliases => :BroadcastAddress attribute :gateway_address, :aliases => :GatewayAddress attribute :rnat_address, :aliases => :RnatAddress def rnats @rnats ||= Fog::Compute::Ecloud::Rnats.new(:service => service, :href => "#{service.base_path}/rnats/networks/#{id}") end def ips @ips ||= Fog::Compute::Ecloud::IpAddresses.new(:service => service, :href => href) end def edit_rnat_association(options) options[:uri] = href data = service.rnat_associations_edit_network(options).body task = Fog::Compute::Ecloud::Tasks.new(:service => service, :href => data[:href])[0] end def id href.scan(/\d+/)[0] end def environment reload if other_links.nil? environment_href = other_links.detect { |l| l[:type] == "application/vnd.tmrk.cloud.environment" }[:href] self.service.environments.get(environment_href) end def location environment.id end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/login_banners.rb0000644000004100000410000000101712261242551023304 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/login_banner' module Fog module Compute class Ecloud class LoginBanners < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::LoginBanner def all data = service.get_login_banners(href).body load(data) end def get(uri) if data = service.get_login_banner(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/catalog.rb0000644000004100000410000000214512261242551022101 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/catalog_item' module Fog module Compute class Ecloud class Catalog < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::CatalogItem def all data = service.get_catalog(href).body#[:Locations][:Location][:Catalog][:CatalogEntry] if data[:Locations][:Location].is_a?(Hash) data = [] if data[:Locations][:Location][:Catalog].is_a?(String) && data[:Locations][:Location][:Catalog].empty? load(data) elsif data[:Locations][:Location].is_a?(Array) r_data = [] data[:Locations][:Location].each do |d| unless d[:Catalog].is_a?(String) && d[:Catalog].empty? d[:Catalog][:CatalogEntry].each do |c| r_data << c end end end load(r_data) end end def get(uri) if data = service.get_catalog_item(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/firewall_acls.rb0000644000004100000410000000111712261242551023274 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/firewall_acl' module Fog module Compute class Ecloud class FirewallAcls < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::FirewallAcl def all data = service.get_firewall_acls(href).body data = data[:FirewallAcl] ? data[:FirewallAcl] : data load(data) end def get(uri) if data = service.get_firewall_acl(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/association.rb0000644000004100000410000000107412261242551023003 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Association < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :ip_address, :aliases => :IpAddress def delete data = service.rnat_associations_delete(href).body task = Fog::Compute::Ecloud::Tasks.new(:service => service, :href => href)[0] end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/ssh_key.rb0000644000004100000410000000071312261242551022133 0ustar www-datawww-datamodule Fog module Compute class Ecloud class SshKey < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :default, :aliases => :Default, :type => :boolean attribute :finger_print, :aliases => :FingerPrint def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/locations.rb0000644000004100000410000000106712261242551022464 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/location' module Fog module Compute class Ecloud class Locations < Fog::Ecloud::Collection model Fog::Compute::Ecloud::Location undef_method :create identity :href def all data = service.get_organization(href).body[:Locations][:Location] load(data) end def get(uri) if data = service.get_location(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/virtual_machine_assigned_ips.rb0000644000004100000410000000116712261242551026374 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/virtual_machine_assigned_ip' module Fog module Compute class Ecloud class VirtualMachineAssignedIps < Fog::Ecloud::Collection identity :virtual_machine_id model Fog::Compute::Ecloud::VirtualMachineAssignedIp def all data = service.get_virtual_machine_assigned_ips(self.identity).body load(data) end def get(uri) if data = service.get_virtual_machine_assigned_ip(self.identity) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/compute_pool.rb0000644000004100000410000000554112261242551023177 0ustar www-datawww-datamodule Fog module Compute class Ecloud class ComputePool < Fog::Ecloud::Model identity :href attribute :href, :aliases => :Href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links, :squash => :Link attribute :all_servers, :aliases => :VirtualMachines attribute :purchased, :aliases => :Purchased attribute :cpu_burst, :aliases => :CpuBurst attribute :memory_burst, :aliases => :MemoryBurst def servers @servers ||= Fog::Compute::Ecloud::Servers.new( :service => service, :href => "#{service.base_path}/virtualMachines/computePools/#{id}" ) end def layout @layout ||= Fog::Compute::Ecloud::Layouts.new(:service => service, :href => "#{service.base_path}/layout/computePools/#{id}").first end def cpu_usage # time ? query = "/details?time=#{Time.parse(time).utc.strftime('%Y-%m-%dT%H:%M:%SZ')}" : query = "" @cpu_usage ||= Fog::Compute::Ecloud::CpuUsageDetailSummary.new(:service => service, :href => "#{service.base_path}/computePools/#{id}/usage/cpu") end def memory_usage # time ? query = "/details?time=#{Time.parse(time).utc.strftime('%Y-%m-%dT%H:%M:%SZ')}" : query = "" @memory_usage ||= Fog::Compute::Ecloud::MemoryUsageDetailSummary.new(:service => service, :href => "#{service.base_path}/computePools/#{id}/usage/memory") end def storage_usage @storage_usage ||= Fog::Compute::Ecloud::StorageUsageDetailSummary.new(:service => service, :href => "#{service.base_path}/computePools/#{id}/usage/storage") end def operating_system_families @operating_system_families ||= Fog::Compute::Ecloud::OperatingSystemFamilies.new(:service => service, :href => "#{service.base_path}/operatingSystemFamilies/computePools/#{id}") end def templates @templates ||= self.service.templates(:href => "#{service.base_path}/templates/computePools/#{id}") end def detached_disks @detached_disks ||= self.service.detached_disks(:href => "#{service.base_path}/detacheddisks/computepools/#{id}") end def environment @environment ||= begin reload unless other_links environment_link = other_links.find{|l| l[:type] == "application/vnd.tmrk.cloud.environment"} self.service.environments.get(environment_link[:href]) end end def edit(options) options[:uri] = href data = service.compute_pool_edit(options).body pool = collection.from_data(data) end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/rows.rb0000644000004100000410000000152612261242551021463 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/row' module Fog module Compute class Ecloud class Rows < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::Row def all data = service.get_layout(href).body[:Rows][:Row] load(data) end def get(uri) data = service.get_row(uri).body if data == "" nil else new(data) end rescue Excon::Errors::NotFound nil end def create(options = {}) options[:uri] = "#{service.base_path}/layoutRows/environments/#{environment_id}/action/createLayoutRow" data = service.rows_create(options).body new(data) end def environment_id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/server_configuration_options.rb0000644000004100000410000000113012261242551026470 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/server_configuration_option' module Fog module Compute class Ecloud class ServerConfigurationOptions < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::ServerConfigurationOption def all data = service.get_server_configuration_options(href).body load(data) end def get(uri) if data = service.get_server_configuration_option(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/user.rb0000644000004100000410000000255712261242551021454 0ustar www-datawww-datamodule Fog module Compute class Ecloud class User < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :first_name, :aliases => :FirstName attribute :last_name, :aliases => :LastName attribute :email, :aliases => :Email attribute :status, :aliases => :Status attribute :last_login, :aliases => :LastLogin attribute :multifactor_authentication, :aliases => :MultifactorAuthentication attribute :is_administrator, :aliases => :IsAdministrator, :type => :boolean attribute :is_api_user, :aliases => :IsApiUser, :type => :boolean attribute :is_alert_notification_enabled, :aliases => :IsAlertNotificationEnabled, :type => :boolean attribute :is_multifactor_authentication_enabled, :aliases => :IsMultifactorAuthenticationEnabled, :type => :boolean def roles @roles = Fog::Compute::Ecloud::Roles.new(:service => service, :href => "#{service.base_path}/admin/roles/users/#{id}") end def api_keys @api_keys = Fog::Compute::Ecloud::ApiKeys.new(:service => service, :href => "#{service.base_path}/admin/apiKeys/users/#{id}") end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/admin_organizations.rb0000644000004100000410000000067712261242551024536 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/admin_organization' module Fog module Compute class Ecloud class AdminOrganizations < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::AdminOrganization def get(uri) if data = service.get_admin_organization(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/catalog_configuration.rb0000644000004100000410000000130012261242551025020 0ustar www-datawww-datamodule Fog module Compute class Ecloud class CatalogConfiguration < Fog::Ecloud::Model identity :href attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :processor_count, :aliases => :ProcessorCount, :type => :integer attribute :memory, :aliases => :Memory attribute :operating_system, :aliases => :OperatingSystem attribute :disks, :aliases => :Disks attribute :network_adapters, :aliases => :NetworkAdapters, :type => :integer attribute :network_mappings, :aliases => :NetworkMappings def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/monitor.rb0000644000004100000410000000330212261242551022152 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Monitor < Fog::Ecloud::Model identity :href attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :interval, :aliases => :Interval, :type => :integer attribute :response_timeout, :aliases => :ResponseTimeout, :type => :integer attribute :retries, :aliases => :Retries, :type => :integer attribute :downtime, :aliases => :Downtime, :type => :integer attribute :enabled, :aliases => :Enabled, :type => :boolean attribute :request_uri, :aliases => :RequestUri attribute :http_headers, :aliases => :HttpHeaders attribute :response_codes, :aliases => :ResponseCodes attribute :send_string, :aliases => :SendString attribute :receive_string, :aliases => :ReceiveString def edit(options = {}) href = "#{service.base_path}/internetServices/#{internet_service_id}/monitor?type=" case type when "application/vnd.tmrk.cloud.pingMonitor" options[:uri] = href + "ping" data = service.monitors_edit_ping(options).body when "application/vnd.tmrk.cloud.httpMonitor" options[:uri] = href + "http" data = service.monitors_edit_http(options).body when "application/vnd.tmrk.cloud.ecvMonitor" options[:uri] = href + "ecv" data = service.monitors_edit_ecv(options).body end object = collection.from_data(data) end def internet_service_id other_links[:Link][:href].scan(/\d+/)[0] end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/hardware_configuration.rb0000644000004100000410000000105312261242551025210 0ustar www-datawww-datamodule Fog module Compute class Ecloud class HardwareConfiguration < Fog::Ecloud::Model identity :href attribute :processor_count, :aliases => :ProcessorCount, :type => :integer attribute :memory, :aliases => :Memory, :squash => :Value # {:Memory => {:Value => 15}} attribute :storage, :aliases => :Disks, :squash => :Disk attribute :network_cards, :aliases => :Nics, :squash => :Nic def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/operating_system_families.rb0000644000004100000410000000112712261242551025733 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/operating_system_family' module Fog module Compute class Ecloud class OperatingSystemFamilies < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::OperatingSystemFamily def all data = service.get_operating_system_families(href).body[:OperatingSystemFamily] load(data) end def get(uri) if data = service.get_operating_system(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/server_configuration_option.rb0000644000004100000410000000050712261242551026314 0ustar www-datawww-datamodule Fog module Compute class Ecloud class ServerConfigurationOption < Fog::Ecloud::Model identity :href attribute :disk, :aliases => :Disk attribute :customization, :aliases => :Customization def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/support_tickets.rb0000644000004100000410000000105312261242551023726 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/support_ticket' module Fog module Compute class Ecloud class SupportTickets < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::SupportTicket def all data = service.get_support_tickets(href).body[:TicketReference] load(data) end def get(uri) if data = service.get_support_ticket(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/ip_addresses.rb0000644000004100000410000000130512261242551023131 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/ip_address' module Fog module Compute class Ecloud class IpAddresses < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::IpAddress def all data = service.get_network(href).body data = if data[:IpAddresses] data[:IpAddresses][:IpAddress] else data end data = data.nil? ? [] : data load(data) end def get(uri) if data = service.get_ip_address(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/layout.rb0000644000004100000410000000056412261242551022007 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Layout < Fog::Ecloud::Model identity :href attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links def rows @rows ||= self.service.rows(:href => href) end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/public_ips.rb0000644000004100000410000000137612261242551022625 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/public_ip' module Fog module Compute class Ecloud class PublicIps < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::PublicIp def all data = service.get_public_ips(href).body data = data[:PublicIp] ? data[:PublicIp] : data load(data) end def get(uri) data = service.get_public_ip(uri).body new(data) rescue Fog::Errors::NotFound nil end def activate data = service.public_ip_activate(href + "/action/activatePublicIp").body ip = Fog::Compute::Ecloud::PublicIps.new(:service => service, :href => data[:href])[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/storage_usage_detail.rb0000644000004100000410000000050212261242551024634 0ustar www-datawww-datamodule Fog module Compute class Ecloud class StorageUsageDetail < Fog::Ecloud::Model identity :href attribute :disk_count, :aliases => :DiskCount attribute :allocated, :aliases => :Allocated def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/physical_device.rb0000644000004100000410000000105212261242551023616 0ustar www-datawww-datamodule Fog module Compute class Ecloud class PhysicalDevice < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :tags, :aliases => :Tags attribute :layout, :aliases => :Layout attribute :network_host, :aliases => :NetworkHost attribute :classification, :aliases => :Classification attribute :model, :aliases => :Model def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/tag.rb0000644000004100000410000000027712261242551021246 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Tag < Fog::Ecloud::Model identity :name def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/virtual_machine_assigned_ip.rb0000644000004100000410000000156012261242551026206 0ustar www-datawww-datamodule Fog module Compute class Ecloud class VirtualMachineAssignedIp < Fog::Ecloud::Model identity :href attribute :network, :aliases => :Networks attribute :address def id href.scan(/\d+/)[0] end def network=(network) network = network.dup network_address = network[:Network] @network = self.service.networks.new(network_address) network_id = @network.href.match(/(\d+)$/)[1] address_ip = network_address[:IpAddresses][:IpAddress] @address = self.service.ip_addresses.new( :href => "#{service.base_path}/ipaddresses/networks/#{network_id}/#{address_ip}", :name => address_ip ) end attr_reader :network def address=(address); end attr_reader :address end end end end fog-1.19.0/lib/fog/ecloud/models/compute/tags.rb0000644000004100000410000000076012261242551021426 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/tag' module Fog module Compute class Ecloud class Tags < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::Tag def all data = service.get_tags(href).body[:DeviceTag] load(data) end def get(uri) if data = service.get_tag(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/admin_organization.rb0000644000004100000410000000341212261242551024341 0ustar www-datawww-datamodule Fog module Compute class Ecloud class AdminOrganization < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links, :squash => :Link attribute :multifactor_summary, :aliases => :MultifactorSummary attribute :support_access, :aliases => :SupportAccess def ssh_keys @ssh_keys = Fog::Compute::Ecloud::SshKeys.new(:service => service, :href => "#{service.base_path}/admin/sshKeys/organizations/#{organization.id}") end def password_complexity_rules @password_complexity_rules = Fog::Compute::Ecloud::PasswordComplexityRules.new(:service => service, :href => "#{service.base_path}/admin/organizations/#{organization.id}/passwordComplexityRules") end def login_banner @login_banner = Fog::Compute::Ecloud::LoginBanner.new(:service => service, :href => "#{service.base_path}/admin/organizations/#{organization.id}/loginBanner") end def authentication_levels @authentication_levels = Fog::Compute::Ecloud::AuthenticationLevels.new(:service => service, :href => "#{service.base_path}/admin/organizations/#{organization.id}/authenticationLevels") end def id href.scan(/\d+/)[0] end def organization @organization ||= begin reload unless other_links organization_link = other_links.find{|l| l[:type] == "application/vnd.tmrk.cloud.organization"} self.service.organizations.new(organization_link) end end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/group.rb0000644000004100000410000000156712261242551021632 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Group < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :index, :aliases => :Index def servers @servers = Fog::Compute::Ecloud::Servers.new(:service => service, :href => href) end def edit(options = {}) options[:uri] = href data = service.groups_edit(options).body end def move_up service.groups_moveup(href).body end def move_down service.groups_movedown(href).body end def delete service.groups_delete(href).body end def id href.scan(/\d+/)[0] end alias destroy delete end end end end fog-1.19.0/lib/fog/ecloud/models/compute/rnat.rb0000644000004100000410000000131412261242551021430 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Rnat < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :default, :aliases => :Default, :type => :boolean attribute :public_ip, :aliases => :PublicIp def networks @networks = Fog::Compute::Ecloud::Networks.new(:service => service, :href => href) end def associations @associations = Fog::Compute::Ecloud::Associations.new(:service => service, :href => href) end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/associations.rb0000644000004100000410000000140612261242551023165 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/association' module Fog module Compute class Ecloud class Associations < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::Association def all data = service.get_associations(href).body if data[:Associations] data = data[:Associations] if data.is_a?(String) && data.empty? data = [] elsif data.is_a?(Hash) data = data[:Association] end end load(data) end def get(uri) if data = service.get_association(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/layouts.rb0000644000004100000410000000076312261242551022173 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/layout' module Fog module Compute class Ecloud class Layouts < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::Layout def all data = service.get_layouts(href).body load(data) end def get(uri) if data = service.get_layout(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/backup_internet_services.rb0000644000004100000410000000166612261242551025556 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/backup_internet_service' module Fog module Compute class Ecloud class BackupInternetServices < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::BackupInternetService def all data = service.get_backup_internet_services(href).body load(data) end def get(uri) if data = service.get_backup_internet_service(uri) new(data.body) end rescue Fog::Errors::NotFound nil end def from_data(data) new(data) end def create(options) options[:uri] = href + "/action/createBackupInternetService" options[:enabled] ||= true data = service.backup_internet_service_create(options) new(data) end def internet_service_id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/ssh_keys.rb0000644000004100000410000000077712261242551022330 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/ssh_key' module Fog module Compute class Ecloud class SshKeys < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::SshKey def all data = service.get_ssh_keys(href).body[:SshKey] load(data) end def get(uri) if data = service.get_ssh_key(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/groups.rb0000644000004100000410000000153212261242551022005 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/group' module Fog module Compute class Ecloud class Groups < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::Group def all data = service.get_groups(href).body data = if data == "" "" else data[:Groups] ? data[:Groups][:Group] : data end if data == "" || !data.is_a?(Array) && data[:type] == "application/vnd.tmrk.cloud.layoutRow" nil else load(data) end end def get(uri) data = service.get_group(uri).body if data == "" nil else new(data) end rescue Excon::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/operating_systems.rb0000644000004100000410000000075112261242551024247 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/operating_system' module Fog module Compute class Ecloud class OperatingSystems < Fog::Ecloud::Collection model Fog::Compute::Ecloud::OperatingSystem identity :data def all load(data) end def get(uri) if data = service.get_operating_system(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/support_ticket.rb0000644000004100000410000000163212261242551023546 0ustar www-datawww-datamodule Fog module Compute class Ecloud class SupportTicket < Fog::Ecloud::Model identity :href attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :date, :aliases => :Date attribute :status, :aliases => :Status attribute :category, :aliases => :Category attribute :detected_by, :aliases => :DetectedBy attribute :severity, :aliases => :Severity attribute :device, :aliases => :Device attribute :classification, :aliases => :Classification attribute :owner, :aliases => :Owner attribute :description, :aliases => :Description attribute :information, :aliases => :Information attribute :solution, :aliases => :Solution attribute :history, :aliases => :History def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/environment.rb0000644000004100000410000001030212261242551023025 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Environment < Fog::Ecloud::Model identity :href ignore_attributes :xmlns, :xmlns_xsi, :xmlns_xsd attribute :name attribute :type attribute :other_links, :aliases => :Links, :squash => :Link def public_ips @public_ips ||= Fog::Compute::Ecloud::PublicIps.new(:service => service, :href => "#{service.base_path}/publicIps/environments/#{id}") end def internet_services @internet_services ||= Fog::Compute::Ecloud::InternetServices.new(:service => service, :href => "#{service.base_path}/networkSummary/environments/#{id}") end def node_services @node_services ||= Fog::Compute::Ecloud::Nodes.new(:service => service, :href => "#{service.base_path}/networkSummary/environments/#{id}") end def backup_internet_services @backup_internet_services ||= Fog::Compute::Ecloud::BackupInternetServices.new(:service => service, :href => "#{service.base_path}/backupInternetServices/environments/#{id}") end def networks @networks ||= self.service.networks(:href => "#{service.base_path}/networks/environments/#{id}") end def servers @servers = nil pools = compute_pools pools.each do |c| if pools.index(c) == 0 @servers = c.servers else c.servers.each { |s| @servers << s } end end @servers end def layout @layout ||= self.service.layouts(:href => "#{service.base_path}/layout/environments/#{id}").first end def rows @rows ||= layout.rows end def tasks @tasks ||= Fog::Compute::Ecloud::Tasks.new(:service => service, :href => "#{service.base_path}/tasks/environments/#{id}") end def firewall_acls @firewall_acls ||= Fog::Compute::Ecloud::FirewallAcls.new(:service => service, :href => "#{service.base_path}/firewallAcls/environments/#{id}") end def compute_pools @compute_pools ||= Fog::Compute::Ecloud::ComputePools.new(:service => service, :href => "#{service.base_path}/computePools/environments/#{id}") end def physical_devices @physical_devices ||= Fog::Compute::Ecloud::PhysicalDevices.new(:service => service, :href => "#{service.base_path}/physicalDevices/environments/#{id}") end def trusted_network_groups @trusted_network_groups ||= Fog::Compute::Ecloud::TrustedNetworkGroups.new(:service => service, :href => "#{service.base_path}/trustedNetworkGroups/environments/#{id}") end def catalog @catalog = service.catalog(:href => "#{service.base_path}/admin/catalog/organizations/#{organization.id}") end def rnats @rnats ||= Fog::Compute::Ecloud::Rnats.new(:service => service, :href => "#{service.base_path}/rnats/environments/#{id}") end def create_trusted_network_group(options = {}) options[:uri] = "#{service.base_path}/trustedNetworkGroups/environments/#{id}/action/createTrustedNetworkGroup" data = service.trusted_network_groups_create(options).body tng = Fog::Compute::Ecloud::TrustedNetworkGroups.new(:service => service, :href => data[:href])[0] end def create_firewall_acl(options = {}) options[:uri] = "#{service.base_path}/firewallAcls/environments/#{id}/action/createFirewallAcl" options[:permission] ||= "deny" options[:protocol] ||= "any" data = service.firewall_acls_create(options).body acl = Fog::Compute::Ecloud::FirewallAcls.new(:service => service, :href => data[:href])[0] end def id href.scan(/\d+/)[0] end def organization @organization ||= begin reload unless other_links organization_link = other_links.find{|l| l[:type] == "application/vnd.tmrk.cloud.organization"} self.service.organizations.new(organization_link) end end end Vdc = Environment end end end fog-1.19.0/lib/fog/ecloud/models/compute/operating_system.rb0000644000004100000410000000045312261242551024063 0ustar www-datawww-datamodule Fog module Compute class Ecloud class OperatingSystem < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/catalog_item.rb0000644000004100000410000000124612261242551023120 0ustar www-datawww-datamodule Fog module Compute class Ecloud class CatalogItem < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :status, :aliases => :Status attribute :alerts, :aliases => :Alerts attribute :files, :aliases => :Files def configuration @configuration = Fog::Compute::Ecloud::CatalogConfigurations.new(:service => service, :href => "#{service.base_path}/admin/catalog/#{id}/configuration") end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/trusted_network_groups.rb0000644000004100000410000000121212261242551025323 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/trusted_network_group' module Fog module Compute class Ecloud class TrustedNetworkGroups < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::TrustedNetworkGroup def all data = service.get_trusted_network_groups(href).body data = data[:TrustedNetworkGroup] ? data[:TrustedNetworkGroup] : data load(data) end def get(uri) if data = service.get_trusted_network_group(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/operating_system_family.rb0000644000004100000410000000102112261242551025414 0ustar www-datawww-datamodule Fog module Compute class Ecloud class OperatingSystemFamily < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :operating_system_family, :aliases => :OperatingSystems def operating_systems @operating_systems ||= self.service.operating_systems(:data => operating_system_family[:OperatingSystem]) end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/firewall_acl.rb0000644000004100000410000000146212261242551023114 0ustar www-datawww-datamodule Fog module Compute class Ecloud class FirewallAcl < Fog::Ecloud::Model identity :href attribute :type, :aliases => :Type attribute :links, :aliases => :Links attribute :permission, :aliases => :Permission attribute :acl_type, :aliases => :AclType attribute :port_type, :aliases => :PortType attribute :protocol, :aliases => :Protocol attribute :source, :aliases => :Source attribute :destination, :aliases => :Destination attribute :port_range, :aliases => :PortRange def tasks @tasks = Fog::Compute::Ecloud::Tasks.new(:service => service, :href => "#{service.base_path}/tasks/virtualMachines/#{id}") end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/users.rb0000644000004100000410000000076012261242551021631 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/user' module Fog module Compute class Ecloud class Users < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::User def all data = service.get_users(href).body[:User] load(data) end def get(uri) if data = service.get_user(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/internet_services.rb0000644000004100000410000000233312261242551024221 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/internet_service' module Fog module Compute class Ecloud class InternetServices < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::InternetService def all data = service.get_internet_services(href).body[:InternetServices] if data.is_a?(Hash) load(data[:InternetService]) elsif data.is_a?(String) && data.empty? load([]) end end def get(uri) data = service.get_internet_service(uri).body new(data) rescue Fog::Errors::NotFound nil end def create(options) options[:uri] = "#{service.base_path}/internetServices/publicIps/#{public_ip_id}/action/createInternetService" options[:protocol] ||= "TCP" options[:enabled] ||= true options[:description] ||= "" options[:persistence] ||= {} options[:persistence][:type] ||= "None" data = service.internet_service_create(options).body object = new(data) end def public_ip_id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/internet_service.rb0000644000004100000410000000714412261242551024043 0ustar www-datawww-datamodule Fog module Compute class Ecloud class InternetService < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :actions, :aliases => :Actions attribute :protocol, :aliases => :Protocol attribute :port, :aliases => :Port, :type => :integer attribute :enabled, :aliases => :Enabled, :type => :boolean attribute :description, :aliases => :Description attribute :public_ip, :aliases => :PublicIp attribute :persistence, :aliases => :Persistence attribute :redirect_url, :aliases => :RedirectUrl attribute :trusted_network_group, :aliases => :TrustedNetworkGroup attribute :backup_internet_service, :aliases => :BackupInternetService def ready? !self.port.nil? end def nodes @nodes ||= Fog::Compute::Ecloud::Nodes.new(:service => service, :href => href) end def monitors @monitors ||= Fog::Compute::Ecloud::Monitors.new(:service => service, :href => "#{service.base_path}/internetServices/#{id}/monitor") end def save unless persisted? result = service.internet_service_create( collection.href, _compose_service_data ) merge_attributes(result.body) else service.configure_internet_service( href, _compose_service_data, _compose_ip_data ) end end def edit(options) options[:uri] = href data = service.internet_service_edit(options).body task = Fog::Compute::Ecloud::Tasks.new(:service => service, :href => data[:href])[0] end def delete data = service.internet_service_delete(href).body self.service.tasks.new(data) end def create_monitor(options = {}) options = {:type => :default}.merge(options) case options[:type] when :default data = service.monitors_create_default(href + "/action/createDefaultMonitor").body when :ping options[:enabled] ||= true options[:uri] = href + "/action/createPingMonitor" data = service.monitors_create_ping(options).body when :http options[:uri] = href + "/action/createHttpMonitor" data = service.monitors_create_http(options).body when :ecv options[:uri] = href + "/action/createEcvMonitor" data = service.monitors_create_ecv(options).body when :loopback data = service.monitors_create_loopback(href).body end monitor = Fog::Compute::Ecloud::Monitors.new(:service => service, :href => data[:href]) end def disable_monitor data = service.monitors_disable(href + "/action/disableMonitor").body task = Fog::Compute::Ecloud::Tasks.new(:service => service, :href => data[:href]) end def id href.scan(/\d+/)[0] end private def _compose_service_data #For some reason inject didn't work service_data = {} self.class.attributes.select{ |attribute| attribute != :backup_service_data }.each { |attribute| service_data[attribute] = send(attribute) } service_data.reject! {|k, v| v.nil? } service_data end alias destroy delete end end end end fog-1.19.0/lib/fog/ecloud/models/compute/authentication_level.rb0000644000004100000410000000144612261242551024700 0ustar www-datawww-datamodule Fog module Compute class Ecloud class AuthenticationLevel < Fog::Ecloud::Model identity :href attribute :basic_enabled, :aliases => :BasicEnabled, :type => :boolean attribute :sha1_enabled, :aliases => :SHA1Enabled, :type => :boolean attribute :Sha256_enabled, :aliases => :SHA256Enabled, :type => :boolean attribute :Sha512_enabled, :aliases => :SHA512Enabled, :type => :boolean attribute :hmacsha1_enabled, :aliases => :HMACSHA1Enabled, :type => :boolean attribute :hmacsha256_enabled, :aliases => :HMACSHA256Enabled, :type => :boolean attribute :hmacsha512_enabled, :aliases => :HMACSHA512Enabled, :type => :boolean def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/templates.rb0000644000004100000410000000233012261242551022461 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/template' module Fog module Compute class Ecloud class Templates < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::Template def all r_data = [] data = service.get_templates(href).body[:Families] data[:Family].is_a?(Hash) ? data = [data[:Family]] : data = data[:Family] data.each do |d| cats = d[:Categories][:Category] cats = [cats] if cats.is_a?(Hash) cats.each do |cat| cat[:OperatingSystems][:OperatingSystem].is_a?(Hash) ? cat = [cat[:OperatingSystems][:OperatingSystem]] : cat = cat[:OperatingSystems][:OperatingSystem] cat.each do |os| os[:Templates][:Template].is_a?(Hash) ? os = [os[:Templates][:Template]] : os = os[:Templates][:Template] os.each do |template| r_data << template end end end end load(r_data) end def get(uri) if data = service.get_template(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/physical_devices.rb0000644000004100000410000000106512261242551024005 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/physical_device' module Fog module Compute class Ecloud class PhysicalDevices < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::PhysicalDevice def all data = service.get_physical_devices(href).body[:PhysicalDevice] || [] load(data) end def get(uri) if data = service.get_physical_device(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/node.rb0000644000004100000410000000244312261242551021415 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Node < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :ip_address, :aliases => :IpAddress attribute :protocol, :aliases => :Protocol attribute :port, :aliases => :Port, :type => :integer attribute :enabled, :aliases => :Enabled, :type => :boolean attribute :description, :aliases => :Description def ready? !self.name.nil? end def tasks @tasks ||= Fog::Compute::Ecloud::Tasks.new(:service => service, :href => "#{service.base_path}/tasks/virtualMachines/#{id}") end def delete data = service.node_service_delete(href).body self.service.tasks.new(data) end def edit(options) options[:uri] = href options[:description] ||= "" options = {:name => name}.merge(options) data = service.node_service_edit(options).body task = Fog::Compute::Ecloud::Tasks.new(:service => service, :href => data[:href])[0] end def id href.scan(/\d+/)[0] end alias destroy delete end end end end fog-1.19.0/lib/fog/ecloud/models/compute/cpu_usage_detail.rb0000644000004100000410000000045412261242551023765 0ustar www-datawww-datamodule Fog module Compute class Ecloud class CpuUsageDetail < Fog::Ecloud::Model identity :href attribute :time, :aliases => :Time attribute :value, :aliases => :Value def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/row.rb0000644000004100000410000000261512261242551021300 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Row < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :index, :aliases => :Index def groups @groups = self.service.groups(:href => href) end def edit(options) options[:uri] = href service.rows_edit(options).body end def move_up(options) options[:uri] = href + "/action/moveup" service.rows_moveup(options).body end def move_down(options) options[:uri] = href + "/action/movedown" service.rows_movedown(options).body end def delete service.rows_delete(href).body end def create_group(options = {}) options[:uri] = "#{service.base_path}/layoutGroups/environments/#{environment_id}/action/createLayoutGroup" options[:row_name] = name options[:href] = href data = service.groups_create(options).body group = self.service.groups.new(data) end def environment_id reload if other_links.nil? other_links[:Link][:href].scan(/\d+/)[0] end def id href.scan(/\d+/)[0] end alias destroy delete end end end end fog-1.19.0/lib/fog/ecloud/models/compute/login_banner.rb0000644000004100000410000000047712261242551023132 0ustar www-datawww-datamodule Fog module Compute class Ecloud class LoginBanner < Fog::Ecloud::Model identity :href attribute :display, :aliases => :Display, :type => :boolean attribute :text, :aliases => :Text def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/public_ip.rb0000644000004100000410000000126612261242551022440 0ustar www-datawww-datamodule Fog module Compute class Ecloud class PublicIp < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :ip_type, :aliases => :IpType def internet_services @internet_services = Fog::Compute::Ecloud::InternetServices.new(:service => service, :href => href) end def environment_id other_links[:Link].detect { |l| l[:type] == "application/vnd.tmrk.cloud.environment" }[:href].scan(/\d+/)[0] end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/storage_usage_detail_summary.rb0000644000004100000410000000114512261242551026415 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/storage_usage_detail' module Fog module Compute class Ecloud class StorageUsageDetailSummary < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::StorageUsageDetail def all data = service.get_storage_usage_detail_summary(href).body[:VirtualMachines][:VirtualMachine] load(data) end def get(uri) if data = service.get_storage_usage_detail(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/api_key.rb0000644000004100000410000000076212261242551022113 0ustar www-datawww-datamodule Fog module Compute class Ecloud class ApiKey < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :access_key, :aliases => :AccessKey attribute :status, :aliases => :Status attribute :private_key, :aliases => :PrivateKey def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/backup_internet_service.rb0000644000004100000410000000262412261242551025366 0ustar www-datawww-datamodule Fog module Compute class Ecloud class BackupInternetService < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :protocol, :aliases => :Protocol attribute :enabled, :aliases => :Enabled, :type => :boolean attribute :description, :aliases => :Description attribute :persistence, :aliases => :Persistence attribute :redirect_url, :aliases => :RedirectUrl def tasks @tasks = Fog::Compute::Ecloud::Tasks.new(:service => service, :href => href) end def internet_services @internet_services = Fog::Compute::Ecloud::InternetServices.new(:service => service, :href => href) end def node_services @node_services = Fog::Compute::Ecloud::NodeServices.new(:service => service, :href => href) end def edit(options) options[:uri] = href data = service.backup_internet_service_edit(options).body object = collection.from_data(data) end def delete data = service.backup_internet_service_delete(href).body task = Fog::Compute::Ecloud::Tasks.new(:service => service, :href => data[:href])[0] end def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/api_keys.rb0000644000004100000410000000076612261242551022302 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/api_key' module Fog module Compute class Ecloud class ApiKeys < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::ApiKey def all data = service.get_api_keys(href).body load(data) end def get(uri) if data = service.get_api_key(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/server.rb0000644000004100000410000003073212261242551022000 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Server < Fog::Ecloud::Model extend Forwardable identity :href attribute :description, :aliases => :Description attribute :hardware_configuration, :aliases => :HardwareConfiguration attribute :ip_addresses, :aliases => :IpAddresses, :squash => :AssignedIpAddresses attribute :layout, :aliases => :Layout attribute :name, :aliases => :Name attribute :operating_system, :aliases => :OperatingSystem attribute :other_links, :aliases => :Links, :squash => :Link attribute :powered_on, :aliases => :PoweredOn, :type => :boolean attribute :status, :aliases => :Status attribute :tags, :aliases => :Tags attribute :tools_status, :aliases => :ToolsStatus attribute :type, :aliases => :Type def cpus hardware_configuration.processor_count end def memory # always in MB hardware_configuration.memory.to_i end def location end def flavor_id {:ram => hardware_configuration.memory.to_i, :cpus => hardware_configuration.processor_count} end def storage hardware_configuration.storage[:Disk] end def tasks @tasks ||= self.service.tasks(:href => "#{service.base_path}/tasks/virtualMachines/#{id}") end def processes @processes ||= Fog::Compute::Ecloud::GuestProcesses.new(:service, service, :href => "#{service.base_path}/virtualMachines/#{id}/guest/processes") end def hardware_configuration=(hardware_configuration) @hardware_configuration = self.service.hardware_configurations.new(hardware_configuration) end def hardware_configuration @hardware_configuration ||= self.service.hardware_configurations.new(:href => "#{service.base_path}/virtualMachines/#{id}/hardwareConfiguration") @hardware_configuration.reload end def configuration @configuration ||= Fog::Compute::Ecloud::ServerConfigurationOptions.new(:service => service, :href => "#{service.base_path}/virtualMachines/#{id}/configurationOptions")[0] end def ips @ips = self.service.virtual_machine_assigned_ips(:virtual_machine_id => self.id) end def networks @networks ||= self.service.networks(:href => "#{service.base_path}/virtualMachines/#{id}/assignedIps") end def power_on power_operation( :power_on => :powerOn ) end def power_off power_operation( :power_off => :powerOff ) end def shutdown power_operation( :power_shutdown => :shutdown ) end def power_reset power_operation( :power_reset => :reboot ) end def delete data = service.virtual_machine_delete(href).body self.service.tasks.new(data) end def copy(options = {}) options = {:type => :copy}.merge(options) options[:source] ||= href if options[:type] == :copy options[:cpus] ||= 1 options[:memory] ||= 512 options[:customization] ||= :linux options[:tags] ||= [] options[:powered_on] ||= false if options[:ips] options[:ips] = options[:ips].is_a?(String) ? [options[:ips]] : options[:ips] else options[:network_uri] = options[:network_uri].is_a?(String) ? [options[:network_uri]] : options[:network_uri] options[:network_uri].each do |uri| index = options[:network_uri].index(uri) ip = Fog::Compute::Ecloud::IpAddresses.new(:service => service, :href => uri).detect { |i| i.host == nil }.name options[:ips] ||= [] options[:ips][index] = ip end end data = service.virtual_machine_copy("#{service.base_path}/virtualMachines/computePools/#{compute_pool_id}/action/copyVirtualMachine", options).body elsif options[:type] == :identical data = service.virtual_machine_copy_identical("#{service.base_path}/virtualMachines/computePools/#{compute_pool_id}/action/copyIdenticalVirtualMachine", options).body end vm = collection.from_data(data) vm end def rnats rnats = Fog::Compute::Ecloud::Rnats.new(:service => service, :href => "#{service.base_path}/rnats/environments/#{environment_id}") associations = nil rnats.each do |rnat| if rnats.index(rnat) == 0 associations = rnat.associations.select do |association| ips.any? do |ip| association.name == ip.name end end else rnat.associations.select do |association| ips.each do |ip| if ip.name == association.name associations << association end end end end end associations end def edit(options = {}) data = service.virtual_machine_edit(href, options).body if data[:type] == "application/vnd.tmrk.cloud.task" task = Fog::Compute::Ecloud::Tasks.new(:service => service, :href => data[:href])[0] end end def create_rnat(options) options[:host_ip_href] ||= ips.first.href options[:uri] = "#{service.base_path}/rnats/environments/#{environment_id}/action/createAssociation" data = service.rnat_associations_create_device(options).body rnat = Fog::Compute::Ecloud::Associations.new(:service => service, :href => data[:href])[0] end def disks c = hardware_configuration.reload.storage c = c.is_a?(Hash) ? [c] : c @disks = c end def add_disk(size) index = disks.map { |d| d[:Index].to_i }.sort[-1] + 1 vm_disks = disks << {:Index => index.to_s, :Size=>{:Unit => "GB", :Value => size.to_s}, :Name => "Hard Disk #{index + 1}"} data = service.virtual_machine_edit_hardware_configuration(href + "/hardwareConfiguration", _configuration_data(:disks => vm_disks)).body task = self.service.tasks.new(data) end def detach_disk(index) options = {} options[:disk] = disks.detect { |disk_hash| disk_hash[:Index] == index.to_s } options[:name] = self.name options[:description] = self.description data = service.virtual_machine_detach_disk(href + "/hardwareconfiguration/disks/actions/detach", options).body detached_disk = self.service.detached_disks.new(data) end def attach_disk(detached_disk) options = {} options[:name] = detached_disk.name options[:href] = detached_disk.href data = service.virtual_machine_attach_disk(href + "/hardwareconfiguration/disks/actions/attach", options).body task = self.service.tasks.new(data) end def delete_disk(index) vm_disks = disks.delete_if { |h| h[:Index] == index.to_s } data = service.virtual_machine_edit_hardware_configuration(href + "/hardwareconfiguration", _configuration_data(:disks => vm_disks)).body task = self.service.tasks.new(data) end def nics c = hardware_configuration.network_cards c = c.is_a?(Hash) ? [c] : c @nics = c end def add_nic(network) unit_number = nics.map { |n| n[:UnitNumber].to_i }.sort[-1] + 1 vm_nics = nics << {:UnitNumber => unit_number, :Network => {:href => network.href, :name => network.name, :type => "application/vnd.tmrk.cloud.network"}} data = service.virtual_machine_edit_hardware_configuration(href + "/hardwareConfiguration", _configuration_data(:nics => vm_nics)).body task = self.service.tasks.new(:href => data[:href])[0] end def add_ip(options) slice_ips = begin ips rescue [] end slice_networks = if slice_ips.empty? [] else ips.map { |ip| {:href => ip.network.href, :name => ip.network.name.split(' ')[0], :type => ip.network.type} }.push({:href => options[:href], :name => options[:network_name], :type => "application/vnd.tmrk.cloud.network"}).uniq end slice_ips = slice_ips.map { |i| {:name => i.address.name, :network_name => i.network.name} }.push({:name => options[:ip], :network_name => options[:network_name]}).uniq slice_ips.each do |ip| slice_networks.each do |network| if network[:name] == ip[:network_name] network[:ips] ||= [] network[:ips].push(ip[:name]) end end end data = service.virtual_machine_edit_assigned_ips(href + "/assignedIps", slice_networks).body task = self.service.tasks.new(data) end def delete_ip(options) slice_ips = begin ips rescue [] end slice_networks = if slice_ips.empty? [] else ips.map do |ip| { :href => ip.network.href, :name => ip.network.name.split(' ')[0], :type => ip.network.type, } end#.delete_if { |ip| ip[:href] == options[:href] && ip[:name] == options[:network_name] } end slice_ips.map! { |i| {:name => i.address.name, :network_name => i.network.name, :network_name => i.network.name } }.delete_if { |ip| ip[:name] == options[:ip] } slice_ips.each do |ip| slice_networks.each do |network| if network[:name] == ip[:network_name] network[:ips].delete(ip[:name]) end end end data = service.virtual_machine_edit_assigned_ips(href + "/assignedips", slice_networks).body task = self.service.tasks.new(data) end def upload_file(options) service.virtual_machine_upload_file(href + "/guest/action/files", options) true end def storage_size vm_disks = disks disks.map! { |d| d[:Size][:Value].to_i }.inject(0){|sum,item| sum + item} * 1024 * 1024 end def ready? load_unless_loaded! unless status =~ /NotDeployed|Orphaned|TaskInProgress|CopyInProgress/ true else false end end def on? powered_on == true end def off? powered_on == false end def compute_pool_id other_links.detect { |l| l[:type] == "application/vnd.tmrk.cloud.computePool" }[:href].scan(/\d+/)[0] end def compute_pool reload if other_links.nil? @compute_pool = self.service.compute_pools.new(:href => other_links.detect { |l| l[:type] == "application/vnd.tmrk.cloud.computePool" }[:href]) end def environment_id other_links.detect { |l| l[:type] == "application/vnd.tmrk.cloud.environment" }[:href].scan(/\d+/)[0] end def id href.scan(/\d+/)[0] end private def _configuration_data(options = {}) {:cpus => (options[:cpus] || hardware_configuration.processor_count), :memory => (options[:memory] || hardware_configuration.memory), :disks => (options[:disks] || disks), :nics => (options[:nics] || nics)} end def power_operation(op) requires :href begin service.send(op.keys.first, href + "/action/#{op.values.first}" ) rescue Excon::Errors::Conflict => e #Frankly we shouldn't get here ... raise e unless e.to_s =~ /because it is already powered o(n|ff)/ end true end alias destroy delete end end end end fog-1.19.0/lib/fog/ecloud/models/compute/organizations.rb0000644000004100000410000000147212261242551023360 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/organization' module Fog module Compute class Ecloud class Organizations < Fog::Ecloud::Collection model Fog::Compute::Ecloud::Organization undef_method :create identity :href def all data = service.get_organizations(organization_uri).body load(data[:Organization]) end def get(uri) if data = service.get_organization(uri) new(data.body) end rescue Fog::Errors::NotFound nil end def organization_uri @organization_uri ||= service.default_organization_uri end private def organization_uri=(new_organization_uri) @organization_uri = new_organization_uri end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/detached_disks.rb0000644000004100000410000000105412261242551023423 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/detached_disk' module Fog module Compute class Ecloud class DetachedDisks < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::DetachedDisk def all data = service.get_detached_disks(href).body[:DetachedDisk] data = [] if data.nil? load(data) end def get(uri) data = service.get_detached_disk(uri).body new(data) rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/tasks.rb0000644000004100000410000000120712261242551021612 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/task' module Fog module Compute class Ecloud class Tasks < Fog::Ecloud::Collection model Fog::Compute::Ecloud::Task identity :href attribute :other_links, :aliases => :Links attribute :total_count, :aliases => :TotalCount def all data = service.get_tasks(href).body data = data[:Task] ? data[:Task] : data load(data) end def get(uri) if data = service.get_task(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/template.rb0000644000004100000410000000136312261242551022303 0ustar www-datawww-datamodule Fog module Compute class Ecloud class Template < Fog::Ecloud::Model identity :href attribute :name, :aliases => :Name attribute :type, :aliases => :Type attribute :other_links, :aliases => :Links attribute :operating_system, :aliases => :OperatingSystem attribute :description, :aliases => :Description attribute :storage, :aliases => :Storage attribute :network_adapters, :aliases => :NetworkAdapters attribute :customization, :aliases => :Customization attribute :licensed_software, :aliases => :LicensedSoftware def id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/nodes.rb0000644000004100000410000000200612261242551021573 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/node' module Fog module Compute class Ecloud class Nodes < Fog::Ecloud::Collection identity :href model Fog::Compute::Ecloud::Node def all data = service.get_nodes(href).body if data[:NodeServices] load(data[:NodeServices][:NodeService]) else load([]) end end def get(uri) data = service.get_node(uri).body new(data) rescue Fog::Errors::NotFound nil end def create(options) options[:uri] = "#{service.base_path}/nodeServices/internetServices/#{internet_service_id}/action/createNodeService" options[:protocol] ||= "TCP" options[:enabled] ||= true options[:description] ||= "" data = service.node_service_create(options).body object = new(data) end def internet_service_id href.scan(/\d+/)[0] end end end end end fog-1.19.0/lib/fog/ecloud/models/compute/networks.rb0000644000004100000410000000140312261242551022337 0ustar www-datawww-datarequire 'fog/ecloud/models/compute/network' module Fog module Compute class Ecloud class Networks < Fog::Ecloud::Collection attribute :href, :aliases => :Href model Fog::Compute::Ecloud::Network def all body = service.get_networks(self.href).body body = body[:Networks] ? body[:Networks][:Network] : body[:Network] data = case body when NilClass then [] when Array then body when Hash then [body] end load(data) end def get(uri) if data = service.get_network(uri) new(data.body) end rescue Fog::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/ecloud/compute.rb0000644000004100000410000010750512261242551017212 0ustar www-datawww-datarequire 'fog/ecloud/collection' require 'fog/ecloud/model' require 'builder' module Fog module Compute class Ecloud < Fog::Service API_URL = "https://services.enterprisecloud.terremark.com" attr_reader :authentication_method, :version #### Credentials #requires recognizes :ecloud_username, :ecloud_password, :ecloud_version, :ecloud_access_key, :ecloud_private_key, :ecloud_authentication_method #### Models model_path 'fog/ecloud/models/compute' model :organization collection :organizations model :location collection :locations model :catalog_item collection :catalog model :catalog_configuration collection :catalog_configurations model :environment collection :environments model :task collection :tasks model :compute_pool collection :compute_pools model :server collection :servers model :virtual_machine_assigned_ip collection :virtual_machine_assigned_ips model :hardware_configuration collection :hardware_configurations model :server_configuration_option collection :server_configuration_options model :guest_process collection :guest_processes model :layout collection :layouts model :row collection :rows model :group collection :groups model :internet_service collection :internet_services model :node collection :nodes model :monitor collection :monitors model :cpu_usage_detail collection :cpu_usage_detail_summary model :memory_usage_detail collection :memory_usage_detail_summary model :storage_usage_detail collection :storage_usage_detail_summary model :operating_system_family collection :operating_system_families model :operating_system collection :operating_systems model :template collection :templates model :firewall_acl collection :firewall_acls model :network collection :networks model :ip_address collection :ip_addresses model :physical_device collection :physical_devices model :public_ip collection :public_ips model :trusted_network_group collection :trusted_network_groups model :backup_internet_service collection :backup_internet_services model :rnat collection :rnats model :association collection :associations model :tag collection :tags model :admin_organization collection :admin_organizations model :ssh_key collection :ssh_keys model :password_complexity_rule collection :password_complexity_rules model :authentication_level collection :authentication_levels model :login_banner collection :login_banners model :user collection :users model :role collection :roles model :ssh_key collection :ssh_keys model :support_ticket collection :support_tickets model :detached_disk collection :detached_disks #### Requests request_path 'fog/ecloud/requests/compute' request :backup_internet_service_create request :backup_internet_service_delete request :backup_internet_service_edit request :compute_pool_edit request :firewall_acls_create request :firewall_acls_delete request :get_admin_organization request :get_api_key request :get_api_keys request :get_association request :get_associations request :get_authentication_level request :get_authentication_levels request :get_backup_internet_service request :get_backup_internet_services request :get_catalog request :get_catalog_configuration request :get_catalog_configurations request :get_catalog_item request :get_compute_pool request :get_compute_pools request :get_cpu_usage_detail request :get_cpu_usage_detail_summary request :get_environment request :get_firewall_acl request :get_firewall_acls request :get_group request :get_groups request :get_guest_process request :get_guest_processes request :get_hardware_configuration request :get_internet_service request :get_internet_services request :get_ip_address request :get_layout request :get_layouts request :get_location request :get_locations request :get_login_banner request :get_login_banners request :get_memory_usage_detail request :get_memory_usage_detail_summary request :get_monitor request :get_monitors request :get_network request :get_network_summary request :get_networks request :get_node request :get_nodes request :get_operating_system request :get_operating_system_families request :get_organization request :get_organizations request :get_password_complexity_rule request :get_password_complexity_rules request :get_physical_device request :get_physical_devices request :get_public_ip request :get_public_ips request :get_rnat request :get_rnats request :get_role request :get_roles request :get_row request :get_rows request :get_server request :get_server_configuration_option request :get_server_configuration_options request :get_servers request :get_ssh_key request :get_ssh_keys request :get_storage_usage_detail request :get_storage_usage_detail_summary request :get_support_ticket request :get_support_tickets request :get_tag request :get_tags request :get_task request :get_tasks request :get_template request :get_templates request :get_trusted_network_group request :get_trusted_network_groups request :get_user request :get_users request :get_virtual_machine_assigned_ips request :get_detached_disks request :get_detached_disk request :groups_create request :groups_delete request :groups_edit request :groups_movedown request :groups_moveup request :internet_service_create request :internet_service_delete request :internet_service_edit request :monitors_create_default request :monitors_create_ecv request :monitors_create_http request :monitors_create_loopback request :monitors_create_ping request :monitors_disable request :monitors_edit_ecv request :monitors_edit_http request :monitors_edit_ping request :monitors_enable request :node_service_create request :node_service_delete request :node_service_edit request :power_off request :power_on request :power_reset request :power_shutdown request :public_ip_activate request :rnat_associations_create_device request :rnat_associations_delete request :rnat_associations_edit_network request :rows_create request :rows_delete request :rows_edit request :rows_movedown request :rows_moveup request :trusted_network_groups_create request :trusted_network_groups_delete request :trusted_network_groups_edit request :virtual_machine_edit_assigned_ips request :virtual_machine_copy request :virtual_machine_copy_identical request :virtual_machine_create_from_template request :virtual_machine_delete request :virtual_machine_edit request :virtual_machine_edit_hardware_configuration request :virtual_machine_import request :virtual_machine_upload_file request :virtual_machine_detach_disk request :virtual_machine_attach_disk module Shared attr_accessor :base_path attr_reader :versions_uri def validate_data(required_opts = [], options = {}) unless required_opts.all? { |opt| options.has_key?(opt) } raise ArgumentError.new("Required data missing: #{(required_opts - options.keys).map(&:inspect).join(", ")}") end end def id_from_uri(uri) uri.match(/(\d+)$/)[1].to_i end def default_organization_uri "#{@base_path}/organizations" end end class Real include Shared class << self def basic_request(name, expects=[200], method=:get, headers={}, body='') define_method(name) do |uri| request({ :expects => expects, :method => method, :headers => headers, :body => body, :parse => true, :uri => uri }) end end end def initialize(options = {}) require 'fog/core/parser' @base_path = options[:base_path] || '/cloudapi/ecloud' @connections = {} @connection_options = options[:connection_options] || {} @host = options[:ecloud_host] || API_URL @persistent = options[:persistent] || false @version = options[:ecloud_version] || "2013-06-01" @authentication_method = options[:ecloud_authentication_method] || :cloud_api_auth @access_key = options[:ecloud_access_key] @private_key = options[:ecloud_private_key] if @private_key.nil? || @authentication_method == :basic_auth @authentication_method = :basic_auth @username = options[:ecloud_username] @password = options[:ecloud_password] if @username.nil? || @password.nil? raise ArgumentError, "No credentials (cloud auth, or basic auth) passed!" end else @hmac = Fog::HMAC.new("sha256", @private_key) end end def request(params) # Convert the uri to a URI if it's a string. if params[:uri].is_a?(String) params[:uri] = URI.parse(@host + params[:uri]) end host_url = "#{params[:uri].scheme}://#{params[:uri].host}#{params[:uri].port ? ":#{params[:uri].port}" : ''}" # Hash connections on the host_url ... There's nothing to say we won't get URI's that go to # different hosts. @connections[host_url] ||= Fog::Connection.new(host_url, @persistent, @connection_options) # Set headers to an empty hash if none are set. headers = set_extra_headers_for(params) || set_extra_headers_for({}) # Make the request options = { :expects => (params[:expects] || 200), :method => params[:method] || 'GET', :path => params[:uri].path + "#{"?#{params[:uri].query}" if params[:uri].query}", :headers => headers } unless params[:body].nil? || params[:body].empty? options.merge!({:body => params[:body]}) end response = @connections[host_url].request(options) # Parse the response body into a hash unless response.body.empty? if params[:parse] document = Fog::ToHashDocument.new parser = Nokogiri::XML::SAX::PushParser.new(document) parser << response.body parser.finish response.body = document.body end end response end private # if Authorization and x-tmrk-authorization are used, the x-tmrk-authorization takes precendence. def set_extra_headers_for(params) params[:headers] = { 'x-tmrk-version' => @version, 'Date' => Time.now.utc.strftime("%a, %d %b %Y %H:%M:%S GMT"), }.merge(params[:headers] || {}) if params[:method]=="POST" || params[:method]=="PUT" params[:headers].merge!({"Content-Type" => 'application/xml'}) unless params[:headers]['Content-Type'] params[:headers].merge!({"Accept" => 'application/xml'}) end unless params[:body].nil? || params[:body].empty? params[:headers].merge!({"x-tmrk-contenthash" => "Sha256 #{Base64.encode64(Digest::SHA2.digest(params[:body].to_s)).chomp}"}) end if @authentication_method == :basic_auth params[:headers].merge!({'Authorization' => "Basic #{Base64.encode64(@username+":"+@password).delete("\r\n")}"}) elsif @authentication_method == :cloud_api_auth signature = cloud_api_signature(params) params[:headers].merge!({ "x-tmrk-authorization" => %{CloudApi AccessKey="#{@access_key}" SignatureType="HmacSha256" Signature="#{signature}"}, "Authorization" => %{CloudApi AccessKey="#{@access_key}" SignatureType="HmacSha256" Signature="#{signature}"} }) end params[:headers] end def cloud_api_signature(params) verb = params[:method].upcase headers = params[:headers] path = params[:uri].path canonicalized_headers = canonicalize_headers(headers) canonicalized_resource = canonicalize_resource(path) string = [ verb, headers['Content-Length'].to_s, headers['Content-Type'].to_s, headers['Date'].to_s, canonicalized_headers, canonicalized_resource + "\n" ].join("\n") Base64.encode64(@hmac.sign(string)).chomp end # section 5.6.3.2 in the ~1000 page pdf spec def canonicalize_headers(headers) tmp = headers.inject({}) {|ret, h| ret[h.first.downcase] = h.last if h.first.match(/^x-tmrk/i) ; ret } tmp.reject! {|k,v| k == "x-tmrk-authorization" } tmp = tmp.sort.map{|e| "#{e.first}:#{e.last}" }.join("\n") tmp end # section 5.6.3.3 in the ~1000 page pdf spec def canonicalize_resource(path) uri, query_string = path.split("?") return uri if query_string.nil? query_string_pairs = query_string.split("&").sort.map{|e| e.split("=") } tm_query_string = query_string_pairs.map{|x| "#{x.first.downcase}:#{x.last}" }.join("\n") "#{uri.downcase}\n#{tm_query_string}\n" end end class Mock include Shared def self.data @data ||= Hash.new do |hash, key| hash[key] = begin compute_pool_id = Fog.credentials[:ecloud_compute_pool_id] || Fog::Mock.random_numbers(3).to_i environment_id = Fog.credentials[:ecloud_environment_id] || Fog::Mock.random_numbers(3).to_i public_ip_id = Fog.credentials[:ecloud_public_ip_id] || Fog::Mock.random_numbers(6).to_i internet_service_id = Fog::Mock.random_numbers(6).to_i node_service_id = Fog::Mock.random_numbers(6).to_i environment_name = Fog.credentials[:ecloud_environment_name] || Fog::Mock.random_letters(12) location_id = Fog::Mock.random_numbers(4).to_i network_id = Fog.credentials[:ecloud_network_id] || Fog::Mock.random_numbers(6).to_i network_ip = Fog::Ecloud.ip_address public_ip = Fog.credentials[:ecloud_public_ip_name] || Fog::Ecloud.ip_address ip_address_id = Fog::Ecloud.ip_address ip_address2_id = Fog::Ecloud.ip_address operating_system_id = Fog::Mock.random_numbers(7).to_i operating_system_family_id = Fog::Mock.random_numbers(7).to_i organization_id = Fog::Mock.random_numbers(7).to_i organization_name = Fog::Mock.random_letters(7) template_id = Fog.credentials[:ecloud_template_id] || Fog::Mock.random_numbers(7).to_i ssh_key_id = Fog.credentials[:ecloud_ssh_key_id] || Fog::Mock.random_numbers(4).to_i ssh_key_name = Fog.credentials[:ecloud_ssh_key_name] || "root" environment = { :id => environment_id, :href => "/cloudapi/ecloud/environments/#{environment_id}", :name => environment_name, :type => "application/vnd.tmrk.cloud.environment" } organization = { :href => "/cloudapi/ecloud/organizations/#{organization_id}", :type => "application/vnd.tmrk.cloud.organization", :name => organization_name, :Links => { :Link => [ Fog::Ecloud.keep(environment, :href, :name, :type), { :href => "/cloudapi/ecloud/admin/organizations/#{organization_id}", :name => organization_name, :type => "application/vnd.tmrk.cloud.admin.organization", :rel => "alternate", }, { :href => "/cloudapi/ecloud/devicetags/organizations/#{organization_id}", :type => "application/vnd.tmrk.cloud.deviceTag; type=collection", :rel => "down", }, { :href => "/cloudapi/ecloud/alerts/organizations/#{organization_id}", :type => "application/vnd.tmrk.cloud.alertLog", :rel => "down", }, ], }, :Locations => { :Location => [ { :href => "/cloudapi/ecloud/locations/#{location_id}", :name => organization_name, :Catalog => { :href => "/cloudapi/ecloud/admin/catalog/organizations/#{organization_id}/locations/#{location_id}", :type => "application/vnd.tmrk.cloud.admin.catalogEntry; type=collection" }, :Environments => { :Environment => [environment] } } ] } } environment.merge!( :Links => { :Link => [ Fog::Ecloud.keep(organization, :href, :name, :type), ] } ) admin_organization = { :id => organization_id, :href => "/cloudapi/ecloud/admin/organizations/#{organization_id}", :type => "application/vnd.tmrk.cloud.admin.organization", :name => organization_name, :Links => { :Link => [ Fog::Ecloud.keep(organization, :href, :type, :name) ], }, :organization_id => organization_id, } compute_pool = { :id => compute_pool_id, :href => "/cloudapi/ecloud/computepools/#{compute_pool_id}", :name => Fog::Mock.random_letters(12), :type => "application/vnd.tmrk.cloud.computePool", :environment_id => environment_id, :Links => { :Link => [ Fog::Ecloud.keep(organization, :href, :name, :type), Fog::Ecloud.keep(environment, :href, :name, :type), ] } } public_ip = { :id => public_ip_id, :href => "/cloudapi/ecloud/publicips/#{public_ip_id}", :name => public_ip, :type => "application/vnd.tmrk.cloud.publicIp", :IpType => "none", :environment_id => environment_id, :Links => { :Link => [ Fog::Ecloud.keep(environment, :href, :name, :type), ], }, :InternetServices => { :InternetService => [ ], }, } internet_service = { :id => internet_service_id, :href => "/cloudapi/ecloud/internetservices/#{internet_service_id}", :name => Fog::Mock.random_letters(6), :type => "application/vnd.tmrk.cloud.internetService", :public_ip_id => public_ip_id, :Links => { :Link => [ Fog::Ecloud.keep(public_ip, :href, :name, :type), ], }, :NodeServices => { :NodeService => [ ] }, } node_service = { :id => node_service_id, :href => "/cloudapi/ecloud/nodeservices/#{node_service_id}", :name => Fog::Mock.random_letters(6), :type => "application/vnd.tmrk.cloud.nodeService", :internet_service_id => internet_service_id, :Links => { :Link => [ Fog::Ecloud.keep(internet_service, :href, :name, :type) ], }, } internet_service[:NodeServices][:NodeService].push(node_service) public_ip[:InternetServices][:InternetService].push(internet_service) network = { :id => network_id, :href => "/cloudapi/ecloud/networks/#{network_id}", :name => "#{network_ip}/#{Fog::Mock.random_numbers(2)}", :type => "application/vnd.tmrk.cloud.network", :Address => network_ip, :NetworkType => "Dmz", :BroadcastAddress => network_ip, :GatewayAddress => network_ip, :environment_id => environment_id, :Links => { :Link => [ Fog::Ecloud.keep(environment, :href, :name, :type), ] }, :IpAddresses => { :IpAddress => [], }, } ip_address = { :id => ip_address_id, :href => "/cloudapi/ecloud/ipaddresses/networks/#{network_id}/#{ip_address_id}", :name => ip_address_id, :type => "application/vnd.tmrk.cloud.ipAddress", :network_id => network_id, :Links => { :Link => [ Fog::Ecloud.keep(network, :href, :name, :type), ], }, :Reserved => "false", :Host => nil, :DetectedOn => nil, } ip_address2 = ip_address.dup.merge(:id => ip_address2_id, :href => "/cloudapi/ecloud/ipaddresses/networks/#{network_id}/#{ip_address2_id}", :name => ip_address2_id) network[:IpAddresses][:IpAddress].push(ip_address).push(ip_address2) short_name = "solaris10_64guest" operating_system = { :short_name => short_name, :compute_pool_id => compute_pool_id, :href => "/cloudapi/ecloud/operatingsystems/#{short_name}/computepools/#{compute_pool_id}", :name => "Sun Solaris 10 (64-bit)", :type => "application/vnd.tmrk.cloud.operatingSystem", :FamilyName => "Solaris", :Links => { :Link => Fog::Ecloud.keep(compute_pool, :href, :name, :type), }, :ConfigurationOptions => { :Processor => { :Minimum => "1", :Maximum => "8", :StepFactor => "1" }, :Memory => { :MinimumSize => { :Unit => "MB", :Value => "800" }, :MaximumSize => { :Unit => "MB", :Value => "16384" }, :StepFactor => { :Unit => "MB", :Value => "4" } }, :Disk => { :Minimum => "1", :Maximum => "15", :SystemDisk => { :ResourceCapacityRange => { :MinimumSize => { :Unit => "GB", :Value => "1" }, :MaximumSize => { :Unit => "GB", :Value => "512" }, :StepFactor => { :Unit => "GB", :Value => "1"} }, :MonthlyCost => "0" }, :DataDisk => { :ResourceCapacityRange => { :MinimumSize => { :Unit => "GB", :Value => "1" }, :MaximumSize => { :Unit => "GB", :Value => "512" }, :StepFactor => { :Unit => "GB", :Value => "1" } }, :MonthlyCost => "0" } }, :NetworkAdapter=> { :Minimum => "1", :Maximum => "4", :StepFactor => "1" } } } template = { :id => template_id, :href => "/cloudapi/ecloud/templates/#{template_id}/computepools/#{compute_pool_id}", :type => "application/vnd.tmrk.cloud.template", :name => "Sun Solaris 10 (x64)", :compute_pool_id => compute_pool_id, :OperatingSystem => Fog::Ecloud.keep(operating_system, :href, :name, :type), :Memory => { :MinimumSize => { :Unit => "MB", :Value => "800" }, :MaximumSize => { :Unit => "MB", :Value => "16384" }, :StepFactor => { :Unit => "MB", :Value => "4" } }, :Storage => { :Size => { :Unit => "GB", :Value => "7" } }, :NetworkAdapters => "1", :Links => { :Link => [ Fog::Ecloud.keep(compute_pool, :href, :name, :type), ] } } operating_system_family = { :id => operating_system_family_id, :compute_pool_id => compute_pool_id, :OperatingSystemFamily => { :Name => "Linux", :OperatingSystems => { :OperatingSystem => [Fog::Ecloud.keep(operating_system, :href, :name, :type)], } }, :Links => { :Link => [ Fog::Ecloud.keep(compute_pool, :href, :name, :type), ] } } ssh_key = { :id => ssh_key_id, :href => "/cloudapi/ecloud/admin/sshKeys/#{ssh_key_id}", :name => ssh_key_name, :admin_organization_id => organization_id, :Links => { :Link => [ Fog::Ecloud.keep(admin_organization, :href, :name, :type), Fog::Ecloud.keep(organization, :href, :name, :type), ] }, :Default => "true", :FingerPrint => Fog::Ecloud.mac_address } layout = { :id => environment_id, :href => "/cloudapi/ecloud/layout/environments/#{environment_id}", :type => "application/vnd.tmrk.cloud.deviceLayout", :Links => { :Link => [ Fog::Ecloud.keep(environment, :name, :href, :type), ], }, :Rows => { :Row => [ ], }, :environment_id => environment_id } { :compute_pools => {compute_pool_id => compute_pool}, :environments => {environment_id => environment}, :public_ips => {public_ip_id => public_ip}, :internet_services => {internet_service_id => internet_service}, :node_services => {node_service_id => node_service}, :networks => {network_id => network}, :organizations => {organization_id => organization}, :admin_organizations => {organization_id => admin_organization}, :operating_systems => {operating_system_id => operating_system}, :operating_system_families => {operating_system_family_id => operating_system_family}, :servers => {}, :tasks => {}, :templates => {template_id => template}, :ssh_keys => {ssh_key_id => ssh_key}, :detached_disks => {}, :template_href => (Fog.credentials[:ecloud_template_href] || "/cloudapi/ecloud/templates/#{template_id}/computepools/#{compute_pool_id}"), :rows => {}, :groups => {}, :layouts => {environment_id => layout}, } end end end def self.reset @data = nil end def initialize(options={}) @base_path = '/cloudapi/ecloud' @ecloud_api_key = options[:ecloud] end def data self.class.data[@ecloud_api_key] end def reset_data self.class.data.delete(@ecloud_api_key) end def response(params={}) body = params[:body] headers = { "Content-Type" => "application/xml" }.merge(params[:headers] || {}) status = params[:status] || 200 response = Excon::Response.new(:body => body, :headers => headers, :status => status) if params.has_key?(:expects) && ![*params[:expects]].include?(response.status) raise(Excon::Errors.status_error(params, response)) else response end end def deep_copy(o) Marshal.load(Marshal.dump(o)) end end end end end fog-1.19.0/lib/fog/go_grid.rb0000644000004100000410000000021112261242551015657 0ustar www-datawww-datarequire 'fog/core' module Fog module GoGrid extend Fog::Provider service(:compute, 'go_grid/compute', 'Compute') end end fog-1.19.0/lib/fog/hp.rb0000644000004100000410000002652112261242551014670 0ustar www-datawww-datarequire 'fog/core' require 'fog/hp/simple_http_instrumentor' module Fog module HP # define a specific version for the HP Provider unless const_defined?(:VERSION) VERSION = '0.0.22' end extend Fog::Provider module Errors class ServiceError < Fog::Errors::Error attr_reader :response_data def self.slurp(error) if error.response.body.empty? data = nil message = nil else begin data = Fog::JSON.decode(error.response.body) message = data['message'] if message.nil? and !data.values.first.nil? message = data.values.first['message'] end rescue Fog::JSON::DecodeError message = error.response.body #### body is not in JSON format, so just return as is end end new_error = super(error, message) new_error.instance_variable_set(:@response_data, data) new_error end end class InternalServerError < ServiceError; end class Conflict < ServiceError; end class NotFound < ServiceError; end class Forbidden < ServiceError; end class ServiceUnavailable < ServiceError; end class BadRequest < ServiceError attr_reader :validation_errors def self.slurp(error) 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 new_error end end end service(:block_storage, 'hp/block_storage', 'BlockStorage') service(:block_storage_v2, 'hp/block_storage_v2', 'BlockStorageV2') service(:cdn, 'hp/cdn', 'CDN') service(:compute, 'hp/compute', 'Compute') service(:dns, 'hp/dns', 'DNS') service(:lb, 'hp/lb', 'LB') service(:network, 'hp/network', 'Network') service(:storage, 'hp/storage', 'Storage') # legacy swauth 1.0/1.1 style authentication def self.authenticate_v1(options, connection_options = {}) hp_auth_uri = options[:hp_auth_uri] || "https://region-a.geo-1.objects.hpcloudsvc.com/auth/v1.0/" endpoint = URI.parse(hp_auth_uri) @scheme = endpoint.scheme || "http" @host = endpoint.host || "region-a.geo-1.objects.hpcloudsvc.com" @port = endpoint.port.to_s || "80" if (endpoint.path) @auth_path = endpoint.path.slice(1, endpoint.path.length) # remove the leading slash else @auth_path = "auth/v1.0" end service_url = "#{@scheme}://#{@host}:#{@port}" # Set the User-Agent @user_agent = options[:user_agent] set_user_agent_header(connection_options, "fog/#{Fog::VERSION}", @user_agent) connection = Fog::Connection.new(service_url, false, connection_options) @hp_access_key = options[:hp_access_key] @hp_secret_key = options[:hp_secret_key] response = connection.request({ :expects => [200, 204], :headers => { 'X-Auth-Key' => @hp_secret_key, 'X-Auth-User' => @hp_access_key }, :method => 'GET', :path => @auth_path }) response.headers.reject do |key, value| !['X-Server-Management-Url', 'X-Storage-Url', 'X-CDN-Management-Url', 'X-Auth-Token'].include?(key) end return { :auth_token => response.headers['X-Auth-Token'], :endpoint_url => nil, :cdn_endpoint_url => response.headers['X-Storage-Url'] } end def self.service_catalog(options, connection_options = {}) creds = authenticate_v2(options, connection_options) return {} if creds.nil? return {} if creds[:service_catalog].nil? return creds[:service_catalog] end # keystone based control services style authentication def self.authenticate_v2(options, connection_options = {}) unless options[:credentials].nil? expires = true begin expire = DateTime.parse(options[:credentials][:expires]) expires = false if expire > DateTime.now rescue end if expires options = options.clone options.delete(:credentials) else service_catalog = options[:credentials][:service_catalog] type = options[:hp_service_type] zone = options[:hp_avl_zone] begin creds = options[:credentials].clone creds[:endpoint_url] = get_endpoint_url(service_catalog, type, zone) begin creds[:cdn_endpoint_url] = get_endpoint_url(service_catalog, "CDN", zone) rescue end return creds rescue end options = options.clone options.delete(:credentials) end end hp_auth_uri = options[:hp_auth_uri] || "https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/tokens" # append /tokens if missing from auth uri @hp_auth_uri = hp_auth_uri.include?('tokens')? hp_auth_uri : hp_auth_uri + "tokens" endpoint = URI.parse(@hp_auth_uri) @scheme = endpoint.scheme || "https" @host = endpoint.host || "region-a.geo-1.identity.hpcloudsvc.com" @port = endpoint.port.to_s || "35357" if (endpoint.path) @auth_path = endpoint.path.slice(1, endpoint.path.length) # remove the leading slash else @auth_path = "v2.0/tokens" end service_url = "#{@scheme}://#{@host}:#{@port}" # Set the User-Agent. If the caller sets a user_agent, use it. @user_agent = options[:user_agent] set_user_agent_header(connection_options, "fog/#{Fog::VERSION}", @user_agent) connection = Fog::Connection.new(service_url, false, connection_options) ### Implement HP Control Services Authentication services ### # Get the style of auth credentials passed, defaults to access/secret key style @hp_use_upass_auth_style = options[:hp_use_upass_auth_style] || false @hp_access_key = options[:hp_access_key] @hp_secret_key = options[:hp_secret_key] @hp_tenant_id = options[:hp_tenant_id] @hp_service_type = options[:hp_service_type] @hp_avl_zone = options[:hp_avl_zone] ### Decide which auth style to use unless (@hp_use_upass_auth_style) # If Access Key style credentials are provided, use that request_body = { 'auth' => { 'apiAccessKeyCredentials' => { 'accessKey' => "#{@hp_access_key}", 'secretKey' => "#{@hp_secret_key}" } } } else # Otherwise use the Username/Password style request_body = { 'auth' => { 'passwordCredentials' => { 'username' => "#{@hp_access_key}", 'password' => "#{@hp_secret_key}" } } } end # add tenant_id if specified request_body['auth']['tenantId'] = @hp_tenant_id if @hp_tenant_id ### Make the call to CS to get auth token and service catalog response = connection.request( { :expects => 200, :headers => { 'Content-Type' => 'application/json' }, :method => 'POST', :body => Fog::JSON.encode(request_body), :path => @auth_path } ) body = Fog::JSON.decode(response.body) ### fish out auth_token and endpoint for the service auth_token = body['access']['token']['id'] expires = body['access']['token']['expires'] service_catalog = get_service_catalog(body['access']['serviceCatalog']) endpoint_url = get_endpoint_url(service_catalog, @hp_service_type, @hp_avl_zone) begin cdn_endpoint_url = get_endpoint_url(service_catalog, "CDN", @hp_avl_zone) rescue end creds = { :auth_token => auth_token, :expires => expires, :service_catalog => service_catalog, :endpoint_url => endpoint_url, :cdn_endpoint_url => cdn_endpoint_url } return creds end # CGI.escape, but without special treatment on spaces def self.escape(str,extra_exclude_chars = '') str.gsub(/([^a-zA-Z0-9_.-#{extra_exclude_chars}]+)/) do '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase end end # converts any attributes hash from aliased keys to original attribute keys def self.convert_aliased_attributes_to_original(model, attributes) original_attributes = {} attributes.each do |k, v| if orig_key = model.aliases.invert[k] original_attributes[orig_key] = v else original_attributes[k] = v end end original_attributes end private def self.get_service_catalog(body) raise "Unable to parse service catalog." unless body service_catalog = {} body.each do |s| name = s["name"] next if name.nil? name = name.to_sym next if s['endpoints'].nil? service_catalog[name] = {} s['endpoints'].each do |ep| next if ep['region'].nil? next if ep['publicURL'].nil? next if ep['publicURL'].empty? service_catalog[name][ep['region'].to_sym] = ep['publicURL'] end end return service_catalog end def self.get_endpoint_url(service_catalog, service_type, avl_zone) return nil if service_type.nil? service_type = service_type.to_sym avl_zone = avl_zone.to_sym unless service_catalog[service_type].nil? unless service_catalog[service_type][avl_zone].nil? return service_catalog[service_type][avl_zone] end end raise "Unable to retrieve endpoint service url for availability zone '#{avl_zone}' from service catalog. " end def self.set_user_agent_header(conn_opts, base_str, client_str) if client_str user_agent = {'User-Agent' => base_str + " (#{client_str})"} else user_agent = {'User-Agent' => base_str} end if conn_opts[:headers] conn_opts[:headers] = user_agent.merge!(conn_opts[:headers]) else conn_opts[:headers] = user_agent end end class Mock def self.etag Fog::Mock.random_hex(32) end def self.key_fingerprint fingerprint = [] 20.times do fingerprint << Fog::Mock.random_hex(2) end fingerprint.join(':') end def self.key_material private_key = OpenSSL::PKey::RSA.generate(1024) public_key = private_key.public_key return private_key.to_s, public_key.to_s end def self.user_id "dev_" + Fog::Mock.random_numbers(14) end def self.instance_id Fog::Mock.random_numbers(6) end def self.ip_address ip = [] 4.times do ip << Fog::Mock.random_numbers(rand(3) + 1).to_i.to_s # remove leading 0 end ip.join('.') end def self.uuid # pattern of 8-4-4-4-12 hexadecimal digits uuid = [] [8,4,4,4,12].each do |x| uuid << Fog::Mock.random_hex(x) end uuid.join('-') end def self.mac_address mac_add = [] 6.times do mac_add << Fog::Mock.random_hex(2) end mac_add.join(':') end end end end fog-1.19.0/lib/fog/ibm/0000755000004100000410000000000012261242552014476 5ustar www-datawww-datafog-1.19.0/lib/fog/ibm/requests/0000755000004100000410000000000012261242552016351 5ustar www-datawww-datafog-1.19.0/lib/fog/ibm/requests/storage/0000755000004100000410000000000012261242552020015 5ustar www-datawww-datafog-1.19.0/lib/fog/ibm/requests/storage/create_volume.rb0000644000004100000410000000526212261242552023201 0ustar www-datawww-datamodule Fog module Storage class IBM class Real # Requests a new Storage Volume be created. # # ==== Parameters # * name<~String> - The alias to use to referance storage volume # * offeringID<~String> - offering id can be requested from /computecloud/enterprise/api/rest/20100331/offerings/storage # * format<~String> - filesystem format for volume # * location<~String> - datacenter location for volume # * size<~String> - size of volume desired (Small, Medium, Large) (varies by location what size actually is) # * storageAreaID<~String> - (not supported yet) # # === Returns # * response<~Excon::Response>: # * body<~Hash>: # * name<~String> - The alias to use to referance storage volume # * format<~String> - filesystem format for storage # * location<~String> - datacenter location for storage # * createdTime<~Integer> - Epoch time of creation # * size<~String> - size of storage desired (Small, Medium, Large) (varies by location what size actually is) # * productCodes<~Array> - # * offeringID<~String> - offering id can be requested from /computecloud/enterprise/api/rest/20100331/offerings/storage # * id<~String> - id of new storage # * owner<~String> - owner of new storage # * state<~Integer> - state of newly requested storage def create_volume(name, offering_id, format, location_id, size) request( :method => 'POST', :expects => 200, :path => '/storage', :body => { 'name' => name, 'offeringID' => offering_id, 'format' => format, 'location' => location_id, 'size' => size } ) end end class Mock def create_volume(name, offering_id, format, location_id, size) volume = Fog::IBM::Mock.create_volume(name, offering_id, format, location_id, size) self.data[:volumes][volume['id']] = volume response = Excon::Response.new response.status = 200 response.body = format_create_volume_response_for(volume['id']) response end # The create_volume response doesn't contain ioPrice either def format_create_volume_response_for(volume_id) # If we aren't attached/ready, make us ready ready_volume(volume_id) unless volume_attached? volume_id self.data[:volumes][volume_id].reject { |k,v| k == 'ioPrice' } end end end end end fog-1.19.0/lib/fog/ibm/requests/storage/delete_volume.rb0000644000004100000410000000174612261242552023203 0ustar www-datawww-datamodule Fog module Storage class IBM class Real # Deletes the storage that the authenticated user manages with the specified :storage_id # # ==== Parameters # * volume_id<~String> - Id of storage volume # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # *'success'<~Bool>: true or false for success def delete_volume(volume_id) request( :method => 'DELETE', :expects => 200, :path => "/storage/#{volume_id}" ) end end class Mock def delete_volume(volume_id) response = Excon::Response.new if volume_exists? volume_id self.data[:volumes].delete volume_id response.status = 200 response.body = {"success"=>true} else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/ibm/requests/storage/list_offerings.rb0000644000004100000410000000476512261242552023373 0ustar www-datawww-datamodule Fog module Storage class IBM class Real # Returns the offerings of storage for the authenticated user # # ==== Parameters # No parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'volumes'<~Array>: list of images # * 'name'<~String>: Name of storage offering # * 'price'<~Hash>: hash containing pricing information # * 'pricePerQuantity'<~Integer>: # * 'effectiveDate'<~Integer>: starting date price is effective # * 'rate'<~Float>: rate per unit # * 'countryCode'<~String>: # * 'currencyCode'<~String>: currency used # * 'location'<~String>: datacenter location string # * 'id'<~String>: id of offering # * 'formats'<~Array>: filesystem format storage offered with # * 'label'<~String>: label for filesystem # * 'id'<~String>: string used for id of format # * 'capacity'<~Integer>: size in GB's def list_offerings request( :method => 'GET', :expects => 200, :path => '/offerings/storage' ) end end class Mock def list_offerings response = Excon::Response.new response.status = 200 response.body = {"volumes"=> [{"name"=>"Small", "price"=> {"pricePerQuantity"=>1, "effectiveDate"=>-1, "rate"=>0.0384, "countryCode"=>"897", "unitOfMeasure"=>"UHR", "currencyCode"=>"USD"}, "location"=>"61", "id"=>"20001208", "formats"=> [{"label"=>"ext3", "id"=>"EXT3"}, {"label"=>"raw", "id"=>"RAW"}], "capacity"=>256}, {"name"=>"Small", "price"=> {"pricePerQuantity"=>1, "effectiveDate"=>-1, "rate"=>0.0384, "countryCode"=>"897", "unitOfMeasure"=>"UHR", "currencyCode"=>"USD"}, "location"=>"141", "id"=>"20001208", "formats"=> [{"label"=>"ext3", "id"=>"EXT3"}, {"label"=>"raw", "id"=>"RAW"}], "capacity"=>256}]}, response end end end end end fog-1.19.0/lib/fog/ibm/requests/storage/get_volume.rb0000644000004100000410000000406012261242552022510 0ustar www-datawww-datamodule Fog module Storage class IBM class Real # Used to retrieve the specified storage volume for specified volume_id # # ==== Parameters # * volume_id<~String> - Id of storage volume # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def get_volume(volume_id) request( :method => 'GET', :expects => 200, :path => "/storage/#{volume_id}" ) end end class Mock # For whatever reason, get_volume returns different data than an entry in list_volumes def get_volume(volume_id) response = Excon::Response.new if volume_exists? volume_id response.status = 200 response.body = format_get_volume_response_for(volume_id) else response.status = 404 end response end # get_volume response doesn't contain instanceId def format_get_volume_response_for(volume_id) # If we aren't attached/ready, make us ready ready_volume(volume_id) unless volume_attached? volume_id self.data[:volumes][volume_id].reject { |k,v| k == 'instanceId' } end # The list_volumes response doesn't contain ioPrice def format_list_volumes_response self.data[:volumes].values.dup.map { |volume| volume.reject { |k,v| k == 'ioPrice'} } end def volume_exists?(volume_id) self.data[:volumes].key? volume_id end # Checks if an volume is Active def volume_ready?(volume_id) self.data[:volumes][volume_id]['state'] == 4 end def volume_attached?(volume_id) self.data[:volumes][volume_id]['instanceId'] != "0" end # Sets volume status to Detached if it's not already set, and or attached def ready_volume(volume_id) # If not ready, make ready self.data[:volumes][volume_id]['state'] = 4 end end end end end fog-1.19.0/lib/fog/ibm/requests/storage/list_volumes.rb0000644000004100000410000000251512261242552023072 0ustar www-datawww-datamodule Fog module Storage class IBM class Real # Returns the list of storage volumes # # ==== Parameters # No parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'volumes'<~Array>: list of images # * 'name'<~String>: Name of image # * 'format'<~String>: filesystem volume is formatted with # * 'location'<~String>: datacenter location string # * 'createdTime'<~Integer>: creation time in Epoch int # * 'size'<~String>: size in GB's (as a string) # * 'productCodes'<~Array>: unsure.. # * 'offeringId'<~String>: # * 'id'<~String>: volume id # * 'owner'<~String>: owner's email address # * 'state'<~Integer>: known so far: 4 provisioned, unattached; 5 provisioned, attached def list_volumes request( :method => 'GET', :expects => 200, :path => '/storage' ) end end class Mock def list_volumes response = Excon::Response.new response.status = 200 response.body = { 'volumes' => format_list_volumes_response } response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/0000755000004100000410000000000012261242552020025 5ustar www-datawww-datafog-1.19.0/lib/fog/ibm/requests/compute/get_location.rb0000644000004100000410000000313312261242552023021 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Get a location # # ==== Parameters # * location_id<~String> - Id of location # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'name'<~String>: location name # * 'location'<~String>: # * 'capabilities'<~Array>: # * 'oss.storage.format'<~Hash>: # * 'entries'<~Array>: list of supported volume formats # * 'oss.instance.spec.i386'<~Array>: unsure.. returns empty array # * 'oss.instance.spec.x86_64'<~Array>: unsure.. returns empty array # * 'oss.storage.availabilityarea'<~Array>: availability area unsupported # * 'id'<~String>: id of location # * 'description'<~String>: description including geographic location # * 'state'<~String>: state of datacenter def get_location(location_id) request( :method => 'GET', :expects => 200, :path => "/locations/#{location_id}" ) end end class Mock def get_location(location_id) response = Excon::Response.new if location_exists? location_id response.status = 200 response.body = self.data[:locations][location_id] else response.status = 404 end response end def location_exists?(location_id) self.data[:locations].key? location_id end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/create_key.rb0000644000004100000410000000366312261242552022475 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Requests a new keypair to be created # # ==== Parameters # * name<~String> - name to give new key # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'keyName'<~String>: name of new key # * 'lastModifiedTime'<~Integer>: epoch time of last modification # * 'default'<~Bool>: is default? # * 'instanceIds'<~Array>: id's of instances using key (should be empty upon creation) # * 'keyMaterial'<~String>: private key contents def create_key(name, public_key=nil) request( :method => 'POST', :expects => 200, :path => '/keys', :body => { 'name' => name, 'publicKey' => public_key } ) end end class Mock # SmartCloud returns the private key when create_key is called # We need to store both the private and public key for later use def create_key(name, public_key=nil) response = Excon::Response.new response.status = 200 attributes = { "keyName" => name, "lastModifiedTime" => Fog::IBM::Mock.launch_time, "default" => false, "instanceIds" => [], } if public_key.nil? private_key = Fog::IBM::Mock.key_material public_key = private_key.public_key response.body = attributes.merge("keyMaterial" => private_key.to_s) else response.body = { 'success' => true } end self.data[:keys][name] = attributes.merge("keyMaterial" => public_key.to_s) self.data[:private_keys][name] = attributes.merge("keyMaterial" => private_key.to_s) response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/get_image_manifest.rb0000644000004100000410000000235012261242552024161 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Returns manifest of image specified by id # # ==== Parameters # 'image_id'<~String>: id of desired image # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'manifest'<~String>: manifest of image in xml def get_image_manifest(image_id) request( :method => 'GET', :expects => 200, :path => "/offerings/image/#{image_id}/manifest" ) end end class Mock # TODO: Create a data store for this. def get_image_manifest(image_id) response = Excon::Response.new response.status = 200 response.body = {"manifest"=> "\n\t\n\t\t\n\t\t\t0.0.0.0/0\n\t\t\t1\n\t\t\t65535\n\t\t\n\t\n"} response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/create_image.rb0000644000004100000410000000321212261242552022755 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Requests an image to be created from an Instance # # ==== Parameters # * instance_id<~String> - id of instance to save # * name<~String> - name of image to be created # * description<~String> - description of image to be created # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'name'<~String>: name of new image # * 'createdTime'<~Integer>: epoch time at creation # * 'productCodes'<~Array>: # * 'id'<~String>: id of new image # * 'description'<~String>: description # * 'visibility'<~String>: visibility level ("PRIVATE", etc) # * 'state'<~Integer>: status of image def create_image(instance_id, name, description) request( :method => 'PUT', :expects => 200, :path => "/instances/#{instance_id}", :body => { 'state' => 'save', 'name' => name, 'description' => description } ) end end class Mock def create_image(instance_id, name, description) response = Excon::Response.new if instance_exists? instance_id image = Fog::IBM::Mock.private_image(name, description) self.data[:images][image["id"]] = image response.status = 200 response.body = image else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/delete_address.rb0000644000004100000410000000212512261242552023321 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Deletes the Address that the authenticated user manages with the specified :address_id # # ==== Parameters # * address_id<~String> - Id of address # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # *'success'<~Bool>: true or false for success def delete_address(address_id) request( :method => 'DELETE', :expects => 200, :path => "/addresses/#{address_id}" ) end end class Mock def delete_address(address_id) response = Excon::Response.new if address_exists? address_id self.data[:addresses].delete address_id response.status = 200 response.body = { "success" => true } else response.status = 404 end response end def address_exists?(address_id) self.data[:addresses].key? address_id end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/delete_key.rb0000644000004100000410000000164712261242552022474 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Deletes the key specified with key_name # # ==== Parameters # * key_name<~String> - name of key to be deleted # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # *'success'<~Bool>: true or false for success def delete_key(key_name) request( :method => 'DELETE', :expects => 200, :path => "/keys/#{key_name}" ) end end class Mock def delete_key(key_name) response = Excon::Response.new if key_exists? key_name self.data[:keys].delete(key_name) response.status = 200 response.body = {"success"=>true} else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/get_request.rb0000644000004100000410000000566412261242552022714 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Returns list of instances created with request specified by request_id # # ==== Parameters # * request_id<~String> - Id of request # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * instances<~Array>: array of instances created with request # * 'name'<~String>: instance name # * 'location'<~String>: instance location id # * 'keyName'<~String>: instance assigned keypair # * 'primaryIP'<~Hash>: assigned ip address, type, and hostname # * 'productCodes'<~Array>: associated product codes # * 'requestId'<~String>: # * 'imageId'<~String>: # * 'launchTime'<~Integer>: UNIX time integer representing when the instance was launched # * 'id'<~String>: instance id # * 'volumes'<~Array>: # * 'isMiniEphemeral'<~Boolean>: minimal local storage # * 'instanceType'<~String>: instance type # * 'diskSize'<~String>: instance disk size # * 'requestName'<~String>: instance request name # * 'secondaryIP'<~Array>: additional IP Addresses associated with this instance # * 'status'<~Integer>: instance status flag # * 'software'<~Array>: Software associated with this instance # * 'application'<~Hash>: Application name, type, and version (primarily OS information) # * 'expirationTime'<~Integer>: UNIX timestamp representing when the instance expires # * 'owner'<~String>: instance owner def get_request(request_id) request( :expects => 200, :method => 'GET', :path => "computecloud/enterprise/api/rest/20100331/requests/#{request_id}" ) end end class Mock def get_request(request_id) response = Excon::Response.new response.status = 200 response.body = {"instances"=> [{"name"=>"test from fog", "location"=>"101", "keyName"=>"mykey", "primaryIP"=> {"type"=>0, "ip"=>"42.42.42.42 ", "hostname"=>"42.42.42.42 "}, "productCodes"=>[], "requestId"=>"75364", "imageId"=>"20020159", "launchTime"=>1304012220770, "id"=>"75064", "volumes"=>[], "instanceType"=>"SLV32.2/4096/60*350", "requestName"=>"test from fog", "secondaryIP"=>[], "status"=>1, "software"=> [{"name"=>"SUSE Linux Enterprise Server", "type"=>"OS", "version"=>"11 SP1"}], "expirationTime"=>1367084229205, "owner"=>"user@example.com"}]} response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/modify_instance.rb0000644000004100000410000000467212261242552023536 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Modify an instance # # ==== Parameters # * instance_id<~String> - id of instance to rename # * params<~Hash> - depends on type of request # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'success'<~Bool>: # OR # * response<~Excon::Response>: # * body<~Hash>: # ???? # * 'expirationTime'<~Integer>: new expiration time of instance (epoch) # # Note: The feature of dynamically attaching or detaching storage is only # supported by data centers where the KVM host version is RHEL 6.1. If the # feature is not supported by the data center, you will get an exception like # "Unsupported exception. Dynamic features are not supported on the KVM # Host". def modify_instance(instance_id, options={}) request( :method => 'PUT', :expects => 200, :path => "/instances/#{instance_id}", :body => options ) end end class Mock def modify_instance(instance_id, params={}) response = Excon::Response.new if instance_exists? instance_id if params['state'] == 'restart' self.data[:instances][instance_id]["status"] = "8" response.status = 200 response.body = { "success" => true } elsif params['type'] == 'attach' || params['type'] == 'detach' if Fog::Storage[:ibm].volume_exists?(params['volume_id']) # TODO: Update the instance in the data hash, assuming IBM ever gets this feature working properly. response.status = 415 else response.status = 404 end elsif params['name'] self.data[:instances][instance_id]["name"] = params['name'] response.status = 200 response.body = { "success" => true } elsif params['expirationTime'] self.data[:instances][instance_id]["expirationTime"] = params['expirationTime'] response.status = 200 response.body = { 'expirationTime' => params['expirationTime'] } end else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/get_instance_logs.rb0000644000004100000410000000107512261242552024044 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Get an instance's logs # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * logs<~Array>: # TODO: docs def get_instance_logs(instance_id, start_index=nil) request( :method => 'GET', :expects => 200, :path => "/instances/#{instance_id}/logs" + (start_index ? "?startIndex=#{start_index}" : '') ) end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/list_images.rb0000644000004100000410000000405112261242552022652 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Returns the list of Images available to be provisioned on the IBM DeveloperCloud. # # ==== Parameters # No parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'images'<~Array>: list of images # * 'name'<~String>: image name # * 'location'<~String>: instance location id # * 'createdTime'<~Integer>: time created in epoch time # * 'supportedInstanceTypes'<~Array>: list of prices per image # * 'pricePerQuantity'<~Integer>: # * 'effectiveDate'<~Fixnum>: # * 'rate'<~Float>: price per unit # * 'countryCode'<~String>: # * 'unitOfMeasure'<~String>: unit of measurement # * 'currencyCode'<~String>: currency billed in # * 'productCodes'<~Array>: # * 'id'<~String>: # * 'documentation'<~String>: link to documentation for image # * 'manifest'<~String>: link to xml manifest file # * 'description'<~String>: text description of image # * 'visibility'<~String>: status of visibilty of image. known values so far are "PUBLIC" and "PRIVATE" # * 'platform'<~String>: operating system # * 'architecture'<~String>: architecture supported by image # * 'documentation'<~String>: link to documentation for image # * 'owner'<~String>: owner of image # * 'state'<~Integer>: state of availability of image def list_images request( :method => 'GET', :expects => 200, :path => '/offerings/image' ) end end class Mock def list_images response = Excon::Response.new response.status = 200 response.body = {'images' => self.data[:images].values} response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/get_key.rb0000644000004100000410000000231412261242552022001 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Returns details of key by name specified # # ==== Parameters # 'key_name'<~String>: name of key to request # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'keyName'<~String>: Name of key # * 'lastModifiedTime'<~Integer>: epoch time of last modification # * 'default'<~Bool>: bool if key is default for user # * 'instanceIds'<~Array>: list of instances associated with key # * 'keyMaterial'<~String>: public key def get_key(key_name) request( :method => 'GET', :expects => 200, :path => "/keys/#{key_name}" ) end end class Mock def get_key(key_name) response = Excon::Response.new if key_exists? key_name response.status = 200 response.body = self.data[:keys][key_name] else response.status = 404 end response end def key_exists?(name) self.data[:keys].key? name end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/delete_instance.rb0000644000004100000410000000275712261242552023513 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Deletes the Instance that the authenticated user manages with the specified :instance_id # # ==== Parameters # * instance_id<~String> - Id of instance # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # *'success'<~Bool>: true or false for success def delete_instance(instance_id) request( :method => 'DELETE', :expects => 200, :path => "/instances/#{instance_id}" ) end end class Mock def delete_instance(instance_id) response = Excon::Response.new if deleteable? instance_id # remove from memoreeeez. self.data[:instances].delete instance_id response.body = { 'success' => true } response.status = 200 else # TODO: we should really return a 412 if the instance is in an invalid state, and a 404 if it doesn't exist. response.status = 404 end response end # we can't delete the instance if it doesn't exist, or is in an invalid state. def deleteable?(instance_id) return false unless instance_exists? instance_id instance = self.data[:instances][instance_id] return false if [0, 1, 7, 14, 15].include?(instance["status"].to_i) true end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/create_address.rb0000644000004100000410000000277612261242552023336 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Requests a new static IP address to be created # # ==== Parameters # * location_id<~String> - id of location # * offering_id<~String> - id for offering # * vlan_id<~String> - id of vlan # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'location'<~String>: location of new address # * 'offeringId'<~String>: offering id of new address # * 'id'<~String>: id # * 'ip'<~String>: returns string of spaces (ip not yet allocated right after creation) # * 'state'<~Integer>: status of address (0 when new) def create_address(location, offering_id, options={}) request( :method => 'POST', :expects => 200, :path => '/addresses', :body => { 'offeringID' => offering_id, 'location' => location, 'vlanID' => options[:vlan_id] } ) end end class Mock def create_address(location_id, offering_id="20001223", options={}) address = Fog::IBM::Mock.create_address(location_id, offering_id, options) self.data[:addresses][address['id']] = address response = Excon::Response.new response.status = 200 response.body = address response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/list_vlans.rb0000644000004100000410000000232212261242552022527 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Returns the vlan offerings for user # # ==== Parameters # No parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'addresses'<~Array>: list of addresses # * 'location'<~String>: location of address # * 'mode'<~Integer>: # * 'offeringId'<~String>: offering ID # * 'id'<~String>: id # * 'type'<~Integer>: TODO unsure # * 'ip'<~String>: IP address.. with space at the end # * 'hostname'<~String>: seems to be same as ip # * 'state'<~Integer>: state of address def list_vlans request( :method => 'GET', :expects => 200, :path => '/offerings/vlan' ) end end class Mock def list_vlans response = Excon::Response.new response.status = 200 response.body = {"vlan"=> [{"location"=>"101", "id"=>"75321", "name"=>"FOG-VLAN1"}]} response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/clone_image.rb0000644000004100000410000000245612261242552022623 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Clones image specified by image_id # # ==== Parameters # * image_id<~String> - id of image to be cloned # * name<~String> - name of new image # * description<~String> - description of new image # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ImageID'<~String>: id of new image def clone_image(image_id, name, description) request( :method => 'POST', :expects => 200, :path => "/offerings/image/#{image_id}", :body => { 'name' => name, 'description' => description } ) end end class Mock def clone_image(image_id, name, description) response = Excon::Response.new if image_exists? image_id id = Fog::IBM::Mock.instance_id self.data[:images][id] = self.data[:images][image_id].merge('id' => id, 'name' => name, 'description' => description) response.status = 200 response.body = { "ImageID" => id } else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/get_image_agreement.rb0000644000004100000410000000653312261242552024331 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Returns license agreement of image specified by id # # ==== Parameters # 'image_id'<~String>: id of desired image # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'text'<~String>: text of license # * 'id'<~String>: id of image # * 'attachments'<~Array>: Additional agreements attached to image # * 'label'<~String>: description of attachment # * 'url'<~String>: url to retrieve attachment # * 'type'<~Integer>: type of attachment def get_image_agreement(image_id) request( :method => 'GET', :expects => 200, :path => "/offerings/image/#{image_id}/agreement" ) end end class Mock # TODO: Fix this so they work. def get_image_agreement(image_id) response = Excon::Response.new response.status = 200 response.body = {"text"=> "test, operating system is SUSE Linux Enterprise Server/11 SP1 - English\n\nYour access to and use of the Service, including all selected options, are governed by the terms of the Agreement signed between your Enterprise and IBM. Each Service is also governed by one or more Attachments (including, for example, Image Terms Attachments). Applicable Attachments are part of the Agreement between you and IBM and include Attachments for Services you acquire after the Agreement was signed. The Agreement also references applicable IBM and third party end user license agreements that govern the use of IBM software and operating system software provided as part of an Image.\n\nYou are responsible for complying with the terms of the Agreement (including applicable Attachments) and applicable license agreements. You may review the terms for the Service by 1) obtaining information regarding the Agreement from your Account Administrator and 2) accessing the Asset Catalog to review specific Image Terms and end user license agreements for IBM and third party software provided as part of an Image. ", "id"=>"20020159", "attachments"=> [{"label"=>"Service Description for Developement & Test Service", "url"=> "https://www-147.ibm.com/cloud/enterprise/static/internal_user_agreement.pdf", "type"=>0}, {"label"=>"Smart Business on the IBM Public Cloud Agreement", "url"=> "https://www-147.ibm.com/cloud/enterprise/static/internal_user_agreement.pdf", "type"=>1}, {"label"=> "End User License for SUSE 10.2 Linux Enterprise Server software", "url"=> "https://www.novell.com/licensing/eula/sles_10/sles_10_english.pdf", "type"=>2}, {"label"=> "End User License for SUSE 11.0 Linux Enterprise Server software", "url"=>"https://www.novell.com/licensing/eula/sles_11/sles_11_en.pdf", "type"=>2}, {"label"=>"End User License for RedHat Linux RHEL software", "url"=>"https://www.redhat.com/licenses/", "type"=>2}]} response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/get_instance.rb0000644000004100000410000000536212261242552023023 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Returns the Instance that the authenticated user manages with the specified :instance_id # # ==== Parameters # * instance_id<~String> - Id of instance # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'name'<~String>: instance name # * 'location'<~String>: instance location id # * 'keyName'<~String>: instance assigned keypair # * 'primaryIP'<~Hash>: assigned ip address, type, and hostname # * 'productCodes'<~Array>: associated product codes # * 'requestId'<~String>: # * 'imageId'<~String>: # * 'launchTime'<~Integer>: UNIX time integer representing when the instance was launched # * 'id'<~String>: instance id # * 'volumes'<~Array>: # * 'isMiniEphemeral'<~Boolean>: minimal local storage # * 'instanceType'<~String>: instance type # * 'diskSize'<~String>: instance disk size # * 'requestName'<~String>: instance request name # * 'secondaryIP'<~Array>: additional IP Addresses associated with this instance # * 'status'<~Integer>: instance status flag # * 'software'<~Array>: Software associated with this instance # * 'application'<~Hash>: Application name, type, and version (primarily OS information) # * 'expirationTime'<~Integer>: UNIX timestamp representing when the instance expires # * 'owner'<~String>: instance owner def get_instance(instance_id) request( :method => 'GET', :expects => 200, :path => "/instances/#{instance_id}" ) end end class Mock def get_instance(instance_id) response = Excon::Response.new if instance_exists? instance_id activate_instance(instance_id) # Set it to Active if it's not running response.status = 200 response.body = self.data[:instances][instance_id] else raise Fog::Compute::IBM::NotFound end response end # Checks if an instance exists def instance_exists?(instance_id) self.data[:instances].key? instance_id end # Sets instance status to Active if it's not already set. def activate_instance(instance_id) self.data[:instances][instance_id]["status"] = 5 unless instance_active? instance_id end # Checks if an instance is Active def instance_active?(instance_id) self.data[:instances][instance_id]["status"] == 5 end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/list_keys.rb0000644000004100000410000000403012261242552022355 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Returns list of instances that the authenticated user manages. # # ==== Parameters # No parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'instances'<~Array>: list of instances # * 'name'<~String>: instance name # * 'location'<~String>: instance location id # * 'keyName'<~String>: instance assigned keypair # * 'primaryIP'<~Hash>: assigned ip address, type, and hostname # * 'productCodes'<~Array>: associated product codes # * 'requestId'<~String>: # * 'imageId'<~String>: # * 'launchTime'<~Integer>: UNIX time integer representing when the instance was launched # * 'id'<~String>: instance id # * 'volumes'<~Array>: # * 'isMiniEphemeral'<~Boolean>: minimal local storage # * 'instanceType'<~String>: instance type # * 'diskSize'<~String>: instance disk size # * 'requestName'<~String>: instance request name # * 'secondaryIP'<~Array>: additional IP Addresses associated with this instance # * 'status'<~Integer>: instance status flag # * 'software'<~Array>: Software associated with this instance # * 'application'<~Hash>: Application name, type, and version (primarily OS information) # * 'expirationTime'<~Integer>: UNIX timestamp representing when the instance expires # * 'owner'<~String>: instance owner def list_keys request( :method => 'GET', :expects => 200, :path => '/keys' ) end end class Mock def list_keys response = Excon::Response.new response.status = 200 response.body = {'keys' => self.data[:keys].values} response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/get_image.rb0000644000004100000410000000424512261242552022300 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Returns details of image specified by id # # ==== Parameters # 'image_id'<~String>: id of desired image # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'name'<~String>: image name # * 'location'<~String>: instance location id # * 'createdTime'<~Integer>: time created in epoch time # * 'supportedInstanceTypes'<~Array>: list of prices per image # * 'pricePerQuantity'<~Integer>: # * 'effectiveDate'<~Fixnum>: # * 'rate'<~Float>: price per unit # * 'countryCode'<~String>: # * 'unitOfMeasure'<~String>: unit of measurement # * 'currencyCode'<~String>: currency billed in # * 'productCodes'<~Array>: # * 'id'<~String>: # * 'documentation'<~String>: link to documentation for image # * 'manifest'<~String>: link to xml manifest file # * 'description'<~String>: text description of image # * 'visibility'<~String>: status of visibilty of image. known values so far are "PUBLIC" and "PRIVATE" # * 'platform'<~String>: operating system # * 'architecture'<~String>: architecture supported by image # * 'documentation'<~String>: link to documentation for image # * 'owner'<~String>: owner of image # * 'state'<~Integer>: state of availability of image def get_image(image_id) request( :method => 'GET', :expects => 200, :path => "/offerings/image/#{image_id}" ) end end class Mock def get_image(image_id) response = Excon::Response.new if image_exists? image_id response.status = 200 response.body = self.data[:images][image_id] else response.status = 404 end response end private def image_exists?(image_id) self.data[:images].key? image_id end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/list_addresses.rb0000644000004100000410000000326312261242552023366 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Returns the list of static IP addresses for current user # # ==== Parameters # No parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'addresses'<~Array>: list of addresses # * 'location'<~String>: location of address # * 'mode'<~Integer>: # * 'offeringId'<~String>: offering ID # * 'id'<~String>: id # * 'type'<~Integer>: TODO unsure # * 'ip'<~String>: IP address.. with space at the end # * 'hostname'<~String>: seems to be same as ip # * 'state'<~Integer>: state of address def list_addresses request( :method => 'GET', :expects => 200, :path => '/addresses' ) end end class Mock def list_addresses # Loop through addresses and update states and values if they aren't set self.data[:addresses].values.each do |address| address['state'] = 2 if address['state'] == 0 address['ip'] = Fog::IBM::Mock.ip_address if address['ip'].empty? address['mode'] = 0 unless address.key? 'mode' address['hostname'] = Fog::IBM::Mock.hostname unless address.key? 'hostname' address['type'] = 1 unless address.key? 'type' end response = Excon::Response.new response.status = 200 response.body = { 'addresses' => self.data[:addresses].values } response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/delete_image.rb0000644000004100000410000000213112261242552022753 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Deletes the image that the authenticated user manages with the specified :image_id # # ==== Parameters # * image_id<~String> - Id of image # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # *'success'<~Bool>: true or false for success def delete_image(image_id) request( :method => 'DELETE', :expects => 200, :path => "/offerings/image/#{image_id}" ) end end class Mock def delete_image(image_id) response = Excon::Response.new # TODO: We should probably check that an image is deleteable. # i.e. that the user has appropriate permissions if image_exists? image_id self.data[:images].delete image_id response.status = 200 response.body = {"success"=>true} else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/list_instances.rb0000644000004100000410000000406312261242552023377 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Returns list of instances that the authenticated user manages. # # ==== Parameters # No parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'instances'<~Array>: list of instances # * 'name'<~String>: instance name # * 'location'<~String>: instance location id # * 'keyName'<~String>: instance assigned keypair # * 'primaryIP'<~Hash>: assigned ip address, type, and hostname # * 'productCodes'<~Array>: associated product codes # * 'requestId'<~String>: # * 'imageId'<~String>: # * 'launchTime'<~Integer>: UNIX time integer representing when the instance was launched # * 'id'<~String>: instance id # * 'volumes'<~Array>: # * 'isMiniEphemeral'<~Boolean>: minimal local storage # * 'instanceType'<~String>: instance type # * 'diskSize'<~String>: instance disk size # * 'requestName'<~String>: instance request name # * 'secondaryIP'<~Array>: additional IP Addresses associated with this instance # * 'status'<~Integer>: instance status flag # * 'software'<~Array>: Software associated with this instance # * 'application'<~Hash>: Application name, type, and version (primarily OS information) # * 'expirationTime'<~Integer>: UNIX timestamp representing when the instance expires # * 'owner'<~String>: instance owner def list_instances request( :method => 'GET', :expects => 200, :path => '/instances' ) end end class Mock def list_instances response = Excon::Response.new response.status = 200 response.body = { 'instances' => self.data[:instances].values } response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/list_locations.rb0000644000004100000410000000144112261242552023400 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Returns the list of Images available to be provisioned on the IBM DeveloperCloud. # # ==== Parameters # No parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'locations'<~Array>: list of locations def list_locations request( :method => 'GET', :expects => 200, :path => "/locations" ) end end class Mock def list_locations response = Excon::Response.new response.status = 200 response.body = { "locations" => self.data[:locations].values } response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/create_instance.rb0000644000004100000410000000743112261242552023506 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Requests a new Instance to be created. # # ==== Parameters # * name<~String> - The alias to use to reference this instance # * image_id<~String> - The id of the image to create this instance from # * instance_type<~String> - The instance type to use for this instance # * location<~String> - The id of the Location where this instance will be created # * options<~Hash>: # * :key_name<~String> - The public key to use for accessing the created instance # * :ip<~String> - The ID of a static IP address to associate with this instance # * :volume_id<~String> - The ID of a storage volume to associate with this instance # * :vlan_id<~String> - The ID of a Vlan offering to associate with this instance. # * :secondary_ip<~String> - Comma separated list of static IP IDs to associate with this instance. # * :is_mini_ephermal<~Boolean> - Whether or not the instance should be provisioned with the root segment only # * :configuration_data<~Hash> - Arbitrary name/value pairs defined by the image being created # * :anti_collocation_instance<~String> - The ID of an existing anti-collocated instance. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'name'<~String>: instance name # * 'location'<~String>: instance location id # * 'keyName'<~String>: instance assigned keypair # * 'primaryIP'<~Hash>: assigned ip address, type, and hostname # * 'productCodes'<~Array>: associated product codes # * 'requestId'<~String>: # * 'imageId'<~String>: # * 'launchTime'<~Integer>: epoch time in ms representing when the instance was launched def create_instance(name, image_id, instance_type, location, options={}) body_data = { 'name' => name, 'imageID' => image_id, 'instanceType' => instance_type, 'location' => location, 'publicKey' => options[:key_name], 'ip' => options[:ip], 'volumeID' => options[:volume_id], 'vlanID' => options[:vlan_id], 'isMiniEphemeral' => options[:is_mini_ephemeral], 'Configuration Data' => options[:configuration_data], 'antiCollocationInstance' => options[:anti_collocation_instance] } if options[:secondary_ip] options[:secondary_ip].split(',').map(&:strip).each_with_index do |n, idx| body_data.merge!({"secondary.ip.#{idx}" => n}) end end request( :method => 'POST', :expects => 200, :path => '/instances', :body => body_data ) end end class Mock def create_instance(name, image_id, instance_type, location, options={}) response = Excon::Response.new # Since we want to test error conditions, we have a little regex that traps specially formed # instance type strings. case name when /FAIL:\ (\d{3})/ response.status = $1.to_i raise Excon::Errors.status_error({:expects => 200}, response) else instance = Fog::IBM::Mock.create_instance(name, image_id, instance_type, location, options) self.data[:instances][instance['id']] = instance response.status = 200 response.body = {"instances" => [ instance ]} response end end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/list_address_offerings.rb0000644000004100000410000000343312261242552025077 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Returns the offerings of static address types/pricing for the authenticated user # # ==== Parameters # No parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'addresses'<~Array>: list of address offerings # * 'price'<~Hash>: pricing info for specific address offering # * 'price'<~Hash>: hash containing pricing information # * 'pricePerQuantity'<~Integer>: # * 'effectiveDate'<~Integer>: starting date price is effective # * 'rate'<~Float>: rate per unit # * 'countryCode'<~String>: # * 'unitOfMeasure'<~String>: # * 'currencyCode'<~String>: currency used # * 'location'<~String>: datacenter location string # * 'ipType'<~Integer>: type of ip address # * 'id'<~String>: id of offering def list_address_offerings request( :expects => 200, :method => 'GET', :path => '/offerings/address' ) end end class Mock def list_address_offerings response = Excon::Response.new response.status = 200 response.body = {"addresses"=> [{"price"=> {"pricePerQuantity"=>1, "effectiveDate"=>1302566400000, "rate"=>0.01, "countryCode"=>"897", "unitOfMeasure"=>"UHR", "currencyCode"=>"USD"}, "location"=>"101", "ipType"=>0, "id"=>"20001223"}]} response end end end end end fog-1.19.0/lib/fog/ibm/requests/compute/modify_key.rb0000644000004100000410000000257612261242552022523 0ustar www-datawww-datamodule Fog module Compute class IBM class Real # Modify a key # # ==== Parameters # * key_name<~String> - name of key to be modified # * params<~Hash> - depends on type of request # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'success'<~Bool>: success status of update request def modify_key(key_name, params={}) request( :method => 'PUT', :expects => 200, :path => "/keys/#{key_name}", :body => params ) end end class Mock def modify_key(key_name, params={}) response = Excon::Response.new if key_exists? key_name if params['public_key'] self.data[:keys][key_name]['keyMaterial'] = public_key self.data[:keys][key_name]['lastModifiedTime'] = Fog::IBM::Mock.launch_time end if params['default'] self.data[:keys].values.each do |key| key['default'] = false end self.data[:keys][key_name]['default'] = true end response.status = 200 response.body = {"success"=>true} else response.status = 404 end response end end end end end fog-1.19.0/lib/fog/ibm/models/0000755000004100000410000000000012261242552015761 5ustar www-datawww-datafog-1.19.0/lib/fog/ibm/models/storage/0000755000004100000410000000000012261242552017425 5ustar www-datawww-datafog-1.19.0/lib/fog/ibm/models/storage/volume.rb0000644000004100000410000000523012261242552021261 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Storage class IBM class Volume < Fog::Model STATES = { 0 => 'New', 1 => 'Creating', 2 => 'Deleting', 3 => 'Deleted', 4 => 'Detached', 5 => 'Attached', 6 => 'Failed', 7 => 'Deletion pending', 8 => 'Being cloned', 9 => 'Cloning', 10 => 'Attaching', 11 => 'Detaching', 12 => 'Copying', 13 => 'Importing', 14 => 'Transfer retrying', } identity :id attribute :instance_id, :aliases => "instanceId" attribute :io_price, :aliases => "ioPrice" attribute :name attribute :state attribute :size attribute :offering_id, :aliases => "offeringId" attribute :owner attribute :created_at, :aliases => "createdTime" attribute :location_id, :aliases => "location" attribute :product_codes, :aliases => "productCodes" attribute :format attribute :storage_area, :aliases => 'storageArea' attribute :platform_version, :aliases => 'platformVersion' attribute :clone_status, :aliases => 'cloneStatus' def attached? state == "Attached" end def attach(instance_id) requires :id service.attach_volume(instance_id, id).body['success'] end def detach(instance_id) requires :id service.detach_volume(instance_id, id).body['success'] end def created_at Time.at(attributes[:created_at].to_f / 1000) end def destroy requires :id service.delete_volume(id) true end def instance return nil if instance_id.nil? || instance_id == "0" || instance_id == "" Fog::Compute[:ibm].servers.get(instance_id) end def location requires :location_id Fog::Compute[:ibm].locations.get(location_id) end # Are we ready to be attached to an instance? def ready? # TODO: Not sure if this is the only state we should be matching. state == "Detached" end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :name, :offering_id, :format, :location_id, :size data = service.create_volume(name, offering_id, format, location_id, size) merge_attributes(data.body) true end def state STATES[attributes[:state]] end end end end end fog-1.19.0/lib/fog/ibm/models/storage/offerings.rb0000644000004100000410000000047012261242552021735 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/ibm/models/storage/offering' module Fog module Storage class IBM class Offerings < Fog::Collection model Fog::Storage::IBM::Offering def all load(service.list_offerings.body['volumes']) end end end end end fog-1.19.0/lib/fog/ibm/models/storage/offering.rb0000644000004100000410000000062612261242552021555 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Storage class IBM class Offering < Fog::Model identity :id attribute :location attribute :name attribute :label attribute :capacity attribute :supported_sizes, :aliases => 'supportedSizes' attribute :supported_formats, :aliases => 'formats' attribute :price end end end end fog-1.19.0/lib/fog/ibm/models/storage/volumes.rb0000644000004100000410000000074712261242552021454 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/ibm/models/storage/volume' module Fog module Storage class IBM class Volumes < Fog::Collection model Fog::Storage::IBM::Volume def all load(service.list_volumes.body['volumes']) end def get(volume_id) begin new(service.get_volume(volume_id).body) rescue Fog::Storage::IBM::NotFound nil end end end end end end fog-1.19.0/lib/fog/ibm/models/compute/0000755000004100000410000000000012261242552017435 5ustar www-datawww-datafog-1.19.0/lib/fog/ibm/models/compute/address.rb0000644000004100000410000000266712261242552021422 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class IBM class Address < Fog::Model STATES = { 0 => 'New', 1 => 'Allocating', 2 => 'Free', 3 => 'Attached', 4 => 'Releasing', 5 => 'Released', 6 => 'Failed', 7 => 'Release pending', } identity :id attribute :type attribute :location attribute :ip attribute :state attribute :instance_id, :aliases => 'instanceId' attribute :offering_id, :aliases => 'offeringId' attribute :vlan_id, :aliases => 'vlanId' attribute :hostname attribute :mode attribute :owner def initialize(new_attributes={}) super(new_attributes) self.offering_id ||= '20001223' self.location ||= '82' end def save requires :offering_id, :location data = service.create_address(location, offering_id, :vlan_id => vlan_id, :ip => ip) merge_attributes(data.body) true end def state STATES[attributes[:state]] end def ready? state == 'Free' || state == 'Released' end def destroy requires :id service.delete_address(id).body['success'] end end end end end fog-1.19.0/lib/fog/ibm/models/compute/addresses.rb0000644000004100000410000000110612261242552021735 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/ibm/models/compute/address' module Fog module Compute class IBM class Addresses < Fog::Collection model Fog::Compute::IBM::Address def all load(service.list_addresses.body['addresses']) end def get(address_id) begin address = service.list_addresses.body new(address['addresses'].find{|address| address['id'] == address_id.to_s }) rescue Fog::Compute::IBM::NotFound nil end end end end end end fog-1.19.0/lib/fog/ibm/models/compute/vlan.rb0000644000004100000410000000031112261242552020715 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class IBM class Vlan < Fog::Model identity :id attribute :name attribute :location end end end end fog-1.19.0/lib/fog/ibm/models/compute/location.rb0000644000004100000410000000041212261242552021567 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class IBM class Location < Fog::Model identity :id attribute :name attribute :location attribute :capabilities attribute :description end end end end fog-1.19.0/lib/fog/ibm/models/compute/images.rb0000644000004100000410000000073712261242552021236 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/ibm/models/compute/image' module Fog module Compute class IBM class Images < Fog::Collection model Fog::Compute::IBM::Image def all load(service.list_images.body['images']) end def get(image_id) begin new(service.get_image(image_id).body) rescue Fog::Compute::IBM::NotFound nil end end end end end end fog-1.19.0/lib/fog/ibm/models/compute/servers.rb0000644000004100000410000000075512261242552021462 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/ibm/models/compute/server' module Fog module Compute class IBM class Servers < Fog::Collection model Fog::Compute::IBM::Server def all load(service.list_instances.body['instances']) end def get(server_id) begin new(service.get_instance(server_id).body) rescue Fog::Compute::IBM::NotFound nil end end end end end end fog-1.19.0/lib/fog/ibm/models/compute/instance-type.rb0000644000004100000410000000034712261242552022551 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class IBM class InstanceType < Fog::Model identity :id attribute :detail attribute :label attribute :price end end end end fog-1.19.0/lib/fog/ibm/models/compute/instance-types.rb0000644000004100000410000000036112261242552022730 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/ibm/models/compute/instance-type' module Fog module Compute class IBM class InstanceTypes < Fog::Collection model Fog::Compute::IBM::InstanceType end end end end fog-1.19.0/lib/fog/ibm/models/compute/locations.rb0000644000004100000410000000076712261242552021767 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/ibm/models/compute/location' module Fog module Compute class IBM class Locations < Fog::Collection model Fog::Compute::IBM::Location def all load(service.list_locations.body['locations']) end def get(location_id) begin new(service.get_location(location_id).body) rescue Fog::Compute::IBM::NotFound nil end end end end end end fog-1.19.0/lib/fog/ibm/models/compute/keys.rb0000644000004100000410000000117312261242552020737 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/ibm/models/compute/key' module Fog module Compute class IBM class Keys < Fog::Collection model Fog::Compute::IBM::Key def all load(service.list_keys.body['keys']) end def get(key_id) begin new(service.get_key(key_id).body) rescue Fog::Compute::IBM::NotFound nil end end def default find {|key| key.default? } end def default=(key_name) service.modify_key(key_name, 'default' => true) end end end end end fog-1.19.0/lib/fog/ibm/models/compute/key.rb0000644000004100000410000000150312261242552020551 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class IBM class Key < Fog::Model identity :name, :aliases => 'keyName' attribute :default attribute :public_key, :aliases => 'keyMaterial' attribute :instance_ids, :aliases => 'instanceIds' attribute :modified_at, :aliases => 'lastModifiedTime' def save requires :name data = service.create_key(name, public_key) merge_attributes(data.body) data.body['keyName'] == name end def destroy data = service.delete_key(identity) data.body['success'] end def default? default end def instances instance_ids.map { Fog::Compute[:ibm].servers.get(instance_id) } end end end end end fog-1.19.0/lib/fog/ibm/models/compute/server.rb0000644000004100000410000001307412261242552021275 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class IBM class Server < Fog::Compute::Server STATES = { 0 => 'New', 1 => 'Provisioning', 2 => 'Failed', 3 => 'Removed', 4 => 'Rejected', 5 => 'Active', 6 => 'Unknown', 7 => 'Deprovisioning', 8 => 'Restarting', 9 => 'Starting', 10 => 'Stopping', 11 => 'Stopped', 12 => 'Deprovisioning pending', 13 => 'Restart pending', 14 => 'Attaching', 15 => 'Detaching' } identity :id attribute :disk_size, :aliases => 'diskSize' attribute :expires_at, :aliases => 'expirationTime' attribute :image_id, :aliases => 'imageId' attribute :instance_type, :aliases => 'instanceType' attribute :ip attribute :key_name, :aliases => 'keyName' attribute :launched_at, :aliases => 'launchTime' attribute :location_id, :aliases => 'location' attribute :name attribute :owner attribute :primary_ip, :aliases => 'primaryIP' attribute :product_codes, :aliases => 'productCodes' attribute :request_id, :aliases => 'requestId' attribute :request_name, :aliases => 'requestName' attribute :is_mini_ephemeral, :aliases => 'isMiniEphemeral' attribute :secondary_ip, :aliases => 'secondaryIP' attribute :software attribute :state, :aliases => 'status' attribute :volume_ids, :aliases => 'volumes' attribute :vlan_id, :aliases => 'vlanID' def initialize(new_attributes={}) super(new_attributes) self.name ||= 'fog-instance' self.image_id ||= '20010001' self.location_id ||= '41' self.instance_type ||= 'COP32.1/2048/60' self.key_name ||= 'fog' end def save requires :name, :image_id, :instance_type, :location_id data = service.create_instance(name, image_id, instance_type, location_id, :key_name => key_name, :vlan_id => vlan_id, :secondary_ip => secondary_ip) data.body['instances'].each do |iattrs| if iattrs['name'] == name merge_attributes(iattrs) return true end end false end def state STATES[attributes[:state]] end def ready? state == "Active" end def reboot requires :id service.modify_instance(id, 'state' => 'restart').body['success'] end def destroy requires :id service.delete_instance(id).body['success'] end def rename(name) requires :id if service.modify_instance(id, 'name' => name).body["success"] attributes[:name] = name else return false end true end def allocate_ip(wait_for_ready=true) requires :location_id new_ip = service.addresses.new(:location => location_id) new_ip.save new_ip.wait_for(Fog::IBM.timeout) { ready? } if wait_for_ready secondary_ip << new_ip new_ip end def addresses addys = secondary_ip.map {|ip| Fog::Compute[:ibm].addresses.new(ip) } # Set an ID, in case someone tries to save addys << service.addresses.new(attributes[:primary_ip].merge( :id => "0", :location => location_id, :state => 3 )) addys end def attach(volume_id) requires :id data = service.modify_instance(id, {'type' => 'attach', 'storageID' => volume_id}) data.body end def detach(volume_id) requires :id data = service.modify_instance(id, {'type' => 'detach', 'storageID' => volume_id}) data.body end def launched_at Time.at(attributes[:launched_at].to_f / 1000) end def expires_at Time.at(attributes[:expires_at].to_f / 1000) end # Sets expiration time - Pass an instance of Time. def expire_at(time) expiry_time = (time.tv_sec * 1000).to_i data = service.modify_instance(id, 'expirationTime' => expiry_time) if data.body['expirationTime'] == expiry_time attributes[:expires_at] = expiry_time true else false end end # Expires the instance immediately def expire! expire_at(Time.now + 5) end def image requires :image_id service.images.get(image_id) end def location requires :location_id service.locations.get(location_id) end def public_hostname primary_ip ? primary_ip['hostname'] : nil end def public_ip_address primary_ip ? primary_ip['ip'] : nil end # Creates an image from the current instance # if name isn't passed then we'll take the current name and timestamp it def to_image(opts={}) options = { :name => name + " as of " + Time.now.strftime("%Y-%m-%d %H:%M"), :description => "" }.merge(opts) service.create_image(id, options[:name], options[:description]).body end alias :create_image :to_image end end end end fog-1.19.0/lib/fog/ibm/models/compute/image.rb0000644000004100000410000000334112261242552021045 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/ibm/models/compute/instance-types' module Fog module Compute class IBM class Image < Fog::Model STATES = { 0 => 'New', 1 => 'Available', 2 => 'Unavailable', 3 => 'Deleted', 4 => 'Capturing', 5 => 'Importing', 6 => 'Copying', 7 => 'Failed', } identity :id attribute :architecture attribute :created_at, :aliases => 'createdTime' attribute :description attribute :documentation attribute :location attribute :manifest attribute :name attribute :owner attribute :platform attribute :product_codes, :aliases => 'productCodes' attribute :state attribute :supported_instance_types, :aliases => 'supportedInstanceTypes' attribute :visibility attribute :volume_id def initialize(new_attributes = {}) super(new_attributes) attributes[:supported_instance_types] = Fog::Compute::IBM::InstanceTypes.new.load(attributes[:supported_instance_types]) if attributes[:supported_instance_types] end def save requires :id, :volume_id data = service.create_image(id, volume_id) merge_attributes(data.body) data.body['success'] end def state STATES[attributes[:state]] end def ready? state == 'Available' end def clone(name, description) service.clone_image(id, name, description).body['ImageID'] end def destroy requires :id service.delete_image(id).body['success'] end end end end end fog-1.19.0/lib/fog/ibm/models/compute/vlans.rb0000644000004100000410000000103012261242552021077 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/ibm/models/compute/vlan' module Fog module Compute class IBM class Vlans < Fog::Collection model Fog::Compute::IBM::Vlan def all load(service.list_vlans.body['vlan']) end def get(vlan_id) begin vlan = service.list_vlans.body new(vlan['vlan'].find{|vlan| vlan['id'] == vlan_id.to_s }) rescue Fog::Compute::IBM::NotFound nil end end end end end end fog-1.19.0/lib/fog/ibm/compute.rb0000644000004100000410000002200512261242552016476 0ustar www-datawww-datarequire 'fog/ibm' require 'fog/compute' module Fog module Compute class IBM < Fog::Service requires :ibm_username, :ibm_password recognizes :location model_path 'fog/ibm/models/compute' model :image collection :images model :server collection :servers model :address collection :addresses model :key collection :keys model :location collection :locations model :vlan collection :vlans request_path 'fog/ibm/requests/compute' request :list_images request :create_image request :clone_image request :delete_image request :get_image request :get_image_agreement request :get_image_manifest # request :get_image_swbundles # request :get_image_swbundle request :list_instances request :create_instance request :delete_instance request :modify_instance request :get_instance request :get_instance_logs # request :get_instance_swbundle request :get_request request :list_addresses request :list_address_offerings request :list_vlans request :create_address request :delete_address request :list_keys request :create_key request :delete_key request :modify_key request :get_key request :list_locations request :get_location class Real def initialize(options={}) @connection = Fog::IBM::Connection.new(options[:ibm_username], options[:ibm_password]) end private def request(options) begin @connection.request(options) rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Compute::IBM::NotFound.slurp(error) else error end end end end class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = { :instances => {}, :images => populate_images, :keys => {}, :locations => populate_locations, :private_keys => {}, :addresses => {} } end end def self.reset @data = nil end def data self.class.data[@ibm_username] end def reset_data self.class.data.delete(@ibm_username) @data = self.class.data[@ibm_username] end def initialize(options={}) @ibm_username = options[:ibm_username] @ibm_password = options[:ibm_password] @data = self.class.data[@ibm_username] end def self.populate_images images = {} images["20010001"] = { "name"=>"SUSE Linux Enterprise Server 11 SP1 for x86", "manifest"=>"https://www-147.ibm.com/cloud/enterprise/ram.ws/RAMSecure/artifact/{6CD09CE4-E99B-D72F-6C29-233C9B2A1676}/1.0/parameters.xml", "state"=>1, "visibility"=>"PUBLIC", "owner"=>"SYSTEM", "platform"=>"SUSE Linux Enterprise Server/11 SP1", "location"=>"41", "createdTime"=>1282466781000, "supportedInstanceTypes"=> [{"detail"=>"Copper - 32 bit (vCPU: 1, RAM: 2 GiB, Disk: 60 GiB)", "label"=>"Copper 32 bit", "price"=>{"rate"=>0.095, "unitOfMeasure"=>"UHR ", "countryCode"=>"897", "effectiveDate"=>-1, "currencyCode"=>"USD", "pricePerQuantity"=>1}, "id"=>"COP32.1/2048/60"}, {"detail"=>"Bronze - 32 bit (vCPU: 1, RAM: 2 GiB, Disk: 235 GiB)", "label"=>"Bronze 32 bit", "price"=>{"rate"=>0.115, "unitOfMeasure"=>"UHR ", "countryCode"=>"897", "effectiveDate"=>-1, "currencyCode"=>"USD", "pricePerQuantity"=>1}, "id"=>"BRZ32.1/2048/60*175"}, {"detail"=>"Silver - 32 bit (vCPU: 2, RAM: 4 GiB, Disk: 410 GiB)", "label"=>"Silver 32 bit", "price"=>{"rate"=>0.2, "unitOfMeasure"=>"UHR ", "countryCode"=>"897", "effectiveDate"=>-1, "currencyCode"=>"USD", "pricePerQuantity"=>1}, "id"=>"SLV32.2/4096/60*350"}, {"detail"=>"Gold - 32 bit (vCPU: 4, RAM: 4 GiB, Disk: 410 GiB)", "label"=>"Gold 32 bit", "price"=>{"rate"=>0.33, "unitOfMeasure"=>"UHR ", "countryCode"=>"897", "effectiveDate"=>-1, "currencyCode"=>"USD", "pricePerQuantity"=>1}, "id"=>"GLD32.4/4096/60*350"}], "productCodes"=>["rtpSr7dKs9ARDmuPy6WPgV"], "documentation"=>"https://www-147.ibm.com/cloud/enterprise/ram.ws/RAMSecure/artifact/{6CD09CE4-E99B-D72F-6C29-233C9B2A1676}/1.0/GettingStarted.html", "id"=>"20010001", "description"=>"Suse Linux 32 bit" } images end def self.populate_locations locations = {} locations["41"] = { "state"=>1, "location"=>"RTP", "capabilities"=>[ {"entries"=>{"EXT3"=>["ext3"], "RAW"=>["raw"]}, "id"=>"oss.storage.format"}, {"entries"=>{}, "id"=>"oss.instance.spec.i386"}, {"entries"=>{}, "id"=>"oss.instance.spec.x86_64"}, {"entries"=>{}, "id"=>"oss.storage.availabilityarea"}], "name"=>"Raleigh, U.S.A", "id"=>"41", "description"=>"This data center is located in Raleigh, North Carolina, U.S.A. The services provided are: Guest Instances, Image Capture, Persistent Storage, Reserved IP, Private VLAN/VPN." } locations["61"] = { "state"=>1, "location"=>"EHN", "capabilities"=>[ {"entries"=>{"EXT3"=>["ext3"], "RAW"=>["raw"]}, "id"=>"oss.storage.format"}, {"entries"=>{}, "id"=>"oss.instance.spec.i386"}, {"entries"=>{}, "id"=>"oss.instance.spec.x86_64"}, {"entries"=>{}, "id"=>"oss.storage.availabilityarea"}], "name"=>"Ehningen, Germany", "id"=>"61", "description"=>"This data center is located in Ehningen(near Baden-Wurttemberg), Germany. The services provided are: Guest Instances, Image Capture, Persistent Storage, Reserved IP, Private VLAN/VPN." } locations["82"] = { "state"=>1, "location"=>"us-co-dc1", "capabilities"=>[ {"entries"=>{"EXT3"=>["ext3"], "RAW"=>["raw"]}, "id"=>"oss.storage.format"}, {"entries"=>{}, "id"=>"oss.instance.spec.i386"}, {"entries"=>{}, "id"=>"oss.instance.spec.x86_64"}, {"entries"=>{}, "id"=>"oss.storage.availabilityarea"}], "name"=>"Boulder1, U.S.A", "id"=>"82", "description"=>"This data center is located in Boulder(near Denver), Colorado, U.S.A. The services provided are: Guest Instances, Image Capture, Persistent Storage, Reserved IP, Private VLAN/VPN." } locations["101"] = { "state"=>1, "location"=>"ca-on-dc1", "capabilities"=>[ {"entries"=>{"EXT3"=>["ext3"], "RAW"=>["raw"]}, "id"=>"oss.storage.format"}, {"entries"=>{}, "id"=>"oss.instance.spec.i386"}, {"entries"=>{}, "id"=>"oss.instance.spec.x86_64"}, {"entries"=>{}, "id"=>"oss.storage.availabilityarea"}], "name"=>"Markham, Canada", "id"=>"101", "description"=>"This data center is located in Markham(near Toronto), Ontario, Canada. The services provided are: Guest Instances, Image Capture, Persistent Storage, Reserved IP, Private VLAN/VPN." } locations["121"] = { "state"=>1, "location"=>"ap-jp-dc1", "capabilities"=>[ {"entries"=>{"EXT3"=>["ext3"], "RAW"=>["raw"]}, "id"=>"oss.storage.format"}, {"entries"=>{}, "id"=>"oss.instance.spec.i386"}, {"entries"=>{}, "id"=>"oss.instance.spec.x86_64"}, {"entries"=>{}, "id"=>"oss.storage.availabilityarea"}], "name"=>"Makuhari, Japan", "id"=>"121", "description"=>"This data center is located in Makuhari(near Tokoyo), Japan. The services provided are: Guest Instances, Image Capture, Persistent Storage, Reserved IP, Private VLAN/VPN." } locations["141"] = { "state"=>1, "location"=>"ap-sg-dc1", "capabilities"=>[ {"entries"=>{"EXT3"=>["ext3"], "RAW"=>["raw"]}, "id"=>"oss.storage.format"}, {"entries"=>{}, "id"=>"oss.instance.spec.i386"}, {"entries"=>{}, "id"=>"oss.instance.spec.x86_64"}, {"entries"=>{}, "id"=>"oss.storage.availabilityarea"}], "name"=>"Singapore, Singapore", "id"=>"141", "description"=>"This data center is located in Singapore. The services provided are: Guest Instances, Image Capture, Persistent Storage, Reserved IP, Private VLAN/VPN." } locations end end end end end fog-1.19.0/lib/fog/ibm/storage.rb0000644000004100000410000000326012261242552016470 0ustar www-datawww-datarequire 'fog/ibm' require 'fog/storage' module Fog module Storage class IBM < Fog::Service requires :ibm_username, :ibm_password recognizes :location model_path 'fog/ibm/models/storage' model :offering collection :offerings model :volume collection :volumes request_path 'fog/ibm/requests/storage' request :list_offerings request :list_volumes request :create_volume request :delete_volume request :get_volume class Real def initialize(options={}) @connection = Fog::IBM::Connection.new(options[:ibm_username], options[:ibm_password]) end private def request(options) begin @connection.request(options) rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Storage::IBM::NotFound.slurp(error) else error end end end end class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = { :volumes => {}, } end end def self.reset @data = nil end def data self.class.data[@ibm_username] end def reset_data self.class.data.delete(@ibm_username) @data = self.class.data[@ibm_username] end def initialize(options={}) @ibm_username = options[:ibm_username] @ibm_password = options[:ibm_password] @data = self.class.data[@ibm_username] end end end end end fog-1.19.0/lib/fog/orchestration.rb0000644000004100000410000000115612261242552017143 0ustar www-datawww-datamodule Fog module Orchestration def self.[](provider) self.new(:provider => provider) end def self.new(attributes) attributes = attributes.dup # Prevent delete from having side effects provider = attributes.delete(:provider).to_s.downcase.to_sym if self.providers.include?(provider) require "fog/#{provider}/network" return Fog::Orchestration.const_get(Fog.providers[provider]).new(attributes) end raise ArgumentError.new("#{provider} has no orchestration service") end def self.providers Fog.services[:orchestration] end end end fog-1.19.0/lib/fog/support.rb0000644000004100000410000000103312261242552015765 0ustar www-datawww-datamodule Fog module Support def self.[](provider) self.new(:provider => provider) end def self.new(attributes) attributes = attributes.dup provider = attributes.delete(:provider).to_s.downcase.to_sym if provider == :stormondemand require 'fog/storm_on_demand/support' Fog::Support::StormOnDemand.new(attributes) else raise ArgumentError.new("#{provider} has no support service") end end def self.providers Fog.services[:support] end end end fog-1.19.0/lib/fog/rackspace.rb0000644000004100000410000001322712261242552016215 0ustar www-datawww-datarequire 'fog/core' require 'fog/rackspace/mock_data' require 'fog/rackspace/service' require 'fog/rackspace/errors' module Fog module Rackspace extend Fog::Provider US_AUTH_ENDPOINT = 'https://identity.api.rackspacecloud.com/v2.0' unless defined? US_AUTH_ENDPOINT UK_AUTH_ENDPOINT = 'https://lon.identity.api.rackspacecloud.com/v2.0' unless defined? UK_AUTH_ENDPOINT module Errors 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 service(:auto_scale, 'rackspace/auto_scale', 'AutoScale') service(:block_storage, 'rackspace/block_storage', 'BlockStorage') service(:cdn, 'rackspace/cdn', 'CDN') service(:compute, 'rackspace/compute', 'Compute') service(:compute_v2, 'rackspace/compute_v2', 'Compute v2') service(:dns, 'rackspace/dns', 'DNS') service(:storage, 'rackspace/storage', 'Storage') service(:load_balancers, 'rackspace/load_balancers', 'LoadBalancers') service(:identity, 'rackspace/identity', 'Identity') service(:databases, 'rackspace/databases', 'Databases') service(:monitoring, 'rackspace/monitoring', 'Monitoring') service(:queues, 'rackspace/queues', 'Queues') def self.authenticate(options, connection_options = {}) rackspace_auth_url = options[:rackspace_auth_url] rackspace_auth_url ||= options[:rackspace_endpoint] == Fog::Compute::RackspaceV2::LON_ENDPOINT ? "lon.auth.api.rackspacecloud.com" : "auth.api.rackspacecloud.com" url = rackspace_auth_url.match(/^https?:/) ? \ rackspace_auth_url : 'https://' + rackspace_auth_url uri = URI.parse(url) connection = Fog::Connection.new(url, false, connection_options) @rackspace_api_key = options[:rackspace_api_key] @rackspace_username = options[:rackspace_username] response = connection.request({ :expects => [200, 204], :headers => { 'X-Auth-Key' => @rackspace_api_key, 'X-Auth-User' => @rackspace_username }, :method => 'GET', :path => (uri.path and not uri.path.empty?) ? uri.path : 'v1.0' }) response.headers.reject do |key, value| !['X-Server-Management-Url', 'X-Storage-Url', 'X-CDN-Management-Url', 'X-Auth-Token'].include?(key) end end def self.json_response?(response) return false unless response && response.headers response.headers['Content-Type'] =~ %r{application/json}i ? true : false end def self.normalize_url(endpoint) return nil unless endpoint str = endpoint.chomp " " str = str.chomp "/" str.downcase end # CGI.escape, but without special treatment on spaces def self.escape(str,extra_exclude_chars = '') # '-' is a special character inside a regex class so it must be first or last. # Add extra excludes before the final '-' so it always remains trailing, otherwise # an unwanted range is created by mistake. str.gsub(/([^a-zA-Z0-9_.#{extra_exclude_chars}-]+)/) do '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase end end end end fog-1.19.0/lib/fog/ibm.rb0000644000004100000410000001236612261242552015033 0ustar www-datawww-datarequire 'fog/core' module Fog module IBM extend Fog::Provider service(:compute, 'ibm/compute', 'Compute') service(:storage, 'ibm/storage', 'Storage') # Provisioning is very slow. We'll pass this arg explicitly until there's a way # to set the default timeout on a per-provider basis. def self.timeout 1800 end class Connection < Fog::Connection def initialize(user, password) @user = user @password = password @endpoint = URI.parse('https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331') @base_path = @endpoint.path super("#{@endpoint.scheme}://#{@endpoint.host}:#{@endpoint.port}") end def request(options) options[:path] = @base_path + options[:path] options[:headers] ||= {} options[:headers]['Authorization'] = auth_header options[:headers]['Accept'] = 'application/json' options[:headers]['Accept-Encoding'] = 'gzip' unless options[:body].nil? options[:headers]['Content-Type'] = 'application/x-www-form-urlencoded' options[:body] = form_encode(options[:body]) end response = super(options) unless response.body.empty? response.body = Fog::JSON.decode(response.body) end response end def auth_header @auth_header ||= 'Basic ' + Base64.encode64("#{@user}:#{@password}").gsub("\n",'') end def form_encode(params) params.reject {|k, v| v.nil? }.map {|pair| pair.map {|x| URI.escape(x.to_s) }.join('=') }.join('&') end end class Mock class << self def id Fog::Mock.random_numbers(7).to_i.to_s end alias :instance_id :id alias :request_id :id def primary_ip { "type" => 0, "ip" => Fog::IBM::Mock.ip_address, "hostname" => Fog::IBM::Mock.hostname } end def ip_address ip = [] 4.times do ip << Fog::Mock.random_numbers(rand(3) + 1).to_i.to_s # remove leading 0 end ip.join('.') end def hostname "vhost" + Fog::Mock.random_numbers(3).to_i.to_s + ".fake.compute.ihost.com" end # Miliseconds since epoch def launch_time (Time.now.tv_sec * 1000).to_i end # 1 year from now, in miliseconds since epoch def expiry_time ((Time.now.tv_sec + 31556926) * 1000).to_i end def owner "user" + Fog::Mock.random_numbers(3).to_i.to_s + "@company.com" end def key_material OpenSSL::PKey::RSA.generate(1024) end def private_image(name, description) { "name" => name, "createdTime" => Fog::IBM::Mock.launch_time, "productCodes"=> [], "id" => Fog::IBM::Mock.instance_id, "description" => description, "visibility" => "PRIVATE", "state" => 0 } end def create_instance(name, image_id, instance_type, location, options) { "name" => name, "location" => location, "keyName" => options[:key_name], "primaryIP" => Fog::IBM::Mock.primary_ip, "productCodes" => [], "requestId" => Fog::IBM::Mock.request_id, "imageId" => image_id, "launchTime" => Fog::IBM::Mock.launch_time, "id" => Fog::IBM::Mock.instance_id, "volumes" => [], "isMiniEphemeral" => "false", "instanceType" => instance_type, "diskSize" => "60", "requestName" => "", "secondaryIP" => [], "status" => 1, "software" => [ { "name"=>"SUSE Linux Enterprise Server", "type"=>"OS", "version"=>"11 SP1" } ], "expirationTime"=> Fog::IBM::Mock.expiry_time, "owner" => Fog::IBM::Mock.owner } end def create_volume(name, format, location_id, size, offering_id) { "instanceId" => "0", "state" => 1, "size" => size, "offeringId" => offering_id, "ioPrice" => { "rate" => 0.11, "unitOfMeasure" => "CNT", "countryCode" => "897", "effectiveDate" => Fog::IBM::Mock.launch_time, "currencyCode" => "USD", "pricePerQuantity" => 1 }, "owner" => Fog::IBM::Mock.owner, "createdTime" => Fog::IBM::Mock.launch_time, "location" => location_id, "productCodes"=> [], "format" => format, "name" => name, "id" => Fog::IBM::Mock.id, } end def create_address(location_id, offering_id, vlan_id) # TODO: Figure out vlan handling { "id" => Fog::IBM::Mock.id, "location" => location_id, "offeringId"=> offering_id, "ip" => "", "state" => 0 } end end end end end fog-1.19.0/lib/fog/ninefold/0000755000004100000410000000000012261242552015525 5ustar www-datawww-datafog-1.19.0/lib/fog/ninefold/requests/0000755000004100000410000000000012261242552017400 5ustar www-datawww-datafog-1.19.0/lib/fog/ninefold/requests/compute/0000755000004100000410000000000012261242552021054 5ustar www-datawww-datafog-1.19.0/lib/fog/ninefold/requests/compute/remove_from_load_balancer_rule.rb0000644000004100000410000000047512261242552027604 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def remove_from_load_balancer_rule(options={}) request 'removeFromLoadBalancerRule', options, :expects => [200], :response_prefix => 'removefromloadbalancerruleresponse', :response_type => Hash end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/query_async_job_result.rb0000644000004100000410000000047612261242552026202 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def query_async_job_result(options = {}) request('queryAsyncJobResult', options, :expects => [200], :response_prefix => 'queryasyncjobresultresponse', :response_type => Array) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_async_jobs.rb0000644000004100000410000000046512261242552024573 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_async_jobs(options = {}) request('listAsyncJobs', options, :expects => [200], :response_prefix => 'listasyncjobsresponse/asyncjobs', :response_type => Array) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_virtual_machines.rb0000644000004100000410000000051412261242552025771 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_virtual_machines(options = {}) request('listVirtualMachines', options, :expects => [200], :response_prefix => 'listvirtualmachinesresponse/virtualmachine', :response_type => Array) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_service_offerings.rb0000644000004100000410000000052012261242552026133 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_service_offerings(options = {}) request('listServiceOfferings', options, :expects => [200], :response_prefix => 'listserviceofferingsresponse/serviceoffering', :response_type => Array) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_resource_limits.rb0000644000004100000410000000051012261242552025640 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_resource_limits(options = {}) request('listResourceLimits', options, :expects => [200], :response_prefix => 'listresourcelimitsresponse/resourcelimit', :response_type => Array) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_hypervisors.rb0000644000004100000410000000047312261242552025035 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_hypervisors(options = {}) request('listHypervisors', options, :expects => [200], :response_prefix => 'listhypervisorsresponse/hypervisor', :response_type => Array) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_disk_offerings.rb0000644000004100000410000000050412261242552025427 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_disk_offerings(options = {}) request('listDiskOfferings', options, :expects => [200], :response_prefix => 'listdiskofferingsresponse/diskoffering', :response_type => Array) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_templates.rb0000644000004100000410000000046312261242552024435 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_templates(options = {}) request('listTemplates', options, :expects => [200], :response_prefix => 'listtemplatesresponse/template', :response_type => Array) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_network_offerings.rb0000644000004100000410000000052012261242552026164 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_network_offerings(options = {}) request('listNetworkOfferings', options, :expects => [200], :response_prefix => 'listnetworkofferingsresponse/networkoffering', :response_type => Array) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/disable_static_nat.rb0000644000004100000410000000046312261242552025220 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def disable_static_nat(options = {}) request('disableStaticNat', options, :expects => [200], :response_prefix => 'disablestaticnatresponse', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/reboot_virtual_machine.rb0000644000004100000410000000047712261242552026135 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def reboot_virtual_machine(options = {}) request('rebootVirtualMachine', options, :expects => [200], :response_prefix => 'rebootvirtualmachineresponse', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/assign_to_load_balancer_rule.rb0000644000004100000410000000047012261242552027245 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def assign_to_load_balancer_rule(options={}) request 'assignToLoadBalancerRule', options, :expects => [200], :response_prefix => 'assigntoloadbalancerruleresponse', :response_type => Hash end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/create_load_balancer_rule.rb0000644000004100000410000000045712261242552026527 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def create_load_balancer_rule(options={}) request 'createLoadBalancerRule', options, :expects => [200], :response_prefix => 'createloadbalancerruleresponse', :response_type => Hash end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/start_virtual_machine.rb0000644000004100000410000000047412261242552025775 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def start_virtual_machine(options = {}) request('startVirtualMachine', options, :expects => [200], :response_prefix => 'startvirtualmachineresponse', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/stop_virtual_machine.rb0000644000004100000410000000047112261242552025622 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def stop_virtual_machine(options = {}) request('stopVirtualMachine', options, :expects => [200], :response_prefix => 'stopvirtualmachineresponse', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_load_balancer_rule_instances.rb0000644000004100000410000000051112261242552030275 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_load_balancer_rule_instances(options={}) request 'listLoadBalancerRuleInstances', options, :expects => [200], :response_prefix => 'listloadbalancerruleinstancesresponse', :response_type => Hash end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/delete_load_balancer_rule.rb0000644000004100000410000000045712261242552026526 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def delete_load_balancer_rule(options={}) request 'deleteLoadBalancerRule', options, :expects => [200], :response_prefix => 'deleteloadbalancerruleresponse', :response_type => Hash end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_public_ip_addresses.rb0000644000004100000410000000052312261242552026437 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_public_ip_addresses(options = {}) request('listPublicIpAddresses', options, :expects => [200], :response_prefix => 'listpublicipaddressesresponse/publicipaddress', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_zones.rb0000644000004100000410000000044312261242552023573 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_zones(options = {}) request('listZones', options, :expects => [200], :response_prefix => 'listzonesresponse/zone', :response_type => Array) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_events.rb0000644000004100000410000000044712261242552023745 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_events(options = {}) request('listEvents', options, :expects => [200], :response_prefix => 'listeventsresponse/event', :response_type => Array) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/reset_password_for_virtual_machine.rb0000644000004100000410000000053712261242552030552 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def reset_password_for_virtual_machine(options = {}) request('resetPasswordForVirtualMachine', options, :expects => [200], :response_prefix => 'resetpasswordforvirtualmachineresponse', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/update_virtual_machine.rb0000644000004100000410000000047712261242552026125 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def update_virtual_machine(options = {}) request('updateVirtualMachine', options, :expects => [200], :response_prefix => 'updatevirtualmachineresponse', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/associate_ip_address.rb0000644000004100000410000000047112261242552025553 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def associate_ip_address(options = {}) request('associateIpAddress', options, :expects => [200], :response_prefix => 'associateipaddressresponse', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/create_ip_forwarding_rule.rb0000644000004100000410000000050612261242552026606 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def create_ip_forwarding_rule(options = {}) request('createIpForwardingRule', options, :expects => [200], :response_prefix => 'createipforwardingruleresponse', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/destroy_virtual_machine.rb0000644000004100000410000000050212261242552026321 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def destroy_virtual_machine(options = {}) request('destroyVirtualMachine', options, :expects => [200], :response_prefix => 'destroyvirtualmachineresponse', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_load_balancer_rules.rb0000644000004100000410000000045712261242552026422 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_load_balancer_rules(options={}) request 'listLoadBalancerRules', options, :expects => [200], :response_prefix => 'listloadbalancerrulesresponse', :response_type => Hash end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/deploy_virtual_machine.rb0000644000004100000410000000047712261242552026137 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def deploy_virtual_machine(options = {}) request('deployVirtualMachine', options, :expects => [200], :response_prefix => 'deployvirtualmachineresponse', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_accounts.rb0000644000004100000410000000045712261242552024261 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_accounts(options = {}) request('listAccounts', options, :expects => [200], :response_prefix => 'listaccountsresponse/account', :response_type => Array) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/enable_static_nat.rb0000644000004100000410000000046012261242552025040 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def enable_static_nat(options = {}) request('enableStaticNat', options, :expects => [200], :response_prefix => 'enablestaticnatresponse', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/delete_ip_forwarding_rule.rb0000644000004100000410000000050612261242552026605 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def delete_ip_forwarding_rule(options = {}) request('deleteIpForwardingRule', options, :expects => [200], :response_prefix => 'deleteipforwardingruleresponse', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/disassociate_ip_address.rb0000644000004100000410000000050212261242552026246 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def disassociate_ip_address(options = {}) request('disassociateIpAddress', options, :expects => [200], :response_prefix => 'disassociateipaddressresponse', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/change_service_for_virtual_machine.rb0000644000004100000410000000055612261242552030454 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def change_service_for_virtual_machine(options = {}) request('changeServiceForVirtualMachine', options, :expects => [200], :response_prefix => 'changeserviceforvirtualmachineresponse/virtualmachine', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_networks.rb0000644000004100000410000000045712261242552024316 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_networks(options = {}) request('listNetworks', options, :expects => [200], :response_prefix => 'listnetworksresponse/network', :response_type => Array) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/update_load_balancer_rule.rb0000644000004100000410000000046312261242552026543 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def update_load_balancer_rule(options={}) request 'updateLoadBalancerRule', options, :expects => [200], :response_prefix => 'updateloadbalancerruleresponse', :response_type => Hash end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_capabilities.rb0000644000004100000410000000047612261242552025074 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_capabilities(options = {}) request('listCapabilities', options, :expects => [200], :response_prefix => 'listcapabilitiesresponse/capability', :response_type => Array) end end end end end fog-1.19.0/lib/fog/ninefold/requests/compute/list_ip_forwarding_rules.rb0000644000004100000410000000052412261242552026501 0ustar www-datawww-datamodule Fog module Compute class Ninefold class Real def list_ip_forwarding_rules(options = {}) request('listIpForwardingRules', options, :expects => [200], :response_prefix => 'listipforwardingrulesresponse/ipforwardingrule', :response_type => Hash) end end end end end fog-1.19.0/lib/fog/ninefold/models/0000755000004100000410000000000012261242552017010 5ustar www-datawww-datafog-1.19.0/lib/fog/ninefold/models/compute/0000755000004100000410000000000012261242552020464 5ustar www-datawww-datafog-1.19.0/lib/fog/ninefold/models/compute/address.rb0000644000004100000410000000510412261242552022436 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Ninefold class Address < Fog::Model identity :id attribute :account attribute :allocated attribute :associatednetworkid attribute :domain attribute :domainid attribute :forvirtualnetwork attribute :ipaddress attribute :issourcenat attribute :isstaticnat attribute :jobid attribute :jobstatus attribute :networkid attribute :state attribute :virtualmachinedisplayname attribute :virtualmachineid attribute :virtualmachinename attribute :vlanid attribute :vlanname attribute :zoneid attribute :zonename def initialize(attributes={}) super end def destroy requires :identity self.jobid = extract_job_id(service.disassociate_ip_address(:id => identity)) true end def enable_static_nat(server) server.kind_of?(Integer) ? serverid = server : serverid = server.identity res = service.enable_static_nat(:virtualmachineid => serverid, :ipaddressid => identity) reload to_boolean(res['success']) end def disable_static_nat() self.jobid = extract_job_id(service.disable_static_nat(:ipaddressid => identity)) true end def reload self.virtualmachinedisplayname = nil self.virtualmachineid = nil self.virtualmachinename = nil super end def ready? if jobid && service.query_async_job_result(:jobid => jobid)['jobstatus'] == 0 false else # No running job, we are ready. Refresh data. reload true end end def save raise "Operation not supported" if self.identity requires :zoneid options = { :zoneid => zoneid, :networkid => networkid, :account => account, :domainid => domainid }.delete_if {|k,v| v.nil? || v == "" } data = service.associate_ip_address(options) merge_attributes(data) true end private def extract_job_id(job) if job.kind_of? Integer job else job['jobid'] || job['id'] end end # needed to hack around API inconsistencies def to_boolean(val) val && (val.to_s.match(/(true|t|yes|y|1)$/i) != nil) end end end end end fog-1.19.0/lib/fog/ninefold/models/compute/addresses.rb0000644000004100000410000000113712261242552022770 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/ninefold/models/compute/address' module Fog module Compute class Ninefold class Addresses < Fog::Collection model Fog::Compute::Ninefold::Address def all data = service.list_public_ip_addresses load(data) end def get(identifier) return nil if identifier.nil? || identifier == "" data = service.list_public_ip_addresses(:id => identifier) if data.empty? nil else new(data[0]) end end end end end end fog-1.19.0/lib/fog/ninefold/models/compute/images.rb0000644000004100000410000000116412261242552022260 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/ninefold/models/compute/image' module Fog module Compute class Ninefold class Images < Fog::Collection model Fog::Compute::Ninefold::Image def all(offering = 'executable') data = service.list_templates(:templatefilter => offering) load(data) end def get(identifier, offering = 'executable') data = service.list_templates(:templatefilter => offering, :id => identifier) if data.empty? nil else new(data[0]) end end end end end end fog-1.19.0/lib/fog/ninefold/models/compute/servers.rb0000644000004100000410000000112512261242552022501 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/ninefold/models/compute/server' module Fog module Compute class Ninefold class Servers < Fog::Collection model Fog::Compute::Ninefold::Server def all data = service.list_virtual_machines load(data) end def get(identifier) return nil if identifier.nil? || identifier == "" data = service.list_virtual_machines(:id => identifier) if data.empty? nil else new(data[0]) end end end end end end fog-1.19.0/lib/fog/ninefold/models/compute/ip_forwarding_rules.rb0000644000004100000410000000117312261242552025057 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/ninefold/models/compute/ip_forwarding_rule' module Fog module Compute class Ninefold class IpForwardingRules < Fog::Collection model Fog::Compute::Ninefold::IpForwardingRule def all data = service.list_ip_forwarding_rules load(data) end def get(identifier) return nil if identifier.nil? || identifier == "" data = service.list_ip_forwarding_rules(:id => identifier) if data.empty? nil else new(data[0]) end end end end end end fog-1.19.0/lib/fog/ninefold/models/compute/flavors.rb0000644000004100000410000000103312261242552022462 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/ninefold/models/compute/flavor' module Fog module Compute class Ninefold class Flavors < Fog::Collection model Fog::Compute::Ninefold::Flavor def all data = service.list_service_offerings load(data) end def get(identifier) data = service.list_service_offerings(:id => identifier) if data.empty? nil else new(data[0]) end end end end end end fog-1.19.0/lib/fog/ninefold/models/compute/ip_forwarding_rule.rb0000644000004100000410000000334512261242552024677 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Ninefold class IpForwardingRule < Fog::Model identity :id attribute :protocol attribute :virtualmachineid attribute :virtualmachinename attribute :ipaddressid attribute :ipaddress attribute :startport attribute :endport attribute :state attribute :jobid def initialize(attributes={}) super end def destroy requires :identity self.jobid = extract_job_id(service.delete_ip_forwarding_rule(:id => identity)) true end def ready? if jobid && service.query_async_job_result(:jobid => jobid)['jobstatus'] == 0 false else # No running job, we are ready. Refresh data. reload true end end def address Ninefold.address.get(ipaddressid) end def address=(addr) self.ipaddressid = addr.identity end def save raise "Operation not supported" if self.identity requires :ipaddressid requires :protocol requires :startport options = { :ipaddressid => ipaddressid, :protocol => protocol, :startport => startport, :endport => endport }.delete_if {|k,v| v.nil? || v == "" } data = service.create_ip_forwarding_rule(options) merge_attributes(data) true end private def extract_job_id(job) if job.kind_of? Integer job else job['jobid'] || job['id'] end end end end end end fog-1.19.0/lib/fog/ninefold/models/compute/flavor.rb0000644000004100000410000000077112261242552022307 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Ninefold class Flavor < Fog::Model identity :id attribute :cpunumber attribute :cpuspeed attribute :created, :type => :time attribute :displaytext attribute :domain attribute :domainid attribute :hosttags attribute :memory attribute :name attribute :offerha attribute :storagetype attribute :tags end end end end fog-1.19.0/lib/fog/ninefold/models/compute/server.rb0000644000004100000410000001235312261242552022323 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class Ninefold class Server < Fog::Compute::Server extend Fog::Deprecation deprecate :serviceofferingid, :flavor_id deprecate :templateid, :image_id identity :id attribute :account attribute :cpunumber attribute :cpuspeed attribute :cpuused attribute :created, :type => :time attribute :displayname attribute :domain attribute :domainid attribute :flavor_id, :aliases => :serviceofferingid attribute :forvirtualnetwork attribute :group attribute :groupid attribute :guestosid attribute :haenable attribute :hostid attribute :hostname attribute :hypervisor attribute :image_id, :aliases => :templateid #attribute :ipaddress attribute :isodisplaytext attribute :isoid attribute :isoname attribute :jobid attribute :jobstatus attribute :memory attribute :name attribute :networkkbsread attribute :networkkbswrite attribute :nic attribute :password attribute :passwordenabled attribute :rootdeviceid attribute :rootdevicetype attribute :securitygroup attribute :serviceofferingname attribute :state attribute :templatedisplaytext attribute :templatename attribute :zoneid attribute :zonename # used for creation only. attribute :networkids attribute :diskofferingid attribute :keypair attribute :securitygroupids attribute :size attribute :userdata #attribute :account_id, :aliases => "account", :squash => "id" #attribute :image_id, :aliases => "image", :squash => "id" #attribute :flavor_id, :aliases => "server_type", :squash => "id" #attribute :zone_id, :aliases => "zone", :squash => "id" def initialize(attributes={}) merge_attributes({ :flavor_id => 105, # '1CPU, 384MB, 80GB HDD' :image_id => 421 # 'XEN Basic Ubuntu 10.04 Server x64 PV r2.0' }) super end # This is temporary - we need to model nics. def ipaddress nic[0] ? nic[0]['ipaddress'] : nil end def reboot requires :identity self.jobid = extract_job_id(service.reboot_virtual_machine(:id => identity)) puts "jobid: " + jobid.to_s true end def start requires :identity self.jobid = extract_job_id(service.start_virtual_machine(:id => identity)) true end def stop requires :identity self.jobid = extract_job_id(service.stop_virtual_machine(:id => identity)) true end def destroy requires :identity self.jobid = extract_job_id(service.destroy_virtual_machine(:id => identity)) 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 ready? if jobid # we do this by polling the last job id status. res = service.query_async_job_result(:jobid => jobid) if res['jobstatus'] == 0 false else # update with new values. merge_attributes(res['jobresult']['virtualmachine']) true end else # No running job, we are ready. Refresh data. reload true end end def save raise "Operation not supported" if self.identity requires :flavor_id, :image_id, :zoneid unless networkids # No network specified, use first in this zone. networks = service.list_networks(:zoneid => zoneid) if networks.empty? raise "No networks. Please create one, or specify a network ID" else # use the network with the lowest ID - the safe default self.networkids = networks.sort {|x,y| x['id'] <=> y['id']}[0]['id'] end end options = { :serviceofferingid => flavor_id, :templateid => image_id, :name => name, :zoneid => zoneid, :networkids => networkids, :account => account, :diskofferingid => diskofferingid, :displayname => displayname, :domainid => domainid, :group => group, :hypervisor => hypervisor, :keypair => keypair, :securitygroupids => securitygroupids, :size => size, :userdata => userdata }.delete_if {|k,v| v.nil? || v == "" } data = service.deploy_virtual_machine(options) merge_attributes(data) true end private def extract_job_id(job) if job.kind_of? Integer job else job['jobid'] || job['id'] end end end end end end fog-1.19.0/lib/fog/ninefold/models/compute/image.rb0000644000004100000410000000161412261242552022075 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Ninefold class Image < Fog::Model identity :id attribute :account attribute :accountid attribute :bootable attribute :created, :type => :time attribute :crossZones attribute :displaytext attribute :domain attribute :domainid attribute :format attribute :hypervisor attribute :isextractable attribute :isfeatured attribute :ispublic attribute :isready attribute :jobid attribute :jobstatus attribute :name attribute :ostypeid attribute :ostypename attribute :passwordenabled attribute :removed attribute :size attribute :status attribute :templatetype attribute :zoneid attribute :zonename end end end end fog-1.19.0/lib/fog/ninefold/compute.rb0000644000004100000410000001217612261242552017535 0ustar www-datawww-datarequire 'fog/ninefold' require 'fog/compute' module Fog module Compute class Ninefold < Fog::Service API_URL = "http://api.ninefold.com/compute/v1.0/" requires :ninefold_compute_key, :ninefold_compute_secret recognizes :ninefold_api_url # allow us to specify non-prod environments model_path 'fog/ninefold/models/compute' model :server collection :servers model :flavor collection :flavors model :image collection :images model :address collection :addresses model :ip_forwarding_rule collection :ip_forwarding_rules request_path 'fog/ninefold/requests/compute' # General list-only stuff request :list_accounts request :list_events request :list_service_offerings request :list_disk_offerings request :list_capabilities request :list_hypervisors request :list_zones request :list_network_offerings request :list_resource_limits # Templates request :list_templates # Virtual Machines request :deploy_virtual_machine request :destroy_virtual_machine request :list_virtual_machines request :reboot_virtual_machine request :stop_virtual_machine request :start_virtual_machine request :change_service_for_virtual_machine request :reset_password_for_virtual_machine request :update_virtual_machine # Jobs request :list_async_jobs request :query_async_job_result # Networks request :list_networks # Addresses request :associate_ip_address request :list_public_ip_addresses request :disassociate_ip_address # NAT request :enable_static_nat request :disable_static_nat request :create_ip_forwarding_rule request :delete_ip_forwarding_rule request :list_ip_forwarding_rules # Load Balancers request :create_load_balancer_rule request :delete_load_balancer_rule request :remove_from_load_balancer_rule request :assign_to_load_balancer_rule request :list_load_balancer_rules request :list_load_balancer_rule_instances request :update_load_balancer_rule class Mock def initialize(options) @api_url = options[:ninefold_api_url] || Fog.credentials[:ninefold_api_url] || API_URL @ninefold_compute_key = options[:ninefold_compute_key] || Fog.credentials[:ninefold_compute_key] @ninefold_compute_secret = options[:ninefold_compute_secret] || Fog.credentials[:ninefold_compute_secret] end def request(options) raise "Not implemented" end end class Real def initialize(options) @api_url = options[:ninefold_api_url] || Fog.credentials[:ninefold_api_url] || API_URL @ninefold_compute_key = options[:ninefold_compute_key] || Fog.credentials[:ninefold_compute_key] @ninefold_compute_secret = options[:ninefold_compute_secret] || Fog.credentials[:ninefold_compute_secret] @connection_options = options[:connection_options] || {} @persistent = options[:persistent] || false @connection = Fog::Connection.new(@api_url, @persistent, @connection_options) end def request(command, params, options) params['response'] = "json" # convert params to strings for sort req_params = params.merge('apiKey' => @ninefold_compute_key, 'command' => command) req = URI.escape(req_params.sort_by{|k,v| k.to_s }.collect{|e| "#{e[0].to_s}=#{e[1].to_s}"}.join('&')) encoded_signature = url_escape(encode_signature(req)) options = { :expects => 200, :method => 'GET', :query => "#{req}&signature=#{encoded_signature}" }.merge(options) begin response = @connection.request(options) end unless response.body.empty? # Because the response is some weird xml-json thing, we need to try and mung # the values out with a prefix, and if there is an empty data entry return an # empty version of the expected type (if provided) response = Fog::JSON.decode(response.body) if options.has_key? :response_prefix keys = options[:response_prefix].split('/') keys.each do |k| if response[k] response = response[k] elsif options[:response_type] response = options[:response_type].new break else end end response else response end end end private def url_escape(string) string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do '%' + $1.unpack('H2' * $1.size).join('%').upcase end.tr(' ', '+') end def encode_signature(data) Base64.encode64(OpenSSL::HMAC.digest('sha1', @ninefold_compute_secret, URI.encode(data.downcase).gsub('+', '%20'))).chomp end end end end end fog-1.19.0/lib/fog/ninefold/storage.rb0000644000004100000410000000274112261242552017522 0ustar www-datawww-datarequire 'fog/ninefold' require 'fog/storage' require 'fog/atmos' module Fog module Storage class Ninefold < Fog::Storage::Atmos STORAGE_HOST = "onlinestorage.ninefold.com" #"api.ninefold.com" STORAGE_PATH = "" #"/storage/v1.0" STORAGE_PORT = "80" # "443" STORAGE_SCHEME = "http" # "https" requires :ninefold_storage_token, :ninefold_storage_secret recognizes :persistent model_path 'fog/atmos/models/storage' model :directory collection :directories model :file collection :files module Utils end class Mock < Fog::Storage::Atmos::Mock include Utils def initialize(options={}) @ninefold_storage_token = options[:ninefold_storage_token] @ninefold_storage_secret = options[:ninefold_storage_secret] end def request(options) raise "Ninefold Storage mocks not implemented" end end class Real < Fog::Storage::Atmos::Real include Utils def initialize(options={}) endpoint = "#{STORAGE_SCHEME}://"\ "#{STORAGE_HOST}:"\ "#{STORAGE_PORT}"\ "#{STORAGE_PATH}" options[:atmos_storage_endpoint] = endpoint options[:atmos_storage_token] = options[:ninefold_storage_token] options[:atmos_storage_secret] = options[:ninefold_storage_secret] super(options) end end end end end fog-1.19.0/lib/fog/identity.rb0000644000004100000410000000135512261242552016111 0ustar www-datawww-datamodule Fog module Identity def self.[](provider) self.new(:provider => provider) end def self.new(attributes) attributes = attributes.dup # Prevent delete from having side effects case provider = attributes.delete(:provider).to_s.downcase.to_sym when :rackspace require 'fog/rackspace/identity' Fog::Rackspace::Identity.new(attributes) else if self.providers.include?(provider) require "fog/#{provider}/identity" return Fog::Identity.const_get(Fog.providers[provider]).new(attributes) end raise ArgumentError.new("#{provider} has no identity service") end end def self.providers Fog.services[:identity] end end end fog-1.19.0/lib/fog/dynect/0000755000004100000410000000000012261242551015214 5ustar www-datawww-datafog-1.19.0/lib/fog/dynect/requests/0000755000004100000410000000000012261242551017067 5ustar www-datawww-datafog-1.19.0/lib/fog/dynect/requests/dns/0000755000004100000410000000000012261242551017653 5ustar www-datawww-datafog-1.19.0/lib/fog/dynect/requests/dns/post_session.rb0000644000004100000410000000207312261242551022732 0ustar www-datawww-datamodule Fog module DNS class Dynect class Real def post_session request( :expects => 200, :idempotent => true, :method => :post, :path => "Session", :body => Fog::JSON.encode({ :customer_name => @dynect_customer, :user_name => @dynect_username, :password => @dynect_password }) ) end end class Mock def post_session response = Excon::Response.new response.status = 200 response.body = { "status" => "success", "data" => { "token" => auth_token, "version" => Fog::Dynect::Mock.version }, "job_id" => Fog::Dynect::Mock.job_id, "msgs"=>[{ "INFO"=>"login: Login successful", "SOURCE"=>"BLL", "ERR_CD"=>nil, "LVL"=>"INFO" }] } response end end end end end fog-1.19.0/lib/fog/dynect/requests/dns/get_zone.rb0000644000004100000410000000301412261242551022010 0ustar www-datawww-datamodule Fog module DNS class Dynect class Real # Get one or more zones # # ==== Parameters # * options<~Hash>: # * zone<~String> - name of zone to lookup, or omit to return list of zones def get_zone(options = {}) request( :expects => 200, :idempotent => true, :method => :get, :path => ['Zone', options['zone']].compact.join('/') ) end end class Mock def get_zone(options = {}) if options['zone'] raise Fog::DNS::Dynect::NotFound unless zone = self.data[:zones][options['zone']] data = { "zone_type" => zone[:zone_type], "serial_style" => zone[:serial_style], "serial" => zone[:serial], "zone" => zone[:zone] } info = "get: Your zone, #{zone[:zone]}" else data = self.data[:zones].collect { |zone, data| "/REST/Zone/#{zone}/" } info = "get: Your #{data.size} zones" end response = Excon::Response.new response.status = 200 response.body = { "status" => "success", "data" => data, "job_id" => Fog::Dynect::Mock.job_id, "msgs" => [{ "INFO" => info, "SOURCE" => "BLL", "ERR_CD" => nil, "LVL" => "INFO" }] } response end end end end end fog-1.19.0/lib/fog/dynect/requests/dns/put_record.rb0000644000004100000410000000452212261242551022351 0ustar www-datawww-datamodule Fog module DNS class Dynect class Real # Update or replace a record # # ==== Parameters # * type<~String> - type of record in ['AAAA', 'ANY', 'A', 'CNAME', 'DHCID', 'DNAME', 'DNSKEY', 'DS', 'KEY', 'LOC', 'MX', 'NSA', 'NS', 'PTR', 'PX', 'RP', 'SOA', 'SPF', 'SRV', 'SSHFP', 'TXT'] # * zone<~String> - zone of record # * rdata<~Hash> - rdata for record # * options<~Hash>: (options vary by type, listing below includes common parameters) # * ttl<~Integer> - ttl for the record, defaults to zone ttl def put_record(type, zone, fqdn, rdata, options = {}) options.merge!('rdata' => rdata) type.to_s.upcase! options = {"#{type}Records" => [options]} unless options['record_id'] path = ["#{type}Record", zone, fqdn].join('/') path += "/#{options.delete('record_id')}" if options['record_id'] request( :body => Fog::JSON.encode(options), :expects => 200, :method => :put, :path => path ) end end class Mock def put_record(type, zone, fqdn, rdata, options = {}) raise Fog::DNS::Dynect::NotFound unless zone = self.data[:zones][zone] records = zone[:records] record_id = zone[:next_record_id] zone[:next_record_id] += 1 record = { :type => type, :zone => zone, :fqdn => fqdn, :rdata => rdata, :ttl => options[:ttl] || zone[:ttl], :record_id => record_id } records[type] << record response = Excon::Response.new response.status = 200 response.body = { "status" => "success", "data" => { "zone" => record[:zone][:zone], "ttl" => record[:ttl], "fqdn" => record[:fqdn], "record_type" => record[:type], "rdata" => record[:rdata], "record_id" => record[:record_id] }, "job_id" => Fog::Dynect::Mock.job_id, "msgs" => [{ "INFO"=>"add: Record added", "SOURCE"=>"BLL", "ERR_CD"=>nil, "LVL"=>"INFO" }] } response end end end end end fog-1.19.0/lib/fog/dynect/requests/dns/post_zone.rb0000644000004100000410000000405712261242551022226 0ustar www-datawww-datamodule Fog module DNS class Dynect class Real # Create a zone # # ==== Parameters # * rname<~String> - administrative contact # * ttl<~Integer> - time to live (in seconds) for records in this zone # * zone<~String> - name of zone to host # * options<~Hash>: # * serial_style<~String> - style of serial number, in ['day', 'epoch', 'increment', 'minute']. Defaults to increment def post_zone(rname, ttl, zone, options = {}) body = Fog::JSON.encode({ :rname => rname, :token => auth_token, :ttl => ttl }.merge!(options)) request( :body => body, :expects => 200, :method => :post, :path => 'Zone/' << zone ) end end class Mock def post_zone(rname, ttl, zone, options = {}) new_zone = self.data[:zones][zone] = { :next_record_id => 0, :records => Hash.new do |records_hash, type| records_hash[type] = [] end, :records_to_delete => [], :rname => rname, :serial_style => options[:serial_style] || "increment", :serial => 0, :ttl => ttl, :zone => zone, :zone_type => "Primary" } response = Excon::Response.new response.status = 200 response.body = { "status" => "success", "data" => { "zone_type" => new_zone[:zone_type], "serial_style" => new_zone[:serial_style], "serial" => new_zone[:serial], "zone" => zone }, "job_id" => Fog::Dynect::Mock.job_id, "msgs" => [{ "INFO" => "create: New zone #{zone} created. Publish it to put it on our server.", "SOURCE" => "BLL", "ERR_CD" => nil, "LVL" => "INFO" }] } response end end end end end fog-1.19.0/lib/fog/dynect/requests/dns/delete_zone.rb0000644000004100000410000000155312261242551022501 0ustar www-datawww-datamodule Fog module DNS class Dynect class Real # Delete a zone # # ==== Parameters # * zone<~String> - zone to host def delete_zone(zone) request( :expects => 200, :method => :delete, :path => "Zone/#{zone}" ) end end class Mock def delete_zone(zone) self.data[:zones].delete(zone) response = Excon::Response.new response.status = 200 response.body = { "status" => "success", "data" => {}, "job_id" => Fog::Dynect::Mock.job_id, "msgs" => [{ "ERR_CD" => '', "INFO" => '', "LVL" => '', "SOURCE" => '' }] } response end end end end end fog-1.19.0/lib/fog/dynect/requests/dns/post_record.rb0000644000004100000410000000421012261242551022520 0ustar www-datawww-datamodule Fog module DNS class Dynect class Real # Create a record # # ==== Parameters # * type<~String> - type of record in ['AAAA', 'ANY', 'A', 'CNAME', 'DHCID', 'DNAME', 'DNSKEY', 'DS', 'KEY', 'LOC', 'MX', 'NSA', 'NS', 'PTR', 'PX', 'RP', 'SOA', 'SPF', 'SRV', 'SSHFP', 'TXT'] # * zone<~String> - zone of record # * rdata<~Hash> - rdata for record # * options<~Hash>: (options vary by type, listing below includes common parameters) # * ttl<~Integer> - ttl for the record, defaults to zone ttl def post_record(type, zone, fqdn, rdata, options = {}) options.merge!('rdata' => rdata) request( :body => Fog::JSON.encode(options), :expects => 200, :method => :post, :path => ["#{type.to_s.upcase}Record", zone, fqdn].join('/') ) end end class Mock def post_record(type, zone, fqdn, rdata, options = {}) raise Fog::DNS::Dynect::NotFound unless zone = self.data[:zones][zone] records = zone[:records] record_id = zone[:next_record_id] zone[:next_record_id] += 1 record = { :type => type, :zone => zone, :fqdn => fqdn, :rdata => rdata, :ttl => options[:ttl] || zone[:ttl], :record_id => record_id } records[type] << record response = Excon::Response.new response.status = 200 response.body = { "status" => "success", "data" => { "zone" => record[:zone][:zone], "ttl" => record[:ttl], "fqdn" => record[:fqdn], "record_type" => record[:type], "rdata" => record[:rdata], "record_id" => record[:record_id] }, "job_id" => Fog::Dynect::Mock.job_id, "msgs" => [{ "INFO"=>"add: Record added", "SOURCE"=>"BLL", "ERR_CD"=>nil, "LVL"=>"INFO" }] } response end end end end end fog-1.19.0/lib/fog/dynect/requests/dns/delete_record.rb0000644000004100000410000000323612261242551023004 0ustar www-datawww-datamodule Fog module DNS class Dynect class Real # Delete a record # # ==== Parameters # * type<~String> - type of record in ['AAAA', 'ANY', 'A', 'CNAME', 'DHCID', 'DNAME', 'DNSKEY', 'DS', 'KEY', 'LOC', 'MX', 'NSA', 'NS', 'PTR', 'PX', 'RP', 'SOA', 'SPF', 'SRV', 'SSHFP', 'TXT'] # * zone<~String> - zone of record # * fqdn<~String> - fqdn of record # * record_id<~String> - id of record def delete_record(type, zone, fqdn, record_id) request( :expects => 200, :idempotent => true, :method => :delete, :path => ["#{type.to_s.upcase}Record", zone, fqdn, record_id].join('/') ) end end class Mock def delete_record(type, zone, fqdn, record_id) raise Fog::DNS::Dynect::NotFound unless zone = self.data[:zones][zone] raise Fog::DNS::Dynect::NotFound unless zone[:records][type].find { |record| record[:fqdn] == fqdn && record[:record_id] == record_id.to_i } zone[:records_to_delete] << { :type => type, :fqdn => fqdn, :record_id => record_id.to_i } response = Excon::Response.new response.status = 200 response.body = { "status" => "success", "data" => {}, "job_id" => Fog::Dynect::Mock.job_id, "msgs" => [{ "INFO" => "delete: Record will be deleted on zone publish", "SOURCE" => "BLL", "ERR_CD" => nil, "LVL" => "INFO" }] } response end end end end end fog-1.19.0/lib/fog/dynect/requests/dns/put_zone.rb0000644000004100000410000000425412261242551022050 0ustar www-datawww-datamodule Fog module DNS class Dynect class Real # Update a zone # # ==== Parameters # * zone<~String> - name or id of zone # * options<~Hash>: # * freeze<~Boolean> - causes zone to become frozen # * publish<~Boolean> - causes all pending changes to be pushed to nameservers # * thaw<~Boolean> - causes zone to cease being frozen def put_zone(zone, options = {}) request( :body => Fog::JSON.encode(options), :expects => 200, :method => :put, :path => 'Zone/' << zone ) end end class Mock def put_zone(zone, options = {}) raise Fog::DNS::Dynect::NotFound unless zone = self.data[:zones][zone] raise ArgumentError unless options.size == 1 response = Excon::Response.new response.status = 200 data = {} if options['freeze'] zone['frozen'] = true info = "freeze: Your zone is now frozen" elsif options['publish'] zone[:changes] = {} zone[:records_to_delete].each do |record| zone[:records][record[:type]].delete_if { |r| r[:fqdn] == record[:fqdn] && r[:record_id] == record[:record_id] } end zone[:records_to_delete] = [] data = { "zone_type" => zone[:zone_type], "serial_style" => zone[:serial_style], "serial" => zone[:serial] += 1, "zone" => zone[:zone] } info = "publish: #{zone[:zone]} published" elsif options['thaw'] zone[:frozen] = false info = "thaw: Your zone is now thawed, you may edit normally" else raise ArgumentError end response.body = { "status" => "success", "data" => data, "job_id" => Fog::Dynect::Mock.job_id, "msgs" => [{ "INFO" => info, "SOURCE"=>"BLL", "ERR_CD"=>nil, "LVL"=>"INFO" }] } response end end end end end fog-1.19.0/lib/fog/dynect/requests/dns/get_record.rb0000644000004100000410000000570112261242551022320 0ustar www-datawww-datamodule Fog module DNS class Dynect class Real # List records of a given type # # ==== Parameters # * type<~String> - type of record in ['AAAA', 'ANY', 'A', 'CNAME', 'DHCID', 'DNAME', 'DNSKEY', 'DS', 'KEY', 'LOC', 'MX', 'NSA', 'NS', 'PTR', 'PX', 'RP', 'SOA', 'SPF', 'SRV', 'SSHFP', 'TXT'] # * zone<~String> - name of zone to lookup # * fqdn<~String> - name of fqdn to lookup # * options<~Hash>: # * record_id<~String> - id of record def get_record(type, zone, fqdn, options = {}) request( :expects => 200, :idempotent => true, :method => :get, :path => ["#{type.to_s.upcase}Record", zone, fqdn, options['record_id']].compact.join('/') ) end end class Mock def get_record(type, zone, fqdn, options = {}) raise ArgumentError unless [ 'AAAA', 'ANY', 'A', 'CNAME', 'DHCID', 'DNAME', 'DNSKEY', 'DS', 'KEY', 'LOC', 'MX', 'NSA', 'NS', 'PTR', 'PX', 'RP', 'SOA', 'SPF', 'SRV', 'SSHFP', 'TXT' ].include? type raise Fog::DNS::Dynect::NotFound unless zone = self.data[:zones][zone] response = Excon::Response.new response.status = 200 if record_id = options['record_id'] raise Fog::DNS::Dynect::NotFound unless record = zone[:records][type].find { |record| record[:record_id] == record_id.to_i } response.body = { "status" => "success", "data" => { "zone" => record[:zone][:zone], "ttl" => record[:ttl], "fqdn" => record[:fqdn], "record_type" => type, "rdata" => record[:rdata], "record_id" => record[:record_id] }, "job_id" => Fog::Dynect::Mock.job_id, "msgs" => [{ "INFO" => "get: Found the record", "SOURCE" => "API-B", "ERR_CD" => nil, "LVL" => "INFO" }] } else records = if type == "ANY" zone[:records].values.flatten.select { |record| record[:fqdn] == fqdn } else zone[:records][type].select { |record| record[:fqdn] == fqdn } end response.body = { "status" => "success", "data" => records.collect { |record| "/REST/#{record[:type]}Record/#{record[:zone][:zone]}/#{record[:fqdn]}/#{record[:record_id]}" }, "job_id" => Fog::Dynect::Mock.job_id, "msgs" => [{ "INFO" => "detail: Found #{records.size} record", "SOURCE" => "BLL", "ERR_CD" => nil, "LVL" => "INFO" }] } end response end end end end end fog-1.19.0/lib/fog/dynect/requests/dns/get_all_records.rb0000644000004100000410000000311212261242551023325 0ustar www-datawww-datamodule Fog module DNS class Dynect class Real # Get one or more node lists # # ==== Parameters # * zone<~String> - zone to lookup node lists for # * options<~Hash> # * fqdn<~String> - fully qualified domain name of node to lookup def get_all_records(zone, options = {}) requested_fqdn = options['fqdn'] || options[:fqdn] request( :expects => 200, :idempotent => true, :method => :get, :path => ['AllRecord', zone, requested_fqdn].compact.join('/') ) end end class Mock def get_all_records(zone, options = {}) raise Fog::DNS::Dynect::NotFound unless zone = self.data[:zones][zone] response = Excon::Response.new response.status = 200 data = [zone[:zone]] if fqdn = options[:fqdn] data = data | zone[:records].collect { |type, records| records.select { |record| record[:fqdn] == fqdn } }.flatten.compact else data = data | zone[:records].collect { |type, records| records.collect { |record| record[:fqdn] } }.flatten end response.body = { "status" => "success", "data" => data, "job_id" => Fog::Dynect::Mock.job_id, "msgs" => [{ "INFO" => "get_tree: Here is your zone tree", "SOURCE" => "BLL", "ERR_CD" => nil, "LVL" => "INFO" }] } response end end end end end fog-1.19.0/lib/fog/dynect/requests/dns/get_node_list.rb0000644000004100000410000000310612261242551023017 0ustar www-datawww-datamodule Fog module DNS class Dynect class Real # Get one or more node lists # # ==== Parameters # * zone<~String> - zone to lookup node lists for # * options<~Hash> # * fqdn<~String> - fully qualified domain name of node to lookup def get_node_list(zone, options = {}) requested_fqdn = options['fqdn'] || options[:fqdn] request( :expects => 200, :idempotent => true, :method => :get, :path => ['AllRecord', zone, requested_fqdn].compact.join('/') ) end end class Mock def get_node_list(zone, options = {}) raise Fog::DNS::Dynect::NotFound unless zone = self.data[:zones][zone] response = Excon::Response.new response.status = 200 data = [zone[:zone]] if fqdn = options[:fqdn] data = data | zone[:records].collect { |type, records| records.select { |record| record[:fqdn] == fqdn } }.flatten.compact else data = data | zone[:records].collect { |type, records| records.collect { |record| record[:fqdn] } }.flatten end response.body = { "status" => "success", "data" => data, "job_id" => Fog::Dynect::Mock.job_id, "msgs" => [{ "INFO" => "get_tree: Here is your zone tree", "SOURCE" => "BLL", "ERR_CD" => nil, "LVL" => "INFO" }] } response end end end end end fog-1.19.0/lib/fog/dynect/dns.rb0000644000004100000410000001011512261242551016323 0ustar www-datawww-datarequire 'fog/dynect' require 'fog/dns' module Fog module DNS class Dynect < Fog::Service requires :dynect_customer, :dynect_username, :dynect_password recognizes :timeout, :persistent recognizes :provider # remove post deprecation model_path 'fog/dynect/models/dns' model :record collection :records model :zone collection :zones request_path 'fog/dynect/requests/dns' request :delete_record request :delete_zone request :get_node_list request :get_all_records request :get_record request :get_zone request :post_record request :post_session request :post_zone request :put_zone request :put_record class JobIncomplete < Error; end class Mock def initialize(options={}) @dynect_customer = options[:dynect_customer] @dynect_username = options[:dynect_username] @dynect_password = options[:dynect_password] end def self.data @data ||= { :zones => {} } end def self.reset @data = nil end def auth_token @auth_token ||= Fog::Dynect::Mock.token end def data self.class.data end def reset_data self.class.reset end end class Real def initialize(options={}) @dynect_customer = options[:dynect_customer] @dynect_username = options[:dynect_username] @dynect_password = options[:dynect_password] @connection_options = options[:connection_options] || {} @host = 'api-v4.dynect.net' @port = options[:port] || 443 @path = options[:path] || '/REST' @persistent = options[:persistent] || false @scheme = options[:scheme] || 'https' @version = options[:version] || '3.5.2' @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def auth_token @auth_token ||= post_session.body['data']['token'] end def request(params) begin # any request could redirect to a job params[:expects] = Array(params[:expects]) | [307] params[:headers] ||= {} params[:headers]['Content-Type'] = 'application/json' params[:headers]['API-Version'] = @version params[:headers]['Auth-Token'] = auth_token unless params[:path] == 'Session' params[:path] = "#{@path}/#{params[:path]}" unless params[:path] =~ %r{^#{Regexp.escape(@path)}/} response = @connection.request(params) if response.body.empty? response.body = {} elsif response.headers['Content-Type'] == 'application/json' response.body = Fog::JSON.decode(response.body) end if response.body['status'] == 'failure' raise Error, response.body['msgs'].first['INFO'] end if response.status == 307 && params[:path] !~ %r{^/REST/Job/} response = poll_job(response, params[:expects]) end response rescue Excon::Errors::HTTPStatusError => error if @auth_token && error.message =~ /login: (Bad or expired credentials|inactivity logout)/ @auth_token = nil retry else raise error end end response end def poll_job(response, original_expects, time_to_wait = 10) job_location = response.headers['Location'] Fog.wait_for(time_to_wait) do response = request(:expects => original_expects, :method => :get, :path => job_location) response.body['status'] != 'incomplete' end if response.body['status'] == 'incomplete' raise JobIncomplete.new("Job #{response.body['job_id']} is still incomplete") end response end end end end end fog-1.19.0/lib/fog/dynect/models/0000755000004100000410000000000012261242551016477 5ustar www-datawww-datafog-1.19.0/lib/fog/dynect/models/dns/0000755000004100000410000000000012261242551017263 5ustar www-datawww-datafog-1.19.0/lib/fog/dynect/models/dns/zones.rb0000644000004100000410000000101612261242551020744 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/dynect/models/dns/zone' module Fog module DNS class Dynect class Zones < Fog::Collection model Fog::DNS::Dynect::Zone def all data = service.get_zone.body['data'].map do |zone| { :domain => zone } end load(data) end def get(zone_id) new(service.get_zone('zone' => zone_id).body['data']) rescue Excon::Errors::NotFound nil end end end end end fog-1.19.0/lib/fog/dynect/models/dns/record.rb0000644000004100000410000000313712261242551021072 0ustar www-datawww-datarequire 'fog/core/model' module Fog module DNS class Dynect class Record < Fog::Model extend Fog::Deprecation identity :id attribute :name, :aliases => [:fqdn, 'fqdn'] attribute :rdata attribute :serial_style attribute :ttl attribute :type, :aliases => 'record_type' def destroy requires :identity, :name, :type, :zone service.delete_record(type, zone.identity, name, identity) true end def save requires :name, :type, :rdata, :zone options = { :ttl => ttl } options.delete_if {|key, value| value.nil?} data = service.post_record(type, zone.identity, name, rdata, options).body['data'] # avoid overwriting zone object with zone string data = data.reject {|key, value| key == 'zone'} merge_attributes(data) zone.publish records = service.get_record(type, zone.identity, name).body['data'] # data in format ['/REST/xRecord/domain/fqdn/identity] records.map! do |record| tokens = record.split('/') { :identity => tokens.last, :type => tokens[2][0...-6] # everything before 'Record' } end record = records.detect {|record| record[:type] == type} merge_attributes(record) true end def zone @zone end private def zone=(new_zone) @zone = new_zone end end end end end fog-1.19.0/lib/fog/dynect/models/dns/zone.rb0000644000004100000410000000244412261242551020567 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/dynect/models/dns/records' module Fog module DNS class Dynect class Zone < Fog::Model identity :domain attribute :domain, :aliases => 'zone' attribute :email, :aliases => 'rname' attribute :serial attribute :serial_style attribute :ttl attribute :type, :aliases => 'zone_type' def initialize(attributes={}) super end def destroy requires :domain service.delete_zone(domain) true end undef_method :domain= def domain=(new_domain) attributes[:domain] = new_domain.split('/').last end def publish requires :identity data = service.put_zone(identity, 'publish' => true) true end def records @records ||= Fog::DNS::Dynect::Records.new(:zone => self, :service => service) end def nameservers raise 'nameservers Not Implemented' end def save self.ttl ||= 3600 requires :domain, :email, :ttl data = service.post_zone(email, ttl, domain).body['data'] merge_attributes(data) true end end end end end fog-1.19.0/lib/fog/dynect/models/dns/records.rb0000644000004100000410000000335512261242551021257 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/dynect/models/dns/record' module Fog module DNS class Dynect class Records < Fog::Collection attribute :zone model Fog::DNS::Dynect::Record def all(options = {}) requires :zone data = [] service.get_all_records(zone.domain, options).body['data'].each do |url| (_, _, t, _, fqdn, id) = url.split('/') type = t.gsub(/Record$/, '') # leave out the default, read only records # by putting this here we don't make the secondary request for these records next if ['NS', 'SOA'].include?(type) record = service.get_record(type, zone.domain, fqdn, 'record_id' => id).body['data'] data << { :identity => record['record_id'], :fqdn => record['fqdn'], :type => record['record_type'], :rdata => record['rdata'] } end load(data) end def get(record_id) requires :zone list = service.get_all_records(zone.domain, {}).body['data'] url = list.detect { |e| e =~ /\/#{record_id}$/ } return unless url (_, _, t, _, fqdn, id) = url.split('/') type = t.gsub(/Record$/, '') record = service.get_record(type, zone.domain, fqdn, 'record_id' => id).body['data'] new({ :identity => record['record_id'], :fqdn => record['fqdn'], :type => record['record_type'], :rdata => record['rdata'] }) end def new(attributes = {}) requires :zone super({:zone => zone}.merge!(attributes)) end end end end end fog-1.19.0/lib/fog/atmos/0000755000004100000410000000000012261242551015051 5ustar www-datawww-datafog-1.19.0/lib/fog/atmos/requests/0000755000004100000410000000000012261242551016724 5ustar www-datawww-datafog-1.19.0/lib/fog/atmos/requests/storage/0000755000004100000410000000000012261242551020370 5ustar www-datawww-datafog-1.19.0/lib/fog/atmos/requests/storage/head_namespace.rb0000644000004100000410000000074712261242551023642 0ustar www-datawww-datamodule Fog module Storage class Atmos class Real def head_namespace(namespace = '', options = {}) options = options.reject {|key, value| value.nil?} request({ :expects => 200, :method => 'HEAD', :path => "namespace/" + namespace, :query => {}, :parse => true }.merge(options)) end end end end end fog-1.19.0/lib/fog/atmos/requests/storage/delete_namespace.rb0000644000004100000410000000071412261242551024175 0ustar www-datawww-datamodule Fog module Storage class Atmos class Real def delete_namespace(namespace = '', options = {}) options = options.reject {|key, value| value.nil?} request({ :expects => 204, :method => 'DELETE', :path => "namespace/" + namespace, :query => options }.merge(options)) end end end end end fog-1.19.0/lib/fog/atmos/requests/storage/put_namespace.rb0000644000004100000410000000074512261242551023547 0ustar www-datawww-datamodule Fog module Storage class Atmos class Real def put_namespace(namespace = '', options = {}) options = options.reject {|key, value| value.nil?} request({ :expects => 200, :method => 'PUT', :path => "namespace/" + namespace, :query => {}, :parse => true }.merge(options)) end end end end end fog-1.19.0/lib/fog/atmos/requests/storage/post_namespace.rb0000644000004100000410000000074712261242551023726 0ustar www-datawww-datamodule Fog module Storage class Atmos class Real def post_namespace(namespace = '', options = {}) options = options.reject {|key, value| value.nil?} request({ :expects => 201, :method => 'POST', :path => "namespace/" + namespace, :query => {}, :parse => true }.merge(options)) end end end end end fog-1.19.0/lib/fog/atmos/requests/storage/get_namespace.rb0000644000004100000410000000074512261242551023516 0ustar www-datawww-datamodule Fog module Storage class Atmos class Real def get_namespace(namespace = '', options = {}) options = options.reject {|key, value| value.nil?} request({ :expects => 200, :method => 'GET', :path => "namespace/" + namespace, :query => {}, :parse => true }.merge(options)) end end end end end fog-1.19.0/lib/fog/atmos/models/0000755000004100000410000000000012261242551016334 5ustar www-datawww-datafog-1.19.0/lib/fog/atmos/models/storage/0000755000004100000410000000000012261242551020000 5ustar www-datawww-datafog-1.19.0/lib/fog/atmos/models/storage/directory.rb0000644000004100000410000000243012261242551022330 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Storage class Atmos class Directory < Fog::Model identity :key, :aliases => :Filename attribute :objectid, :aliases => :ObjectID def files @files ||= begin Fog::Storage::Atmos::Files.new( :directory => self, :service => service ) end end def directories @directories ||= begin Fog::Storage::Atmos::Directories.new( :directory => self, :service => service ) end end def save self.key = attributes[:directory].key + key if attributes[:directory] self.key = key + '/' unless key =~ /\/$/ res = service.post_namespace key reload end def destroy(opts={}) if opts[:recursive] files.each {|f| f.destroy } directories.each do |d| d.files.each {|f| f.destroy } d.destroy(opts) end end service.delete_namespace key end end end end end fog-1.19.0/lib/fog/atmos/models/storage/files.rb0000644000004100000410000000445312261242551021435 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/atmos/models/storage/file' module Fog module Storage class Atmos class Files < Fog::Collection attribute :directory attribute :limit attribute :marker attribute :path attribute :prefix model Fog::Storage::Atmos::File def all(options = {}) requires :directory directory ? ns = directory.key : ns = '' ns = ns + '/' unless ns =~ /\/$/ data = service.get_namespace(ns).body[:DirectoryList] data = {:DirectoryEntry => []} if data.kind_of? String data[:DirectoryEntry] = [data[:DirectoryEntry]] if data[:DirectoryEntry].kind_of? Hash files = data[:DirectoryEntry].select {|de| de[:FileType] == 'regular'} files.each do |s| data = service.head_namespace(directory.key + s[:Filename], :parse => false) headers = Hash[data.headers["x-emc-meta"].split(", ").collect{|s|s.split("=")}] s[:content_length] = data.headers["Content-Length"] s[:content_type] = data.headers["Content-Type"] s[:created_at] = headers["ctime"] s[:directory] = directory end # TODO - Load additional file meta? load(files) end def get(key, &block) requires :directory data = service.get_namespace(directory.key + key, :parse => false)#, &block) file_data = data.headers.merge({ :body => data.body, :key => key }) new(file_data) rescue Fog::Storage::Atmos::NotFound nil end def get_url(key) requires :directory if self.directory.public_url "#{self.directory.public_url}/#{key}" end end def head(key, options = {}) requires :directory data = service.head_namespace(directory.key + key, :parse => false) file_data = data.headers.merge({ :body => data.body, :key => key }) new(file_data) rescue Fog::Storage::Atmos::NotFound nil end def new(attributes = {}) requires :directory super({ :directory => directory }.merge!(attributes)) end end end end end fog-1.19.0/lib/fog/atmos/models/storage/directories.rb0000644000004100000410000000267512261242551022653 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/atmos/models/storage/directory' module Fog module Storage class Atmos class Directories < Fog::Collection attribute :directory model Fog::Storage::Atmos::Directory def all directory ? ns = directory.key : ns = '' ns = ns + '/' unless ns =~ /\/$/ data = service.get_namespace(ns).body[:DirectoryList] data = {:DirectoryEntry => []} if data.kind_of? String data[:DirectoryEntry] = [data[:DirectoryEntry]] if data[:DirectoryEntry].kind_of? Hash dirs = data[:DirectoryEntry].select {|de| de[:FileType] == 'directory'} dirs.each do |d| d[:Filename] = ns + d[:Filename] if directory d[:Filename] += '/' unless d[:Filename] =~ /\/$/ end load(dirs) end def get(key, options = {}) return nil if key == '' # Root dir shouldn't be retrieved like this. key =~ /\/$/ ? ns = key : ns = key + '/' res = service.get_namespace ns emc_meta = res.headers['x-emc-meta'] obj_id = emc_meta.scan(/objectid=(\w+),/).flatten[0] new(:objectid => obj_id, :key => ns) rescue Fog::Storage::Atmos::NotFound nil end def new(attributes ={}) attributes = {:directory => directory}.merge(attributes) if directory super(attributes) end end end end end fog-1.19.0/lib/fog/atmos/models/storage/file.rb0000644000004100000410000000660012261242551021246 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Storage class Atmos class File < Fog::Model identity :key, :aliases => :Filename attribute :content_length, :aliases => ['bytes', 'Content-Length'], :type => :integer attribute :content_type, :aliases => ['content_type', 'Content-Type'] attribute :objectid, :aliases => :ObjectID attribute :created_at, :aliases => :ctime def body attributes[:body] ||= if objectid collection.get(identity).body else '' end end def body=(new_body) attributes[:body] = new_body end def directory @directory end def copy(target_directory_key, target_file_key, options={}) target_directory = service.directories.new(:key => target_directory_key) target_directory.files.create( :key => target_file_key, :body => body ) end def destroy requires :directory, :key service.delete_namespace([directory.key, key].join('/')) true end def meta_data requires :directory, :key service.get_namespace([directory.key, key].join('/') + "?metadata/system") end def file_size data = meta_data meta_data.headers["x-emc-meta"].match(/size=\d+/).to_s.gsub(/size=/,"") end def public=(new_public) # NOOP - we don't need to flag files as public, getting the public URL for a file handles it. end # By default, expire in 5 years def public_url(expires = (Time.now + 5 * 365 * 24 * 60 * 60)) file = directory.files.head(key) self.objectid = if file && file.to_s.strip != "" then file.attributes['x-emc-meta'].scan(/objectid=(\w+),/).flatten[0] else nil end if self.objectid && self.objectid.to_s.strip != "" klass = service.ssl? ? URI::HTTPS : URI::HTTP uri = klass.build(:host => service.host, :port => service.port.to_i, :path => "/rest/objects/#{self.objectid}" ) sb = "GET\n" sb += uri.path.downcase + "\n" sb += service.uid + "\n" sb += String(expires.to_i()) signature = service.sign( sb ) uri.query = "uid=#{CGI::escape(service.uid)}&expires=#{expires.to_i()}&signature=#{CGI::escape(signature)}" uri.to_s else nil end end def save(options = {}) requires :body, :directory, :key directory.kind_of?(Directory) ? ns = directory.key : ns = directory ns += key options[:headers] ||= {} options[:headers]['Content-Type'] = content_type if content_type options[:body] = body begin data = service.post_namespace(ns, options) self.objectid = data.headers['location'].split('/')[-1] rescue => error if error.message =~ /The resource you are trying to create already exists./ data = service.put_namespace(ns, options) else raise error end end # merge_attributes(data.headers) true end private def directory=(new_directory) @directory = new_directory end end end end end fog-1.19.0/lib/fog/atmos/storage.rb0000644000004100000410000001266112261242551017050 0ustar www-datawww-datarequire 'fog/atmos' require 'fog/storage' module Fog module Storage class Atmos < Fog::Service requires :atmos_storage_endpoint, :atmos_storage_secret, :atmos_storage_token recognizes :persistent model_path 'fog/atmos/models/storage' model :directory collection :directories model :file collection :files request_path 'fog/atmos/requests/storage' # request :delete_container request :get_namespace request :head_namespace request :post_namespace request :put_namespace request :delete_namespace module Utils ENDPOINT_REGEX = /(https*):\/\/([a-zA-Z0-9\.\-]+)(:[0-9]+)?(\/.*)?/ def ssl? protocol = @endpoint.match(ENDPOINT_REGEX)[1] raise ArgumentError, 'Invalid endpoint URL' if protocol.nil? return true if protocol == 'https' return false if protocol == 'http' raise ArgumentError, "Unknown protocol #{protocol}" end def port port = @endpoint.match(ENDPOINT_REGEX)[3] return ssl? ? 443 : 80 if port.nil? port.split(':')[1].to_i end def host @endpoint.match(ENDPOINT_REGEX)[2] end def api_path @endpoint.match(ENDPOINT_REGEX)[4] end def setup_credentials(options) @storage_token = options[:atmos_storage_token] @storage_secret = options[:atmos_storage_secret] @storage_secret_decoded = Base64.decode64(@storage_secret) @endpoint = options[:atmos_storage_endpoint] @prefix = self.ssl? ? 'https' : 'http' @storage_host = self.host @storage_port = self.port @api_path = self.api_path end end class Mock include Utils def initialize(options={}) setup_credentials(options) end def request(options) raise "Atmos Storage mocks not implemented" end end class Real include Utils def initialize(options={}) setup_credentials(options) @connection_options = options[:connection_options] || {} @hmac = Fog::HMAC.new('sha1', @storage_secret_decoded) @persistent = options.fetch(:persistent, false) @connection = Fog::Connection.new("#{@prefix}://#{@storage_host}:#{@storage_port}", @persistent, @connection_options) end def uid @storage_token#.split('/')[-1] end def sign(string) value = @hmac.sign(string) Base64.encode64( value ).chomp() end def reload @connection.reset end def request(params, &block) req_path = params[:path] # Force set host and port params.merge!({ :host => @storage_host, :path => "#{@api_path}/rest/#{params[:path]}", }) # Set default method and headers params = {:method => 'GET', :headers => {}}.merge params params[:headers]["Content-Type"] ||= "application/octet-stream" # Add request date params[:headers]["date"] = Time.now().httpdate() params[:headers]["x-emc-uid"] = @storage_token # Build signature string signstring = "" signstring += params[:method] signstring += "\n" signstring += params[:headers]["Content-Type"] signstring += "\n" if( params[:headers]["range"] ) signstring += params[:headers]["range"] end signstring += "\n" signstring += params[:headers]["date"] signstring += "\n" signstring += "/rest/" + URI.unescape( req_path ).downcase query_str = params[:query].map{|k,v| "#{k}=#{v}"}.join('&') signstring += '?' + query_str unless query_str.empty? signstring += "\n" customheaders = {} params[:headers].each { |key,value| case key when 'x-emc-date', 'x-emc-signature' #skip when /^x-emc-/ customheaders[ key.downcase ] = value end } header_arr = customheaders.sort() header_arr.each { |key,value| # Values are lowercase and whitespace-normalized signstring += key + ":" + value.strip.chomp.squeeze( " " ) + "\n" } digest = @hmac.sign(signstring.chomp()) signature = Base64.encode64( digest ).chomp() params[:headers]["x-emc-signature"] = signature params.delete(:host) #invalid excon request parameter parse = params.delete(:parse) begin response = @connection.request(params, &block) rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Storage::Atmos::NotFound.slurp(error) else error end end unless response.body.empty? if parse document = Fog::ToHashDocument.new parser = Nokogiri::XML::SAX::PushParser.new(document) parser << response.body parser.finish response.body = document.body end end response end end end end end fog-1.19.0/lib/fog/ovirt/0000755000004100000410000000000012261242552015072 5ustar www-datawww-datafog-1.19.0/lib/fog/ovirt/requests/0000755000004100000410000000000012261242552016745 5ustar www-datawww-datafog-1.19.0/lib/fog/ovirt/requests/compute/0000755000004100000410000000000012261242552020421 5ustar www-datawww-datafog-1.19.0/lib/fog/ovirt/requests/compute/list_vm_volumes.rb0000644000004100000410000000071412261242552024177 0ustar www-datawww-datamodule Fog module Compute class Ovirt class Real def list_vm_volumes(vm_id) client.vm_volumes(vm_id).map {|ovirt_obj| ovirt_attrs ovirt_obj} end end class Mock def list_vm_volumes(vm_id) xml = read_xml 'volumes.xml' Nokogiri::XML(xml).xpath('/disks/disk').collect do |vol| ovirt_attrs OVIRT::Volume::new(self, vol) end end end end end end fog-1.19.0/lib/fog/ovirt/requests/compute/list_clusters.rb0000644000004100000410000000073412261242552023651 0ustar www-datawww-datamodule Fog module Compute class Ovirt class Real def list_clusters(filters = {}) client.clusters(filters).map {|ovirt_obj| ovirt_attrs ovirt_obj} end end class Mock def list_clusters(filters = {}) xml = read_xml 'clusters.xml' Nokogiri::XML(xml).xpath('/clusters/cluster').collect do |cl| ovirt_attrs OVIRT::Cluster::new(self, cl) end end end end end end fog-1.19.0/lib/fog/ovirt/requests/compute/add_interface.rb0000644000004100000410000000070112261242552023514 0ustar www-datawww-datamodule Fog module Compute class Ovirt class Real def add_interface(id, options = {}) raise ArgumentError, "instance id is a required parameter" unless id client.add_interface(id, options) end end class Mock def add_interface(id, options = {}) raise ArgumentError, "instance id is a required parameter" unless id true end end end end endfog-1.19.0/lib/fog/ovirt/requests/compute/list_virtual_machines.rb0000644000004100000410000000072312261242552025340 0ustar www-datawww-datamodule Fog module Compute class Ovirt class Real def list_virtual_machines(filters = {}) client.vms(filters).map {|ovirt_obj| ovirt_attrs ovirt_obj} end end class Mock def list_virtual_machines(filters = {}) xml = read_xml 'vms.xml' Nokogiri::XML(xml).xpath('/vms/vm').collect do |vm| ovirt_attrs OVIRT::VM::new(self, vm) end end end end end end fog-1.19.0/lib/fog/ovirt/requests/compute/vm_ticket.rb0000644000004100000410000000043512261242552022735 0ustar www-datawww-datamodule Fog module Compute class Ovirt class Real def vm_ticket(id, options = {}) client.set_ticket(id, options) end end class Mock def vm_ticket(id, options = {}) "Secret" end end end end end fog-1.19.0/lib/fog/ovirt/requests/compute/mock_files/0000755000004100000410000000000012261242552022534 5ustar www-datawww-datafog-1.19.0/lib/fog/ovirt/requests/compute/mock_files/volumes.xml0000644000004100000410000000325512261242552024755 0ustar www-datawww-data Disk 2 5368709120 data ok virtio raw true false false false Disk 1 8589934592 system ok virtio cow true true false false fog-1.19.0/lib/fog/ovirt/requests/compute/mock_files/vms.xml0000644000004100000410000001223412261242552024065 0ustar www-datawww-data test-vm1 server down 1073741824 false 1 spice 1