fog-1.42.0/0000755000004100000410000000000013171001215012370 5ustar www-datawww-datafog-1.42.0/Rakefile0000644000004100000410000001305113171001215014035 0ustar www-datawww-datarequire 'bundler/setup' require 'rake/testtask' require 'date' require 'rubygems' require 'rubygems/package_task' require 'yard' require File.dirname(__FILE__) + '/lib/fog' require "tasks/changelog_task" Fog::Rake::ChangelogTask.new require "tasks/github_release_task" Fog::Rake::GithubReleaseTask.new ############################################################################# # # 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 package_gem_file "pkg/#{gem_file}" 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', 'test:travis'] Rake::TestTask.new do |t| t.pattern = File.join("spec", "**", "*_spec.rb") t.libs << "spec" end namespace :test do mock = ENV['FOG_MOCK'] || 'true' task :travis do sh("export FOG_MOCK=#{mock} && bundle exec shindont") end task :openvz do sh("export FOG_MOCK=#{mock} && bundle exec shindont tests/openvz") end task :cloudstack do sh("export FOG_MOCK=#{mock} && bundle exec shindont tests/cloudstack") end task :vcloud_director do sh("export FOG_MOCK=#{mock} && bundle exec shindont tests/vcloud_director") end task :vcloud_director_specs do puts "Running vCloud Minitest Suite" Rake::TestTask.new do |t| Dir.glob('./spec/vcloud_director/**/*_spec.rb').each { |file| require file} end 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 PROVIDER=#{provider} && 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 Fog::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 Fog::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 #{package_gem_file}" 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}'" end task :git_push_release do sh "git push origin master" ::Rake::Task[:github_release].invoke end task :gem_push do sh "gem push #{package_gem_file}" 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 "Install fog-#{version}.gem" task "install" do Rake::Task[:build].invoke sh "gem install #{package_gem_file} --no-document" end 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 fog-1.42.0/bin/0000755000004100000410000000000013171001215013140 5ustar www-datawww-datafog-1.42.0/bin/fog0000755000004100000410000000340713171001215013645 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 Fog::Formatador.display_line('Welcome to fog interactive!') Fog::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.42.0/Gemfile0000644000004100000410000000035613171001215013667 0ustar www-datawww-datasource "https://rubygems.org" group :development, :test do # This is here because gemspec doesn't support require: false gem "netrc", :require => false gem "octokit", :require => false gem "rspec", :require => false end gemspec fog-1.42.0/tests/0000755000004100000410000000000013171001215013532 5ustar www-datawww-datafog-1.42.0/tests/cloudsigma/0000755000004100000410000000000013171001215015661 5ustar www-datawww-datafog-1.42.0/tests/cloudsigma/requests/0000755000004100000410000000000013171001215017534 5ustar www-datawww-datafog-1.42.0/tests/cloudsigma/requests/snapshots_tests.rb0000644000004100000410000000533213171001215023330 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudsigma] | snapshot requests', ['cloudsigma']) do @snapshot_format = { 'uuid' => String, 'allocated_size' => Fog::Nullable::Integer, 'drive' => Fog::Nullable::Hash, 'meta' => Fog::Nullable::Hash, 'name' => String, 'owner' => Fog::Nullable::Hash, 'resource_uri' => Fog::Nullable::String, 'status' => String, 'tags' => Array, 'timestamp' => String } @promoted_volume_format = { 'uuid' => String, 'affinities' => Array, 'allow_multimount' => Fog::Boolean, 'jobs' => Array, 'licenses' => Array, 'media' => String, 'meta' => Fog::Nullable::Hash, 'mounted_on' => Array, 'name' => String, 'owner' => Fog::Nullable::Hash, 'resource_uri' => Fog::Nullable::Hash, # this field's type is the only difference from volume format 'size' => Integer, 'status' => String, 'storage_type' => String, 'tags' => Array } @volume = Fog::Compute[:cloudsigma].volumes.create(:name => 'fogsnapshottest', :size => 1024**3, :media => :disk) @volume.wait_for { available? } unless Fog.mocking? @snapshot_create_args = {:name => 'fogtest', :drive => @volume.uuid} tests('success') do tests("#create_snapshot(#@snapshot_create_args)").formats(@snapshot_format, false) do @resp_snapshot = Fog::Compute[:cloudsigma].create_snapshot(@snapshot_create_args).body['objects'].first @snapshot_uuid = @resp_snapshot['uuid'] @resp_snapshot end @snapshot = Fog::Compute[:cloudsigma].snapshots.get(@snapshot_uuid) @snapshot.wait_for { available? } tests("#update_snapshot(#@snapshot_uuid)").formats(@snapshot_format, false) do @resp_snapshot['name'] = 'fogtest_renamed' @resp_snapshot = Fog::Compute[:cloudsigma].update_snapshot(@snapshot_uuid, @resp_snapshot).body @resp_snapshot end # promote snapshot to a drive tests("#promote_snapshot(#@snapshot_uuid)").formats(@promoted_volume_format, false) do @resp_promoted_volume = Fog::Compute[:cloudsigma].clone_snapshot(@snapshot_uuid).body @resp_promoted_volume end # cleanup @promoted_volume = Fog::Compute[:cloudsigma].volumes.get(@resp_promoted_volume['uuid']) @promoted_volume.wait_for { available? } unless Fog.mocking? @promoted_volume.destroy tests("#delete_snapshot(#@snapshot_uuid)").succeeds do resp = Fog::Compute[:cloudsigma].delete_snapshot(@snapshot_uuid) resp.body.empty? && resp.status == 204 end end tests('failure') do tests("#get_snapshot(#@snapshot_uuid)|deleted|").raises(Fog::CloudSigma::Errors::NotFound) do Fog::Compute[:cloudsigma].get_snapshot(@snapshot_uuid).body end end @volume.destroy end fog-1.42.0/tests/cloudsigma/requests/server_tests.rb0000644000004100000410000000454413171001215022620 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudsigma] | server requests', ['cloudsigma']) do @server_format = { 'uuid' => String, 'cpu' => Integer, 'cpus_instead_of_cores' => Fog::Boolean, 'drives' => Array, 'enable_numa' => Fog::Boolean, 'hv_relaxed' => Fog::Boolean, 'hv_tsc' => Fog::Boolean, 'mem' => Integer, 'meta' => Fog::Nullable::Hash, 'name' => String, 'nics' => Array, 'owner' => Fog::Nullable::Hash, 'resource_uri' => Fog::Nullable::String, 'runtime' => Fog::Nullable::Hash, 'smp' => Integer, 'status' => String, 'tags' => Array, 'vnc_password' => String } @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.42.0/tests/cloudsigma/requests/volumes_tests.rb0000644000004100000410000000316213171001215022777 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudsigma] | volume requests', ['cloudsigma']) do @volume_format = { 'uuid' => String, 'affinities' => Array, 'allow_multimount' => Fog::Boolean, 'jobs' => Array, 'licenses' => Array, 'media' => String, 'meta' => Fog::Nullable::Hash, 'mounted_on' => Array, 'name' => String, 'owner' => Fog::Nullable::Hash, 'resource_uri' => Fog::Nullable::String, 'size' => Integer, 'status' => String, 'storage_type' => String, 'tags' => Array } @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(#@volume_uuid)|deleted|").raises(Fog::CloudSigma::Errors::NotFound) do Fog::Compute[:cloudsigma].get_volume(@volume_uuid).body end end end fog-1.42.0/tests/cloudsigma/models/0000755000004100000410000000000013171001215017144 5ustar www-datawww-datafog-1.42.0/tests/cloudsigma/models/snapshots_tests.rb0000644000004100000410000000077213171001215022743 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudsigma] | snapshots collection', ['cloudsigma']) do volume = Fog::Compute[:cloudsigma].volumes.create(:name => 'fogtest', :size => 1024**3, :media => :disk) volume.wait_for { available? } unless Fog.mocking? snapshots = Fog::Compute[:cloudsigma].snapshots snapshot_create_args = {:name => 'fogtest', :drive => volume.uuid} collection_tests(snapshots, snapshot_create_args, true) do @instance.wait_for(timeout=60) { available? } end volume.destroy end fog-1.42.0/tests/cloudsigma/models/server_tests.rb0000644000004100000410000000376313171001215022232 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 end fog-1.42.0/tests/cloudsigma/models/snapshot_tests.rb0000644000004100000410000000125013171001215022550 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudsigma] | snapshot model', ['cloudsigma']) do volume = Fog::Compute[:cloudsigma].volumes.create(:name => 'fogmodeltest', :size => 1024**3, :media => :disk) volume.wait_for { available? } unless Fog.mocking? snapshots = Fog::Compute[:cloudsigma].snapshots snapshot_create_args = {:name => 'fogtest', :drive => volume.uuid} model_tests(snapshots, snapshot_create_args, true) do @instance.wait_for(timeout=60) { available? } tests('#update').succeeds do @instance.name = 'fogtest_renamed' @instance.save @instance.reload returns('fogtest_renamed') { @instance.name } end end volume.destroy end fog-1.42.0/tests/cloudsigma/models/volumes_tests.rb0000644000004100000410000000052213171001215022404 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 end fog-1.42.0/tests/cloudsigma/models/servers_tests.rb0000644000004100000410000000064013171001215022404 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudsigma] | servers collection', ['cloudsigma']) do # mark as pending, the collection_tests are not quite what in line with how CloudSigma servers operate pending 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) end fog-1.42.0/tests/cloudsigma/models/volume_tests.rb0000644000004100000410000000116013171001215022220 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudsigma] | volume model', ['cloudsigma']) do volumes = Fog::Compute[:cloudsigma].volumes volume_create_args = {:name => 'fogmodeltest', :size => 1024**3, :media => :cdrom} model_tests(volumes, volume_create_args, true) do @instance.wait_for(timeout=60) { available? } tests('#update').succeeds do @instance.media = 'disk' #@instance.size = 1024**3 # resizes disk @instance.save @instance.reload @instance.wait_for(timeout=60) { available? } #returns(1024**3) { @instance.size } returns('disk') { @instance.media } end end end fog-1.42.0/tests/storage/0000755000004100000410000000000013171001215015176 5ustar www-datawww-datafog-1.42.0/tests/storage/helper.rb0000644000004100000410000000027113171001215017002 0ustar www-datawww-datadef storage_providers { :aws => { :mocked => true }, :local => { :mocked => false }, :rackspace => { :mocked => false } } end fog-1.42.0/tests/storage/models/0000755000004100000410000000000013171001215016461 5ustar www-datawww-datafog-1.42.0/tests/storage/models/directory_test.rb0000644000004100000410000000127113171001215022052 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.42.0/tests/storage/models/file_tests.rb0000644000004100000410000000213613171001215021151 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.42.0/tests/storage/models/files_tests.rb0000644000004100000410000000114413171001215021332 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.42.0/tests/storage/models/directories_tests.rb0000644000004100000410000000062113171001215022543 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 end fog-1.42.0/tests/helper.rb0000644000004100000410000000372413171001215015344 0ustar www-datawww-dataENV['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 require 'ostruct' Excon.defaults.merge!(:debug_request => true, :debug_response => true) require File.expand_path(File.join(File.dirname(__FILE__), 'helpers', 'mock_helper')) # This overrides the default 600 seconds timeout during live test runs if Fog.mocking? FOG_TESTING_TIMEOUT = ENV['FOG_TEST_TIMEOUT'] || 2000 Fog.timeout = 2000 Fog::Logger.warning "Setting default fog timeout to #{Fog.timeout} seconds" # These sets of tests do not behave nicely when running mocked tests Thread.current[:tags] << '-xenserver' Thread.current[:tags] << '-joyent' Thread.current[:tags] << '-dreamhost' else FOG_TESTING_TIMEOUT = Fog.timeout end def lorem_file File.open(File.dirname(__FILE__) + '/lorem.txt', 'r') end def array_differences(array_a, array_b) (array_a - array_b) | (array_b - array_a) end # 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 - ["openvz"] available_providers = Fog.available_providers.map {|provider| provider.downcase} unavailable_providers = all_providers - available_providers if !ENV['PROVIDER'].nil? && unavailable_providers.include?(ENV['PROVIDER']) Fog::Formatador.display_line("[red]Requested provider #{ENV['PROVIDER']} is not available.[/]" + "[red]Check if .fog file has correct configuration (see '#{Fog.credentials_path}')[/]") exit(0) end for provider in unavailable_providers Fog::Formatador.display_line("[yellow]Skipping tests for [bold]#{provider}[/] [yellow]due to lacking credentials (add some to '#{Fog.credentials_path}' to run them)[/]") end fog-1.42.0/tests/zerigo/0000755000004100000410000000000013171001215015031 5ustar www-datawww-datafog-1.42.0/tests/zerigo/requests/0000755000004100000410000000000013171001215016704 5ustar www-datawww-datafog-1.42.0/tests/zerigo/requests/dns/0000755000004100000410000000000013171001215017470 5ustar www-datawww-datafog-1.42.0/tests/zerigo/requests/dns/dns_tests.rb0000644000004100000410000002745113171001215022034 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'].map {|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("list host records with options") do pending if Fog.mocking? result = false response = Fog::DNS[:zerigo].list_hosts(@zone_id, {:per_page=>2, :page=>1}) if response.status == 200 hosts = response.body["hosts"] if (hosts.count == 2) 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.42.0/tests/core/0000755000004100000410000000000013171001215014462 5ustar www-datawww-datafog-1.42.0/tests/core/current_machine_tests.rb0000644000004100000410000000141613171001215021401 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.42.0/tests/core/service_tests.rb0000644000004100000410000000117013171001215017670 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 end fog-1.42.0/tests/core/wait_for_tests.rb0000644000004100000410000000045613171001215020050 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.42.0/tests/core/uuid_tests.rb0000644000004100000410000000041113171001215017173 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 end fog-1.42.0/tests/core/timeout_tests.rb0000644000004100000410000000031213171001215017713 0ustar www-datawww-dataShindo.tests('Fog#timeout', 'core') do tests('timeout').returns(FOG_TESTING_TIMEOUT) do Fog.timeout end tests('timeout = 300').returns(300) do Fog.timeout = 300 Fog.timeout end end fog-1.42.0/tests/core/mocking_tests.rb0000644000004100000410000000351213171001215017661 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.42.0/tests/core/credential_tests.rb0000644000004100000410000000475013171001215020351 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.42.0/tests/core/attribute_tests.rb0000644000004100000410000000360313171001215020236 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.42.0/tests/core/parser_tests.rb0000644000004100000410000000430513171001215017527 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.42.0/tests/lorem.txt0000644000004100000410000000067613171001215015422 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.42.0/tests/vcloud/0000755000004100000410000000000013171001215015026 5ustar www-datawww-datafog-1.42.0/tests/vcloud/data/0000755000004100000410000000000013171001215015737 5ustar www-datawww-datafog-1.42.0/tests/vcloud/data/api_+_v1.0_+_network_+_10000644000004100000410000000405013171001215022025 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.42.0/tests/vcloud/data/api_+_vApp_+_vm-20000644000004100000410000003041613171001215020712 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.42.0/tests/vcloud/data/api_+_v1.0_+_vApp_+_vm-20000644000004100000410000003033313171001215021666 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.42.0/tests/vcloud/data/api_+_vdc_+_10000644000004100000410000001100613171001215020131 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.42.0/tests/vcloud/data/api_+_v1.0_+_vApp_+_vapp-10000644000004100000410000007367213171001215022226 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.42.0/tests/vcloud/data/api_+_v1.0_+_admin_+_network_+_20000644000004100000410000001264513171001215023421 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.42.0/tests/vcloud/data/api_+_v1.0_+_vApp_+_vm-10000644000004100000410000002660013171001215021667 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.42.0/tests/vcloud/data/api_+_org_+_0000644000004100000410000000110413171001215020061 0ustar www-datawww-data fog-1.42.0/tests/vcloud/data/api_+_org_+_10000644000004100000410000000354013171001215020150 0ustar www-datawww-data Some fancy Description My Full Name fog-1.42.0/tests/vcloud/data/api_+_network_+_10000644000004100000410000000410413171001215021047 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.42.0/tests/vcloud/data/api_+_v1.0_+_login0000644000004100000410000000111713171001215021013 0ustar www-datawww-data fog-1.42.0/tests/vcloud/data/api_+_v1.0_+_org_+_10000644000004100000410000000356713171001215021137 0ustar www-datawww-data Some fancy Description My Full Name fog-1.42.0/tests/vcloud/data/api_+_vApp_+_vapp-10000644000004100000410000007311613171001215021241 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.42.0/tests/vcloud/data/api_+_v1.0_+_vdc_+_10000644000004100000410000001065513171001215021120 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.42.0/tests/vcloud/data/api_+_admin_+_network_+_20000644000004100000410000001270513171001215022440 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.42.0/tests/vcloud/data/api_+_sessions0000644000004100000410000000175013171001215020576 0ustar www-datawww-data fog-1.42.0/tests/vcloud/data/api_+_v1.0_+_network_+_20000644000004100000410000000271613171001215022035 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.42.0/tests/vcloud/requests/0000755000004100000410000000000013171001215016701 5ustar www-datawww-datafog-1.42.0/tests/vcloud/requests/compute/0000755000004100000410000000000013171001215020355 5ustar www-datawww-datafog-1.42.0/tests/vcloud/requests/compute/disk_configure_tests.rb0000644000004100000410000001116313171001215025121 0ustar www-datawww-dataShindo.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.42.0/tests/vcloud/models/0000755000004100000410000000000013171001215016311 5ustar www-datawww-datafog-1.42.0/tests/vcloud/models/compute/0000755000004100000410000000000013171001215017765 5ustar www-datawww-datafog-1.42.0/tests/vcloud/models/compute/networks_tests.rb0000644000004100000410000000430713171001215023414 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.42.0/tests/vcloud/models/compute/vdcs_tests.rb0000644000004100000410000000156113171001215022476 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.42.0/tests/vcloud/models/compute/helper.rb0000644000004100000410000000110313171001215021564 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.42.0/tests/vcloud/models/compute/server_tests.rb0000644000004100000410000001164113171001215023045 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.42.0/tests/vcloud/models/compute/organizations_tests.rb0000644000004100000410000000120213171001215024416 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.42.0/tests/vcloud/models/compute/organization_tests.rb0000644000004100000410000000155413171001215024245 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.42.0/tests/vcloud/models/compute/servers_tests.rb0000644000004100000410000000150113171001215023222 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.42.0/tests/vcloud/models/compute/network_tests.rb0000644000004100000410000000610413171001215023226 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.42.0/tests/vcloud/models/compute/vdc_tests.rb0000644000004100000410000000372313171001215022315 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.42.0/tests/vcloud/models/compute/vapp_tests.rb0000644000004100000410000000253213171001215022504 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.42.0/tests/vcloud/models/compute/vapps_tests.rb0000644000004100000410000000136213171001215022667 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.42.0/tests/go_grid/0000755000004100000410000000000013171001215015144 5ustar www-datawww-datafog-1.42.0/tests/go_grid/requests/0000755000004100000410000000000013171001215017017 5ustar www-datawww-datafog-1.42.0/tests/go_grid/requests/compute/0000755000004100000410000000000013171001215020473 5ustar www-datawww-datafog-1.42.0/tests/go_grid/requests/compute/image_tests.rb0000644000004100000410000000000013171001215023312 0ustar www-datawww-datafog-1.42.0/tests/vcloud_director/0000755000004100000410000000000013171001215016721 5ustar www-datawww-datafog-1.42.0/tests/vcloud_director/requests/0000755000004100000410000000000013171001215020574 5ustar www-datawww-datafog-1.42.0/tests/vcloud_director/requests/compute/0000755000004100000410000000000013171001215022250 5ustar www-datawww-datafog-1.42.0/tests/vcloud_director/requests/compute/vdc_storage_profile_tests.rb0000644000004100000410000000215413171001215030041 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.42.0/tests/vcloud_director/requests/compute/edge_gateway_tests.rb0000644000004100000410000002064713171001215026455 0ustar www-datawww-dataShindo.tests('Compute::VcloudDirector | edge gateway requests', ['vclouddirector']) do FIREWALL_RULE_ID = '9999' @dhcp_configuration = { :GatewayDhcpService => { :IsEnabled => "true", :pools => [{ :IsEnabled => "true", :Network => "testNet", :DefaultLeaseTime => "65", :MaxLeaseTime => "650", :LowIpAddress => "192.168.9.2", :HighIpAddress => "192.168.9.20" }] } } @vpn_configuration = { :GatewayIpsecVpnService => { :IsEnabled => "true", :Tunnel => [{ :Name => "test vpn", :PeerIpAddress => "110.110.110.110", :PeerId => "1223-123UDH-12321", :LocalIpAddress => "192.168.90.90", :LocalId => "202UB-9602-UB629", :PeerSubnet => [{ :Name => "192.168.0.0/18", :Gateway => "192.168.0.0", :Netmask => "255.255.192.0", }], :SharedSecret => "dont tell anyone", :SharedSecretEncrypted => "false", :EncryptionProtocol => "AES", :Mtu => "1500", :IsEnabled => "true", :LocalSubnet => [{ :Name => "VDC Network", :Gateway => "192.168.90.254", :Netmask => "255.255.255.0" }] }] } } @routing_service_configuration = { :StaticRoutingService => { :IsEnabled => "true", :StaticRoute => [ { :Name => "Test static route #1", :Network => "192.168.192.0/24", :NextHopIp => "192.168.0.1", :GatewayInterface => {} } ] } } @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" } ] } }.merge!(@vpn_configuration).merge!(@dhcp_configuration) @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 DHCP configuration').returns(@new_edge_gateway_configuration[:GatewayDhcpService][:IsEnabled]) do edge_gateway = @service.get_edge_gateway(@edge_gateway_id).body edge_gateway[:Configuration][:EdgeGatewayServiceConfiguration][:GatewayDhcpService][:IsEnabled] end tests('#check for VPN').returns(@new_edge_gateway_configuration[:GatewayIpsecVpnService][:IsEnabled]) do edge_gateway = @service.get_edge_gateway(@edge_gateway_id).body edge_gateway[:Configuration][:EdgeGatewayServiceConfiguration][:GatewayIpsecVpnService][:IsEnabled] end 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 tests('#check Static Routing service configuration').returns(true) do edge_gateway = @service.get_edge_gateway(@edge_gateway_id).body gateway_interface = edge_gateway[:Configuration][:GatewayInterfaces][:GatewayInterface].first @routing_service_configuration[:StaticRoutingService][:StaticRoute].first[:GatewayInterface] = { :type => gateway_interface[:type], :name => gateway_interface[:name], :href => gateway_interface[:href] } response = @service.post_configure_edge_gateway_services(@edge_gateway_id, @routing_service_configuration) @service.process_task(response.body) edge_gateway = @service.get_edge_gateway(@edge_gateway_id).body edge_gateway[:Configuration][:EdgeGatewayServiceConfiguration][:StaticRoutingService][:IsEnabled] == "true" end tests('#check VPN xml from generator').returns(true) do xml = Nokogiri.XML Fog::Generators::Compute::VcloudDirector::EdgeGatewayServiceConfiguration.new(@vpn_configuration).generate_xml #Not comprehensive, only checks that the generator actually knows how to handle it and that the output looks vagely sane paths = { 'GatewayIpsecVpnService>IsEnabled' => 'true', 'Tunnel>Name' => 'test vpn', 'Tunnel>PeerIpAddress' => '110.110.110.110', 'Tunnel>LocalSubnet>Gateway' => '192.168.90.254', 'Tunnel>PeerSubnet>Netmask' => '255.255.192.0' } paths.none? { |path| (xml.css path[0]).inner_text != path[1] } end tests('#check DHCP xml from generator').returns(true) do xml = Nokogiri.XML Fog::Generators::Compute::VcloudDirector::EdgeGatewayServiceConfiguration.new(@dhcp_configuration).generate_xml paths = { 'GatewayDhcpService>IsEnabled' => "true", 'GatewayDhcpService>Pool>IsEnabled' => "true", 'GatewayDhcpService>Pool>Network' => "testNet", 'GatewayDhcpService>Pool>DefaultLeaseTime' => "65", 'GatewayDhcpService>Pool>MaxLeaseTime' => "650", 'GatewayDhcpService>Pool>LowIpAddress' => "192.168.9.2", 'GatewayDhcpService>Pool>HighIpAddress' => "192.168.9.20" } paths.none? { |path| (xml.css path[0]).inner_text != path[1] } 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.42.0/tests/vcloud_director/requests/compute/task_tests.rb0000644000004100000410000000255313171001215024766 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].find {|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.42.0/tests/vcloud_director/requests/compute/helper.rb0000644000004100000410000000150613171001215024056 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].find 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].find do |l| l[:type] == 'application/vnd.vmware.vcloud.vdc+xml' end link[:href].split('/').last end end end end fog-1.42.0/tests/vcloud_director/requests/compute/disk_tests.rb0000644000004100000410000001753513171001215024764 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].find {|e| e[:Key] == 'fog-test-key'} entry[:TypedValue][:xsi_type] end tests('boolean').returns('MetadataBooleanValue') do entry = @metadata[:MetadataEntry].find {|e| e[:Key] == 'fog-test-boolean'} entry[:TypedValue][:xsi_type] end tests('datetime').returns('MetadataDateTimeValue') do entry = @metadata[:MetadataEntry].find {|e| e[:Key] == 'fog-test-datetime'} entry[:TypedValue][:xsi_type] end tests('number').returns('MetadataNumberValue') do entry = @metadata[:MetadataEntry].find {|e| e[:Key] == 'fog-test-number'} entry[:TypedValue][:xsi_type] end tests('key-update').returns('MetadataStringValue') do entry = @metadata[:MetadataEntry].find {|e| e[:Key] == 'fog-test-key-update'} entry[:TypedValue][:xsi_type] end tests('boolean-update').returns('MetadataBooleanValue') do entry = @metadata[:MetadataEntry].find {|e| e[:Key] == 'fog-test-boolean-update'} entry[:TypedValue][:xsi_type] end tests('datetime-update').returns('MetadataDateTimeValue') do entry = @metadata[:MetadataEntry].find {|e| e[:Key] == 'fog-test-datetime-update'} entry[:TypedValue][:xsi_type] end tests('number-update').returns('MetadataNumberValue') do entry = @metadata[:MetadataEntry].find {|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.42.0/tests/vcloud_director/requests/compute/supported_systems_tests.rb0000644000004100000410000000056013171001215027634 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.42.0/tests/vcloud_director/requests/compute/catalog_tests.rb0000644000004100000410000000323113171001215025430 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].find 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.42.0/tests/vcloud_director/requests/compute/versions_tests.rb0000644000004100000410000000064113171001215025670 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].find {|i| i[:Version] == '5.1'} end end fog-1.42.0/tests/vcloud_director/requests/compute/organization_tests.rb0000644000004100000410000000266413171001215026533 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].find {|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.42.0/tests/vcloud_director/requests/compute/query_tests.rb0000644000004100000410000001021513171001215025163 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.find {|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.42.0/tests/vcloud_director/requests/compute/session_tests.rb0000644000004100000410000000070613171001215025505 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.42.0/tests/vcloud_director/requests/compute/users_tests.rb0000644000004100000410000000120313171001215025154 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.42.0/tests/vcloud_director/requests/compute/admin_tests.rb0000644000004100000410000000073413171001215025113 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.42.0/tests/vcloud_director/requests/compute/network_tests.rb0000644000004100000410000001444213171001215025515 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 (get_network)').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_network('00000000-0000-0000-0000-000000000000') end tests('Retrieve non-existent OrgNetwork (get_network_complete)').raises(Fog::Compute::VcloudDirector::Forbidden) do @service.get_network_complete('00000000-0000-0000-0000-000000000000') end tests('#get_network').data_matches_schema(GET_NETWORK_FORMAT) do link = @org[:Link].find 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].find 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_complete(@created_net_id).body net[:name] end end tests('#get_network_complete schema').data_matches_schema(VcloudDirector::Compute::Schema::NETWORK_TYPE) do link = @org[:Link].find 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_complete(@network_id).body end tests('#get_network_complete') do new_network = @service.get_network_complete(@created_net_id).body tests('network has a :name') do new_network.fetch(:name) end tests('network has a :Description') do new_network.fetch(:Description) end tests('network has a :Gateway') do new_network[:Configuration][:IpScopes][:IpScope][:Gateway] end tests('network has a several :IpRanges') do new_network[:Configuration][:IpScopes][:IpScope][:IpRanges].size >= 1 end end tests('#put_network') do new_options = { :Description => "Testing put_network", :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', } } original_network = @service.get_network_complete(@created_net_id).body name = original_network[:name] task = @service.put_network(@created_net_id, name, new_options).body @service.process_task(task) tests('fetched :Gateway matches updated :Gateway').returns( new_options[:Configuration][:IpScopes][:IpScope][:Gateway] ) do net = @service.get_network_complete(@created_net_id).body net[:Configuration][:IpScopes][:IpScope][:Gateway] end tests('fetched :IpRanges count is matches updated data').returns( new_options[:Configuration][:IpScopes][:IpScope][:IpRanges].size ) do net = @service.get_network_complete(@created_net_id).body # dammit, the API returns with IpRange as a list, not IpRanges net[:Configuration][:IpScopes][:IpScope][:IpRanges][:IpRange].size end tests('fetched :Network matches updated :Description').returns( new_options[:Description] ) do net = @service.get_network_complete(@created_net_id).body net[:Description] end end tests('#delete_network') do @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.42.0/tests/vcloud_director/requests/compute/media_tests.rb0000644000004100000410000002117313171001215025102 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].find {|e| e[:Key] == 'fog-test-key'} entry[:TypedValue][:xsi_type] end tests('boolean').returns('MetadataBooleanValue') do entry = @metadata[:MetadataEntry].find {|e| e[:Key] == 'fog-test-boolean'} entry[:TypedValue][:xsi_type] end tests('datetime').returns('MetadataDateTimeValue') do entry = @metadata[:MetadataEntry].find {|e| e[:Key] == 'fog-test-datetime'} entry[:TypedValue][:xsi_type] end tests('number').returns('MetadataNumberValue') do entry = @metadata[:MetadataEntry].find {|e| e[:Key] == 'fog-test-number'} entry[:TypedValue][:xsi_type] end tests('key-update').returns('MetadataStringValue') do entry = @metadata[:MetadataEntry].find {|e| e[:Key] == 'fog-test-key-update'} entry[:TypedValue][:xsi_type] end tests('boolean-update').returns('MetadataBooleanValue') do entry = @metadata[:MetadataEntry].find {|e| e[:Key] == 'fog-test-boolean-update'} entry[:TypedValue][:xsi_type] end tests('datetime-update').returns('MetadataDateTimeValue') do entry = @metadata[:MetadataEntry].find {|e| e[:Key] == 'fog-test-datetime-update'} entry[:TypedValue][:xsi_type] end tests('number-update').returns('MetadataNumberValue') do entry = @metadata[:MetadataEntry].find {|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.42.0/tests/vcloud_director/requests/compute/schema_helper.rb0000644000004100000410000005244613171001215025407 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] } NETWORK_CONFIGURATION_TYPE = { :IpScopes => { :IpScope => { :IsInherited => String, :Gateway => Fog::Nullable::String, :Netmask => String, :Dns1 => String, :Dns2 => String, :DnsSuffix => String, :IsEnabled=> String, :IpRanges=> IP_RANGES_TYPE, } }, :FenceMode => Fog::Nullable::String, :RetainNetInfoAcrossDeployments => String, } NETWORK_TYPE = { :name => String, :href => String, :type => String, :id => String, :Description => String, :Configuration => NETWORK_CONFIGURATION_TYPE, :IsShared => String, } 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.42.0/tests/vcloud_director/requests/compute/groups_tests.rb0000644000004100000410000000121013171001215025330 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.42.0/tests/vcloud_director/requests/compute/vdc_tests.rb0000644000004100000410000000246513171001215024602 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].find 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.42.0/tests/vcloud_director/requests/compute/ovf_descriptor_tests.rb0000644000004100000410000000252313171001215027051 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].find 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].find 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].find 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.42.0/tests/vcloud_director/requests/compute/vapp_tests.rb0000644000004100000410000001166213171001215024773 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}).body").returns(Hash) do @service.get_vapp(@vapp_id).body.class end tests("#get_vapp(#{@vapp_id}).body[:name]").returns(String) do @service.get_vapp(@vapp_id).body[:name].class end tests("#get_vapp(#{@vapp_id}).body[:href]").returns(v[:href]) do @service.get_vapp(@vapp_id).body[:href] end tests("#get_lease_settings_section_vapp(#{@vapp_id})").returns(Hash) do @service.get_lease_settings_section_vapp(@vapp_id).body.class end tests("#get_lease_settings_section_vapp(#{@vapp_id}).body[:DeploymentLeaseInSeconds] is >= 0").returns(true) do Integer(@service.get_lease_settings_section_vapp(@vapp_id).body[:DeploymentLeaseInSeconds]) >= 0 end tests("#get_vapp(#{@vapp_id}).body[:LeaseSettingsSection[:DeploymentLeaseInSeconds] is >= 0").returns(true) do Integer(@service.get_vapp(@vapp_id).body[:LeaseSettingsSection][:DeploymentLeaseInSeconds]) >= 0 end tests("#get_vapp(#{@vapp_id}).body[:NetworkConfigSection]").returns(Hash) do @service.get_vapp(@vapp_id).body[:NetworkConfigSection].class end tests("#get_network_config_section_vapp(#{@vapp_id})").returns(Hash) do @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_vapp(#{@vapp_id}).body[:'ovf:StartupSection']").returns(Hash) do @service.get_vapp(@vapp_id).body[:"ovf:StartupSection"].class end tests("#put_product_sections(#{@vapp_id})").returns(Hash) do pending if Fog.mocking? @service.put_product_sections(@vapp_id, ["a" => "1"]).body.class end tests("#get_startup_section(#{@vapp_id})").returns(Hash) do @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 @service.get_vapp_owner(@vapp_id).body end tests("#get_vapp(#{@vapp_id}).body[:Owner]").data_matches_schema(VcloudDirector::Compute::Schema::OWNER_TYPE) do @service.get_vapp(@vapp_id).body[:Owner] 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 @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.42.0/tests/vcloud_director/requests/compute/vm_tests.rb0000644000004100000410000001753513171001215024454 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_vapp(#{vm_id}).body").returns(Hash) do @service.get_vapp(vm_id).body.class end tests("#get_vapp(#{vm_id}).body[:name]").returns(String) do @service.get_vapp(vm_id).body[:name].class end tests("#get_vapp(#{vm_id}).body[:href]").returns(vm[:href]) do @service.get_vapp(vm_id).body[:href] end tests("#get_vapp(#{vm_id}).body[:GuestCustomizationSection]").returns(Hash) do @service.get_vapp(vm_id).body[:GuestCustomizationSection].class end tests("#get_vapp(#{vm_id}).body[:GuestCustomizationSection]").data_matches_schema(VcloudDirector::Compute::Schema::GUEST_CUSTOMIZATION_SECTION_TYPE) do @service.get_vapp(vm_id).body[:GuestCustomizationSection] end tests("#get_guest_customization_system_section_vapp(#{vm_id})").returns(Hash) do @service.get_guest_customization_system_section_vapp(vm_id).body.class end tests("#get_guest_customization_system_section_vapp(#{vm_id})").data_matches_schema(VcloudDirector::Compute::Schema::GUEST_CUSTOMIZATION_SECTION_TYPE) do @service.get_guest_customization_system_section_vapp(vm_id).body end tests("#get_vapp(#{vm_id}).body[:NetworkConnectionSection]").returns(Hash) do @service.get_vapp(vm_id).body[:NetworkConnectionSection].class end tests("#get_network_connection_system_section_vapp(#{vm_id})").returns(Hash) do @service.get_network_connection_system_section_vapp(vm_id).body.class end tests("#get_vapp(#{vm_id}).body[:'ovf:OperatingSystemSection']").returns(Hash) do @service.get_vapp(vm_id).body[:'ovf:OperatingSystemSection'].class end tests("#get_operating_system_section(#{vm_id})").returns(Hash) do @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_vapp(#{vm_id}).body[:RuntimeInfoSection]").data_matches_schema(VcloudDirector::Compute::Schema::RUNTIME_INFO_SECTION_TYPE) do @service.get_vapp(vm_id).body[:RuntimeInfoSection] end tests("#get_runtime_info_section_type(#{vm_id})").data_matches_schema(VcloudDirector::Compute::Schema::RUNTIME_INFO_SECTION_TYPE) do @service.get_runtime_info_section_type(vm_id).body end tests("#get_snapshot_section(#{vm_id})").returns(Hash) do @service.get_snapshot_section(vm_id).body.class end tests("#get_vapp(#{vm_id}).body[:VmCapabilities]").data_matches_schema(VcloudDirector::Compute::Schema::VM_CAPABILITIES_TYPE) do @service.get_vapp(vm_id).body[:VmCapabilities] end tests("#get_vm_capabilities(#{vm_id})").data_matches_schema(VcloudDirector::Compute::Schema::VM_CAPABILITIES_TYPE) do @service.get_vm_capabilities(vm_id).body end tests("#get_vapp(#{vm_id}).body[:'ovf:VirtualHardwareSection']").returns(Hash) do @section = @service.get_vapp(vm_id).body[:'ovf:VirtualHardwareSection'].class 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 @service.get_cpu_rasd_item(vm_id).body.class end tests("#get_disks_rasd_items_list(#{vm_id})").returns(Hash) do @service.get_disks_rasd_items_list(vm_id).body.class end tests("#get_disks_rasd_items_list(#{vm_id}).body[:Item]").returns(Array) do @service.get_disks_rasd_items_list(vm_id).body[:Item].class end tests("#get_media_drives_rasd_items_list(#{vm_id})").returns(Hash) do @service.get_media_drives_rasd_items_list(vm_id).body.class end tests("#get_media_drives_rasd_items_list(#{vm_id}).body[:Item]").returns(Array) do @service.get_media_drives_rasd_items_list(vm_id).body[:Item].class end tests("#get_memory_rasd_item(#{vm_id})").returns(Hash) do @service.get_memory_rasd_item(vm_id).body.class end tests("#get_vapp(#{vm_id}) ovf:VirtualHardwareSection has a Network adapter listed").returns(Hash) do @service.get_vapp(vm_id).body[:'ovf:VirtualHardwareSection'][:'ovf:Item'].detect do |rasd_item| rasd_item[:'rasd:ElementName'] =~ /^Network adapter/ end.class end tests("#get_network_cards_items_list(#{vm_id})").returns(Hash) do @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.42.0/tests/vcloud_director/fixtures/0000755000004100000410000000000013171001215020572 5ustar www-datawww-datafog-1.42.0/tests/vcloud_director/fixtures/vapp.xml0000644000004100000410000014365713171001215022302 0ustar www-datawww-data Lease settings section 0 0 VApp startup section The list of logical networks The configuration parameters for logical networks true 192.168.96.1 255.255.255.0 192.168.33.71 192.168.33.72 test.com true 192.168.96.2 192.168.96.128 bridged false true true 10.81.196.1 255.255.255.0 true 10.81.196.201 10.81.196.240 bridged false true Snapshot information section 2014-07-08T23:33:21.817-04:00 false Virtual hardware requirements Virtual Hardware Family 0 summoning-dark vmx-08 00:50:56:29:0c:a0 1 true nfs-net-01 E1000 ethernet adapter on "nfs-net-01" Network adapter 1 1 E1000 10 00:50:56:29:0c:9f 0 true Non-DMZNetwork E1000 ethernet adapter on "Non-DMZNetwork" Network adapter 0 2 E1000 10 0 SCSI Controller SCSI Controller 0 3 lsilogicsas 6 0 Hard disk Hard disk 1 2000 3 17 0 IDE Controller IDE Controller 0 4 5 1 false CD/DVD Drive CD/DVD Drive 1 3002 4 15 hertz * 10^6 Number of Virtual CPUs 2 virtual CPU(s) 5 0 3 2 0 byte * 2^20 Memory Size 2048 MB of memory 6 0 4 2048 0 Specifies the operating system installed Microsoft Windows Server 2008 R2 (64-bit) Specifies the available VM network connections 0 1 10.81.196.205 true 00:50:56:29:0c:a0 POOL 0 192.168.96.4 true 00:50:56:29:0c:9f POOL Specifies Guest OS Customization Settings true false f09c53c0-d0b3-4a31-9c8d-19de2c676e1e false false false true false summoning-dark Specifies Runtime info Snapshot information section 2014-07-08T23:33:24.510-04:00 a395377e-8f69-4ba4-8b09-f5ea93f7367e VMware ESXi 5.1.0 VMware, Inc. en false false Virtual hardware requirements Virtual Hardware Family 0 sam-vimes vmx-09 00:50:56:29:0c:a1 0 true Non-DMZNetwork Vmxnet3 ethernet adapter on "Non-DMZNetwork" Network adapter 0 1 VMXNET3 10 00:50:56:29:0c:a2 1 true nfs-net-01 Vmxnet3 ethernet adapter on "nfs-net-01" Network adapter 1 2 VMXNET3 10 0 SCSI Controller SCSI Controller 0 3 lsilogic 6 0 Hard disk Hard disk 1 2000 3 17 0 IDE Controller IDE Controller 0 4 5 1 true CD/DVD Drive CD/DVD Drive 1 3002 4 15 hertz * 10^6 Number of Virtual CPUs 1 virtual CPU(s) 5 0 3 1 0 byte * 2^20 Memory Size 2048 MB of memory 6 0 4 2048 0 Specifies the operating system installed Oracle Linux 4/5/6 (64-bit) Specifies the available VM network connections 0 0 192.168.96.5 true 00:50:56:29:0c:a1 POOL 1 10.81.196.206 true 00:50:56:29:0c:a2 POOL Specifies Guest OS Customization Settings true false 315485fb-e4a2-4dae-8890-2c21439da1fb false false false true false if [ x$1 == x"postcustomization" ]; then fi sam-vimes.test.com Specifies Runtime info Snapshot information section 2014-07-08T23:33:24.537-04:00 3186dd46-8976-49d3-b9f9-9bbd432d187e VMware ESXi 5.1.0 VMware, Inc. en false false fog-1.42.0/tests/vcloud_director/fixtures/vm.xml0000644000004100000410000004726513171001215021754 0ustar www-datawww-data Virtual hardware requirements Virtual Hardware Family 0 nas.test.com vmx-09 00:50:56:29:0c:18 0 true Non-DMZNetwork Vmxnet3 ethernet adapter on "Non-DMZNetwork" Network adapter 0 1 VMXNET3 10 00:50:56:29:0c:19 1 true nfs-net-01 Vmxnet3 ethernet adapter on "nfs-net-01" Network adapter 1 2 VMXNET3 10 0 SCSI Controller SCSI Controller 0 3 lsilogic 6 0 Hard disk Hard disk 1 2000 3 17 0 IDE Controller IDE Controller 0 4 5 1 true CD/DVD Drive CD/DVD Drive 1 3002 4 15 hertz * 10^6 Number of Virtual CPUs 1 virtual CPU(s) 5 0 3 1 0 byte * 2^20 Memory Size 2048 MB of memory 6 0 4 2048 0 Specifies the operating system installed Oracle Linux 4/5/6 (64-bit) Specifies the available VM network connections 0 0 192.168.96.10 true 00:50:56:29:0c:18 POOL 1 10.81.196.204 true 00:50:56:29:0c:19 POOL Specifies Guest OS Customization Settings true false 17a2a3a9-248c-475d-8ee0-8dd45f7f8368 false false false true false if [ x$1 == x"postcustomization" ]; then fi nas.test.com Specifies Runtime info Snapshot information section 2014-07-08T00:35:59.703-04:00 b6b1835b-cb2a-49c2-832f-93212a757858 VMware ESXi 5.1.0 VMware, Inc. en false false fog-1.42.0/tests/vcloud_director/fixtures/test.iso0000644000004100000410000000001613171001215022262 0ustar www-datawww-dataNOT A REAL ISOfog-1.42.0/tests/vcloud_director/ensure_list_tests.rb0000644000004100000410000000505513171001215023031 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.42.0/tests/vcloud_director/generators/0000755000004100000410000000000013171001215021072 5ustar www-datawww-datafog-1.42.0/tests/vcloud_director/generators/compute/0000755000004100000410000000000013171001215022546 5ustar www-datawww-datafog-1.42.0/tests/vcloud_director/generators/compute/compose_vapp_tests.rb0000644000004100000410000001260213171001215027011 0ustar www-datawww-datarequire 'fog/vcloud_director/generators/compute/compose_vapp' Shindo.tests("Compute::VcloudDirector - ComposeVapp", ['vclouddirector']) do @vapp_configuration = { :Description => 'a description', :InstantiationParams => { :DefaultStorageProfile => 'profile', :NetworkConfig => [ { :networkName => 'net1', :networkHref => 'http://net1', :fenceMode => 'bridged' }, { :networkName => 'net2', :networkHref => 'http://net2', :fenceMode => 'isolated' }, ] }, :source_templates => [ { :href => 'http://template_1' }, { :href => 'http://template_2' } ], :source_vms => [ { :href => 'http://vm_1', :networks => [ { :networkName => 'vm_net_1', :IsConnected => true, :IpAddressAllocationMode => 'POOL', }, { :networkName => 'vm_net_2', :IsConnected => false, :IpAddressAllocationMode => 'DHCP' } ] }, { :href => 'http://vm_2', :guest_customization => { :Enabled => true, :ComputerName => 'wally', :ChangeSid => false, :JoinDomainEnabled => false, :AdminPasswordEnabled => true, :AdminPasswordAuto => false, :AdminPassword => 'password', :ResetPasswordRequired => false, :CustomizationScript => 'ls -sal', }, :StorageProfileHref => 'http://profile_1' } ] } tests('#check xml from generator').returns(true) do xml = Nokogiri.XML Fog::Generators::Compute::VcloudDirector::ComposeVapp.new(@vapp_configuration).generate_xml tags_with_values = { 'ComposeVAppParams>Description' => 'a description', 'ComposeVAppParams>AllEULAsAccepted' => 'true', 'ComposeVAppParams>InstantiationParams>DefaultStorageProfileSection>StorageProfile' => 'profile', "ComposeVAppParams>InstantiationParams>NetworkConfigSection>NetworkConfig[networkName='net1']>Configuration>ParentNetwork[href='http://net1']~FenceMode" => 'bridged', "ComposeVAppParams>InstantiationParams>NetworkConfigSection>NetworkConfig[networkName='net2']>Configuration>ParentNetwork[href='http://net2']~FenceMode" => 'isolated', 'ComposeVAppParams>SourcedItem>InstantiationParams>NetworkConnectionSection>PrimaryNetworkConnectionIndex' => '0', "ComposeVAppParams>SourcedItem>InstantiationParams>NetworkConnectionSection>NetworkConnection[network='vm_net_1']>NetworkConnectionIndex" => '0', "ComposeVAppParams>SourcedItem>InstantiationParams>NetworkConnectionSection>NetworkConnection[network='vm_net_1']>IsConnected" => 'true', "ComposeVAppParams>SourcedItem>InstantiationParams>NetworkConnectionSection>NetworkConnection[network='vm_net_1']>IpAddressAllocationMode" => 'POOL', "ComposeVAppParams>SourcedItem>InstantiationParams>NetworkConnectionSection>NetworkConnection[network='vm_net_2']>NetworkConnectionIndex" => '1', "ComposeVAppParams>SourcedItem>InstantiationParams>NetworkConnectionSection>NetworkConnection[network='vm_net_2']>IsConnected" => 'false', "ComposeVAppParams>SourcedItem>InstantiationParams>NetworkConnectionSection>NetworkConnection[network='vm_net_2']>IpAddressAllocationMode" => 'DHCP', "ComposeVAppParams>SourcedItem>Source[href='http://vm_2']~InstantiationParams>GuestCustomizationSection>Enabled" => 'true', "ComposeVAppParams>SourcedItem>Source[href='http://vm_2']~InstantiationParams>GuestCustomizationSection>ComputerName" => 'wally', "ComposeVAppParams>SourcedItem>Source[href='http://vm_2']~InstantiationParams>GuestCustomizationSection>ChangeSid" => 'false', "ComposeVAppParams>SourcedItem>Source[href='http://vm_2']~InstantiationParams>GuestCustomizationSection>JoinDomainEnabled" => 'false', "ComposeVAppParams>SourcedItem>Source[href='http://vm_2']~InstantiationParams>GuestCustomizationSection>AdminPasswordEnabled" => 'true', "ComposeVAppParams>SourcedItem>Source[href='http://vm_2']~InstantiationParams>GuestCustomizationSection>AdminPasswordAuto" => 'false', "ComposeVAppParams>SourcedItem>Source[href='http://vm_2']~InstantiationParams>GuestCustomizationSection>AdminPassword" => 'password', "ComposeVAppParams>SourcedItem>Source[href='http://vm_2']~InstantiationParams>GuestCustomizationSection>ResetPasswordRequired" => 'false', "ComposeVAppParams>SourcedItem>Source[href='http://vm_2']~InstantiationParams>GuestCustomizationSection>CustomizationScript" => 'ls -sal', } empty_tags = [ "ComposeVAppParams>SourcedItem>Source[href='http://template_1']", "ComposeVAppParams>SourcedItem>Source[href='http://template_2']", "ComposeVAppParams>SourcedItem>Source[href='http://vm_1']", "ComposeVAppParams>SourcedItem>Source[href='http://vm_2']", "ComposeVAppParams>SourcedItem>Source[href='http://vm_2']~StorageProfile[href='http://profile_1']", ] tags_with_values_match = tags_with_values.none? do |path| match = ((xml.css path[0]).inner_text == path[1]) puts "\tExpected '#{path[1]}' on css path '#{path[0]}' but found '#{(xml.css path[0]).inner_text}'" unless match !match end tags_match = empty_tags.none? do |path| node = xml.css path puts "\tExpected to find '#{path}' but found '#{node}'." if node.empty? node.empty? end tags_with_values_match && tags_match end endfog-1.42.0/tests/vcloud_director/models/0000755000004100000410000000000013171001215020204 5ustar www-datawww-datafog-1.42.0/tests/vcloud_director/models/compute/0000755000004100000410000000000013171001215021660 5ustar www-datawww-datafog-1.42.0/tests/vcloud_director/models/compute/vapp_template_tests.rb0000644000004100000410000000172613171001215026276 0ustar www-datawww-datarequire File.expand_path(File.join(File.dirname(__FILE__), 'helper')) Shindo.tests("Compute::VcloudDirector | vapp_templates", ['vclouddirector', 'all']) do # unless there is atleast one vapp we cannot run these tests pending if vdc.vapp_templates.empty? vapp_templates = vdc.vapp_templates vapp = vapp_templates.first tests("Compute::VcloudDirector | vapp_template") 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.vAppTemplate+xml"){ vapp.type } end tests("Compute::VcloudDirector | vapp_template vms") do tests("#vms").returns(Fog::Compute::VcloudDirector::TemplateVms) { vapp.vms.class } pending if Fog.mock? vm = vapp.vms[0] tests("#name").returns(String){ vm.name.class } tests("#type").returns("application/vnd.vmware.vcloud.vm+xml"){ vm.type } end end fog-1.42.0/tests/vcloud_director/models/compute/vdcs_tests.rb0000644000004100000410000000420513171001215024367 0ustar www-datawww-datarequire File.expand_path(File.join(File.dirname(__FILE__), 'helper')) Shindo.tests("Compute::VcloudDirector | vdcs", ['vclouddirector', 'all']) do 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 pending if Fog.mocking? # We should also be able to find this same vdc via Query API tests("Compute::VcloudDirector | vdcs", ['find_by_query']) do tests('we can retrieve :name without lazy loading').returns(vdc.name) do query_vdc = vdcs.find_by_query(:filter => "name==#{vdc.name}").first query_vdc.attributes[:name] end tests('by name').returns(vdc.name) do query_vdc = vdcs.find_by_query(:filter => "name==#{vdc.name}").first query_vdc.name end end end fog-1.42.0/tests/vcloud_director/models/compute/helper.rb0000644000004100000410000000202613171001215023464 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.find {|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.42.0/tests/vcloud_director/models/compute/catalogs_tests.rb0000644000004100000410000000331413171001215025225 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.42.0/tests/vcloud_director/models/compute/organizations_tests.rb0000644000004100000410000000141313171001215026315 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.42.0/tests/vcloud_director/models/compute/vapp_life_cycle_tests.rb0000644000004100000410000001012713171001215026554 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.42.0/tests/vcloud_director/models/compute/catalog_items_tests.rb0000644000004100000410000000367713171001215026257 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 } tests("#vapp_template").returns(VappTemplate){ catalog_item.vapp_template.class } 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.42.0/tests/vcloud_director/models/compute/vms_tests.rb0000644000004100000410000001217313171001215024240 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.find {|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("#deployed").returns(String){ vm.deployed.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 } tests("#network_adapters").returns(Array){ vm.network_adapters.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 # We should also be able to find this VM via Query API # :name is not unique for VMs though, so let us query by href tests("Compute::VcloudDirector | vm", ['find_by_query']) do tests('we can retrieve :name without lazy loading').returns(vm.name) do query_vm = vms.find_by_query(:filter => "href==#{vm.href}").first query_vm.attributes[:name] end tests('we can retrieve name via model object returned by query').returns(vm.name) do query_vm = vms.find_by_query(:filter => "href==#{vm.href}").first query_vm.name end end end fog-1.42.0/tests/vcloud_director/models/compute/tasks_tests.rb0000644000004100000410000000377013171001215024563 0ustar www-datawww-datarequire File.expand_path(File.join(File.dirname(__FILE__), 'helper')) Shindo.tests('Compute::VcloudDirector | tasks', ['vclouddirector']) do @service = Fog::Compute::VcloudDirector.new() if Fog.mocking? # add a bunch of tasks 50.times do task_id = @service.enqueue_task( "Bogus Task", 'BogusTaskName', { :href => 'https://example.com/api/bogus/12345678-1234-1234-1234-123456789012', :name => 'Bogus object', :type => 'application/vnd.vmware.vcloud.bogus+xml' } ) end end 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(Time) { task.end_time.class } tests('#expiry_time').returns(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 # We should also be able to find tasks via the Query API # NB: Query name == task.operation_name tests("Compute::VcloudDirector | tasks", ['find_by_query']) do tests('we can retrieve :name without lazy loading').returns(task.operation_name) do query_task = tasks.find_by_query(:filter => "name==#{task.operation_name}").first query_task.attributes[:name] end tests('by name').returns(task.operation_name) do query_task = tasks.find_by_query(:filter => "name==#{task.operation_name}").first query_task.name end end end fog-1.42.0/tests/vcloud_director/models/compute/network_tests.rb0000644000004100000410000001121713171001215025122 0ustar www-datawww-datarequire File.expand_path(File.join(File.dirname(__FILE__), 'helper')) Shindo.tests("Compute::VcloudDirector | networks", ['vclouddirector', 'all']) do # unless there is at least one network we cannot run these tests pending if organization.networks.empty? service = Fog::Compute::VcloudDirector.new networks = organization.networks network_raw = nil # Run initial tests against a natRouted network, since these # are more likely to be created, and must be populated with # Gateway and EdgeGateway sections network = networks.find do |net| network_raw = service.get_network_complete(net.id).body network_raw[:Configuration][:FenceMode] == 'natRouted' end # We don't have a sufficiently populated natRouted network to test against pending if network_raw.nil? UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/ IP_REGEX = /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ tests("Compute::VcloudDirector | network") do tests("#id").returns(0) { network.id =~ UUID_REGEX } tests("#name").returns(String) { network.name.class } tests("#href").returns(String) { network.href.class } tests("#type").returns("application/vnd.vmware.vcloud.orgNetwork+xml"){ network.type } end tests("Compute::VcloudDirector | network", ['lazy load attrs']) do network.lazy_load_attrs.each do |lazy_attr| tests("##{lazy_attr} is not loaded yet").returns(NonLoaded) { network.attributes[lazy_attr] } end end tests("Compute::VcloudDirector | network", ['load on demand']) do network_raw_gateway = network_raw[:Configuration][:IpScopes][:IpScope][:Gateway] tests("#gateway is not loaded yet").returns(NonLoaded) { network.attributes[:gateway] } tests("#gateway is loaded on demand").returns(network_raw_gateway) { network.gateway } tests("#gateway is now loaded").returns(true) { network.attributes[:gateway] != NonLoaded } end tests("Compute::VcloudDirector | network", ['all lazy load attrs should now be loaded with data']) do network.lazy_load_attrs.each do |field| tests("##{field.to_s} is now loaded").returns(true) { network.attributes[field] != NonLoaded } end end tests("Compute::VcloudDirector | network", ['ip_ranges is an array of start-end pairs']) do tests("#ip_ranges is an Array").returns(Array) { network.ip_ranges.class } network.ip_ranges.each do |range| tests("each ip_range has a :start_address").returns(0) { range[:start_address] =~ IP_REGEX } tests("each ip_range has an :end_address").returns(0) { range[:end_address] =~ IP_REGEX } end end tests("Compute::VcloudDirector | network", ['is_shared is a string boolean']) do tests("#is_shared is either 'true' or 'false'").returns(true) { [ 'false', 'true' ].include?(network.is_shared) } end # NB: get_by_name is buggy with orgVdcNetworks - network names are only # unique per-vDC, not per organization. # As a result, it returns the *first* network matching that name. tests("Compute::VcloudDirector | networks", ['get']) do tests("#get_by_name").returns(network.name) { networks.get_by_name(network.name).name } tests("#get").returns(network.id) { networks.get(network.id).id } end # Now let's also check against an isolated network, since these have some # additional features like DHCP ServiceConfigurations. isolated_network_raw = nil isolated_network = networks.find do |net| isolated_network_raw = service.get_network_complete(net.id).body isolated_network_raw[:Configuration][:FenceMode] == 'isolated' end pending if isolated_network_raw.nil? tests("Compute::VcloudDirector | isolated network", ['load on demand']) do tests("#fence_mode is not loaded yet").returns(NonLoaded) { isolated_network.attributes[:fence_mode] } tests("#fence_mode is loaded on demand").returns('isolated') { isolated_network.fence_mode } tests("#fence_mode is now loaded").returns(true) { isolated_network.attributes[:fence_mode] != NonLoaded } end # We should also be able to find these same networks via Query API tests("Compute::VcloudDirector | networks", ['find_by_query']) do tests('we can retrieve :name without lazy loading').returns(network.name) do query_network = networks.find_by_query(:filter => "name==#{network.name}").first query_network.attributes[:name] end tests('by name: natRouted').returns(network.name) do query_network = networks.find_by_query(:filter => "name==#{network.name}").first query_network.name end tests('by name: isolated').returns(isolated_network.name) do query_network = networks.find_by_query(:filter => "name==#{isolated_network.name}").first query_network.name end end end fog-1.42.0/tests/vcloud_director/models/compute/media_tests.rb0000644000004100000410000000435013171001215024510 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.42.0/tests/vcloud_director/models/compute/vapp_tests.rb0000644000004100000410000000472613171001215024406 0ustar www-datawww-datarequire File.expand_path(File.join(File.dirname(__FILE__), 'helper')) Shindo.tests("Compute::VcloudDirector | vapps", ['vclouddirector', 'all']) do # 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 tests("Compute::VcloudDirector | vapp", ['custom_fields']) do pending if Fog.mocking? tests("#set_custom_field").returns('2'){ vapp.custom_fields[:custom_field] = '2' } tests("#get_custom_field_by_name").returns('2') { vapp.custom_fields[:custom_field].value } tests("#delete_custom_field").returns([]){ vapp.custom_fields.delete(:custom_field); vapp.custom_fields } end # We should also be able to find this vApp via Query API tests("Compute::VcloudDirector | vapps", ['find_by_query']) do tests('we can retrieve :name without lazy loading').returns(vapp.name) do query_vapp = vapps.find_by_query(:filter => "name==#{vapp.name}").first query_vapp.attributes[:name] end tests('we can retrieve name via model object returned by query').returns(vapp.name) do query_vapp = vapps.find_by_query(:filter => "name==#{vapp.name}").first query_vapp.name end end end fog-1.42.0/tests/ibm/0000755000004100000410000000000013171001215014301 5ustar www-datawww-datafog-1.42.0/tests/ibm/requests/0000755000004100000410000000000013171001215016154 5ustar www-datawww-datafog-1.42.0/tests/ibm/requests/storage/0000755000004100000410000000000013171001215017620 5ustar www-datawww-datafog-1.42.0/tests/ibm/requests/storage/volume_tests.rb0000644000004100000410000000620713171001215022703 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.42.0/tests/ibm/requests/compute/0000755000004100000410000000000013171001215017630 5ustar www-datawww-datafog-1.42.0/tests/ibm/requests/compute/image_tests.rb0000644000004100000410000000615613171001215022471 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.42.0/tests/ibm/requests/compute/key_tests.rb0000644000004100000410000000342713171001215022175 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.42.0/tests/ibm/requests/compute/vlan_tests.rb0000644000004100000410000000055213171001215022341 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.42.0/tests/ibm/requests/compute/location_tests.rb0000644000004100000410000000115113171001215023205 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.42.0/tests/ibm/requests/compute/address_tests.rb0000644000004100000410000000250413171001215023025 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.42.0/tests/ibm/requests/compute/instance_tests.rb0000644000004100000410000000654113171001215023211 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.42.0/tests/ibm/models/0000755000004100000410000000000013171001215015564 5ustar www-datawww-datafog-1.42.0/tests/ibm/models/storage/0000755000004100000410000000000013171001215017230 5ustar www-datawww-datafog-1.42.0/tests/ibm/models/storage/volume_tests.rb0000644000004100000410000000310013171001215022300 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.42.0/tests/ibm/models/compute/0000755000004100000410000000000013171001215017240 5ustar www-datawww-datafog-1.42.0/tests/ibm/models/compute/keys_tests.rb0000644000004100000410000000167413171001215021772 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.42.0/tests/ibm/models/compute/image_tests.rb0000644000004100000410000000120413171001215022066 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.42.0/tests/ibm/models/compute/server_tests.rb0000644000004100000410000000506113171001215022317 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.42.0/tests/ibm/models/compute/key_tests.rb0000644000004100000410000000103113171001215021572 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.42.0/tests/ibm/models/compute/servers_tests.rb0000644000004100000410000000214713171001215022504 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.42.0/tests/ibm/models/compute/locations_tests.rb0000644000004100000410000000065013171001215023003 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.42.0/tests/watchr.rb0000644000004100000410000000070713171001215015353 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.42.0/tests/dns/0000755000004100000410000000000013171001215014316 5ustar www-datawww-datafog-1.42.0/tests/dns/helper.rb0000644000004100000410000000212113171001215016116 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' } }, :rage4 => { :mocked => false } } 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.42.0/tests/dns/models/0000755000004100000410000000000013171001215015601 5ustar www-datawww-datafog-1.42.0/tests/dns/models/zones_tests.rb0000644000004100000410000000065513171001215020514 0ustar www-datawww-datafor provider, config in dns_providers # FIXME: delay/timing breaks things :( next if [:dnsmadeeasy, :rage4].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.42.0/tests/dns/models/zone_tests.rb0000644000004100000410000000064713171001215020332 0ustar www-datawww-datafor provider, config in dns_providers # FIXME: delay/timing breaks things :( next if [:dnsmadeeasy, :rage4].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.42.0/tests/dns/models/records_tests.rb0000644000004100000410000000132413171001215021011 0ustar www-datawww-datafor provider, config in dns_providers # FIXME: delay/timing breaks things :( next if [:dnsmadeeasy, :rage4].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.42.0/tests/dns/models/record_tests.rb0000644000004100000410000000235213171001215020630 0ustar www-datawww-datafor provider, config in dns_providers # FIXME: delay/timing breaks things :( next if [:dnsmadeeasy, :rage4].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.42.0/tests/dnsmadeeasy/0000755000004100000410000000000013171001215016027 5ustar www-datawww-datafog-1.42.0/tests/dnsmadeeasy/requests/0000755000004100000410000000000013171001215017702 5ustar www-datawww-datafog-1.42.0/tests/dnsmadeeasy/requests/dns/0000755000004100000410000000000013171001215020466 5ustar www-datawww-datafog-1.42.0/tests/dnsmadeeasy/requests/dns/dns_tests.rb0000644000004100000410000000650413171001215023026 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.42.0/tests/glesys/0000755000004100000410000000000013171001215015040 5ustar www-datawww-datafog-1.42.0/tests/glesys/requests/0000755000004100000410000000000013171001215016713 5ustar www-datawww-datafog-1.42.0/tests/glesys/requests/compute/0000755000004100000410000000000013171001215020367 5ustar www-datawww-datafog-1.42.0/tests/glesys/requests/compute/helper.rb0000644000004100000410000002212113171001215022171 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' => { 'timeperiod' => String, 'currency' => String }, 'serverid' => String, 'datacenter' => String, 'memorysize' => Integer, 'cpucores' => Integer, 'transfer' => Integer, 'bandwidth' => 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, 'bandwidth' => String, 'description' => String } } ) EDIT = DETAILS.merge( 'debug' => { 'input' => { 'serverid' => Fog::Nullable::String, 'disksize' => String, 'memorysize' => String, 'cpucores' => String, 'bandwidth' => 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::Float, '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 SshKeys ADD = { 'debug' => { 'input' => { 'sshkey' => String, 'description' => String } }, 'sshkey' => { 'id' => Integer, 'account' => String, 'description' => String, 'data' => String }, 'status' => { 'timestamp' => String, 'code' => Integer, 'text' => String, 'transactionid' => Fog::Nullable::String } } REMOVE = { 'debug' => { 'input' => { 'sshkeyids' => String, } }, 'status' => { 'timestamp' => String, 'code' => Integer, 'text' => String, 'transactionid' => Fog::Nullable::String } } LIST = { 'debug' => { 'input' => [] }, 'sshkeys' => [ { 'id' => Integer, 'account' => String, 'description' => String, 'data' => 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.42.0/tests/glesys/requests/compute/template_tests.rb0000644000004100000410000000044213171001215023751 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.42.0/tests/glesys/requests/compute/server_tests.rb0000644000004100000410000001162113171001215023445 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 => 'VMware', :templatename => 'Debian 7.0 64-bit', "+ ":disksize => '10', :memorysize => '512', :cpucores => '1', :transfer => '500', :bandwidth => '10'" @create_vz = ":hostname => #@hostname, :rootpassword => 'pw#{Time.now.to_i}', "+ ":datacenter => 'Stockholm', :platform => 'OpenVZ', :templatename => 'Debian 7.0 64-bit', "+ ":disksize => '10', :memorysize => '256', :cpucores => '2', :transfer => '500', :bandwidth => '10'" 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, :description => "Fog test server", :rootpassword => "pw#{Time.now.to_i}", :datacenter => "Falkenberg", :platform => "VMware", :templatename => "Debian 7.0 64-bit", :disksize => "10", :memorysize => "512", :cpucores => "1", :transfer => "500", :bandwidth => "10" ) @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 7.0 64-bit", :disksize => "10", :memorysize => "256", :cpucores => "2", :transfer => "500", :bandwidth => "10" ) @serverid = vm.body['response']['server']['serverid'] vm.body['response'] end unless Fog.mocking? Fog::Compute[:glesys].servers.get(@serverid).wait_for { ready? } end tests("#edit #{@serverid}").formats(Glesys::Compute::Formats::Servers::EDIT) do pending if Fog.mocking? vm = Fog::Compute[:glesys].edit( :serverid => @serverid, :disksize => "10", :memorysize => "512", :cpucores => "1", :bandwidth => "10" ) 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.42.0/tests/glesys/requests/compute/ip_tests.rb0000644000004100000410000000346513171001215022556 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.42.0/tests/glesys/requests/compute/ssh_key_tests.rb0000644000004100000410000000356413171001215023613 0ustar www-datawww-dataShindo.tests("Fog::Compute[:glesys] | ssh_key requests", ["glesys", "compute"]) do @testdescription = "My test key to be removed" @testdata = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDv+r/dCIDv+YazWsyc1WCixR+iOeaswTx1U45h6vh4/ fog-unittest@GleSYS" @testdata_malformed = "ssh-rot13 AAAAthis_is_not_an_ssh_key fog-unittest@GleSYS" tests("success") do tests("#ssh_key_add").formats(Glesys::Compute::Formats::SshKeys::ADD) do pending if Fog.mocking? @resp = Fog::Compute[:glesys].ssh_key_add(:description => @testdescription, :sshkey => @testdata) @resp.body["response"] end unless Fog.mocking? Fog::Compute[:glesys].ssh_keys.destroy(@resp.body["response"]["sshkey"]["id"]) @key = Fog::Compute[:glesys].ssh_keys.create(:description => @testdescription, :data => @testdata) end tests("#ssh_key_list").formats(Glesys::Compute::Formats::SshKeys::LIST) do pending if Fog.mocking? @resp = Fog::Compute[:glesys].ssh_key_list @resp.body["response"] end unless Fog.mocking? Fog::Compute[:glesys].ssh_keys.destroy(@key.id) @key = Fog::Compute[:glesys].ssh_keys.create(:description => @testdescription, :data => @testdata) end tests("#ssh_key_remove").formats(Glesys::Compute::Formats::SshKeys::REMOVE) do pending if Fog.mocking? @resp = Fog::Compute[:glesys].ssh_key_remove(:sshkeyids => @key.id) @resp.body["response"] end end tests("failure") do tests("#ssh_key_add with malformed key data").raises(Excon::Errors::HTTPStatusError) do pending if Fog.mocking? Fog::Compute[:glesys].ssh_key_add(:description => @testdescription, :data => @testdata_malformed) end tests("#ssh_key_remove with nonexistent/invalid key id").raises(Excon::Errors::HTTPStatusError) do pending if Fog.mocking? Fog::Compute[:glesys].ssh_key_remove(:id => -1) end end end fog-1.42.0/tests/rage4/0000755000004100000410000000000013171001215014534 5ustar www-datawww-datafog-1.42.0/tests/rage4/requests/0000755000004100000410000000000013171001215016407 5ustar www-datawww-datafog-1.42.0/tests/rage4/requests/dns/0000755000004100000410000000000013171001215017173 5ustar www-datawww-datafog-1.42.0/tests/rage4/requests/dns/dns_tests.rb0000644000004100000410000001722413171001215021534 0ustar www-datawww-dataShindo.tests('Fog::DNS[:rage4] | DNS requests', ['rage4', 'dns']) do @domain = '' @domain_id = nil @record_id = nil @domain_count = 0 @created_domain_list = [] tests("success") do test("get current domain count") do pending if Fog.mocking? response = Fog::DNS[:rage4].list_domains() if response.status == 200 @domain_count = response.body.size end if response.status == 200 response.body = [] end response.status == 200 end test("create domain") do pending if Fog.mocking? domain = generate_unique_domain response = Fog::DNS[:rage4].create_domain(domain) if response.status == 200 @domain_id = response.body['id'] @domain = domain end if response.status == 200 && response.body['id'] != 0 @created_domain_list << response.body['id'] end response.status == 200 && response.body['error'] == "" && response.body['status'] && !@domain_id.nil? end test("create_domain_vanity") do pending if Fog.mocking? domain = generate_unique_domain response = Fog::DNS[:rage4].create_domain_vanity(domain, 'foo.com') if response.status == 200 && response.body['id'] != 0 @created_domain_list << response.body['id'] end response.status == 200 && response.body['error'] == "" && response.body['status'] end test("create_reverse_domain_4") do pending if Fog.mocking? response = Fog::DNS[:rage4].create_reverse_domain_4('192.168.1.1', 29) if response.status == 200 && response.body['id'] != 0 @created_domain_list << response.body['id'] end response.status == 200 && response.body['error'] == "" && response.body['status'] end test("get_domain") do pending if Fog.mocking? response = Fog::DNS[:rage4].get_domain(@domain_id) returns(200) {response.status} returns(@domain_id) {response.body['id']} returns(@domain) {response.body['name']} returns(Fog.credentials[:rage4_email]) {response.body['owner_email']} returns(0) {response.body['type']} returns(0) {response.body['subnet_mask']} end test("get_domain_by_name") do pending if Fog.mocking? response = Fog::DNS[:rage4].get_domain_by_name(@domain) returns(200) {response.status} returns(@domain_id) {response.body['id']} returns(@domain) {response.body['name']} returns(Fog.credentials[:rage4_email]) {response.body['owner_email']} returns(0) {response.body['type']} returns(0) {response.body['subnet_mask']} end test("update_domain") do pending if Fog.mocking? response = Fog::DNS[:rage4].update_domain(@domain_id, {:email => 'test@test.com'}) returns(200) { response.status } returns(true) {response.body['status']} returns(@domain_id) {response.body['id']} returns("") {response.body['error'] } end test("bulk_update_records") do pending if Fog.mocking? data = { :id => @record_id, :priority => 1 } response = Fog::DNS[:rage4].bulk_update_records(@zone_id, { :body => data.to_json } ) returns(200) { response.status } returns(true) {response.body['status']} returns(@domain_id) {response.body['id']} returns("") {response.body['error'] } end test("show_current_usage") do pending if Fog.mocking? response = Fog::DNS[:rage4].show_current_usage(@domain_id) returns(200) { response.status } returns([]) { response.body } end test("show_global_usage") do pending if Fog.mocking? response = Fog::DNS[:rage4].show_global_usage() returns(200) { response.status } returns([]) { response.body } end test("list_record_types") do pending if Fog.mocking? response = Fog::DNS[:rage4].list_record_types() response.body.each do |record_type| returns(true) { !record_type['name'].nil? } returns(true) { !record_type['value'].nil? } end returns(200) { response.status } returns(Array) { response.body.class } end test("list_geo_regions") do pending if Fog.mocking? response = Fog::DNS[:rage4].list_geo_regions() response.body.each do |record_type| returns(true) { !record_type['name'].nil? } returns(true) { !record_type['value'].nil? } end returns(200) { response.status } returns(Array) { response.body.class } end test("create_record") do pending if Fog.mocking? name = "www." + @domain type = 2 #"A" data = "1.2.3.4" response = Fog::DNS[:rage4].create_record(@domain_id, name , data, type) if response.status == 200 @record_id = response.body['id'] end response.status == 200 && response.body['error'] == "" && response.body['status'] && !@record_id.nil? end test("create_record with options") do pending if Fog.mocking? name = "www." + @domain type = 2 #"A" data = "1.2.3.5" options = { :udplimit => true } response = Fog::DNS[:rage4].create_record(@domain_id, name , data, type, options) if response.status == 200 @record_id = response.body['id'] end response.status == 200 && response.body['error'] == "" && response.body['status'] && !@record_id.nil? end test("update_record") do pending if Fog.mocking? name = "www." + @domain type = 2 #"A" data = "4.3.2.1" response = Fog::DNS[:rage4].update_record(@record_id, name, data, type) returns(@record_id) { response.body['id'] } response.status == 200 && response.body['error'] == "" && response.body['status'] end test("update_record with options") do pending if Fog.mocking? name = "www." + @domain type = 2 #"A" data = "4.3.2.1" options = { :udplimit => true } response = Fog::DNS[:rage4].update_record(@record_id, name, data, type, options) returns(@record_id) { response.body['id'] } response.status == 200 && response.body['error'] == "" && response.body['status'] end test("list_records") do pending if Fog.mocking? response = Fog::DNS[:rage4].list_records(@domain_id) # returns nameserver records as well, will only verify # the record we have tracked response.body.each do |record| if record['id'] == @record_id returns(@record_id) { record['id'] } returns("www." + @domain) { record['name'] } returns("A") { record['type'] } returns(3600) { record['ttl'] } returns(nil) { record['priority'] } returns(@domain_id) { record['domain_id'] } returns(0) { record['geo_region_id'] } returns(false) { record['failover_enabled'] } returns(nil) { record['failover_content'] } returns(true) { record['is_active'] } returns(false) { record['geo_lock'] } end end response.status == 200 end test("delete_record") do pending if Fog.mocking? response = Fog::DNS[:rage4].delete_record(@record_id) returns(@record_id) { response.body['id'] } response.status == 200 && response.body['error'] == "" && response.body['status'] end test("delete_domain") do pending if Fog.mocking? response = nil @created_domain_list.each do |domain_id| response = Fog::DNS[:rage4].delete_domain(domain_id) returns(true) {response.body['status']} returns(domain_id) {response.body['id']} returns("") {response.body['error'] } end response.status == 200 end end tests( 'failure') do end end fog-1.42.0/tests/linode/0000755000004100000410000000000013171001215015004 5ustar www-datawww-datafog-1.42.0/tests/linode/requests/0000755000004100000410000000000013171001215016657 5ustar www-datawww-datafog-1.42.0/tests/linode/requests/dns/0000755000004100000410000000000013171001215017443 5ustar www-datawww-datafog-1.42.0/tests/linode/requests/dns/dns_tests.rb0000644000004100000410000001524113171001215022001 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.42.0/tests/linode/requests/compute/0000755000004100000410000000000013171001215020333 5ustar www-datawww-datafog-1.42.0/tests/linode/requests/compute/datacenter_tests.rb0000644000004100000410000000071113171001215024213 0ustar www-datawww-dataShindo.tests('Fog::Compute[:linode] | datacenter requests', ['linode']) do @datacenters_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => [{ 'DATACENTERID' => Integer, 'LOCATION' => String, 'ABBR' => 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.42.0/tests/linode/requests/compute/kernel_tests.rb0000644000004100000410000000102513171001215023360 0ustar www-datawww-dataShindo.tests('Fog::Compute[:linode] | kernel requests', ['linode']) do @kernels_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => [{ 'LABEL' => String, 'ISXEN' => Integer, 'ISKVM' => Integer, 'ISPVOPS' => Integer, 'KERNELID' => Integer }] }) tests('success') do tests('#avail_kernels').formats(@kernels_format) do pending if Fog.mocking? Fog::Compute[:linode].avail_kernels.body end end end fog-1.42.0/tests/linode/requests/compute/linode_tests.rb0000644000004100000410000001566213171001215023366 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, 'IPADDRESS' => String } }) @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 }] }) @images_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => [{ "LAST_USED_DT" => String, "DESCRIPTION" => String, "LABEL" => String, "STATUS" => String, "TYPE" => String, "MINSIZE" => Integer, "ISPUBLIC" => Integer, "CREATE_DT" => String, "FS_TYPE" => String, "CREATOR" => String, "IMAGEID" => Integer }] }) @disk_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => { 'JobID' => Integer, 'DiskID' => Integer } }) @disk_createfromimage_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => { 'JOBID' => Integer, 'DISKID' => Integer } }) @disk_resize_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => { 'JobID' => Integer } }) @disk_imagize_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => { 'JobID' => Integer, 'ImageID' => Integer } }) @disk_update_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => { '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? rand_label = 'testing' + Fog::Mock.random_letters(6) Fog::Compute[:linode].linode_update(@linode_id, :label => rand_label).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_update').formats(@disk_update_format) do pending if Fog.mocking? Fog::Compute[:linode].linode_disk_update(@linode_id, @disk1_id, 'test1-updated', 1).body end tests('#linode_disk_duplicate').formats(@disk_format) do pending if Fog.mocking? Fog::Compute[:linode].linode_disk_duplicate(@linode_id, @disk1_id).body end tests('#linode_disk_resize').formats(@disk_resize_format) do pending if Fog.mocking? Fog::Compute[:linode].linode_disk_resize(@linode_id, @disk1_id, 2).body end tests('#linode_disk_imagize').formats(@disk_imagize_format) do pending if Fog.mocking? data = Fog::Compute[:linode].linode_disk_imagize(@linode_id, @disk1_id, 'test description imageid1', 'test label imageid1').body @image1_id = data['DATA']['ImageID'] data end tests('#linode_disk_createfromdistribution').formats(@disk_format) do pending if Fog.mocking? data = Fog::Compute[:linode].linode_disk_createfromdistribution(@linode_id, 124, 'test1', 750, 'P@SSW)RD').body @disk2_id = data['DATA']['DiskID'] data end tests('#linode_disk_createfromimage').formats(@disk_createfromimage_format) do pending if Fog.mocking? data = Fog::Compute[:linode].linode_disk_createfromimage(@linode_id, @image1_id, 'test1', 3, 'P@SSW)RD', '').body @disk3_id = data['DATA']['DISKID'] data end tests('#image_list').formats(@images_format) do pending if Fog.mocking? Fog::Compute[:linode].image_list(@image_id).body 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('#image_delete').formats(@images_format) do pending if Fog.mocking? Fog::Compute[:linode].image_delete(@image1_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 Fog::Compute[:linode].linode_disk_delete(@linode_id, @disk3_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.42.0/tests/linode/requests/compute/stackscripts_tests.rb0000644000004100000410000000210613171001215024616 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.42.0/tests/linode/requests/compute/helper.rb0000644000004100000410000000023013171001215022132 0ustar www-datawww-dataclass Linode module Compute module Formats BASIC = { 'ERRORARRAY' => [], 'ACTION' => String } end end end fog-1.42.0/tests/linode/requests/compute/nodebalancers_tests.rb0000644000004100000410000000073613171001215024710 0ustar www-datawww-dataShindo.tests('Fog::Compute[:linode] | linodenodebalancers requests', ['linode']) do @linodenodebalancers_format = Linode::Compute::Formats::BASIC.merge({ 'DATA' => [{ 'MONTHLY' => Float, 'HOURLY' => Float, 'CONNECTIONS' => Integer }] }) tests('success') do tests('#avail_nodebalancers').formats(@linodenodebalancers_format) do pending if Fog.mocking? Fog::Compute[:linode].avail_nodebalancers.body end end end fog-1.42.0/tests/linode/requests/compute/distribution_tests.rb0000644000004100000410000000162013171001215024620 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.42.0/tests/linode/requests/compute/linodeplans_tests.rb0000644000004100000410000000211113171001215024405 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, '9' => Integer, '10' => Integer }, 'DISK' => Integer, 'PLANID' => Integer, 'PRICE' => Float, 'RAM' => Integer, 'LABEL' => String, 'XFER' => Integer, 'CORES' => Integer, 'HOURLY' => Float }] }) 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.42.0/tests/fogdocker/0000755000004100000410000000000013171001215015475 5ustar www-datawww-datafog-1.42.0/tests/fogdocker/requests/0000755000004100000410000000000013171001215017350 5ustar www-datawww-datafog-1.42.0/tests/fogdocker/requests/compute/0000755000004100000410000000000013171001215021024 5ustar www-datawww-datafog-1.42.0/tests/fogdocker/requests/compute/image_delete_tests.rb0000644000004100000410000000135213171001215025200 0ustar www-datawww-dataShindo.tests("Fog::Compute[:fogdocker] | image_delete request", 'fogdocker') do compute = Fog::Compute[:fogdocker] image_hash = compute.image_create({'fromImage' => 'mattdm/fedora', 'repo'=>'test', 'tag'=>'delete_image'}) tests("Delete image") do begin response = compute.image_delete(:id => image_hash['id']) test("should be success") { response ? true : false } #mock doesn't throw errors rescue => e #should raise image not found test("error should be a kind of Docker::Error::NotFoundError") { e.kind_of? Docker::Error::NotFoundError} end end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when id option is missing') { compute.container_delete } end end fog-1.42.0/tests/fogdocker/requests/compute/container_delete_tests.rb0000644000004100000410000000106413171001215026100 0ustar www-datawww-dataShindo.tests('Fog::Compute[:fogdocker] | container_delete request', ['fogdocker']) do compute = Fog::Compute[:fogdocker] container = compute.servers.create({'Image' => 'mattdm/fedora:f19', 'Cmd' => ['/bin/bash']}) tests('The response should') do response = compute.container_delete(:id => container.id) test('be a success') { response ? true: false } end tests('The expected options') do raises(ArgumentError, 'raises ArgumentError when id option is missing') { compute.container_delete } end end fog-1.42.0/tests/fogdocker/requests/compute/container_action_tests.rb0000644000004100000410000000247513171001215026122 0ustar www-datawww-dataShindo.tests("Fog::Compute[:fogdocker] | container_action request", 'fogdocker') do compute = Fog::Compute[:fogdocker] name = "fog-#{Time.now.to_i}" response = compute.container_create(:name => name, 'image' => 'mattdm/fedora:f19','Cmd' => ['date']) id = response['id'] tests("Start Container") do response = compute.container_action(:id => id, :action => :start) test("should be a kind of Hash") { response.kind_of? Hash } test("should be running") { response['state_running'] == true } end tests("Stop Container") do response = compute.container_action(:id => id, :action => :stop) test("should be a kind of Hash") { response.kind_of? Hash } end tests("Kill Container") do response = compute.container_action(:id => id, :action => :kill) test("should be a kind of Hash") { response.kind_of? Hash } test("should be stopped") { response['state_running'] == false } end tests("Top Container") do response = compute.container_action(:id => id, :action => :top) test("should be an Array") { response.kind_of? Array } test("should be an array of processes") { !!(response.first['PID'] =~ /^\d+$/) } end tests("Logs Container") do response = compute.container_action(:id => id, :action => :logs) test("should be a String") { response.kind_of? String } end end fog-1.42.0/tests/fogdocker/requests/compute/image_search_tests.rb0000644000004100000410000000073613171001215025210 0ustar www-datawww-dataShindo.tests("Fog::Compute[:fogdocker] | image_search request", 'fogdocker') do compute = Fog::Compute[:fogdocker] tests("Search images") do response = compute.image_search('term' => 'test') test("should be a kind of Array") { response.kind_of? Array} test("Array elements should be a kind of Hash") { response.first.kind_of? Hash} test("response elemetns should have a name") { !response.first['name'].nil? && !response.first['name'].empty? } end end fog-1.42.0/tests/fogdocker/requests/compute/container_create_tests.rb0000644000004100000410000000146213171001215026103 0ustar www-datawww-dataShindo.tests("Fog::Compute[:fogdocker] | container_create request", 'fogdocker') do compute = Fog::Compute[:fogdocker] name_base = Time.now.to_i tests("Create Container") do response = compute.container_create(:name => 'fog-'+name_base.to_s, 'image' => 'mattdm/fedora:f19','Cmd' => ['date'] ) test("should be a kind of Hash") { response.kind_of? Hash} end tests("Fail Creating Container") do begin response = compute.container_create(:name => 'fog-'+name_base.to_s, 'image' => 'mattdm/fedora:f19') test("should be a kind of Hash") { response.kind_of? Hash} #mock never raise exceptions rescue => e #should raise missing command in the create attributes. test("error should be a kind of Docker::Error") { e.kind_of? Docker::Error::ServerError} end end end fog-1.42.0/tests/fogdocker/requests/compute/image_create_tests.rb0000644000004100000410000000144613171001215025205 0ustar www-datawww-dataShindo.tests("Fog::Compute[:fogdocker] | image_create request", 'fogdocker') do compute = Fog::Compute[:fogdocker] tests("Create image") do response = compute.image_create({'fromImage' => 'mattdm/fedora', 'repo'=>'test', 'tag'=>'create_image'}) test("should be a kind of Hash") { response.kind_of? Hash} test("should have an id") { !response['id'].nil? && !response['id'].empty? } end tests("Fail Creating image") do begin response = compute.image_create('fromImage' => 'not/exists') test("should be a kind of Hash") { response.kind_of? Hash} #mock never raise exceptions rescue => e #should raise missing command in the create attributes. test("error should be a kind of Docker::Error") { e.kind_of? Docker::Error::ServerError} end end end fog-1.42.0/tests/fogdocker/requests/compute/api_version_tests.rb0000644000004100000410000000037213171001215025113 0ustar www-datawww-dataShindo.tests('Fog::Compute[:fogdocker] | api_version request', ['fogdocker']) do compute = Fog::Compute[:fogdocker] tests('The response should') do response = compute.api_version() test('be a Hash') { response.kind_of? Hash} end end fog-1.42.0/tests/fogdocker/requests/compute/container_commit_tests.rb0000644000004100000410000000114313171001215026124 0ustar www-datawww-dataShindo.tests("Fog::Compute[:fogdocker] | container_create request", 'fogdocker') do compute = Fog::Compute[:fogdocker] name_base = Time.now.to_i hash = compute.container_create(:name => 'fog-'+name_base.to_s, 'image' => 'mattdm/fedora:f19','Cmd' => ['date'] ) response = {} tests("Commit Container") do response = compute.container_commit(:id=>hash['id']) test("should have Image id") { response.include? 'id'} end test("Delete Commited Image") do result = compute.image_delete(:id=>response['id']) test("should have a deleted message") {result.include?('Deleted')} end end fog-1.42.0/tests/fogdocker/compute_tests.rb0000644000004100000410000000112713171001215020721 0ustar www-datawww-dataShindo.tests('Fog::Compute[:fogdocker]', ['fogdocker']) do compute = Fog::Compute[:fogdocker] tests("Compute collections") do %w{ servers images }.each do |collection| test("it should respond to #{collection}") { compute.respond_to? collection } end end tests("Compute requests") do %w{ api_version container_all container_create container_delete container_get container_action image_all image_create image_delete image_get image_search }.each do |collection| test("it should respond to #{collection}") { compute.respond_to? collection } end end end fog-1.42.0/tests/fogdocker/models/0000755000004100000410000000000013171001215016760 5ustar www-datawww-datafog-1.42.0/tests/fogdocker/models/compute/0000755000004100000410000000000013171001215020434 5ustar www-datawww-datafog-1.42.0/tests/fogdocker/models/compute/image_tests.rb0000644000004100000410000000174213171001215023271 0ustar www-datawww-dataShindo.tests('Fog::Compute[:fogdocker] | image model', ['fogdocker']) do images = Fog::Compute[:fogdocker].images image = images.last.reload 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, :repo_tags, :created, :size ] 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-[:repo_tags]).each do |attribute| test("#{attribute}") { model_attribute_hash.key? attribute } end end end test('be a kind of Fog::Compute::Fogdocker::image') { image.kind_of? Fog::Compute::Fogdocker::Image } end end fog-1.42.0/tests/fogdocker/models/compute/server_tests.rb0000644000004100000410000000367013171001215023517 0ustar www-datawww-dataShindo.tests('Fog::Compute[:fogdocker] | server model', ['fogdocker']) do compute = Fog::Compute[:fogdocker] server = compute.servers.create(:name => "fog-#{Time.now.to_i}", 'image' => 'mattdm/fedora:f19','Cmd' => ['date']) tests('The server model should') do tests('have the action') do test('reload') { server.respond_to? 'reload' } %w{ start restart stop commit destroy}.each do |action| test(action) { server.respond_to? action } end %w{ start restart stop commit destroy}.each do |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, :name, :created, :ipaddress, :state_running, :memory, :cores, :cpu_shares, :hostname, :image, :attach_stdin, :attach_stdout, :attach_stderr, :state_exit_code, :state_pid, :port_bindings, :links, :privileged, :tty, :exposed_ports, :volumes, :environment_variables ] 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.key? attribute } end end end test('be a kind of Fog::Compute::Fogdocker::Server') { server.kind_of? Fog::Compute::Fogdocker::Server } end end fog-1.42.0/tests/fogdocker/models/compute/servers_tests.rb0000644000004100000410000000104713171001215023676 0ustar www-datawww-dataShindo.tests('Fog::Compute[:fogdocker] | servers collection', ['fogdocker']) do servers = Fog::Compute[:fogdocker].servers tests('The servers collection') do test('should not be empty') { not servers.empty? } test('should be a kind of Fog::Compute::Fogdocker::Servers') { servers.kind_of? Fog::Compute::Fogdocker::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.42.0/tests/fogdocker/models/compute/images_tests.rb0000644000004100000410000000043713171001215023454 0ustar www-datawww-dataShindo.tests('Fog::Compute[:fogdocker] | images collection', ['fogdocker']) do images = Fog::Compute[:fogdocker].images tests('The images collection') do test('should be a kind of Fog::Compute::Fogdocker::images') { images.kind_of? Fog::Compute::Fogdocker::Images } end end fog-1.42.0/tests/compute/0000755000004100000410000000000013171001215015206 5ustar www-datawww-datafog-1.42.0/tests/compute/helper.rb0000644000004100000410000000575513171001215017026 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 }, :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' }, :egress_firewall_rule_attributes => { :protocol => "tcp", :network_id => "8aacae29-e0a4-4b7b-8a7a-3ee11cfb4362", :cidr_list =>"10.1.1.0/24"}, :public_ip_address_attributes => {}.tap do |hash| [:zone_id].each do |k| key = "cloudstack_#{k}".to_sym if Fog.credentials[key] hash[k]= Fog.credentials[key] end end end, :mocked => true }, :glesys => { :server_attributes => { :rootpassword => "secret_password_#{Time.now.to_i}", :hostname => "fog.example#{Time.now.to_i}.com" }, :mocked => false }, :ibm => { :server_attributes => {}, :mocked => true }, :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 } } end fog-1.42.0/tests/compute/models/0000755000004100000410000000000013171001215016471 5ustar www-datawww-datafog-1.42.0/tests/compute/models/flavors_tests.rb0000644000004100000410000000062313171001215021715 0ustar www-datawww-datafor provider, config in compute_providers next if [:glesys, :ibm].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.42.0/tests/compute/models/server_tests.rb0000644000004100000410000000252113171001215021546 0ustar www-datawww-datafor provider, config in compute_providers 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(:public_ip_address) responds_to(:scp) responds_to(:ssh) end tests('ssh_ip_address') do tests('defaults to public_ip_address').returns(true) do @instance.ssh_ip_address == @instance.public_ip_address end tests('ssh_ip_address overrides default with Proc').returns(true) do ip_address = '5.5.5.5' @instance.ssh_ip_address = Proc.new {|server| ip_address } @instance.ssh_ip_address == ip_address end tests('Proc yields server').returns(true) do @instance.ssh_ip_address = Proc.new {|server| server } @instance.ssh_ip_address == @instance end tests('ssh_ip_address overrides default with String').returns(true) do ip_address = '5.5.5.5' @instance.ssh_ip_address = ip_address @instance.ssh_ip_address == ip_address end end end end end fog-1.42.0/tests/compute/models/servers_tests.rb0000644000004100000410000000054313171001215021733 0ustar www-datawww-datafor provider, config in compute_providers 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.42.0/tests/opennebula/0000755000004100000410000000000013171001215015662 5ustar www-datawww-datafog-1.42.0/tests/opennebula/requests/0000755000004100000410000000000013171001215017535 5ustar www-datawww-datafog-1.42.0/tests/opennebula/requests/compute/0000755000004100000410000000000013171001215021211 5ustar www-datawww-datafog-1.42.0/tests/opennebula/requests/compute/vm_allocate_tests.rb0000644000004100000410000000525113171001215025251 0ustar www-datawww-dataShindo.tests("Fog::Compute[:opennebula] | vm_create and vm_destroy request", 'opennebula') do compute = Fog::Compute[:opennebula] name_base = Time.now.to_i f = compute.flavors.get_by_name("fogtest") tests("Get 'fogtest' flavor/template") do test("could not get template with name 'fogtest'! This is required for live tests!") {f.kind_of? Array} raise ArgumentError, "Could not get a template with the name 'fogtest'" unless f end f = f.first response = {} tests("Allocate VM") do response = compute.vm_allocate({:name => 'fog-'+name_base.to_s, :flavor => f}) test("response should be a kind of Hash") { response.kind_of? Hash} test("id should be a one-id (Fixnum)") { response['id'].is_a? Fixnum} end tests("Destroy VM") do compute.vm_destroy(response['id']) test("vm should not be in array of vms") { vm_not_exist = true compute.list_vms.each do |vm| if vm['id'] == response['id'] vm_not_exist = false end end vm_not_exist } test("vm should not be in array of vms by filter") { vm_not_exist = true compute.list_vms({:id => response['id']}).each do |vm| if vm['id'] == response['id'] vm_not_exist = false end end vm_not_exist } 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 - no flavor") do begin response = compute.vm_allocate({:name => 'fog-'+name_base.to_s, :flavor => nil}) test("should be a kind of Hash") { response.kind_of? Hash} #mock never raise exceptions rescue => e #should raise vm name already exist exception. test("error should be a kind of ArgumentError") { e.kind_of? ArgumentError} end end tests("Fail Creating VM - nil name") do begin response = compute.vm_allocate({:name => nil, :flavor => f}) test("should be a kind of Hash") { response.kind_of? Hash} #mock never raise exceptions rescue => e #should raise vm name already exist exception. test("error should be a kind of ArgumentError") { e.kind_of? ArgumentError} end end tests("Fail Creating VM - empty name") do begin response = compute.vm_allocate({:name => "", :flavor => f}) test("should be a kind of Hash") { response.kind_of? Hash} #mock never raise exceptions rescue => e #should raise vm name already exist exception. test("error should be a kind of ArgumentError") { e.kind_of? ArgumentError} end end end fog-1.42.0/tests/opennebula/requests/compute/vm_suspend_resume_tests.rb0000644000004100000410000000260713171001215026530 0ustar www-datawww-dataShindo.tests("Fog::Compute[:opennebula] | vm_suspend and vm_resume request", 'opennebula') do compute = Fog::Compute[:opennebula] name_base = Time.now.to_i f = compute.flavors.get_by_name("fogtest") tests("Get 'fogtest' flavor/template") do test("Got template with name 'fogtest'") {f.kind_of? Array} raise ArgumentError, "Could not get a template with the name 'fogtest'! This is required for live tests!" unless f end f = f.first newvm = compute.servers.new newvm.flavor = f newvm.name = 'fogtest-'+name_base.to_s vm = newvm.save vm.wait_for { (vm.state == 'RUNNING') } tests("Suspend VM") do compute.vm_suspend(vm.id) vm.wait_for { (vm.state == 'LCM_INIT') } test("response status should be LCM_INIT and 5") { vm_state = false compute.list_vms.each do |vm_| if vm_['id'] == vm.id if vm_['state'] == 'LCM_INIT' && vm_['status'] == 5 vm_state = true end end end vm_state } end tests("Resume VM") do compute.vm_resume(vm.id) vm.wait_for { (vm.state == 'RUNNING') } test("response status should be LCM_INIT and 5") { vm_state = false compute.list_vms.each do |vm_| if vm_['id'] == vm.id if vm_['state'] == 'RUNNING' && vm_['status'] == 3 vm_state = true end end end vm_state } end vm.destroy end fog-1.42.0/tests/opennebula/requests/compute/vm_disk_snapshot_test.rb0000644000004100000410000000367413171001215026162 0ustar www-datawww-dataShindo.tests("Fog::Compute[:opennebula] | vm_create and destroy request", 'opennebula') do compute = Fog::Compute[:opennebula] name_base = Time.now.to_i f = compute.flavors.get_by_name("fogtest") tests("Get 'fogtest' flavor/template") do test("Got template with name 'fogtest'") {f.kind_of? Array} raise ArgumentError, "Could not get a template with the name 'fogtest'! This is required for live tests!" unless f end f = f.first newvm = compute.servers.new newvm.flavor = f newvm.name = 'fogtest-'+name_base.to_s vm = newvm.save tests("Start VM") do test("response should be a kind of Hash") { vm.kind_of? Fog::Compute::OpenNebula::Server} test("id should be a one-id (Fixnum)") { vm.id.is_a? Fixnum} vm.wait_for { (vm.state == 'RUNNING') } test("VM should be in RUNNING state") { vm.state == 'RUNNING' } sleep(30) # waiting for 30 seconds to let VM finish booting end tests("Create snapshot of the disk and shutdown VM") do img_id = compute.vm_disk_snapshot(vm.id, 0, 'fogtest-'+name_base.to_s) test("Image ID of created snapshot should be a kind of Fixnum") { img_id.is_a? Fixnum } (1..5).each do # wait maximum 5 seconds sleep(1) # The delay is needed for some reason between issueing disk-snapshot and shutdown images = compute.image_pool( { :mine => true, :id => img_id } ) test("Got Image with ID=#{img_id}") { images.kind_of? Array } if images[0].state == 4 # LOCKED, it is normal we must shutdown VM for image to go into READY state break end end compute.servers.shutdown(vm.id) image_state = 4 (1..25).each do # Waiting for up to 50 seconds for Image to become READY sleep(2) images = compute.image_pool( { :mine => true, :id => img_id } ) image_state = images[0].state if image_state == 1 break end end test("New image with ID=#{img_id} should be in state READY.") { image_state == 1 } end end fog-1.42.0/tests/opennebula/compute_tests.rb0000644000004100000410000000067613171001215021116 0ustar www-datawww-dataShindo.tests('Fog::Compute[:opennebula]', ['opennebula']) do compute = Fog::Compute[:opennebula] tests("Compute collections") do %w{networks groups}.each do |collection| test("it should respond to #{collection}") { compute.respond_to? collection } end end tests("Compute requests") do %w{list_networks}.each do |request| test("it should respond to #{request}") { compute.respond_to? request } end end end fog-1.42.0/tests/opennebula/models/0000755000004100000410000000000013171001215017145 5ustar www-datawww-datafog-1.42.0/tests/opennebula/models/compute/0000755000004100000410000000000013171001215020621 5ustar www-datawww-datafog-1.42.0/tests/opennebula/models/compute/networks_tests.rb0000644000004100000410000000131213171001215024241 0ustar www-datawww-dataShindo.tests('Fog::Compute[:opennebula] | networks collection', ['opennebula']) do networks = Fog::Compute[:opennebula].networks tests('The networks collection') do test('should be a kind of Fog::Compute::OpenNebula::Networks') { networks.kind_of? Fog::Compute::OpenNebula::Networks } tests('should be able to reload itself').succeeds { networks.reload } tests('should be able to get a model') do tests('all').succeeds { networks.all } tests('by instance id').succeeds { networks.get networks.first.id } tests('by filter').succeeds { networks.get_by_filter ({ :id => networks.first.id }) } tests('by name').succeeds { networks.get_by_name ("fogtest") } end end end fog-1.42.0/tests/opennebula/models/compute/flavors_tests.rb0000644000004100000410000000132313171001215024043 0ustar www-datawww-dataShindo.tests('Fog::Compute[:opennebula] | flavors collection', ['opennebula']) do flavors = Fog::Compute[:opennebula].flavors tests('The flavors collection should') do test('should be a kind of Fog::Compute::OpenNebula::Flavors') { flavors.kind_of? Fog::Compute::OpenNebula::Flavors } tests('should be able to reload itself').succeeds { flavors.reload } tests('should be able to get models') do tests('all').succeeds { flavors.all } tests('by instance id').succeeds { flavors.get flavors.first.id } tests('by name').succeeds { flavors.get_by_name "fogtest" } tests('by filter').succeeds { flavors.get_by_filter ({:name => "fogtest", :id => flavors.first.id }) } end end end fog-1.42.0/tests/opennebula/models/compute/flavor_tests.rb0000644000004100000410000000314313171001215023662 0ustar www-datawww-dataShindo.tests('Fog::Compute[:opennebula] | flavor model', ['opennebula']) do flavors = Fog::Compute[:opennebula].flavors flavor = flavors.get_by_name('fogtest').last 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 tests("The flavor model should respond to") do [:name, :id, :to_label, :to_s, :get_cpu, :get_vcpu, :get_memory, :get_raw, :get_disk, :get_os, :get_graphics, :get_nic, :get_sched_ds_requirements, :get_sched_ds_rank, :get_sched_requirements, :get_sched_rank, :get_context, :get_user_variables].each do |attribute| test("#{attribute}") { flavor.respond_to? attribute } end end tests("The attributes hash should have key") do [:name, :id, :content, :cpu, :vcpu, :memory, :os, :graphics, :context, :user_variables ].each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::OpenNebula::Flavor') { flavor.kind_of? Fog::Compute::OpenNebula::Flavor } test('have a nic in network fogtest') { flavor.nic[0].vnet.name == "fogtest" } flavor.vcpu = 666 flavor.memory = 666 test('have a 666 MB memory') { flavor.get_memory == "MEMORY=666\n" } test('have a 666 CPUs') { flavor.get_vcpu == "VCPU=666\n" } test('raw parsed properly') { flavor.get_raw == %|RAW=["DATA"="core2duo", "TYPE"="kvm"]\n| } end end fog-1.42.0/tests/opennebula/models/compute/network_tests.rb0000644000004100000410000000167113171001215024066 0ustar www-datawww-dataShindo.tests('Fog::Compute[:opennebula] | network model', ['opennebula']) do networks = Fog::Compute[:opennebula].networks network = networks.get_by_name('fogtest') 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 tests("The network model should respond to") do [:name, :id, :vlan, :uid, :uname, :gid, :description].each do |attribute| test("#{attribute}") { network.respond_to? attribute } end end tests("The attributes hash should have key") do [:name, :id, :uid, :uname, :gid ].each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::OpenNebula::Network') { network.kind_of? Fog::Compute::OpenNebula::Network } end end fog-1.42.0/tests/opennebula/models/compute/groups_tests.rb0000644000004100000410000000116413171001215023711 0ustar www-datawww-dataShindo.tests('Fog::Compute[:opennebula] | groups collection', ['opennebula']) do groups = Fog::Compute[:opennebula].groups tests('The groups collection') do test('should be a kind of Fog::Compute::OpenNebula::Groups') { groups.kind_of? Fog::Compute::OpenNebula::Groups } tests('should be able to reload itself').succeeds { groups.reload } tests('should be able to get a model by id') do tests('by instance id').succeeds { groups.get groups.first.id } end tests('should be able to get a model by name') do tests('by instance id').succeeds { groups.get_by_name "fogtest" } end end end fog-1.42.0/tests/opennebula/models/compute/group_tests.rb0000644000004100000410000000155613171001215023533 0ustar www-datawww-dataShindo.tests('Fog::Compute[:opennebula] | group model', ['opennebula']) do groups = Fog::Compute[:opennebula].groups group = groups.last tests('The group model should') do tests('have the action') do test('reload') { group.respond_to? 'reload' } end tests('have attributes') do model_attribute_hash = group.attributes attributes = tests("The group model should respond to") do [:name, :id, :to_label].each do |attribute| test("#{attribute}") { group.respond_to? attribute } end end tests("The attributes hash should have key") do [:name, :id].each do |attribute| test("#{attribute}") { model_attribute_hash.has_key? attribute } end end end test('be a kind of Fog::Compute::OpenNebula::Group') { group.kind_of? Fog::Compute::OpenNebula::Group } end end fog-1.42.0/tests/helpers/0000755000004100000410000000000013171001215015174 5ustar www-datawww-datafog-1.42.0/tests/helpers/responds_to_helper.rb0000644000004100000410000000037413171001215021423 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.42.0/tests/helpers/formats_helper.rb0000644000004100000410000000705613171001215020543 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.42.0/tests/helpers/succeeds_helper.rb0000644000004100000410000000020613171001215020654 0ustar www-datawww-datamodule Shindo class Tests def succeeds test('succeeds') do !!instance_eval(&Proc.new) end end end end fog-1.42.0/tests/helpers/collection_helper.rb0000644000004100000410000000502713171001215021217 0ustar www-datawww-datadef collection_tests(collection, params = {}, mocks_implemented = true) tests('success') do tests("#new(#{params.inspect})").succeeds do pending if Fog.mocking? && !mocks_implemented collection.new(params) end tests("#create(#{params.inspect})").succeeds do pending if Fog.mocking? && !mocks_implemented @instance = collection.create(params) end # FIXME: work around for timing issue on AWS describe_instances mocks if Fog.mocking? && @instance.respond_to?(:ready?) @instance.wait_for { ready? } end tests("#all").succeeds do pending if Fog.mocking? && !mocks_implemented collection.all end if !Fog.mocking? || mocks_implemented @identity = @instance.identity end tests("#get(#{@identity})").succeeds do pending if Fog.mocking? && !mocks_implemented collection.get(@identity) end tests('Enumerable') do pending if Fog.mocking? && !mocks_implemented methods = [ 'all?', 'any?', 'find', 'detect', 'collect', 'map', 'find_index', 'flat_map', 'collect_concat', 'group_by', 'none?', 'one?' ] # JRuby 1.7.5+ issue causes a SystemStackError: stack level too deep # https://github.com/jruby/jruby/issues/1265 if RUBY_PLATFORM == "java" and JRUBY_VERSION =~ /1\.7\.[5-8]/ methods.delete('all?') end methods.each do |enum_method| if collection.respond_to?(enum_method) tests("##{enum_method}").succeeds do block_called = false collection.send(enum_method) {|x| block_called = true } block_called end end end [ 'max_by','min_by' ].each do |enum_method| if collection.respond_to?(enum_method) tests("##{enum_method}").succeeds do block_called = false collection.send(enum_method) {|x| block_called = true; 0 } block_called end end end end if block_given? yield(@instance) end if !Fog.mocking? || mocks_implemented @instance.destroy end end tests('failure') do if !Fog.mocking? || mocks_implemented @identity = @identity.to_s @identity = @identity.gsub(/[a-zA-Z]/) { Fog::Mock.random_letters(1) } @identity = @identity.gsub(/\d/) { Fog::Mock.random_numbers(1) } @identity end tests("#get('#{@identity}')").returns(nil) do pending if Fog.mocking? && !mocks_implemented collection.get(@identity) end end end fog-1.42.0/tests/helpers/compute/0000755000004100000410000000000013171001215016650 5ustar www-datawww-datafog-1.42.0/tests/helpers/compute/servers_helper.rb0000644000004100000410000000041013171001215022220 0ustar www-datawww-datadef servers_tests(connection, params = {}, mocks_implemented = true) collection_tests(connection.servers, params, mocks_implemented) do if !Fog.mocking? || mocks_implemented @instance.wait_for { ready? } yield if block_given? end end end fog-1.42.0/tests/helpers/compute/server_helper.rb0000644000004100000410000000124613171001215022045 0ustar www-datawww-datadef server_tests(connection, params = {}, mocks_implemented = true) model_tests(connection.servers, params, mocks_implemented) do tests('#reload').returns(true) do pending if Fog.mocking? && !mocks_implemented @instance.wait_for { ready? } identity = @instance.identity !identity.nil? && identity == @instance.reload.identity end responds_to([:ready?, :state]) yield if block_given? tests('#reboot').succeeds do pending if Fog.mocking? && !mocks_implemented @instance.wait_for { ready? } @instance.reboot end if !Fog.mocking? || mocks_implemented @instance.wait_for { ready? } end end end fog-1.42.0/tests/helpers/compute/flavors_helper.rb0000644000004100000410000000146313171001215022214 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.42.0/tests/helpers/model_helper.rb0000644000004100000410000000141413171001215020160 0ustar www-datawww-datadef model_tests(collection, params = {}, mocks_implemented = true) tests('success') do @instance = collection.new(params) tests("#save").succeeds do pending if Fog.mocking? && !mocks_implemented @instance.save end if block_given? yield(@instance) end tests("#destroy").succeeds do pending if Fog.mocking? && !mocks_implemented @instance.destroy end end end # Generates a unique identifier with a random differentiator. # Useful when rapidly re-running tests, so we don't have to wait # serveral minutes for deleted objects to disappear from the API # E.g. 'fog-test-1234' def uniq_id(base_name = 'fog-test') # random_differentiator suffix = rand(65536).to_s(16).rjust(4, '0') [base_name, suffix] * '-' end fog-1.42.0/tests/helpers/formats_helper_tests.rb0000644000004100000410000000702013171001215021754 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.42.0/tests/helpers/mock_helper.rb0000644000004100000410000001131013171001215020005 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', :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', :cloudstack_project_id => 'f1f1f1f1-f1f1-f1f1-f1f1-f1f1f1f1f1f1', :clodo_api_key => 'clodo_api_key', :clodo_username => 'clodo_username', :digitalocean_api_key => 'digitalocean_api_key', :digitalocean_client_id => 'digitalocean_client_id', :digitalocean_token => 'digitalocean_token', :dnsimple_email => 'dnsimple_email', :dnsimple_password => 'dnsimple_password', :dnsmadeeasy_api_key => 'dnsmadeeasy_api_key', :dnsmadeeasy_secret_key => 'dnsmadeeasy_secret_key', :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', :hp_access_key => 'hp_access_key', :hp_secret_key => 'hp_secret_key', :hp_tenant_id => 'hp_tenant_id', :hp_avl_zone => 'hp_avl_zone', :hp_auth_uri => 'http://hp/v2.0/tokens', :os_account_meta_temp_url_key => 'os_account_meta_temp_url_key', :ibm_username => 'ibm_username', :ibm_password => 'ibm_password', :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', # :public_key_path => '~/.ssh/id_rsa.pub', # :private_key_path => '~/.ssh/id_rsa', :opennebula_endpoint => 'http://opennebula:2633/RPC2', :opennebula_username => 'oneadmin', :opennebula_password => 'oneadmin', :openstack_api_key => 'openstack_api_key', :openstack_username => 'openstack_username', :openstack_tenant => 'openstack_tenant', :openstack_auth_url => 'http://openstack:35357/v2.0/tokens', :profitbricks_username => 'profitbricks_username', :profitbricks_password => 'profitbricks_password', :rackspace_api_key => 'rackspace_api_key', :rackspace_region => 'dfw', :rackspace_username => 'rackspace_username', :sakuracloud_api_token => 'sakuracloud_api_token', :sakuracloud_api_token_secret => 'sakuracloud_api_token_secret', :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', :zerigo_email => 'zerigo_email', :zerigo_token => 'zerigo_token', :dynect_customer => 'dynect_customer', :dynect_username => 'dynect_username', :dynect_password => 'dynect_password', :cloudsigma_username => 'csuname', :cloudsigma_password => 'cspass', :docker_username => 'docker-fan', :docker_password => 'i<3docker', :docker_email => 'dockerfan@gmail.com', :docker_url => 'unix://var/run/docker.sock' }.merge(Fog.credentials) end fog-1.42.0/tests/helpers/schema_validator_tests.rb0000644000004100000410000000723113171001215022253 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.42.0/tests/bluebox/0000755000004100000410000000000013171001215015172 5ustar www-datawww-datafog-1.42.0/tests/bluebox/requests/0000755000004100000410000000000013171001215017045 5ustar www-datawww-datafog-1.42.0/tests/bluebox/requests/dns/0000755000004100000410000000000013171001215017631 5ustar www-datawww-datafog-1.42.0/tests/bluebox/requests/dns/dns_tests.rb0000644000004100000410000001463113171001215022171 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.42.0/tests/bluebox/requests/compute/0000755000004100000410000000000013171001215020521 5ustar www-datawww-datafog-1.42.0/tests/bluebox/requests/compute/helper.rb0000644000004100000410000000043613171001215022330 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.42.0/tests/bluebox/requests/compute/template_tests.rb0000644000004100000410000000172313171001215024106 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.42.0/tests/bluebox/requests/compute/product_tests.rb0000644000004100000410000000152313171001215023751 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.42.0/tests/bluebox/requests/compute/block_tests.rb0000644000004100000410000000564013171001215023367 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, 'vsh_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.42.0/tests/bluebox/requests/compute/location_tests.rb0000644000004100000410000000153013171001215024077 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 end fog-1.42.0/tests/bluebox/requests/blb/0000755000004100000410000000000013171001215017604 5ustar www-datawww-datafog-1.42.0/tests/bluebox/requests/blb/helper.rb0000644000004100000410000000306213171001215021411 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.42.0/tests/bluebox/requests/blb/lb_tests.rb0000644000004100000410000000672113171001215021756 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.42.0/tests/clodo/0000755000004100000410000000000013171001215014632 5ustar www-datawww-datafog-1.42.0/tests/clodo/requests/0000755000004100000410000000000013171001215016505 5ustar www-datawww-datafog-1.42.0/tests/clodo/requests/compute/0000755000004100000410000000000013171001215020161 5ustar www-datawww-datafog-1.42.0/tests/clodo/requests/compute/image_tests.rb0000644000004100000410000000135313171001215023014 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.42.0/tests/clodo/requests/compute/server_tests.rb0000644000004100000410000001335513171001215023245 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.42.0/tests/openvz/0000755000004100000410000000000013171001215015053 5ustar www-datawww-datafog-1.42.0/tests/openvz/helper.rb0000644000004100000410000000214613171001215016662 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.42.0/tests/openvz/models/0000755000004100000410000000000013171001215016336 5ustar www-datawww-datafog-1.42.0/tests/openvz/models/compute/0000755000004100000410000000000013171001215020012 5ustar www-datawww-datafog-1.42.0/tests/openvz/models/compute/server_tests.rb0000644000004100000410000000225113171001215023067 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.42.0/tests/openvz/models/compute/servers_tests.rb0000644000004100000410000000154613171001215023260 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.42.0/tests/cloudstack/0000755000004100000410000000000013171001215015666 5ustar www-datawww-datafog-1.42.0/tests/cloudstack/requests/0000755000004100000410000000000013171001215017541 5ustar www-datawww-datafog-1.42.0/tests/cloudstack/requests/security_group_tests.rb0000644000004100000410000000135413171001215024376 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 end fog-1.42.0/tests/cloudstack/requests/service_offering_tests.rb0000644000004100000410000000143213171001215024627 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | service offering requests', ['cloudstack']) do @service_offerings_format = { 'listserviceofferingsresponse' => { 'count' => Integer, 'serviceoffering' => [ 'id' => String, 'name' => String, 'displaytext' => String, 'cpuspeed' => Integer, 'cpunumber' => Integer, 'memory' => Integer, 'created' => String, 'storagetype' => String, 'offerha' => Fog::Boolean, 'limitcpuuse' => Fog::Boolean, 'issystem' => Fog::Boolean, 'defaultuse' => Fog::Boolean ] } } tests('success') do tests('#list_service_offerings').formats(@service_offerings_format) do Fog::Compute[:cloudstack].list_service_offerings end end end fog-1.42.0/tests/cloudstack/requests/egress_firewall_rule_tests.rb0000644000004100000410000000114313171001215025513 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | egress firewall rule requests', ['cloudstack']) do @egress_firewall_rules_format = { 'listegressfirewallrulesresponse' => { 'count' => Integer, 'firewallrule' => [ 'id' => String, 'protocol' => String, 'networkid' => String, 'state' => String, 'cidrlist' => String, 'tags' => Fog::Nullable::Array ] } } tests('success') do tests('#list_egress_firewall_rules').formats(@egress_firewall_rules_format) do Fog::Compute[:cloudstack].list_egress_firewall_rules end end end fog-1.42.0/tests/cloudstack/requests/template_tests.rb0000644000004100000410000000320113171001215023117 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 end fog-1.42.0/tests/cloudstack/requests/firewall_rule_tests.rb0000644000004100000410000000126613171001215024151 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | firewall rule requests', ['cloudstack']) do @firewall_rules_format = { 'listfirewallrulesresponse' => { 'count' => Integer, 'firewallrule' => [ 'id' => String, 'protocol' => String, 'startport' => String, 'endport' => String, 'ipaddressid' => String, 'networkid' => String, 'ipaddress' => String, 'state' => String, 'cidrlist' => String, 'tags' => Fog::Nullable::Array ] } } tests('success') do tests('#list_firewall_rules').formats(@firewall_rules_format) do Fog::Compute[:cloudstack].list_firewall_rules end end end fog-1.42.0/tests/cloudstack/requests/snapshot_tests.rb0000644000004100000410000000134713171001215023154 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 end fog-1.42.0/tests/cloudstack/requests/public_ip_address_tests.rb0000644000004100000410000000204513171001215024764 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | public ip address requests', ['cloudstack']) do @public_ip_addresses_format = { 'listpublicipaddressesresponse' => { 'count' => Integer, 'publicipaddress' => [ 'id' => String, 'ipaddress' => String, 'allocated' => String, 'zoneid' => String, 'zonename' => String, 'issourcenat' => Fog::Boolean, 'projectid' => String, 'project' => String, 'domainid' => String, 'domain' => String, 'forvirtualnetwork' => Fog::Boolean, 'isstaticnat' => Fog::Boolean, 'issystem' => Fog::Boolean, 'associatednetworkid' => String, 'associatednetworkname' => String, 'networkid' => String, 'state' => String, 'physicalnetworkid' => String, 'tags' => Fog::Nullable::Array ] } } tests('success') do tests('#list_public_ip_addresses').formats(@public_ip_addresses_format) do Fog::Compute[:cloudstack].list_public_ip_addresses end end end fog-1.42.0/tests/cloudstack/requests/network_offering_tests.rb0000644000004100000410000000152413171001215024662 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | network offering requests', ['cloudstack']) do @network_offerings_format = { 'listnetworkofferingsresponse' => { 'count' => Integer, 'networkoffering' => [ 'id' => String, 'name' => String, 'displaytext' => String, 'traffictype' => String, 'isdefault' => Fog::Boolean, 'specifyvlan' => Fog::Boolean, 'conservemode' => Fog::Boolean, 'specifyipranges' => Fog::Boolean, 'availability' => String, 'networkrate' => Integer, 'state' => String, 'guestiptype' => String, 'serviceofferingid' => String, ] } } tests('success') do tests('#list_network_offerings').formats(@network_offerings_format) do Fog::Compute[:cloudstack].list_network_offerings end end end fog-1.42.0/tests/cloudstack/requests/ssh_key_pair_tests.rb0000644000004100000410000000077213171001215023776 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 end fog-1.42.0/tests/cloudstack/requests/virtual_machine_tests.rb0000644000004100000410000000425113171001215024464 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.42.0/tests/cloudstack/requests/port_forwarding_rule_tests.rb0000644000004100000410000000163413171001215025551 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | port forwarding rule requests', ['cloudstack']) do @port_forwarding_rule_format = { 'listportforwardingrulesresponse' => { 'count' => Integer, 'portforwardingrule' => [ 'id' => String, 'privateport' => String, 'privateendport' => String, 'protocol' => String, 'publicport' => String, 'publicendport' => String, 'virtualmachineid' => String, 'virtualmachinename' => String, 'virtualmachinedisplayname' => String, 'ipaddressid' => String, 'ipaddress' => String, 'state' => String, 'cidrlist' => String, 'tags' => Fog::Nullable::Array ] } } tests('success') do tests('#list_port_forwarding_rules').formats(@port_forwarding_rule_format) do Fog::Compute[:cloudstack].list_port_forwarding_rules('zoneid' => 1) end end end fog-1.42.0/tests/cloudstack/requests/disk_offering_tests.rb0000644000004100000410000000133513171001215024123 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 end fog-1.42.0/tests/cloudstack/requests/zone_tests.rb0000644000004100000410000000157313171001215022271 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.42.0/tests/cloudstack/requests/volume_tests.rb0000644000004100000410000000265313171001215022625 0ustar www-datawww-dataShindo.tests('Fog::Compute[:cloudstack] | volume requests', ['cloudstack']) do @volumes_format = { 'listvolumesresponse' => { 'count' => Integer, 'volume' => [ 'id' => String, 'name' => String, 'zoneid' => String, 'zonename' => String, 'type' => String, 'size' => Integer, 'created' => String, 'account' => String, 'domainid' => String, 'domain' => String, 'state' => String, 'storagetype' => String, 'hypervisor' => String, 'diskofferingid' => Fog::Nullable::String, 'diskofferingname' => Fog::Nullable::String, 'diskofferingdisplaytext' => Fog::Nullable::String, 'storage' => String, 'destroyed' => Fog::Boolean, 'isextractable' => Fog::Boolean, 'deviceid' => Fog::Nullable::Integer, 'virtualmachineid' => Fog::Nullable::String, '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 Fog::Compute[:cloudstack].list_volumes('zoneid' => 1) end end end fog-1.42.0/tests/cloudstack/requests/os_type_tests.rb0000644000004100000410000000141213171001215022770 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 end fog-1.42.0/tests/cloudstack/compute/0000755000004100000410000000000013171001215017342 5ustar www-datawww-datafog-1.42.0/tests/cloudstack/compute/models/0000755000004100000410000000000013171001215020625 5ustar www-datawww-datafog-1.42.0/tests/cloudstack/compute/models/security_group_tests.rb0000644000004100000410000000077213171001215025465 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.42.0/tests/cloudstack/compute/models/egress_firewall_rule_tests.rb0000644000004100000410000000041713171001215026602 0ustar www-datawww-dataShindo.tests("Fog::Compute[:cloudstack] | egress_firewall_rule", "cloudstack") do config = compute_providers[:cloudstack] compute = Fog::Compute[:cloudstack] model_tests(compute.egress_firewall_rules, config[:egress_firewall_rule_attributes], config[:mocked]) end fog-1.42.0/tests/cloudstack/compute/models/server_tests.rb0000644000004100000410000000120613171001215023701 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.42.0/tests/cloudstack/compute/models/security_groups_tests.rb0000644000004100000410000000076213171001215025647 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.42.0/tests/cloudstack/compute/models/snapshot_tests.rb0000644000004100000410000000077013171001215024237 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.42.0/tests/cloudstack/compute/models/public_ip_address_tests.rb0000644000004100000410000000132113171001215026044 0ustar www-datawww-dataShindo.tests("Fog::Compute[:cloudstack] | public_ip_address", "cloudstack") do config = compute_providers[:cloudstack] compute = Fog::Compute[:cloudstack] model_tests(compute.public_ip_addresses, config[:public_ip_address_attributes], config[:mocked]) do @server = Fog::Compute[:cloudstack].servers.create(config[:server_attributes]) @server.wait_for { ready? } tests('#server=').succeeds do @instance.server = @server end tests('#server') do test(' == @server') do @instance.reload @instance.server_id == @server.id end end test('#server = nil') do @instance.server = nil @instance.server_id.nil? end @server.destroy end end fog-1.42.0/tests/cloudstack/compute/models/volumes_tests.rb0000644000004100000410000000067113171001215024072 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.42.0/tests/cloudstack/compute/models/public_ip_addresses_tests.rb0000644000004100000410000000024713171001215026402 0ustar www-datawww-dataShindo.tests("Fog::Compute[:cloudstack] | public_ip_addresses", ['cloudstack']) do collection_tests(Fog::Compute[:cloudstack].public_ip_addresses, {}, true) end fog-1.42.0/tests/cloudstack/compute/models/disk_offering_tests.rb0000644000004100000410000000037113171001215025206 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.42.0/tests/cloudstack/compute/models/volume_tests.rb0000644000004100000410000000150013171001215023677 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.42.0/tests/cloudstack/compute/models/security_group_rule_tests.rb0000644000004100000410000000165613171001215026516 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.42.0/tests/cloudstack/signed_params_tests.rb0000644000004100000410000000154113171001215022252 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.42.0/tests/dreamhost/0000755000004100000410000000000013171001215015520 5ustar www-datawww-datafog-1.42.0/tests/dreamhost/helper.rb0000644000004100000410000000103613171001215017324 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.42.0/tests/dreamhost/dns_tests.rb0000644000004100000410000000123213171001215020051 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.42.0/tests/dreamhost/requests/0000755000004100000410000000000013171001215017373 5ustar www-datawww-datafog-1.42.0/tests/dreamhost/requests/dns/0000755000004100000410000000000013171001215020157 5ustar www-datawww-datafog-1.42.0/tests/dreamhost/requests/dns/delete_record_tests.rb0000644000004100000410000000122113171001215024522 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.42.0/tests/dreamhost/requests/dns/create_record_tests.rb0000644000004100000410000000173213171001215024532 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.42.0/tests/dreamhost/requests/dns/list_records_tests.rb0000644000004100000410000000122613171001215024423 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.42.0/tests/dreamhost/models/0000755000004100000410000000000013171001215017003 5ustar www-datawww-datafog-1.42.0/tests/dreamhost/models/dns/0000755000004100000410000000000013171001215017567 5ustar www-datawww-datafog-1.42.0/tests/dreamhost/models/dns/zones_tests.rb0000644000004100000410000000122413171001215022473 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.42.0/tests/dreamhost/models/dns/zone_tests.rb0000644000004100000410000000307513171001215022316 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.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.42.0/tests/dreamhost/models/dns/records_tests.rb0000644000004100000410000000126113171001215022777 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.42.0/tests/dreamhost/models/dns/record_tests.rb0000644000004100000410000000376313171001215022625 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.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.42.0/tests/dreamhost/README.md0000644000004100000410000000317513171001215017005 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.42.0/.rubocop_todo.yml0000644000004100000410000002655213171001215015701 0ustar www-datawww-data# This configuration was generated by `rubocop --auto-gen-config` # on 2014-05-26 15:23:01 +0100 using RuboCop version 0.22.0. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. # Offense count: 85 AccessorMethodName: Enabled: false # Offense count: 139 # Cop supports --auto-correct. AlignArray: Enabled: false # Offense count: 449 # Cop supports --auto-correct. # Configuration parameters: EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle, SupportedLastArgumentHashStyles. AlignHash: Enabled: false # Offense count: 104 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. AlignParameters: Enabled: false # Offense count: 3 AmbiguousOperator: Enabled: false # Offense count: 4 AmbiguousRegexpLiteral: Enabled: false # Offense count: 221 # Cop supports --auto-correct. AndOr: Enabled: false # Offense count: 1 ArrayJoin: Enabled: false # Offense count: 9 AsciiComments: Enabled: false # Offense count: 594 # Configuration parameters: AllowSafeAssignment. AssignmentInCondition: Enabled: false # Offense count: 3 # Cop supports --auto-correct. Attr: Enabled: false # Offense count: 35 BlockAlignment: Enabled: false # Offense count: 56 BlockNesting: Max: 7 # Offense count: 230 # Cop supports --auto-correct. Blocks: Enabled: false # Offense count: 1366 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. BracesAroundHashParameters: Enabled: false # Offense count: 9 CaseEquality: Enabled: false # Offense count: 291 # Configuration parameters: IndentWhenRelativeTo, SupportedStyles, IndentOneStep. CaseIndentation: Enabled: false # Offense count: 2 # Configuration parameters: EnforcedStyle, SupportedStyles. ClassAndModuleChildren: Enabled: false # Offense count: 99 # Configuration parameters: CountComments. ClassLength: Max: 1131 # Offense count: 46 ClassVars: Enabled: false # Offense count: 41 # Cop supports --auto-correct. ColonMethodCall: Enabled: false # Offense count: 33 # Configuration parameters: Keywords. CommentAnnotation: Enabled: false # Offense count: 82 # Cop supports --auto-correct. CommentIndentation: Enabled: false # Offense count: 1 ConstantName: Enabled: false # Offense count: 450 CyclomaticComplexity: Max: 46 # Offense count: 29 # Cop supports --auto-correct. DefWithParentheses: Enabled: false # Offense count: 6310 Documentation: Enabled: false # Offense count: 42 # Configuration parameters: EnforcedStyle, SupportedStyles. DotPosition: Enabled: false # Offense count: 34 DoubleNegation: Enabled: false # Offense count: 16 EachWithObject: Enabled: false # Offense count: 2 ElseLayout: Enabled: false # Offense count: 13 # Cop supports --auto-correct. EmptyLines: Enabled: false # Offense count: 64 EmptyLinesAroundAccessModifier: Enabled: false # Offense count: 4 # Cop supports --auto-correct. EmptyLinesAroundBody: Enabled: false # Offense count: 40 # Cop supports --auto-correct. EmptyLiteral: Enabled: false # Offense count: 101 # Configuration parameters: AlignWith, SupportedStyles. EndAlignment: Enabled: false # Offense count: 8 Eval: Enabled: false # Offense count: 1 EvenOdd: Enabled: false # Offense count: 7 # Configuration parameters: Exclude. FileName: Enabled: false # Offense count: 175 # Configuration parameters: EnforcedStyle, SupportedStyles. For: Enabled: false # Offense count: 16 # Configuration parameters: EnforcedStyle, SupportedStyles. FormatString: Enabled: false # Offense count: 143 # Configuration parameters: MinBodyLength. GuardClause: Enabled: false # Offense count: 27 HandleExceptions: Enabled: false # Offense count: 21 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. HashSyntax: Enabled: false # Offense count: 486 # Configuration parameters: MaxLineLength. IfUnlessModifier: Enabled: false # Offense count: 54 # Cop supports --auto-correct. IndentArray: Enabled: false # Offense count: 990 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. IndentHash: Enabled: false # Offense count: 285 # Cop supports --auto-correct. IndentationConsistency: Enabled: false # Offense count: 310 # Cop supports --auto-correct. IndentationWidth: Enabled: false # Offense count: 7 Lambda: Enabled: false # Offense count: 655 # Cop supports --auto-correct. LeadingCommentSpace: Enabled: false # Offense count: 10 # Cop supports --auto-correct. LineEndConcatenation: Enabled: false # Offense count: 6 Loop: Enabled: false # Offense count: 66 # Cop supports --auto-correct. MethodCallParentheses: Enabled: false # Offense count: 87 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. MethodDefParentheses: Enabled: false # Offense count: 2036 # Configuration parameters: CountComments. MethodLength: Max: 1129 # Offense count: 13 # Configuration parameters: EnforcedStyle, SupportedStyles. MethodName: Enabled: false # Offense count: 21 MultilineBlockChain: Enabled: false # Offense count: 66 MultilineIfThen: Enabled: false # Offense count: 13 MultilineTernaryOperator: Enabled: false # Offense count: 85 # Cop supports --auto-correct. NegatedIf: Enabled: false # Offense count: 2 # Cop supports --auto-correct. NegatedWhile: Enabled: false # Offense count: 121 # Configuration parameters: EnforcedStyle, SupportedStyles. Next: Enabled: false # Offense count: 28 # Cop supports --auto-correct. NilComparison: Enabled: false # Offense count: 89 # Cop supports --auto-correct. # Configuration parameters: IncludeSemanticChanges. NonNilCheck: Enabled: false # Offense count: 56 # Cop supports --auto-correct. Not: Enabled: false # Offense count: 220 # Cop supports --auto-correct. NumericLiterals: MinDigits: 14 # Offense count: 3 OneLineConditional: Enabled: false # Offense count: 33 # Configuration parameters: CountKeywordArgs. ParameterLists: Max: 9 # Offense count: 63 # Cop supports --auto-correct. # Configuration parameters: AllowSafeAssignment. ParenthesesAroundCondition: Enabled: false # Offense count: 17 ParenthesesAsGroupedExpression: Enabled: false # Offense count: 189 # Cop supports --auto-correct. # Configuration parameters: PreferredDelimiters. PercentLiteralDelimiters: Enabled: false # Offense count: 24 # Cop supports --auto-correct. PerlBackrefs: Enabled: false # Offense count: 8 # Configuration parameters: NamePrefixBlacklist. PredicateName: Enabled: false # Offense count: 7 # Cop supports --auto-correct. Proc: Enabled: false # Offense count: 640 # Configuration parameters: EnforcedStyle, SupportedStyles. RaiseArgs: Enabled: false # Offense count: 25 # Cop supports --auto-correct. RedundantBegin: Enabled: false # Offense count: 4 RedundantException: Enabled: false # Offense count: 32 # Cop supports --auto-correct. # Configuration parameters: AllowMultipleReturnValues. RedundantReturn: Enabled: false # Offense count: 1939 # Cop supports --auto-correct. RedundantSelf: Enabled: false # Offense count: 66 # Configuration parameters: MaxSlashes. RegexpLiteral: Enabled: false # Offense count: 1 RequireParentheses: Enabled: false # Offense count: 5 # Cop supports --auto-correct. RescueException: Enabled: false # Offense count: 52 RescueModifier: Enabled: false # Offense count: 29 SelfAssignment: Enabled: false # Offense count: 62 # Cop supports --auto-correct. # Configuration parameters: AllowAsExpressionSeparator. Semicolon: Enabled: false # Offense count: 78 ShadowingOuterLocalVariable: Enabled: false # Offense count: 2 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. SignalException: Enabled: false # Offense count: 10 # Configuration parameters: Methods. SingleLineBlockParams: Enabled: false # Offense count: 9 # Cop supports --auto-correct. # Configuration parameters: AllowIfMethodIsEmpty. SingleLineMethods: Enabled: false # Offense count: 909 # Cop supports --auto-correct. SingleSpaceBeforeFirstArg: Enabled: false # Offense count: 4 # Cop supports --auto-correct. SpaceAfterColon: Enabled: false # Offense count: 581 # Cop supports --auto-correct. SpaceAfterComma: Enabled: false # Offense count: 15 # Cop supports --auto-correct. SpaceAfterControlKeyword: Enabled: false # Offense count: 1 # Cop supports --auto-correct. SpaceAfterMethodName: Enabled: false # Offense count: 19 # Cop supports --auto-correct. SpaceAfterNot: Enabled: false # Offense count: 1332 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. SpaceAroundEqualsInParameterDefault: Enabled: false # Offense count: 4362 # Cop supports --auto-correct. SpaceAroundOperators: Enabled: false # Offense count: 441 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. SpaceBeforeBlockBraces: Enabled: false # Offense count: 11 # Cop supports --auto-correct. SpaceBeforeComment: Enabled: false # Offense count: 19 SpaceBeforeFirstArg: Enabled: false # Offense count: 1946 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters. SpaceInsideBlockBraces: Enabled: false # Offense count: 146 # Cop supports --auto-correct. SpaceInsideBrackets: Enabled: false # Offense count: 6159 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SupportedStyles. SpaceInsideHashLiteralBraces: Enabled: false # Offense count: 720 # Cop supports --auto-correct. SpaceInsideParens: Enabled: false # Offense count: 3 # Cop supports --auto-correct. SpecialGlobalVars: Enabled: false # Offense count: 91 # Cop supports --auto-correct. StringConversionInInterpolation: Enabled: false # Offense count: 45608 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, SupportedStyles. StringLiterals: Enabled: false # Offense count: 197 Tab: Enabled: false # Offense count: 592 # Configuration parameters: EnforcedStyleForMultiline, SupportedStyles. TrailingComma: Enabled: false # Offense count: 125 # Cop supports --auto-correct. # Configuration parameters: ExactNameMatch, AllowPredicates, AllowDSLWriters, Whitelist. TrivialAccessors: Enabled: false # Offense count: 94 UnderscorePrefixedVariableName: Enabled: false # Offense count: 42 UnlessElse: Enabled: false # Offense count: 278 # Cop supports --auto-correct. UnusedBlockArgument: Enabled: false # Offense count: 1010 # Cop supports --auto-correct. UnusedMethodArgument: Enabled: false # Offense count: 6 UselessAccessModifier: Enabled: false # Offense count: 405 UselessAssignment: Enabled: false # Offense count: 3 UselessSetterCall: Enabled: false # Offense count: 13 # Cop supports --auto-correct. VariableInterpolation: Enabled: false # Offense count: 29 # Configuration parameters: EnforcedStyle, SupportedStyles. VariableName: Enabled: false # Offense count: 23 Void: Enabled: false # Offense count: 6 # Cop supports --auto-correct. WhileUntilDo: Enabled: false # Offense count: 1 # Configuration parameters: MaxLineLength. WhileUntilModifier: Enabled: false # Offense count: 521 # Cop supports --auto-correct. WordArray: MinSize: 29 fog-1.42.0/RELEASE.md0000644000004100000410000000262513171001215013777 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.md` * 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) * Run `rake github_release` to add release to [github release feed](https://github.com/fog/fog/releases.atom) (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.42.0/.irbrc0000644000004100000410000000426713171001215013503 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.42.0/CONTRIBUTORS.md0000644000004100000410000010555013171001215014655 0ustar www-datawww-data* A.S. Lomoff * Aaron Bell * Aaron Donovan * Aaron Huber * Aaron Suggs * Abhishek Chanda * Achim Ledermüller * Adam Bozanich * Adam Greene * Adam Heinz * Adam Reese * Adam Stegman and Zach Robinson * Adam Tanner * Adam Tucker * Adan Saenz * Ahmed Al Hafoudh * Ahmed Elsabbahy * Akira Matsuda * Akshay Joshi * Akshay Moghe * Alan Ivey * Albert Choi * Alex Coomans * Alex Dunn * Alex Gaudio * Alex Malinovich * Alex Malinovich * Alex Tambellini * Alexander Kolesen * Alexander Lomov * Alexander Wenzowski * Alfonso Juan Dillera * Alfonso Juan Dillera * Alfonso Juan Dillera * Alfred Moreno * Aliaksei Kliuchnikau * Allan * Allan * AltJ * Alvin Garcia * Alvin Garcia * Amitava * Amos Benari * Amy Sutedja * Amy Woodward * Andre Meij * Andreas Gerauer * Andreas Josephson * Andrei Serdeliuc * Andrew Brown * Andrew Bruce * Andrew Donald Kennedy * Andrew Hodges * Andrew Kuklewicz * Andrew Leonard * Andrew Newman * Andrew Newman * Andrew Stangl * Andrew Taylor * Andy Delcambre * Andy Lindeman * Angelo Marletta * Anna Shipman * Anshul Khandelwal * Anthony Accardi * Anthony Eden * Anton Lindstrom * Anton Lindström * Anton Lindström * Antonio <0x414f@gmail.com> * Ariel Zavala * Arnab * Artem * Artem Veremey * Arthur Gunawan * Arvid Andersson * Ash Wilson * Ash Wilson * Athir Nuaimi * Athir Nuaimi * Atsushi Sasaki * Avrohom Katz * BK Box * Barrett Jones * Bart Vercammen * Ben Bleything * Ben Burkert * Ben Butler-Cole * Ben Chadwick * Ben House * Ben Hundley * Ben Sandberg * Ben Turley * Benjamin Chadwick * Benjamin Manns * Benjamin Pillet * Benson Kalahar * Benton Roberts * Benton Roberts * Bert Hajee * Bill Wei * Blake Gentry * Blake Irvin and Eric Saxby * Bob Briski * Bob Lail and Luke Booth * Bobby Wilson * Bohuslav Kabrda * Brad Gignac * Brad Gignac * Brad Heller * Bradley Schaefer * Brandon Dunne * Brendan Fosberry * Brett Lentz * Brett Porter * Brian D. Burns * Brian Dorry * Brian Hartsock * Brian Hartsock * Brian Nelson * Brian O'Keefe * Brian Palmer * Brice Figureau * Bruno Enten * Bruz Marzolf * Bryan Paxton * Bulat Shakirzyanov * Caius Durling * Caleb Tennis * Carl Allen * Carl Caum * Carl Hicks * Carl Loa Odin * Carl Woodward * Carl Woodward * Carlos Sanchez * Casey Abernathy * Celso Fernandes * Cezar Sa Espinola * Chielo Zimmerman * Chirag Jog * Chirag Jog * Chirag Jog * Chmouel Boudjnah * Chris Chalstrom * Chris Chiodo * Chris Frederick * Chris Gianelloni * Chris Hasenpflug * Chris Howe * Chris Kershaw * Chris Luo * Chris Mague * Chris McClimans * Chris Roberts * Chris Thompson * Chris Thompson * Chris Wuest * Chris Wuest * Christian Berendt * Christian Höltje * Christian Ott * Christian Paredes * Christoffer Artmann * Christoph Schiessl * Christoph Witzany * Christophe Larsonneur * Christophe Roux * Christopher Meiklejohn * Christopher Oliver * Christopher Oliver * Christopher Snell * Claudio Poli * Coby Randquist * Cody Herriges * Colin Hebert * Colin Hebert * Curtis Stewart * Curtis Stewart * Cyrus Team * Dan Abel * Dan Bode * Dan Carley * Dan Peterson * Dan Prince * Dan Prince * Dan Prince * Dan Simpson * Daniel Aragao * Daniel Broudy * Daniel Libanori * Daniel Lobato * Daniel Reichert * Daniel Schweighoefer * Danny Garcia * Darren Foo * Darren Hague * Darrin Eden * Dave Benvenuti * Dave Donahue * Dave Myron * Dave Ungerer * David * David Andersen * David Calavera * David Chen * David Davis * David Faber * David Illsley * David Nalley * David Prater * David Wittman * Decklin Foster * Dejan Menges * Denis Barishev * Derek Richard and Karen Wang * Diego Desani * Dmitri Dolguikh * Dmitry Dedov * Dmitry Gutov * Dominic Cleal * DoubleMalt * Doug Henderson * Doug Henderson * Doug McInnes * Dr Nic Williams * Dusty Jones * Dusty Jones * Dylan Egan * Dylan Egan * E.J. Finneran * Edward Middleton * Edward Muller * Edward Muller * Edward Muller * Efe Yardimci * Efe Yardimci * Eric Abbott * Eric Boehs * Eric Chernuka * Eric Hankins * Eric Herot * Eric Hodel * Eric Johnson * Eric Lindvall * Eric Sakowski * Eric Stonfer * Eric Stonfer * Eric Stonfer * Eric Wong * Erik Mackdanz * Erik Michaels-Ober * Erik Terpstra * Erik van Pienbroek * Ethan Devenport * Eugene Howe & Josh Lane * Eugene Howe * Eugene Howe * Evan Light * Evan Petrie * Evan Petrie * Evan Smith * Evgeny Yurchenko * Ewoud Kohl van Wijngaarden * Fabian Wiesel * Fabio Lessa * Ferran Rodenas * Fletcher Nichol * Francois Herbert * Francois Herbert * Frederic Jean * Frederick Cheung * Fujimura Daisuke * Gabe Conradi * Gabriel Horner * Gabriel Rosendorf * Garima Singh * Garret Alfert * Gaurish Sharma * Gavin Sandie * Gavin Sandie * Geoff Pado * George Scott * Geraud * German Germanovich * Gerred Dillon * Glenn Tweedie * Graeme Wilson * Greg Blomquist * Greg Burek * Greg Sutcliffe * Greg Sutcliffe * Grégory Karékinian * Grzesiek Kolodziejczyk * Guilherme Souza * Gustavo Villalta * H. Wade Minter * H. Wade Minter * Harry Wilkinson * Hector Castro * Hemant Kumar * Hendrik Volkmer * Henry Addison * Hippie Hacker * Hiro Asari * Hongbin Lu * Hunter Haugen * Hunter Nield * Ian Downes * Igor Bolotin * Igor Rodionov * Igor Rodionov * Ijonas Kisselbach * Ilja Bobkevic * Irio Irineu Musskopf Junior * Isaac Hollander McCreery * Istvan Hoka * JD Huntington & Jason Hansen * JJ Asghar * Jacob Burkhart & Shai Rosenfeld * Jacob Mattingley * Jade Tucker * James Belchamber * James Bence * James Fairbairn * James Findley * James Fraser * James Healy * James Herdman * James Miller * James Rose * James Rose * James Stremick * James W. Brinkerhoff * Jamie H * Jamie Paton * Jan Raasch * Jared Everett * Jaroslav Barton * Jason Faulkner * Jason Hansen & Josh Lane * Jason Hansen * Jason Montleon * Jason Roelofs * Jason Smith * Jay Faulkner * Jay Perry * Jeff McCune * Jeff Moody * Jeffrey C. Ollie * Jens Braeuer * Jeremy Deininger * Jesse Davis * Jesse Hallett * Jesse Newland * Jesse Proudman * Jesse Proudman * Jesse Scott * Jim Berlage * Jim Salinas * Joachim Nolten * Joakim Kolsjö and Tomas Skogberg * Joe Kinsella * Joe Rafaniello * Joe Topjian * Joe Yates * John Dyer * John E. Vincent * John F. Douthat * John Feminella * John Ferlito * John Hawthorn * John Keiser * John Nishinaga * John Parker * John Wang * John Wang * Jon Crosby * Jon Frisby * Jon Holt * Jon K Hellan * Jon Palmer * Jon Palmer * Jon Topper * Jon-Erik Schneiderhan * Jonas Kongslund * Jonas Kongslund * Jonas Pfenniger * Jonas Pfenniger * Jonathan Serafini * Jonathon Scanes * Joonas Reynders * Jordan Day * Jordan Running * Jose Diaz-Gonzalez * Jose Luis Salas * Josef Stribny * Joseph Anthony Pasquale Holsten * Josh Blancett * Josh Kalderimis * Josh Kearney * Josh Lane & Ines Sombra * Josh Lane & Jason Hansen * Josh Lane & Thom Mahoney * Josh Lane * Josh Lane * Josh Lane * Josh Pasqualetto * Josh Yotty * Joshua Garnett * Joshua Gross * Joshua Krall * Joshua Napoli * Joshua Napoli * Joshua Nichols * Joshua Schairbaum * Josué Lima * Julian Fischer * Julian Weber * Julian Weber * Julio Feijo * Juris Galang * Justin Barry * Justin Clayton * Justin Pratt * Justin Pratt * KATOH Yasufumi * Kaloyan Kanev * Karan Misra * Karl Freeman * Kashif Rasul * Keith Barrette * Keith Duncan * Kelsey Hightower * Kenji Kabashima * Kenny Johnston * Kevin Chan * Kevin McFadden * Kevin Menard * Kevin Menard * Kevin Moore * Kevin Olbrich * Kieran Pilkington * Konstantin Haase * Konstantinos Natsakis * Kunal Parikh * Kunal Thakar * Kyla Kolb * Kyle Drake * Kyle Rames * Kyle Rames * Kyle Tolle * Ladislav Smola * Lance Carlson * Lance Ivy * Larry Gilbert * Larry Wright * Lars Pind * Laurent Bigonville * Lee Henson * Lee Huffman * Lee Huffman * Lee Jensen * Len * Lincoln Stoll * Lincoln Stoll * Lucas Carlson * Luiz Ribeiro * Lukas Zapletal * Luke Robins * Lum * Luqman Amjad * MaF * Manuel Meurer * Marc G Gauthier * Marc Grimme * Marc Grimme * Marc Seeger * Marc Seeger * Marcin Owsiany * Marcus Nilsson * Marek Kasztelnik * Mariusz Pietrzyk * Marjun Pagalan * Mark A. Miller * Mark IJbema * Mark Maglana * Mark Phillips * Mark Rushakoff * Mark Turner * Mark Yen * Markus Schwed * Marques Johansson * Marques Johansson * Marques Johansson * Marshall Yount * Martin Emde * Martin Englund * Martin Matuska * Mat Ellis * Mateusz Juraszek * Matheus Mina * Mathias Meyer * Matt Bostock * Matt Darby * Matt Darby * Matt Eldridge * Matt Gillooly * Matt Griffin * Matt Pokress * Matt Ray * Matt Sanders * Matt Sanders * Matt Sanders * Matt Todd * Matthew Black * Matthew Black * Matthew Breeden * Matthew O'Riordan * Matthias Gröbner * Matthieu Huin * Max Lincoln * Max Lincoln * Max Stepanov * Mevan Samaratunga * Michael Brodhead & Shai Rosenfeld * Michael Brodhead * Michael Conigliaro * Michael D. Hall * Michael Elfassy * Michael Hale * Michael Harrison * Michael Jackson * Michael Keirnan * Michael Linderman * Michael Moll * Michael Rykov * Michael Sprauer * Michael Zeng * Michał Krzyżanowski * Michiel Sikkes * Mick Pollard * Miguel Martinez * Miguel Z * Mike Dillon * Mike Fiedler * Mike Gehard * Mike Hagedorn * Mike Manewitz * Mike Marion * Mike Moore * Mike Pountney * Ming Jin * Mitchell Hashimoto * Naoto TAKAHASHI * Nassos Antoniou * Nat Welch * Nathan Sullivan * Nathan Sutton * Nathan Williams * Neill Turner * Nelvin Driz * Nelvin Driz * Nelvin Driz * Nelvin Driz * Nicholas Ricketts * Nick Huanca * Nick Huanca * Nick Huanuca * Nick Janus * Nick Merwin * Nick Osborn * Nick Osborn * Nick Osborn * Nick Osborn * Nick Osborn * Nico * Nik Wakelin * Nikita Pomyashchiy * Niko Felger * Nils Landt * NomadRain * Oge Nnadi * Oguz Bilgic * Ohad Levy * Ohad Levy * Oleg * Olle Lundberg * Omar Reiss * Oscar Elfving * Ozgur Akan * Pablo Baños López * Pablo Baños López * Pan Thomakos * Parker Selbert * Partha Aji * Patrick Debois * Patrick McKenzie * Paul * Paul Gideon Dann * Paul Thornthwaite * Paul Thornthwaite * Paul Vudmaska * Paulo Henrique Lopes Ribeiro * Paulo Henrique Lopes Ribeiro * Pavel Repin * Pavol Dilung * Pedro Belo * Pedro Nascimento * Pedro Perez * Peter Bonnell * Peter C. Norton * Peter Drake * Peter M. Goldstein * Peter Meier * Peter Souter * Peter Vawser * Peter Weldon * Peter Weldon * Petr Blaho * Phil Cohen * Phil Kates * Phil Kates * Philip Mark Deazeta * Philip Mark Deazeta * Philip Mark M. Deazeta * Philip Potter * Pierre Carrier * Pierre Massat * Pieter van de Bruggen * Pieter van de Bruggen * Piotr Kedziora * Postmodern * Prashant Nadarajan * Pratik Naik * Rad Gruchalski * Raphael Costa * Reda NOUSHI * Reinaldo Junior * Renato Furter * Rich Lane * Richard Hall * Richard Henning * Rick Bradley * Rida Al Barazi * Rizwan Reza * Rob Lockstone * Robert Bousquet * Robert Clark * Rodrigo Estebanez * Romain Haenni * Romain Vrignaud * Romain Vrignaud * Ruben Koster * Rupak Ganguly * Rusty Geldmacher * Ryan Davies * Ryan Richard * Ryan Stout * Sairam * Sam Cooper * Sam Cooper * Sam Kottler * Sam Merritt * Sami Samhuri * Sammy Larbi * Samuel Keeley * Samuel Merritt * Sarah Vessels * Sascha Korth * Scott Carleton * Scott Gonyea * Sean Caffery * Sean Handley * Sean Handley * Sean Handley * Sean Handley * Sean Hart * Sean Hart * Sean Porter * Sebastian Saemann * Sergio Rubio * Sergio Rubio * Seth Chisamore * Shai Rosenfeld & Jacob Burkhart * Shai Rosenfeld * Shai Rosenfeld * Shaun Davis * Shawn Catanzarite * Shay Bergmann * Shlomi Zadok * Simas Cepaitis * Simas Cepaitis * Simon Gate * Simon Josi * Simon Rozet * Simone Carletti * Sjoerd Andringa * Sneha Somwanshi * Spencer Dillard * Stefan Majewsky * Stefano Tortarolo * Stepan G Fedorov * Stepan G. Fedorov * Stephan Kaag * Stephen Augenstein * Stephen Bannasch * Stephen von Takach * Steve Agalloco * Steve Frank * Steve Meyfroidt * Steve Smith * Steven Danna * Stuart Eccles * Sven Pfleiderer * Sylvain Kalache * Tal Yalon * Tal Yalon * Tejas Ravindra Mandke * Terry Howe * Terry Howe * TerryHowe * Thom Mahoney & Eugene Howe * Thom Mahoney * Thom May * Thom May * Thomas Cate * Thomas Cate * Thomas Kadauke * Thomas Wright * Tim * Tim Carey-Smith * Tim Carey-Smith and Andy Delcambre * Timothy Klim * Timothée Peignier * Timur Alperovich * Timur Alperovich * Tobias Nygren * Toby Hede * Todd Willey * Todd Willey * Tom Armitage * Tom Caspy * Tom Hulihan * Tom Mornini * Tom Noonan II * Tom Stuart * Tomas Varaneckas * Tomasz Bak * Tomokazu Hirai * Toni Stjepanovic * Tony Ta * Topper Bowers * Tor-Ake Fransson * Trae Robrock * Trevor Bramble * Trevor Bramble * Trotter Cashion * Tzu-Mainn Chen * Tõnis Simo * Ulf Mansson * Vadim Spivak * Viktor Petersson * Ville Lautanala * Vincent Demeester * Virender Khatri * VirtualStaticVoid * Viven * Warren Bain * Wes Morgan * Wesley Beary * Wesley Beary * Wesley Beary * Wesley Beary * Wesley Beary * Wesley Beary * Weston Platter * Will Leinweber * William Lawson * Wyatt Walter * Xavier Fontrodona * Yamashita Yuu * Yann Hamon * Yauheni Kryudziuk * Your Name * Yousef Ourabi * Yury Tsarev * Zachary Danger Campbell * Ziyad Mir * Ziyad Mir * Zuhaib M Siddique * Zuhaib M Siddique * Zuhaib Siddique * aabes * abenari * alex * althras * angus * anomalousthought * arnab * ashmrtnz * atlantacs * avic85 * bdorry * bdorry * bdorry * bigfleet * biomancer * bmiller * bonkydog * brettcave * brookemckim * bugagazavr * caryp * ccloes * coliver * crazed * croaker * dJason * dblock * deepj * dennis-sig * dm1try * elkelk * endzyme * epdejager * eyurchenko * fbiete@gmail.com * fred-secludit * freeformz * gavin * geemus (Wesley Beary) * geemus (Wesley Beary) * geemus * georgyous * ggoodale * ggoodale * gilles * gregburek * gust * hedgehog * heyryanw * howete * irdan * james-lawrence * jamiehannaford * jblancett * jc00ke * jimworm * joe * joe morgan * joewilliams * jordangbull * jschneiderhan * kanetann * karmab * kbockmanrs * kfafel * leehuffman * leonidlm * lostboy * marios * marios * mattray * mauro catenacci * mlincoln * mriley * msa * neillturner * nightshade427 * ooVoo LLC * phiggins * phillc * questionnet * radekg * rebelagentm * ronen barzel * rsalm * ryanlower * sashap * sawanoboly * seanhandley * seeingidog * snyquist2 * starbelly * stephen charles baldwin * thattommyhall * tipt0e * torake.fransson * unknown * vkhatri * watsonian * wenlock * Ørjan Blom * Обоев Рулон ибн Хаттаб * 应俊 * Raul Roa * zhitongLBN fog-1.42.0/spec/0000755000004100000410000000000013171001215013322 5ustar www-datawww-datafog-1.42.0/spec/vcloud_director/0000755000004100000410000000000013171001215016511 5ustar www-datawww-datafog-1.42.0/spec/vcloud_director/spec_helper.rb0000644000004100000410000000046713171001215021336 0ustar www-datawww-dataif ENV["FOG_MOCK"] == "true" Fog.mock! end if Fog.mock? Fog.credentials = { :vcloud_director_host => 'vcloud-director-host', :vcloud_director_password => 'vcloud_director_password', :vcloud_director_username => 'vcd_user@vcd_org_name', }.merge(Fog.credentials) endfog-1.42.0/spec/vcloud_director/requests/0000755000004100000410000000000013171001215020364 5ustar www-datawww-datafog-1.42.0/spec/vcloud_director/requests/compute/0000755000004100000410000000000013171001215022040 5ustar www-datawww-datafog-1.42.0/spec/vcloud_director/requests/compute/instantiate_vapp_template_spec.rb0000644000004100000410000000427013171001215030646 0ustar www-datawww-datarequire './spec/vcloud_director/spec_helper.rb' require 'minitest/autorun' require './lib/fog/vcloud_director/requests/compute/instantiate_vapp_template.rb' describe Fog::Compute::VcloudDirector::Real do before do Fog.unmock! end let(:xml) do service = Fog::Compute::VcloudDirector.new( { :vcloud_director_host => 'vcloud-director-host', :vcloud_director_password => 'vcloud_director_password', :vcloud_director_username => 'vcd_user@vcd_org_name', } ) params = { :description => 'MY VAPP', :vdc_uri => 'http://vcloud/api/vdc/123456789', :network_uri => 'http://vcloud/api/network/123456789', :template_uri => 'http://vcloud/api/vapptemplate/123456789', :vapp_name => 'http://vcloud/api/vapp/123456789', :network_name => 'NETWORK', :vms_config => [ { :name => 'VM1', :href => 'http://vcloud/api/vm/12345', :storage_profile_href => 'http://vcloud/storage/123456789' }, { :name => 'VM2', :href => 'http://vcloud/api/vm/12345', :storage_profile_href => 'http://vcloud/storage/123456789' } ] } Nokogiri::XML(service.send(:generate_instantiate_vapp_template_request,params)) end it "Generates InstantiateVAppTemplateParams" do xml.xpath('//InstantiateVAppTemplateParams').must_be_instance_of Nokogiri::XML::NodeSet end it "Has a valid Network" do node = xml.xpath('//xmlns:NetworkConfigSection') xml.xpath("//xmlns:NetworkConfig")[0].attr('networkName').must_equal "NETWORK" xml.xpath('//xmlns:ParentNetwork')[0].attr('href').must_equal 'http://vcloud/api/network/123456789' end it "Has valid source VAPP info" do node = xml.xpath('//xmlns:Source[@href="http://vcloud/api/vapptemplate/123456789"]') node.length.must_equal 1 end it "Has valid source VM info" do xml.xpath('//xmlns:Source[@name="VM1"]').length.must_equal 1 xml.xpath('//xmlns:StorageProfile[@href="http://vcloud/storage/123456789"]').length.must_equal 2 end after do Fog.mock! end endfog-1.42.0/spec/vcloud_director/generators/0000755000004100000410000000000013171001215020662 5ustar www-datawww-datafog-1.42.0/spec/vcloud_director/generators/compute/0000755000004100000410000000000013171001215022336 5ustar www-datawww-datafog-1.42.0/spec/vcloud_director/generators/compute/instantiate_vapp_template_params_spec.rb0000644000004100000410000000401213171001215032501 0ustar www-datawww-datarequire './spec/vcloud_director/spec_helper.rb' require 'minitest/autorun' require 'nokogiri' require './lib/fog/vcloud_director/generators/compute/instantiate_vapp_template_params.rb' describe Fog::Generators::Compute::VcloudDirector::InstantiateVappTemplateParams do let(:xml) do params = { :name => 'VAPP_NAME', :Description => 'MY VAPP', :InstantiationParams => { :NetworkConfig => [ { :networkName => 'NETWORK', :networkHref => 'http://vcloud/api/network/123456789', :fenceMode => 'bridged' } ] }, :Source => 'http://vcloud/vapp_template/1234', :source_vms => [ { :name => 'VM1', :href => 'http://vcloud/api/vm/12345', :StorageProfileHref => 'http://vcloud/storage/123456789' }, { :name => 'VM2', :href => 'http://vcloud/api/vm/12345', :StorageProfileHref => 'http://vcloud/storage/123456789' } ] } output = Fog::Generators::Compute::VcloudDirector::InstantiateVappTemplateParams.new(params).generate_xml Nokogiri::XML(output) end it "Generates InstantiateVAppTemplateParams" do xml.xpath('//InstantiateVAppTemplateParams').must_be_instance_of Nokogiri::XML::NodeSet end it "Has a valid Network" do node = xml.xpath('//xmlns:NetworkConfigSection') xml.xpath("//xmlns:NetworkConfig")[0].attr('networkName').must_equal "NETWORK" xml.xpath('//xmlns:ParentNetwork')[0].attr('href').must_equal 'http://vcloud/api/network/123456789' end it "Has valid source VAPP info" do node = xml.xpath('//xmlns:Source[@href="http://vcloud/vapp_template/1234"]') node.length.must_equal 1 end it "Has valid source VM info" do xml.xpath('//xmlns:StorageProfile[@href="http://vcloud/storage/123456789"]').length.must_equal 2 end it "Allows New VM Parameters" do nodes = xml.xpath('//xmlns:VmGeneralParams') nodes.length.must_equal 2 end endfog-1.42.0/spec/spec_helper.rb0000644000004100000410000000033413171001215016140 0ustar www-datawww-dataif ENV["COVERAGE"] require "simplecov" SimpleCov.start do add_filter "/spec/" end end require "minitest/autorun" require "minitest/spec" require "minitest/stub_const" $LOAD_PATH.unshift "lib" require "fog" fog-1.42.0/spec/fog/0000755000004100000410000000000013171001215014075 5ustar www-datawww-datafog-1.42.0/spec/fog/bin/0000755000004100000410000000000013171001215014645 5ustar www-datawww-datafog-1.42.0/spec/fog/bin/bluebox_spec.rb0000644000004100000410000000250513171001215017646 0ustar www-datawww-datarequire "spec_helper" require "fog/bin" require "helpers/bin" describe Bluebox do include Fog::BinSpec let(:subject) { Bluebox } describe "#services" do it "includes all services" do assert_includes Bluebox.services, :compute assert_includes Bluebox.services, :dns assert_includes Bluebox.services, :blb end end describe "#class_for" do describe "when requesting compute service" do it "returns correct class" do assert_equal Fog::Compute::Bluebox, Bluebox.class_for(:compute) end end describe "when requesting dns service" do it "returns correct class" do assert_equal Fog::DNS::Bluebox, Bluebox.class_for(:dns) end end describe "when requesting blb service" do it "returns correct class" do assert_equal Fog::Bluebox::BLB, Bluebox.class_for(:blb) end end end describe "#[]" do describe "when requesting compute service" do it "returns instance" do Fog::Compute::Bluebox.stub(:new, "instance") do assert_equal "instance", Bluebox[:compute] end end end describe "when requesting dns service" do it "returns instance" do Fog::DNS::Bluebox.stub(:new, "instance") do assert_equal "instance", Bluebox[:dns] end end end end end fog-1.42.0/spec/fog/bin/opennebula_spec.rb0000644000004100000410000000024413171001215020334 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe OpenNebula do include Fog::BinSpec let(:subject) { OpenNebula } end fog-1.42.0/spec/fog/bin/softlayer_spec.rb0000644000004100000410000000024213171001215020212 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Softlayer do include Fog::BinSpec let(:subject) { Softlayer } end fog-1.42.0/spec/fog/bin/fogdocker_spec.rb0000644000004100000410000000024213171001215020145 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Fogdocker do include Fog::BinSpec let(:subject) { Fogdocker } end fog-1.42.0/spec/fog/bin/brightbox_spec.rb0000644000004100000410000000131313171001215020172 0ustar www-datawww-datarequire "spec_helper" require "fog/bin" require "helpers/bin" describe Brightbox do include Fog::BinSpec let(:subject) { Brightbox } describe "#services" do it "includes all services" do assert_includes Brightbox.services, :compute assert_includes Brightbox.services, :storage end end describe "#class_for" do describe "when requesting compute service" do it "returns correct class" do assert_equal Fog::Compute::Brightbox, Brightbox.class_for(:compute) end end describe "when requesting storage service" do it "returns correct class" do assert_equal Fog::Storage::Brightbox, Brightbox.class_for(:storage) end end end end fog-1.42.0/spec/fog/bin/rage4_spec.rb0000644000004100000410000000023213171001215017203 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Rage4 do include Fog::BinSpec let(:subject) { Rage4 } end fog-1.42.0/spec/fog/bin/dnsimple_spec.rb0000644000004100000410000000021513171001215020015 0ustar www-datawww-datarequire "spec_helper" require "fog/bin" require "helpers/bin" describe Dnsimple do include Fog::BinSpec let(:subject) { Dnsimple } end fog-1.42.0/spec/fog/bin/google_spec.rb0000644000004100000410000000023413171001215017457 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Google do include Fog::BinSpec let(:subject) { Google } end fog-1.42.0/spec/fog/bin/serverlove_spec.rb0000644000004100000410000000024413171001215020400 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Serverlove do include Fog::BinSpec let(:subject) { Serverlove } end fog-1.42.0/spec/fog/bin/linode_spec.rb0000644000004100000410000000023413171001215017455 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Linode do include Fog::BinSpec let(:subject) { Linode } end fog-1.42.0/spec/fog/bin/glesys_spec.rb0000644000004100000410000000023413171001215017511 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Glesys do include Fog::BinSpec let(:subject) { Glesys } end fog-1.42.0/spec/fog/bin/cloudsigma_spec.rb0000644000004100000410000000022113171001215020326 0ustar www-datawww-datarequire "spec_helper" require "fog/bin" require "helpers/bin" describe CloudSigma do include Fog::BinSpec let(:subject) { CloudSigma } end fog-1.42.0/spec/fog/bin/openstack_spec.rb0000644000004100000410000000024213171001215020171 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe OpenStack do include Fog::BinSpec let(:subject) { OpenStack } end fog-1.42.0/spec/fog/bin/clodo_spec.rb0000644000004100000410000000020713171001215017303 0ustar www-datawww-datarequire "spec_helper" require "fog/bin" require "helpers/bin" describe Clodo do include Fog::BinSpec let(:subject) { Clodo } end fog-1.42.0/spec/fog/bin/xenserver_spec.rb0000644000004100000410000000024213171001215020223 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe XenServer do include Fog::BinSpec let(:subject) { XenServer } end fog-1.42.0/spec/fog/bin/rackspace_spec.rb0000644000004100000410000000024213171001215020136 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Rackspace do include Fog::BinSpec let(:subject) { Rackspace } end fog-1.42.0/spec/fog/bin/cloudstack_spec.rb0000644000004100000410000000022113171001215020333 0ustar www-datawww-datarequire "spec_helper" require "fog/bin" require "helpers/bin" describe Cloudstack do include Fog::BinSpec let(:subject) { Cloudstack } end fog-1.42.0/spec/fog/bin/riakcs_spec.rb0000644000004100000410000000023413171001215017457 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe RiakCS do include Fog::BinSpec let(:subject) { RiakCS } end fog-1.42.0/spec/fog/bin/vsphere_spec.rb0000644000004100000410000000023613171001215017661 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Vsphere do include Fog::BinSpec let(:subject) { Vsphere } end fog-1.42.0/spec/fog/bin/local_spec.rb0000644000004100000410000000023213171001215017273 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Local do include Fog::BinSpec let(:subject) { Local } end fog-1.42.0/spec/fog/bin/dnsmadeeasy_spec.rb0000644000004100000410000000022313171001215020476 0ustar www-datawww-datarequire "spec_helper" require "fog/bin" require "helpers/bin" describe DNSMadeEasy do include Fog::BinSpec let(:subject) { DNSMadeEasy } end fog-1.42.0/spec/fog/bin/zerigo_spec.rb0000644000004100000410000000023413171001215017502 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Zerigo do include Fog::BinSpec let(:subject) { Zerigo } end fog-1.42.0/spec/fog/bin/baremetalcloud_spec.rb0000644000004100000410000000140113171001215021163 0ustar www-datawww-datarequire "spec_helper" require "fog/bin" require "helpers/bin" describe BareMetalCloud do include Fog::BinSpec let(:subject) { BareMetalCloud } describe "#services" do it "includes all services" do assert_includes BareMetalCloud.services, :compute end end describe "#class_for" do describe "when requesting storage service" do it "returns correct class" do assert_equal Fog::Compute::BareMetalCloud, BareMetalCloud.class_for(:compute) end end end describe "#[]" do describe "when requesting compute service" do it "returns instance" do Fog::Compute::BareMetalCloud.stub(:new, "instance") do assert_equal "instance", BareMetalCloud[:compute] end end end end end fog-1.42.0/spec/fog/bin/openvz_spec.rb0000644000004100000410000000023413171001215017524 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Openvz do include Fog::BinSpec let(:subject) { Openvz } end fog-1.42.0/spec/fog/bin/vmfusion_spec.rb0000644000004100000410000000024013171001215020046 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Vmfusion do include Fog::BinSpec let(:subject) { Vmfusion } end fog-1.42.0/spec/fog/bin/powerdns_spec.rb0000644000004100000410000000024313171001215020044 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Fog::PowerDNS do include Fog::BinSpec let(:subject) { PowerDNS } endfog-1.42.0/spec/fog/bin/stormondemand_spec.rb0000644000004100000410000000025213171001215021055 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe StormOnDemand do include Fog::BinSpec let(:subject) { StormOnDemand } end fog-1.42.0/spec/fog/bin/sakuracloud_spec.rb0000644000004100000410000000024613171001215020523 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe SakuraCloud do include Fog::BinSpec let(:subject) { SakuraCloud } end fog-1.42.0/spec/fog/bin/ibm_spec.rb0000644000004100000410000000022613171001215016753 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe IBM do include Fog::BinSpec let(:subject) { IBM } end fog-1.42.0/spec/fog/bin/joyent_spec.rb0000644000004100000410000000023413171001215017513 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Joyent do include Fog::BinSpec let(:subject) { Joyent } end fog-1.42.0/spec/fog/bin/vcloud_spec.rb0000644000004100000410000000023413171001215017477 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Vcloud do include Fog::BinSpec let(:subject) { Vcloud } end fog-1.42.0/spec/fog/bin/aws_spec.rb0000644000004100000410000000557013171001215017005 0ustar www-datawww-datarequire "spec_helper" require "fog/bin" require "helpers/bin" describe AWS do include Fog::BinSpec let(:subject) { AWS } KEY_CLASS_MAPPING = { :auto_scaling => Fog::AWS::AutoScaling, :beanstalk => Fog::AWS::ElasticBeanstalk, :cdn => Fog::CDN::AWS, :cloud_formation => Fog::AWS::CloudFormation, :cloud_watch => Fog::AWS::CloudWatch, :compute => Fog::Compute::AWS, :data_pipeline => Fog::AWS::DataPipeline, :ddb => Fog::AWS::DynamoDB, :dynamodb => Fog::AWS::DynamoDB, :dns => Fog::DNS::AWS, :elasticache => Fog::AWS::Elasticache, :elb => Fog::AWS::ELB, :emr => Fog::AWS::EMR, :glacier => Fog::AWS::Glacier, :iam => Fog::AWS::IAM, :redshift => Fog::AWS::Redshift, :sdb => Fog::AWS::SimpleDB, :simpledb => Fog::AWS::SimpleDB, :ses => Fog::AWS::SES, :sqs => Fog::AWS::SQS, :eu_storage => Fog::Storage::AWS, :storage => Fog::Storage::AWS, :rds => Fog::AWS::RDS, :sns => Fog::AWS::SNS, :sts => Fog::AWS::STS } describe "#services" do it "includes all services" do assert_includes AWS.services, :auto_scaling assert_includes AWS.services, :beanstalk assert_includes AWS.services, :cdn assert_includes AWS.services, :cloud_formation assert_includes AWS.services, :cloud_watch assert_includes AWS.services, :compute assert_includes AWS.services, :data_pipeline assert_includes AWS.services, :dynamodb assert_includes AWS.services, :dns assert_includes AWS.services, :elasticache assert_includes AWS.services, :elb assert_includes AWS.services, :emr assert_includes AWS.services, :glacier assert_includes AWS.services, :iam assert_includes AWS.services, :redshift assert_includes AWS.services, :rds assert_includes AWS.services, :simpledb assert_includes AWS.services, :ses assert_includes AWS.services, :sqs assert_includes AWS.services, :storage assert_includes AWS.services, :sns assert_includes AWS.services, :sts end end describe "#class_for" do describe "when key exists" do it "maps to correct class" do KEY_CLASS_MAPPING.each do |key, klass| assert_equal klass, AWS.class_for(key) end end end describe "when key does not exist" do it "raises ArgumentError" do assert_raises(ArgumentError) { AWS.class_for(:bad_key) } end end end describe "#[]" do describe "when service is recognised" do it "returns correct instance" do KEY_CLASS_MAPPING.each do |key, klass| klass.stub(:new, "#{klass} instance") do assert_equal "#{klass} instance", AWS[key] end end end end describe "when service is not recognised" do it "raises ArgumentError" do assert_raises(ArgumentError) { AWS[:bad_service] } end end end end fog-1.42.0/spec/fog/bin/dynect_spec.rb0000644000004100000410000000021113171001215017464 0ustar www-datawww-datarequire "spec_helper" require "fog/bin" require "helpers/bin" describe Dynect do include Fog::BinSpec let(:subject) { Dynect } end fog-1.42.0/spec/fog/bin/profitbricks_spec.rb0000644000004100000410000000025013171001215020702 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe ProfitBricks do include Fog::BinSpec let(:subject) { ProfitBricks } end fog-1.42.0/spec/fog/bin/ecloud_spec.rb0000644000004100000410000000023413171001215017456 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Ecloud do include Fog::BinSpec let(:subject) { Ecloud } end fog-1.42.0/spec/fog/bin/dreamhost_spec.rb0000644000004100000410000000021713171001215020172 0ustar www-datawww-datarequire "spec_helper" require "fog/bin" require "helpers/bin" describe Dreamhost do include Fog::BinSpec let(:subject) { Dreamhost } end fog-1.42.0/spec/fog/bin/atmos_spec.rb0000644000004100000410000000130213171001215017323 0ustar www-datawww-datarequire "spec_helper" require "fog/bin" require "helpers/bin" describe Atmos do include Fog::BinSpec let(:subject) { Atmos } describe "#services" do it "includes all services" do assert_includes Atmos.services, :storage end end describe "#class_for" do describe "when requesting storage service" do it "returns correct class" do assert_equal Fog::Storage::Atmos, Atmos.class_for(:storage) end end end describe "#[]" do describe "when requesting storage service" do it "returns instance" do Fog::Storage::Atmos.stub(:new, "instance") do assert_equal "instance", Atmos[:storage] end end end end end fog-1.42.0/spec/fog/bin/gogrid_spec.rb0000644000004100000410000000023413171001215017456 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe GoGrid do include Fog::BinSpec let(:subject) { GoGrid } end fog-1.42.0/spec/fog/bin/voxel_spec.rb0000644000004100000410000000023213171001215017336 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe Voxel do include Fog::BinSpec let(:subject) { Voxel } end fog-1.42.0/spec/fog/bin/vclouddirector_spec.rb0000644000004100000410000000025413171001215021235 0ustar www-datawww-datarequire "minitest/autorun" require "fog" require "fog/bin" require "helpers/bin" describe VcloudDirector do include Fog::BinSpec let(:subject) { VcloudDirector } end fog-1.42.0/spec/fog/metering_spec.rb0000644000004100000410000000067013171001215017251 0ustar www-datawww-datarequire "spec_helper" describe Fog::Metering do Fog::Metering.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do assert_raises(ArgumentError) { Fog::Metering[provider] } end end end end end fog-1.42.0/spec/fog/support_spec.rb0000644000004100000410000000066513171001215017157 0ustar www-datawww-datarequire "spec_helper" describe Fog::Support do Fog::Support.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do assert_raises(ArgumentError) { Fog::Support[provider] } end end end end end fog-1.42.0/spec/fog/orchestration_spec.rb0000644000004100000410000000070713171001215020324 0ustar www-datawww-datarequire "spec_helper" describe Fog::Orchestration do Fog::Orchestration.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do assert_raises(ArgumentError) { Fog::Orchestration[provider] } end end end end end fog-1.42.0/spec/fog/account_spec.rb0000644000004100000410000000066513171001215017077 0ustar www-datawww-datarequire "spec_helper" describe Fog::Account do Fog::Account.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do assert_raises(ArgumentError) { Fog::Account[provider] } end end end end end fog-1.42.0/spec/fog/monitoring_spec.rb0000644000004100000410000000067613171001215017632 0ustar www-datawww-datarequire "spec_helper" describe Fog::Monitoring do Fog::Monitoring.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do assert_raises(ArgumentError) { Fog::Monitoring[provider] } end end end end end fog-1.42.0/spec/fog/billing_spec.rb0000644000004100000410000000066513171001215017063 0ustar www-datawww-datarequire "spec_helper" describe Fog::Billing do Fog::Billing.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do assert_raises(ArgumentError) { Fog::Billing[provider] } end end end end end fog-1.42.0/spec/fog/volume_spec.rb0000644000004100000410000000066213171001215016747 0ustar www-datawww-datarequire "spec_helper" describe Fog::Volume do Fog::Volume.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do assert_raises(ArgumentError) { Fog::Volume[provider] } end end end end end fog-1.42.0/spec/fog/image_spec.rb0000644000004100000410000000065713171001215016526 0ustar www-datawww-datarequire "spec_helper" describe Fog::Image do Fog::Image.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do assert_raises(ArgumentError) { Fog::Image[provider] } end end end end end fog-1.42.0/spec/fog/compute_spec.rb0000644000004100000410000000122213171001215017105 0ustar www-datawww-datarequire "spec_helper" describe Fog::Compute do Fog::Compute.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do # These providers do not raise ArgumentError since they have no requirements defined if [:openvz, :vmfusion].include?(provider) assert Fog::Compute[provider] else assert_raises(ArgumentError) { Fog::Compute[provider] } end end end end end end fog-1.42.0/spec/fog/xml/0000755000004100000410000000000013171001215014675 5ustar www-datawww-datafog-1.42.0/spec/fog/xml/connection_spec.rb0000644000004100000410000000164413171001215020400 0ustar www-datawww-datarequire "spec_helper" # @note This is going to be part of fog-xml eventually describe Fog::XML::Connection do before do @connection = Fog::XML::Connection.new("http://localhost") end after do Excon.stubs.clear end it "responds to #request" do assert_respond_to @connection, :request end describe "when request is passed a parser" do it "returns the body after parsing" do @parser = Fog::ToHashDocument.new Excon.stub({}, { :status => 200, :body => "" }) response = @connection.request(:parser => @parser, :mock => true) assert_equal({ :xml => "" }, response.body) end end describe "when request excludes a parser" do it "returns the response body without change" do Excon.stub({}, { :status => 200, :body => "" }) response = @connection.request(:mock => true) assert_equal("", response.body) end end end fog-1.42.0/spec/fog/cdn_spec.rb0000644000004100000410000000065113171001215016202 0ustar www-datawww-datarequire "spec_helper" describe Fog::CDN do Fog::CDN.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do assert_raises(ArgumentError) { Fog::CDN[provider] } end end end end end fog-1.42.0/spec/fog/network_spec.rb0000644000004100000410000000066513171001215017134 0ustar www-datawww-datarequire "spec_helper" describe Fog::Network do Fog::Network.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do assert_raises(ArgumentError) { Fog::Network[provider] } end end end end end fog-1.42.0/spec/fog/bin_spec.rb0000644000004100000410000002153213171001215016207 0ustar www-datawww-datarequire "spec_helper" require "fog/bin" describe Fog do describe "#providers" do it "includes existing providers" do assert_equal "Atmos", Fog.providers[:atmos] assert_equal "AWS", Fog.providers[:aws] assert_equal "BareMetalCloud", Fog.providers[:baremetalcloud] assert_equal "Bluebox", Fog.providers[:bluebox] assert_equal "Brightbox", Fog.providers[:brightbox] assert_equal "Clodo", Fog.providers[:clodo] assert_equal "CloudSigma", Fog.providers[:cloudsigma] assert_equal "Cloudstack", Fog.providers[:cloudstack] assert_equal "DigitalOcean", Fog.providers[:digitalocean] assert_equal "Dnsimple", Fog.providers[:dnsimple] assert_equal "DNSMadeEasy", Fog.providers[:dnsmadeeasy] assert_equal "Dreamhost", Fog.providers[:dreamhost] assert_equal "Dynect", Fog.providers[:dynect] assert_equal "Ecloud", Fog.providers[:ecloud] assert_equal "Fogdocker", Fog.providers[:fogdocker] assert_equal "Glesys", Fog.providers[:glesys] assert_equal "GoGrid", Fog.providers[:gogrid] assert_equal "Google", Fog.providers[:google] assert_equal "IBM", Fog.providers[:ibm] assert_equal "InternetArchive", Fog.providers[:internetarchive] assert_equal "Joyent", Fog.providers[:joyent] assert_equal "Linode", Fog.providers[:linode] assert_equal "Local", Fog.providers[:local] assert_equal "OpenNebula", Fog.providers[:opennebula] assert_equal "OpenStack", Fog.providers[:openstack] assert_equal "Openvz", Fog.providers[:openvz] assert_equal "Ovirt", Fog.providers[:ovirt] assert_equal "PowerDNS", Fog.providers[:powerdns] assert_equal "ProfitBricks", Fog.providers[:profitbricks] assert_equal "Rackspace", Fog.providers[:rackspace] assert_equal "Rage4", Fog.providers[:rage4] assert_equal "RiakCS", Fog.providers[:riakcs] assert_equal "SakuraCloud", Fog.providers[:sakuracloud] assert_equal "Serverlove", Fog.providers[:serverlove] assert_equal "Softlayer", Fog.providers[:softlayer] assert_equal "StormOnDemand", Fog.providers[:stormondemand] assert_equal "Vcloud", Fog.providers[:vcloud] assert_equal "VcloudDirector", Fog.providers[:vclouddirector] assert_equal "Vmfusion", Fog.providers[:vmfusion] assert_equal "Voxel", Fog.providers[:voxel] assert_equal "Vsphere", Fog.providers[:vsphere] assert_equal "XenServer", Fog.providers[:xenserver] assert_equal "Zerigo", Fog.providers[:zerigo] end end describe "#registered_providers" do it "includes existing providers" do assert_includes Fog.registered_providers, "Atmos" assert_includes Fog.registered_providers, "AWS" assert_includes Fog.registered_providers, "BareMetalCloud" assert_includes Fog.registered_providers, "Bluebox" assert_includes Fog.registered_providers, "Brightbox" assert_includes Fog.registered_providers, "Clodo" assert_includes Fog.registered_providers, "CloudSigma" assert_includes Fog.registered_providers, "Cloudstack" assert_includes Fog.registered_providers, "DigitalOcean" assert_includes Fog.registered_providers, "Dnsimple" assert_includes Fog.registered_providers, "DNSMadeEasy" assert_includes Fog.registered_providers, "Dreamhost" assert_includes Fog.registered_providers, "Dynect" assert_includes Fog.registered_providers, "Ecloud" assert_includes Fog.registered_providers, "Fogdocker" assert_includes Fog.registered_providers, "Glesys" assert_includes Fog.registered_providers, "GoGrid" assert_includes Fog.registered_providers, "Google" assert_includes Fog.registered_providers, "IBM" assert_includes Fog.registered_providers, "InternetArchive" assert_includes Fog.registered_providers, "Joyent" assert_includes Fog.registered_providers, "Linode" assert_includes Fog.registered_providers, "Local" assert_includes Fog.registered_providers, "OpenNebula" assert_includes Fog.registered_providers, "OpenStack" assert_includes Fog.registered_providers, "Openvz" assert_includes Fog.registered_providers, "Ovirt" assert_includes Fog.registered_providers, "PowerDNS" assert_includes Fog.registered_providers, "ProfitBricks" assert_includes Fog.registered_providers, "Rackspace" assert_includes Fog.registered_providers, "Rage4" assert_includes Fog.registered_providers, "RiakCS" assert_includes Fog.registered_providers, "SakuraCloud" assert_includes Fog.registered_providers, "Serverlove" assert_includes Fog.registered_providers, "Softlayer" assert_includes Fog.registered_providers, "StormOnDemand" assert_includes Fog.registered_providers, "Vcloud" assert_includes Fog.registered_providers, "VcloudDirector" assert_includes Fog.registered_providers, "Vmfusion" assert_includes Fog.registered_providers, "Voxel" assert_includes Fog.registered_providers, "Vsphere" assert_includes Fog.registered_providers, "XenServer" assert_includes Fog.registered_providers, "Zerigo" end end describe "#available_providers" do it "includes existing providers" do assert_includes Fog.available_providers, "Atmos" if Atmos.available? assert_includes Fog.available_providers, "AWS" if AWS.available? assert_includes Fog.available_providers, "BareMetalCloud" if BareMetalCloud.available? assert_includes Fog.available_providers, "Bluebox" if Bluebox.available? assert_includes Fog.available_providers, "Brightbox" if Brightbox.available? assert_includes Fog.available_providers, "Clodo" if Clodo.available? assert_includes Fog.available_providers, "CloudSigma" if CloudSigma.available? assert_includes Fog.available_providers, "Cloudstack" if Cloudstack.available? assert_includes Fog.available_providers, "DigitalOcean" if DigitalOcean.available? assert_includes Fog.available_providers, "Dnsimple" if Dnsimple.available? assert_includes Fog.available_providers, "DNSMadeEasy" if DNSMadeEasy.available? assert_includes Fog.available_providers, "Dreamhost" if Dreamhost.available? assert_includes Fog.available_providers, "Dynect" if Dynect.available? assert_includes Fog.available_providers, "Ecloud" if Ecloud.available? assert_includes Fog.available_providers, "Fogdocker" if Fogdocker.available? assert_includes Fog.available_providers, "Glesys" if Glesys.available? assert_includes Fog.available_providers, "GoGrid" if GoGrid.available? assert_includes Fog.available_providers, "Google" if Google.available? assert_includes Fog.available_providers, "IBM" if IBM.available? assert_includes Fog.available_providers, "InternetArchive" if InternetArchive.available? assert_includes Fog.available_providers, "Joyent" if Joyent.available? assert_includes Fog.available_providers, "Linode" if Linode.available? assert_includes Fog.available_providers, "Local" if Local.available? assert_includes Fog.available_providers, "OpenNebula" if OpenNebula.available? assert_includes Fog.available_providers, "OpenStack" if OpenStack.available? assert_includes Fog.available_providers, "Openvz" if Openvz.available? assert_includes Fog.available_providers, "Ovirt" if Ovirt.available? assert_includes Fog.available_providers, "PowerDNS" if PowerDNS.available? assert_includes Fog.available_providers, "ProfitBricks" if ProfitBricks.available? assert_includes Fog.available_providers, "Rackspace" if Rackspace.available? assert_includes Fog.available_providers, "Rage4" if Rage4.available? assert_includes Fog.available_providers, "RiakCS" if RiakCS.available? assert_includes Fog.available_providers, "SakuraCloud" if SakuraCloud.available? assert_includes Fog.available_providers, "Serverlove" if Serverlove.available? assert_includes Fog.available_providers, "Softlayer" if Softlayer.available? assert_includes Fog.available_providers, "StormOnDemand" if StormOnDemand.available? assert_includes Fog.available_providers, "Vcloud" if Vcloud.available? assert_includes Fog.available_providers, "VcloudDirector" if VcloudDirector.available? assert_includes Fog.available_providers, "Vmfusion" if Vmfusion.available? assert_includes Fog.available_providers, "Voxel" if Voxel.available? assert_includes Fog.available_providers, "Vsphere" if Vsphere.available? assert_includes Fog.available_providers, "XenServer" if XenServer.available? assert_includes Fog.available_providers, "Zerigo" if Zerigo.available? end end describe "#services" do it "returns Hash of services" do assert_kind_of Hash, Fog.services assert_includes Fog.services, :cdn assert_includes Fog.services, :compute assert_includes Fog.services, :dns assert_includes Fog.services, :storage end end end fog-1.42.0/spec/fog/vpn_spec.rb0000644000004100000410000000065113171001215016241 0ustar www-datawww-datarequire "spec_helper" describe Fog::VPN do Fog::VPN.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do assert_raises(ArgumentError) { Fog::VPN[provider] } end end end end end fog-1.42.0/spec/fog/dns_spec.rb0000644000004100000410000000117113171001215016220 0ustar www-datawww-datarequire "spec_helper" describe Fog::DNS do Fog::DNS.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do # These providers do not raise ArgumentError since they have no requirements defined if [:dnsimple].include?(provider) assert Fog::DNS[provider] else assert_raises(ArgumentError) { Fog::DNS[provider] } end end end end end end fog-1.42.0/spec/fog/identity_spec.rb0000644000004100000410000000067013171001215017270 0ustar www-datawww-datarequire "spec_helper" describe Fog::Identity do Fog::Identity.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do assert_raises(ArgumentError) { Fog::Identity[provider] } end end end end end fog-1.42.0/spec/fog/storage_spec.rb0000644000004100000410000000066513171001215017107 0ustar www-datawww-datarequire "spec_helper" describe Fog::Storage do Fog::Storage.providers.each do |provider| describe "when #{provider} is passed with no available credentials" do it "returns ArgumentError" do # Stub credentials so you still see errors where the tester really has credentials Fog.stub :credentials, {} do assert_raises(ArgumentError) { Fog::Storage[provider] } end end end end end fog-1.42.0/spec/helpers/0000755000004100000410000000000013171001215014764 5ustar www-datawww-datafog-1.42.0/spec/helpers/bin.rb0000644000004100000410000000144713171001215016067 0ustar www-datawww-datamodule Fog module BinSpec extend Minitest::Spec::DSL it "responds to available?" do assert_respond_to subject, :available? end it "responds to class_for" do assert_respond_to subject, :class_for end it "#class_for raises ArgumentError for unknown services" do assert_raises(ArgumentError) { subject.class_for(:unknown) } end it "responds to collections" do skip if subject == ::Google assert_respond_to subject, :collections end it "responds to []" do assert_respond_to subject, :[] end it "#[] when unknown service is passed raises ArgumentError" do assert_raises(ArgumentError) { subject[:bad_service] } end it "responds to services" do assert_respond_to subject, :services end end end fog-1.42.0/LICENSE.md0000644000004100000410000000217113171001215013775 0ustar www-datawww-dataThe MIT License (MIT) Copyright (c) 2009-2016 [CONTRIBUTORS.md](https://github.com/fog/fog/blob/master/CONTRIBUTORS.md) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. fog-1.42.0/.travis.yml0000644000004100000410000000164213171001215014504 0ustar www-datawww-datalanguage: ruby sudo: false dist: trusty script: bundle exec rake travis rvm: - 2.1 - 2.2 - 2.3 - 2.4 - jruby-head gemfile: - Gemfile - gemfiles/Gemfile-edge matrix: fast_finish: true allow_failures: - rvm: jruby-head include: - rvm: 1.9.3 gemfile: gemfiles/Gemfile-1.9 - rvm: 1.9.3 gemfile: gemfiles/Gemfile-edge-1.9 - rvm: jruby-19mode gemfile: gemfiles/Gemfile-1.9 - rvm: jruby-19mode gemfile: gemfiles/Gemfile-edge-1.9 - rvm: 2.0 gemfile: gemfiles/Gemfile-2.0 - rvm: 2.0 gemfile: gemfiles/Gemfile-edge-2.0 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.42.0/lib/0000755000004100000410000000000013171001215013136 5ustar www-datawww-datafog-1.42.0/lib/fog/0000755000004100000410000000000013171001215013711 5ustar www-datawww-datafog-1.42.0/lib/fog/bin/0000755000004100000410000000000013171001215014461 5ustar www-datawww-datafog-1.42.0/lib/fog/bin/brightbox.rb0000644000004100000410000000150613171001215017000 0ustar www-datawww-dataclass Brightbox < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Brightbox when :storage Fog::Storage::Brightbox 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("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.42.0/lib/fog/bin/aws.rb0000644000004100000410000000040113171001215015573 0ustar www-datawww-datarequire 'fog/aws/service_mapper' class AWS < Fog::Bin def self.services Fog::AWS::ServiceMapper.services end def self.[](key) Fog::AWS::ServiceMapper[key] end def self.class_for(key) Fog::AWS::ServiceMapper.class_for(key) end end fog-1.42.0/lib/fog/bin/dreamhost.rb0000644000004100000410000000126413171001215016777 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.42.0/lib/fog/bin/vcloud.rb0000644000004100000410000000111713171001215016302 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.42.0/lib/fog/bin/cloudsigma.rb0000644000004100000410000000125313171001215017136 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 end fog-1.42.0/lib/fog/bin/go_grid.rb0000644000004100000410000000130113171001215016413 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.42.0/lib/fog/bin/rackspace.rb0000644000004100000410000000553113171001215016746 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 :cdn_v2 Fog::Rackspace::CDNV2 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 when :networking Fog::Rackspace::Networking when :networking_v2 Fog::Rackspace::NetworkingV2 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 :cdn_v2 Fog::Rackspace::CDNV2.new 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 when :networking Fog::Rackspace::Networking.new when :networking_v2 Fog::Rackspace::NetworkingV2.new else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Rackspace.services end end end fog-1.42.0/lib/fog/bin/ibm.rb0000644000004100000410000000127513171001215015562 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.42.0/lib/fog/bin/fogdocker.rb0000644000004100000410000000122713171001215016753 0ustar www-datawww-dataclass Fogdocker < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Fogdocker 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 => 'Fogdocker') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Fogdocker.services end end end fog-1.42.0/lib/fog/bin/bluebox.rb0000644000004100000410000000167513171001215016457 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.42.0/lib/fog/bin/clodo.rb0000644000004100000410000000130213171001215016102 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 Fog::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.42.0/lib/fog/bin/zerigo.rb0000644000004100000410000000124213171001215016304 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.42.0/lib/fog/bin/cloudstack.rb0000644000004100000410000000113713171001215017144 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.42.0/lib/fog/bin/softlayer.rb0000644000004100000410000000332513171001215017021 0ustar www-datawww-data# # Author:: Matt Eldridge () # © Copyright IBM Corporation 2014. # # LICENSE: MIT (http://opensource.org/licenses/MIT) # class Softlayer < Fog::Bin class << self def class_for(key) case key when :compute Fog::Compute::Softlayer when :dns Fog::DNS::Softlayer when :network Fog::Network::Softlayer when :storage Fog::Storage::Softlayer 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 :compute Fog::Logger.warning("Softlayer[:compute] is not recommended, use Compute[:aws] for portability") Fog::Compute.new(:provider => :softlayer) when :dns Fog::Logger.warning("Softlayer[:dns] is not recommended, use DNS[:aws] for portability") Fog::DNS.new(:provider => :softlayer) when :network Fog::Network.new(:provider => :softlayer) when :storage Fog::Storage.new(:provider => :softlayer) else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Softlayer.services end end end fog-1.42.0/lib/fog/bin/glesys.rb0000644000004100000410000000127513171001215016321 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.42.0/lib/fog/bin/rage4.rb0000644000004100000410000000123413171001215016010 0ustar www-datawww-dataclass Rage4 < Fog::Bin class << self def class_for(key) case key when :dns Fog::DNS::Rage4 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("Rage4[:dns] is not recommended, use DNS[:rage4] for portability") Fog::DNS.new(:provider => 'Rage4') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def services Fog::Rage4.services end end end fog-1.42.0/lib/fog/bin/dnsmadeeasy.rb0000644000004100000410000000130013171001215017275 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.42.0/lib/fog/bin/bare_metal_cloud.rb0000644000004100000410000000136113171001215020270 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.42.0/lib/fog/bin/linode.rb0000644000004100000410000000161513171001215016263 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.42.0/lib/fog/bin/openvz.rb0000644000004100000410000000130113171001215016322 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.42.0/lib/fog/bin/openstack.rb0000644000004100000410000000525413171001215017003 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 when :baremetal Fog::Baremetal::OpenStack when :planning Fog::Openstack::Planning 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') when :baremetal Fog::Logger.warning("OpenStack[:baremetal] is not recommended, use Baremetal[:openstack] for portability") Fog::Baremetal.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.42.0/lib/fog/bin/vcloud_director.rb0000644000004100000410000000115713171001215020201 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.42.0/lib/fog/bin/opennebula.rb0000644000004100000410000000304213171001215017135 0ustar www-datawww-datamodule OpenNebula # deviates from other bin stuff to accomodate gem class << self def class_for(key) case key when :compute Fog::Compute::OpenNebula 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("OpenNebula[:compute] is not recommended, use Compute[:opennebula] for portability") Fog::Compute.new(:provider => 'OpenNebula') else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def available? begin availability=true unless Gem::Specification::find_by_name("opennebula").nil? rescue Gem::LoadError availability=false rescue availability_gem=Gem.available?("opennebula") 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::OpenNebula.services end end end fog-1.42.0/lib/fog/cloudsigma/0000755000004100000410000000000013171001215016040 5ustar www-datawww-datafog-1.42.0/lib/fog/cloudsigma/connection.rb0000644000004100000410000001524113171001215020527 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::XML::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 end fog-1.42.0/lib/fog/cloudsigma/requests/0000755000004100000410000000000013171001215017713 5ustar www-datawww-datafog-1.42.0/lib/fog/cloudsigma/requests/get_server.rb0000644000004100000410000000046213171001215022407 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.42.0/lib/fog/cloudsigma/requests/get_vlan.rb0000644000004100000410000000042613171001215022041 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.42.0/lib/fog/cloudsigma/requests/get_lib_volume.rb0000644000004100000410000000046313171001215023237 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.42.0/lib/fog/cloudsigma/requests/clone_server.rb0000644000004100000410000000140713171001215022730 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.42.0/lib/fog/cloudsigma/requests/delete_server.rb0000644000004100000410000000047613171001215023077 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.42.0/lib/fog/cloudsigma/requests/list_snapshots.rb0000644000004100000410000000043113171001215023313 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def list_snapshots list_request('snapshots/detail/') end end class Mock def list_snapshots mock_list(:snapshots, 200) end end end end end fog-1.42.0/lib/fog/cloudsigma/requests/open_vnc.rb0000644000004100000410000000146013171001215022050 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.42.0/lib/fog/cloudsigma/requests/clone_libvolume.rb0000644000004100000410000000140613171001215023417 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.42.0/lib/fog/cloudsigma/requests/get_current_usage.rb0000644000004100000410000000036513171001215023751 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.42.0/lib/fog/cloudsigma/requests/stop_server.rb0000644000004100000410000000152713171001215022620 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def stop_server(server_id, graceful_acpi = false) action = graceful_acpi ? :shutdown : :stop request(:path => "servers/#{server_id}/action/", :method => 'POST', :query => {:do => action}, :expects => [200, 202]) end end class Mock def stop_server(server_id, graceful_acpi = false) server = self.data[:servers][server_id] server['status'] = 'stopped' response = Excon::Response.new response.status = 200 response.body = { 'action' => graceful_acpi ? 'shutdown' : 'stop', 'result' => 'success', 'uuid' => server_id } response end end end end end fog-1.42.0/lib/fog/cloudsigma/requests/create_volume.rb0000644000004100000410000000127113171001215023073 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.42.0/lib/fog/cloudsigma/requests/delete_volume.rb0000644000004100000410000000046113171001215023072 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.42.0/lib/fog/cloudsigma/requests/list_vlans.rb0000644000004100000410000000041113171001215022412 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.42.0/lib/fog/cloudsigma/requests/get_subscription.rb0000644000004100000410000000047613171001215023632 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.42.0/lib/fog/cloudsigma/requests/calculate_subscription_price.rb0000644000004100000410000000045213171001215026164 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.42.0/lib/fog/cloudsigma/requests/get_balance.rb0000644000004100000410000000040713171001215022465 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.42.0/lib/fog/cloudsigma/requests/create_snapshot.rb0000644000004100000410000000122513171001215023422 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def create_snapshot(data) create_request("snapshots/", data) end end class Mock def create_snapshot(data) uuid = self.class.random_uuid defaults = {'uuid' => uuid, 'timestamp' => Time.now.strftime("%Y-%m-%d %H:%M:%S.%6N%z"), 'status' => 'creating', 'tags' => [], 'grantees' => [], 'allocated_size' => 0 } mock_create(:snapshots, 201, data, uuid, defaults) end end end end end fog-1.42.0/lib/fog/cloudsigma/requests/delete_snapshot.rb0000644000004100000410000000047613171001215023430 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def delete_snapshot(snap_id) delete_request("snapshots/#{snap_id}/") end end class Mock def delete_snapshot(snap_id) mock_delete(:snapshots, 204, snap_id) end end end end end fog-1.42.0/lib/fog/cloudsigma/requests/clone_snapshot.rb0000644000004100000410000000142113171001215023255 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def clone_snapshot(snap_id, clone_params={}) request(:path => "snapshots/#{snap_id}/action/", :method => 'POST', :query => {:do => :clone}, :body => clone_params, :expects => [200, 202]) end end class Mock def clone_snapshot(snap_id, clone_params={}) snapshot = self.data[:snapshots][snap_id].dup uuid = self.class.random_uuid snapshot['uuid'] = uuid self.data[:snapshots][uuid] = snapshot response = Excon::Response.new response.status = 200 response.body = snapshot response end end end end end fog-1.42.0/lib/fog/cloudsigma/requests/update_server.rb0000644000004100000410000000241413171001215023111 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.42.0/lib/fog/cloudsigma/requests/close_vnc.rb0000644000004100000410000000120413171001215022210 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.42.0/lib/fog/cloudsigma/requests/start_server.rb0000644000004100000410000000142113171001215022761 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.42.0/lib/fog/cloudsigma/requests/get_pricing.rb0000644000004100000410000000115413171001215022533 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.42.0/lib/fog/cloudsigma/requests/list_servers.rb0000644000004100000410000000042113171001215022761 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.42.0/lib/fog/cloudsigma/requests/get_snapshot.rb0000644000004100000410000000046213171001215022740 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def get_snapshot(snap_id) get_request("snapshots/#{snap_id}/") end end class Mock def get_snapshot(snap_id) mock_get(:snapshots, 200, snap_id) end end end end end fog-1.42.0/lib/fog/cloudsigma/requests/list_ips.rb0000644000004100000410000000040113171001215022061 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.42.0/lib/fog/cloudsigma/requests/get_volume.rb0000644000004100000410000000044513171001215022411 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.42.0/lib/fog/cloudsigma/requests/list_volumes.rb0000644000004100000410000000042013171001215022761 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.42.0/lib/fog/cloudsigma/requests/create_server.rb0000644000004100000410000000141413171001215023071 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.42.0/lib/fog/cloudsigma/requests/list_lib_volumes.rb0000644000004100000410000000042713171001215023616 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.42.0/lib/fog/cloudsigma/requests/extend_subscription.rb0000644000004100000410000000071013171001215024331 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.42.0/lib/fog/cloudsigma/requests/update_profile.rb0000644000004100000410000000045213171001215023243 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.42.0/lib/fog/cloudsigma/requests/update_vlan.rb0000644000004100000410000000052513171001215022544 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.42.0/lib/fog/cloudsigma/requests/create_subscription.rb0000644000004100000410000000247313171001215024315 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.42.0/lib/fog/cloudsigma/requests/get_ip.rb0000644000004100000410000000040213171001215021503 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.42.0/lib/fog/cloudsigma/requests/update_volume.rb0000644000004100000410000000051213171001215023107 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.42.0/lib/fog/cloudsigma/requests/clone_volume.rb0000644000004100000410000000137213171001215022732 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.42.0/lib/fog/cloudsigma/requests/list_subscriptions.rb0000644000004100000410000000044213171001215024202 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.42.0/lib/fog/cloudsigma/requests/list_fwpolicies.rb0000644000004100000410000000043313171001215023437 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.42.0/lib/fog/cloudsigma/requests/update_snapshot.rb0000644000004100000410000000052713171001215023445 0ustar www-datawww-datamodule Fog module Compute class CloudSigma class Real def update_snapshot(snap_id, data) update_request("snapshots/#{snap_id}/", data) end end class Mock def update_snapshot(snap_id, data) mock_update(data, :snapshots, 200, snap_id) end end end end end fog-1.42.0/lib/fog/cloudsigma/requests/get_profile.rb0000644000004100000410000000040713171001215022540 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.42.0/lib/fog/cloudsigma/nested_model.rb0000644000004100000410000000364013171001215021032 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 end fog-1.42.0/lib/fog/cloudsigma/docs/0000755000004100000410000000000013171001215016770 5ustar www-datawww-datafog-1.42.0/lib/fog/cloudsigma/docs/getting_started.md0000644000004100000410000000625413171001215022510 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_volume(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_volume(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.42.0/lib/fog/cloudsigma/core.rb0000644000004100000410000000021313171001215017311 0ustar www-datawww-datarequire 'fog/core' require 'fog/json' module Fog module CloudSigma extend Fog::Provider service(:compute, 'Compute') end end fog-1.42.0/lib/fog/cloudsigma/models/0000755000004100000410000000000013171001215017323 5ustar www-datawww-datafog-1.42.0/lib/fog/cloudsigma/models/vlan.rb0000644000004100000410000000120213171001215020603 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_method :save, :update end end end end fog-1.42.0/lib/fog/cloudsigma/models/mountpoint.rb0000644000004100000410000000105213171001215022062 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_method :volume, :drive end end end end fog-1.42.0/lib/fog/cloudsigma/models/volume.rb0000644000004100000410000000406713171001215021166 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' require 'fog/cloudsigma/models/snapshot' 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 model_attribute_array :snapshots, Snapshot 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_method :delete, :destroy def clone(clone_params={}) requires :identity response = service.clone_volume(identity, clone_params) self.class.new(response.body['objects'].first) end def create_snapshot(snapshot_params={}) requires :identity snapshot_params[:drive] = identity response = service.create_snapshot(snapshot_params) Snapshot.new(response.body['objects'].first) end def available? status == 'unmounted' end end end end end fog-1.42.0/lib/fog/cloudsigma/models/profile.rb0000644000004100000410000000277213171001215021320 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 end fog-1.42.0/lib/fog/cloudsigma/models/ipconf.rb0000644000004100000410000000035213171001215021126 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.42.0/lib/fog/cloudsigma/models/rule.rb0000644000004100000410000000102313171001215020613 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.42.0/lib/fog/cloudsigma/models/ips.rb0000644000004100000410000000102013171001215020434 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.42.0/lib/fog/cloudsigma/models/servers.rb0000644000004100000410000000106213171001215021340 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.42.0/lib/fog/cloudsigma/models/balance.rb0000644000004100000410000000040513171001215021234 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.42.0/lib/fog/cloudsigma/models/snapshot.rb0000644000004100000410000000327713171001215021520 0ustar www-datawww-datarequire 'fog/cloudsigma/nested_model' require 'fog/cloudsigma/models/volume' module Fog module Compute class CloudSigma class Snapshot < Fog::CloudSigma::CloudsigmaModel identity :uuid attribute :allocated_size, :type => :integer attribute :drive attribute :grantees, :type => :array attribute :meta attribute :name, :type => :string attribute :owner attribute :permissions, :type => :array attribute :resource_uri, :type => :string attribute :status, :type => :string attribute :tags attribute :timestamp, :type => :string def save if persisted? update else create end end def create requires :name, :drive data = attributes response = service.create_snapshot(data) new_attributes = response.body['objects'].first merge_attributes(new_attributes) end def update requires :identity, :name data = attributes response = service.update_snapshot(identity, data) new_attributes = response.body merge_attributes(new_attributes) end def destroy requires :identity service.delete_snapshot(identity) true end alias_method :delete, :destroy def clone(clone_params={}) requires :identity response = service.clone_snapshot(identity, clone_params) Volume.new(response.body) end alias_method :promote, :clone def available? status == 'available' end end end end end fog-1.42.0/lib/fog/cloudsigma/models/current_usage.rb0000644000004100000410000000105413171001215022516 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.42.0/lib/fog/cloudsigma/models/fwpolicies.rb0000644000004100000410000000056013171001215022015 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.42.0/lib/fog/cloudsigma/models/obj_ref.rb0000644000004100000410000000034313171001215021256 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.42.0/lib/fog/cloudsigma/models/lib_volume.rb0000644000004100000410000000257413171001215022015 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class CloudSigma class LibVolume < Fog::Model identity :uuid attribute :mounted_on 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 end fog-1.42.0/lib/fog/cloudsigma/models/ip.rb0000644000004100000410000000104013171001215020253 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.42.0/lib/fog/cloudsigma/models/fwpolicy.rb0000644000004100000410000000075213171001215021510 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.42.0/lib/fog/cloudsigma/models/nic.rb0000644000004100000410000000075413171001215020427 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 attribute :firewall_policy model_attribute :ip_v4_conf, IPConf model_attribute :ip_v6_conf, IPConf end end end end fog-1.42.0/lib/fog/cloudsigma/models/pricing.rb0000644000004100000410000000104713171001215021305 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 end fog-1.42.0/lib/fog/cloudsigma/models/subscription.rb0000644000004100000410000000271613171001215022402 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.42.0/lib/fog/cloudsigma/models/volumes.rb0000644000004100000410000000105413171001215021342 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.42.0/lib/fog/cloudsigma/models/price_calculation.rb0000644000004100000410000000053613171001215023334 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.42.0/lib/fog/cloudsigma/models/lib_volumes.rb0000644000004100000410000000107613171001215022174 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.42.0/lib/fog/cloudsigma/models/subscriptions.rb0000644000004100000410000000217113171001215022560 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.42.0/lib/fog/cloudsigma/models/snapshots.rb0000644000004100000410000000107013171001215021670 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/cloudsigma/models/snapshot' module Fog module Compute class CloudSigma class Snapshots < Fog::Collection model Fog::Compute::CloudSigma::Snapshot def all resp = service.list_snapshots data = resp.body['objects'] load(data) end def get(snap_id) resp = service.get_snapshot(snap_id) data = resp.body new(data) rescue Fog::CloudSigma::Errors::NotFound return nil end end end end end fog-1.42.0/lib/fog/cloudsigma/models/server.rb0000644000004100000410000001436413171001215021166 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_method :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 shutdown requires :identity service.stop_server(identity, true) end def ready? status == "running" 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 end fog-1.42.0/lib/fog/cloudsigma/models/usage_record.rb0000644000004100000410000000047013171001215022313 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.42.0/lib/fog/cloudsigma/models/price_record.rb0000644000004100000410000000212513171001215022310 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 end fog-1.42.0/lib/fog/cloudsigma/models/vlans.rb0000644000004100000410000000103613171001215020773 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.42.0/lib/fog/cloudsigma/error.rb0000644000004100000410000000226413171001215017522 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 end fog-1.42.0/lib/fog/cloudsigma/mock_data.rb0000644000004100000410000000255113171001215020312 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 end fog-1.42.0/lib/fog/cloudsigma/compute.rb0000644000004100000410000001316313171001215020045 0ustar www-datawww-datarequire 'fog/cloudsigma/core' 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 :snapshot collection :snapshots request :create_snapshot request :get_snapshot request :list_snapshots request :update_snapshot request :delete_snapshot request :clone_snapshot 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.find 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.find 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.find 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.42.0/lib/fog/dreamhost.rb0000644000004100000410000000003413171001215016221 0ustar www-datawww-datarequire 'fog/dreamhost/dns' fog-1.42.0/lib/fog/aws/0000755000004100000410000000000013171001215014503 5ustar www-datawww-datafog-1.42.0/lib/fog/aws/service_mapper.rb0000644000004100000410000001065313171001215020041 0ustar www-datawww-datamodule Fog module AWS # @api private # # This is a temporary lookup helper for extracting into external module. # # Cleaner provider/service registration will replace this code. # class ServiceMapper def self.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 self.[](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.new 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 self.services Fog::AWS.services end end end end fog-1.42.0/lib/fog/bin.rb0000644000004100000410000000510113171001215015003 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/fogdocker' 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/ibm' require 'fog/bin/internet_archive' require 'fog/bin/joyent' require 'fog/bin/linode' require 'fog/bin/local' require 'fog/bin/bare_metal_cloud' require 'fog/bin/rackspace' require 'fog/bin/rage4' require 'fog/bin/riakcs' require 'fog/bin/openstack' require 'fog/bin/ovirt' require 'fog/bin/powerdns' require 'fog/bin/profitbricks' require 'fog/bin/sakuracloud' require 'fog/bin/serverlove' require 'fog/bin/softlayer' require 'fog/bin/storm_on_demand' 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' require 'fog/bin/opennebula' require 'fog/bin/aliyun' fog-1.42.0/lib/fog/zerigo/0000755000004100000410000000000013171001215015210 5ustar www-datawww-datafog-1.42.0/lib/fog/zerigo/requests/0000755000004100000410000000000013171001215017063 5ustar www-datawww-datafog-1.42.0/lib/fog/zerigo/requests/dns/0000755000004100000410000000000013171001215017647 5ustar www-datawww-datafog-1.42.0/lib/fog/zerigo/requests/dns/create_host.rb0000644000004100000410000000750013171001215022476 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.42.0/lib/fog/zerigo/requests/dns/get_zone.rb0000644000004100000410000000365713171001215022021 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.42.0/lib/fog/zerigo/requests/dns/get_zone_stats.rb0000644000004100000410000000324713171001215023232 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.42.0/lib/fog/zerigo/requests/dns/create_zone.rb0000644000004100000410000001224113171001215022472 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.42.0/lib/fog/zerigo/requests/dns/delete_zone.rb0000644000004100000410000000155713171001215022501 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.42.0/lib/fog/zerigo/requests/dns/count_zones.rb0000644000004100000410000000172213171001215022544 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.42.0/lib/fog/zerigo/requests/dns/list_zones.rb0000644000004100000410000000353413171001215022372 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.42.0/lib/fog/zerigo/requests/dns/update_host.rb0000644000004100000410000000400213171001215022507 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.42.0/lib/fog/zerigo/requests/dns/get_host.rb0000644000004100000410000000257213171001215022016 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.42.0/lib/fog/zerigo/requests/dns/update_zone.rb0000644000004100000410000000626113171001215022516 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.42.0/lib/fog/zerigo/requests/dns/list_hosts.rb0000644000004100000410000000436713171001215022401 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 # * 'options'<~Hash> - optional parameters # * 'page' <~Integer> # * 'per_page' <~Integer> # * 'fqdn' <~String> # ==== 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, options={}) request( :query => options, :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, options={}) zone = find_by_zone_id(zone_id) response = Excon::Response.new if zone if options.empty? response.status = 200 response.body = { "hosts" => zone["hosts"] } else hosts = zone["hosts"] hosts = hosts.select {|h| h["fqdn"] == options["fqdn"]} if options["fqdn"] hosts = options["per_page"] ? hosts.each_slice(options["per_page"] - 1).to_a : hosts.each_slice(100).to_a hosts = options["page"] ? hosts[options["page"]] : hosts[0] response.status = 200 response.body = { "hosts" => hosts } end else response.status = 404 end response end end end end end fog-1.42.0/lib/fog/zerigo/requests/dns/count_hosts.rb0000644000004100000410000000221513171001215022544 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.42.0/lib/fog/zerigo/requests/dns/find_hosts.rb0000644000004100000410000000437013171001215022340 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].map { |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.42.0/lib/fog/zerigo/requests/dns/delete_host.rb0000644000004100000410000000163313171001215022476 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.42.0/lib/fog/zerigo/parsers/0000755000004100000410000000000013171001215016667 5ustar www-datawww-datafog-1.42.0/lib/fog/zerigo/parsers/dns/0000755000004100000410000000000013171001215017453 5ustar www-datawww-datafog-1.42.0/lib/fog/zerigo/parsers/dns/create_host.rb0000644000004100000410000000113113171001215022274 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.42.0/lib/fog/zerigo/parsers/dns/get_zone.rb0000644000004100000410000000325113171001215021613 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.42.0/lib/fog/zerigo/parsers/dns/get_zone_stats.rb0000644000004100000410000000072313171001215023032 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.42.0/lib/fog/zerigo/parsers/dns/create_zone.rb0000644000004100000410000000117713171001215022304 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.42.0/lib/fog/zerigo/parsers/dns/count_zones.rb0000644000004100000410000000055313171001215022351 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.42.0/lib/fog/zerigo/parsers/dns/list_zones.rb0000644000004100000410000000136713171001215022200 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.42.0/lib/fog/zerigo/parsers/dns/get_host.rb0000644000004100000410000000112613171001215021614 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.42.0/lib/fog/zerigo/parsers/dns/list_hosts.rb0000644000004100000410000000131513171001215022173 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.42.0/lib/fog/zerigo/parsers/dns/count_hosts.rb0000644000004100000410000000055313171001215022353 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.42.0/lib/fog/zerigo/parsers/dns/find_hosts.rb0000644000004100000410000000131513171001215022140 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.42.0/lib/fog/zerigo/dns.rb0000644000004100000410000000603013171001215016320 0ustar www-datawww-datarequire 'fog/zerigo/core' 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].map { |z| z['hosts'].find { |h| h['id'] == host_id } }.compact.first end end class Real def initialize(options={}) @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::XML::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) 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.42.0/lib/fog/zerigo/core.rb0000644000004100000410000000017613171001215016471 0ustar www-datawww-datarequire 'fog/core' require 'fog/xml' module Fog module Zerigo extend Fog::Provider service(:dns, 'DNS') end end fog-1.42.0/lib/fog/zerigo/models/0000755000004100000410000000000013171001215016473 5ustar www-datawww-datafog-1.42.0/lib/fog/zerigo/models/dns/0000755000004100000410000000000013171001215017257 5ustar www-datawww-datafog-1.42.0/lib/fog/zerigo/models/dns/zones.rb0000644000004100000410000000110013171001215020732 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.42.0/lib/fog/zerigo/models/dns/record.rb0000644000004100000410000000315713171001215021070 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.42.0/lib/fog/zerigo/models/dns/zone.rb0000644000004100000410000000530213171001215020557 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.42.0/lib/fog/zerigo/models/dns/records.rb0000644000004100000410000000223313171001215021245 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.42.0/lib/fog/core/0000755000004100000410000000000013171001215014641 5ustar www-datawww-datafog-1.42.0/lib/fog/core/parser.rb0000644000004100000410000000020013171001215016452 0ustar www-datawww-dataFog::Logger.deprecation("fog/core/parser is deprecated use fog/xml instead [light_black](#{caller.first})[/]") require 'fog/xml'fog-1.42.0/lib/fog/core/deprecated/0000755000004100000410000000000013171001215016741 5ustar www-datawww-datafog-1.42.0/lib/fog/core/deprecated/connection.rb0000644000004100000410000000155013171001215021426 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::Connection def request(params, &block) if params.key?(:parser) Fog::Logger.deprecation("Fog::Connection is deprecated use Fog::XML::Connection instead [light_black](#{caller.first})[/]") else Fog::Logger.deprecation("Fog::Connection is deprecated use Fog::Core::Connection instead [light_black](#{caller.first})[/]") end super(params) end end end fog-1.42.0/lib/fog/vcloud.rb0000644000004100000410000000003513171001215015530 0ustar www-datawww-datarequire 'fog/vcloud/compute' fog-1.42.0/lib/fog/vcloud/0000755000004100000410000000000013171001215015205 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud/examples/0000755000004100000410000000000013171001215017023 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud/examples/more_on_vapps.md0000644000004100000410000000131413171001215022213 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.42.0/lib/fog/vcloud/examples/get_vapp_information.md0000644000004100000410000000044313171001215023560 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.42.0/lib/fog/vcloud/examples/creating_a_connection.md0000644000004100000410000000142513171001215023662 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.42.0/lib/fog/vcloud/examples/get_network_information.md0000644000004100000410000000045413171001215024305 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.42.0/lib/fog/vcloud/examples/creating_a_vapp.md0000644000004100000410000000105613171001215022471 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.42.0/lib/fog/vcloud/examples/README.md0000644000004100000410000000517313171001215020310 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](http://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.42.0/lib/fog/vcloud/requests/0000755000004100000410000000000013171001215017060 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud/requests/compute/0000755000004100000410000000000013171001215020534 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud/requests/compute/get_organization.rb0000644000004100000410000000020213171001215024416 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_organization end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/get_customization_options.rb0000644000004100000410000000021313171001215026377 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_customization_options end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/get_task_list.rb0000644000004100000410000000017713171001215023722 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_task_list end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/get_task.rb0000644000004100000410000000017213171001215022662 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_task end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/get_vm_memory.rb0000644000004100000410000000045113171001215023732 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.42.0/lib/fog/vcloud/requests/compute/configure_vm_memory.rb0000644000004100000410000000361113171001215025135 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.42.0/lib/fog/vcloud/requests/compute/delete_metadata.rb0000644000004100000410000000022013171001215024155 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :delete_metadata, 202, "DELETE" end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/get_vm_disks.rb0000644000004100000410000000044413171001215023541 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.42.0/lib/fog/vcloud/requests/compute/get_server.rb0000644000004100000410000000017413171001215023230 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_server end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/get_vapp_template.rb0000644000004100000410000000020313171001215024554 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_vapp_template end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/configure_node.rb0000644000004100000410000000201213171001215024042 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.42.0/lib/fog/vcloud/requests/compute/power_off.rb0000644000004100000410000000021013171001215023040 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :power_off, 202, 'POST' end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/undeploy.rb0000644000004100000410000000221413171001215022717 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.42.0/lib/fog/vcloud/requests/compute/get_network.rb0000644000004100000410000000017513171001215023414 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_network end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/power_shutdown.rb0000644000004100000410000000021513171001215024146 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :power_shutdown, 204, 'POST' end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/clone_vapp.rb0000644000004100000410000000250013171001215023204 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.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.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.42.0/lib/fog/vcloud/requests/compute/get_network_extensions.rb0000644000004100000410000000021013171001215025661 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_network_extensions end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/login.rb0000644000004100000410000000101713171001215022170 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.42.0/lib/fog/vcloud/requests/compute/configure_network_ip.rb0000644000004100000410000000256713171001215025315 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.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.42.0/lib/fog/vcloud/requests/compute/configure_vapp.rb0000644000004100000410000001321613171001215024073 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.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].find { |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.42.0/lib/fog/vcloud/requests/compute/get_vdc.rb0000644000004100000410000000017113171001215022473 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_vdc end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/configure_vm.rb0000644000004100000410000001400413171001215023543 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.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 end fog-1.42.0/lib/fog/vcloud/requests/compute/delete_node.rb0000644000004100000410000000022413171001215023326 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :delete_node, 200, 'DELETE', {}, "" end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/configure_network.rb0000644000004100000410000000255113171001215024616 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.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.42.0/lib/fog/vcloud/requests/compute/configure_vm_password.rb0000644000004100000410000000330713171001215025471 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.42.0/lib/fog/vcloud/requests/compute/power_reset.rb0000644000004100000410000000021213171001215023412 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :power_reset, 202, 'POST' end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/get_catalog.rb0000644000004100000410000000017513171001215023335 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_catalog end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/configure_metadata.rb0000644000004100000410000000200113171001215024673 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.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.42.0/lib/fog/vcloud/requests/compute/configure_vm_name_description.rb0000644000004100000410000000130013171001215027141 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.42.0/lib/fog/vcloud/requests/compute/get_vapp.rb0000644000004100000410000000017213171001215022666 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_vapp end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/instantiate_vapp_template.rb0000644000004100000410000000734413171001215026335 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.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].find { |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.42.0/lib/fog/vcloud/requests/compute/get_metadata.rb0000644000004100000410000000017613171001215023504 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_metadata end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/configure_org_network.rb0000644000004100000410000001347513171001215025474 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.42.0/lib/fog/vcloud/requests/compute/get_network_ips.rb0000644000004100000410000000031013171001215024256 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.42.0/lib/fog/vcloud/requests/compute/configure_vm_disks.rb0000644000004100000410000001112213171001215024736 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.find { |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.42.0/lib/fog/vcloud/requests/compute/configure_vm_network.rb0000644000004100000410000000266413171001215025325 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.42.0/lib/fog/vcloud/requests/compute/configure_vm_cpus.rb0000644000004100000410000000363313171001215024603 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.42.0/lib/fog/vcloud/requests/compute/power_on.rb0000644000004100000410000000020713171001215022710 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :power_on, 202, 'POST' end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/delete_vapp.rb0000644000004100000410000000021413171001215023346 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :delete_vapp, 202, "DELETE" end end end end fog-1.42.0/lib/fog/vcloud/requests/compute/get_network_ip.rb0000644000004100000410000000031113171001215024074 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.42.0/lib/fog/vcloud/requests/compute/configure_vm_customization_script.rb0000644000004100000410000000265713171001215030132 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.42.0/lib/fog/vcloud/requests/compute/get_catalog_item.rb0000644000004100000410000000020213171001215024342 0ustar www-datawww-datamodule Fog module Vcloud class Compute class Real basic_request :get_catalog_item end end end end fog-1.42.0/lib/fog/vcloud/core.rb0000644000004100000410000000020613171001215016460 0ustar www-datawww-datarequire 'fog/core' require 'fog/xml' module Fog module Vcloud extend Fog::Provider service(:compute, 'Compute') end end fog-1.42.0/lib/fog/vcloud/models/0000755000004100000410000000000013171001215016470 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud/models/compute/0000755000004100000410000000000013171001215020144 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud/models/compute/task.rb0000644000004100000410000000113513171001215021433 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.42.0/lib/fog/vcloud/models/compute/ips.rb0000644000004100000410000000130013171001215021256 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.42.0/lib/fog/vcloud/models/compute/organization.rb0000644000004100000410000000223613171001215023200 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.42.0/lib/fog/vcloud/models/compute/servers.rb0000644000004100000410000000205313171001215022162 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.42.0/lib/fog/vcloud/models/compute/vdc.rb0000644000004100000410000000251113171001215021244 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.42.0/lib/fog/vcloud/models/compute/catalogs.rb0000644000004100000410000000157613171001215022277 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.map { |catalog| catalog.catalog_items } items.each do |i| i.map do |ii| res = ii if ii.name == name end end res end end end end end fog-1.42.0/lib/fog/vcloud/models/compute/network.rb0000644000004100000410000000126613171001215022167 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.42.0/lib/fog/vcloud/models/compute/catalog.rb0000644000004100000410000000077413171001215022113 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.42.0/lib/fog/vcloud/models/compute/ip.rb0000644000004100000410000000166513171001215021111 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.42.0/lib/fog/vcloud/models/compute/tag.rb0000644000004100000410000000067013171001215021247 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.42.0/lib/fog/vcloud/models/compute/tags.rb0000644000004100000410000000121413171001215021425 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 end fog-1.42.0/lib/fog/vcloud/models/compute/catalog_items.rb0000644000004100000410000000144213171001215023305 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.42.0/lib/fog/vcloud/models/compute/vapp.rb0000644000004100000410000000262013171001215021437 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.42.0/lib/fog/vcloud/models/compute/catalog_item.rb0000644000004100000410000000237613171001215023131 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.42.0/lib/fog/vcloud/models/compute/vdcs.rb0000644000004100000410000000132613171001215021432 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.42.0/lib/fog/vcloud/models/compute/vapps.rb0000644000004100000410000000104013171001215021615 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.42.0/lib/fog/vcloud/models/compute/helpers/0000755000004100000410000000000013171001215021606 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud/models/compute/helpers/status.rb0000644000004100000410000000125613171001215023462 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.42.0/lib/fog/vcloud/models/compute/server.rb0000644000004100000410000002417513171001215022010 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.map{|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_method :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.find { |item| item[:"rasd:ResourceType"] == "4" } end end def cpu_mess load_unless_loaded! if virtual_hardware virtual_hardware.find { |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.42.0/lib/fog/vcloud/models/compute/organizations.rb0000644000004100000410000000121013171001215023352 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.42.0/lib/fog/vcloud/models/compute/tasks.rb0000644000004100000410000000107513171001215021621 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.42.0/lib/fog/vcloud/models/compute/networks.rb0000644000004100000410000000256013171001215022350 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.map{|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.42.0/lib/fog/vcloud/compute.rb0000644000004100000410000002552313171001215017215 0ustar www-datawww-datarequire 'fog/vcloud/core' 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' @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::XML::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.42.0/lib/fog/go_grid/0000755000004100000410000000000013171001215015323 5ustar www-datawww-datafog-1.42.0/lib/fog/go_grid/requests/0000755000004100000410000000000013171001215017176 5ustar www-datawww-datafog-1.42.0/lib/fog/go_grid/requests/compute/0000755000004100000410000000000013171001215020652 5ustar www-datawww-datafog-1.42.0/lib/fog/go_grid/requests/compute/support_password_get.rb0000644000004100000410000000113513171001215025474 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.42.0/lib/fog/go_grid/requests/compute/grid_server_get.rb0000644000004100000410000000102213171001215024344 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.42.0/lib/fog/go_grid/requests/compute/grid_server_power.rb0000644000004100000410000000116713171001215024733 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.42.0/lib/fog/go_grid/requests/compute/grid_ip_list.rb0000644000004100000410000000145113171001215023650 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.42.0/lib/fog/go_grid/requests/compute/common_lookup_list.rb0000644000004100000410000000132613171001215025115 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.42.0/lib/fog/go_grid/requests/compute/grid_image_get.rb0000644000004100000410000000165313171001215024132 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.42.0/lib/fog/go_grid/requests/compute/grid_server_add.rb0000644000004100000410000000215013171001215024320 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.42.0/lib/fog/go_grid/requests/compute/grid_image_list.rb0000644000004100000410000000223313171001215024321 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.42.0/lib/fog/go_grid/requests/compute/grid_server_delete.rb0000644000004100000410000000100013171001215025023 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.42.0/lib/fog/go_grid/requests/compute/grid_loadbalancer_list.rb0000644000004100000410000000124713171001215025652 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.42.0/lib/fog/go_grid/requests/compute/grid_server_list.rb0000644000004100000410000000150213171001215024543 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.42.0/lib/fog/go_grid/requests/compute/support_password_list.rb0000644000004100000410000000151613171001215025673 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.42.0/lib/fog/go_grid/core.rb0000644000004100000410000000020713171001215016577 0ustar www-datawww-datarequire 'fog/core' require 'fog/json' module Fog module GoGrid extend Fog::Provider service(:compute, 'Compute') end end fog-1.42.0/lib/fog/go_grid/models/0000755000004100000410000000000013171001215016606 5ustar www-datawww-datafog-1.42.0/lib/fog/go_grid/models/compute/0000755000004100000410000000000013171001215020262 5ustar www-datawww-datafog-1.42.0/lib/fog/go_grid/models/compute/images.rb0000644000004100000410000000121613171001215022054 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.42.0/lib/fog/go_grid/models/compute/servers.rb0000644000004100000410000000134013171001215022276 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.42.0/lib/fog/go_grid/models/compute/password.rb0000644000004100000410000000170113171001215022450 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.42.0/lib/fog/go_grid/models/compute/passwords.rb0000644000004100000410000000143013171001215022632 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.42.0/lib/fog/go_grid/models/compute/server.rb0000644000004100000410000000505113171001215022116 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, :ssh_ip_address, :public_key, :username Fog::SSH.new(ssh_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.42.0/lib/fog/go_grid/models/compute/image.rb0000644000004100000410000000257313171001215021700 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.42.0/lib/fog/go_grid/compute.rb0000644000004100000410000000612513171001215017330 0ustar www-datawww-datarequire 'fog/go_grid/core' 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::XML::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.42.0/lib/fog/cloudsigma.rb0000644000004100000410000000004113171001215016360 0ustar www-datawww-datarequire 'fog/cloudsigma/compute' fog-1.42.0/lib/fog/vcloud_director/0000755000004100000410000000000013171001215017100 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud_director/requests/0000755000004100000410000000000013171001215020753 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud_director/requests/compute/0000755000004100000410000000000013171001215022427 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud_director/requests/compute/post_clone_media.rb0000644000004100000410000000701313171001215026261 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.42.0/lib/fog/vcloud_director/requests/compute/get_organization.rb0000644000004100000410000000704113171001215026321 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.42.0/lib/fog/vcloud_director/requests/compute/put_disk_metadata_item_metadata.rb0000644000004100000410000000333113171001215031314 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.42.0/lib/fog/vcloud_director/requests/compute/get_media_metadata.rb0000644000004100000410000000136313171001215026535 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.42.0/lib/fog/vcloud_director/requests/compute/get_vapp_owner.rb0000644000004100000410000000305213171001215025773 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 class Mock def get_vapp_owner(id) type = 'application/vnd.vmware.vcloud.owner+xml' unless vapp = data[:vapps][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => get_owner_section_body(id) ) end def get_owner_section_body(id) { :type => 'application/vnd.vmware.vcloud.owner+xml', :User => { :type => "application/vnd.vmware.admin.user+xml", :name => "mockuser", :href => make_href("user/12345678-1234-1234-1234-12345678df2b"), } } end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_href.rb0000644000004100000410000000075613171001215024547 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.42.0/lib/fog/vcloud_director/requests/compute/get_org_vdc_gateways.rb0000644000004100000410000000575313171001215027154 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.42.0/lib/fog/vcloud_director/requests/compute/post_answer_vm_pending_question.rb0000644000004100000410000000233213171001215031455 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.42.0/lib/fog/vcloud_director/requests/compute/get_media_owner.rb0000644000004100000410000000444113171001215026107 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.42.0/lib/fog/vcloud_director/requests/compute/post_update_media_metadata.rb0000644000004100000410000000356013171001215030306 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.42.0/lib/fog/vcloud_director/requests/compute/get_task_list.rb0000644000004100000410000001432013171001215025610 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.42.0/lib/fog/vcloud_director/requests/compute/get_task.rb0000644000004100000410000001644713171001215024571 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.42.0/lib/fog/vcloud_director/requests/compute/put_memory.rb0000644000004100000410000000666213171001215025166 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 class Mock def put_memory(id, memory) unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end owner = { :href => make_href("vApp/#{id}"), :type => 'application/vnd.vmware.vcloud.vm+xml' } task_id = enqueue_task( "Updating Virtual Machine #{data[:vms][id][:name]}(#{id})", 'vappUpdateVm', owner, :on_success => lambda do data[:vms][id][:memory_in_mb] = memory 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.42.0/lib/fog/vcloud_director/requests/compute/get_vm.rb0000644000004100000410000000471713171001215024246 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 class Mock def get_vm(id) vapp = get_vapp(id).body vm = parse_vapp_to_vm(vapp) body = {:type => vapp[:type], :vm => vm} Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end # Mock equivalent of Fog::Parsers::Compute::VcloudDirector::Vm def parse_vapp_to_vm(vapp) parser = Fog::Parsers::Compute::VcloudDirector::Vm.new vm = vapp.select {|k| [:href, :name, :status, :type].include? k} network = vapp[:NetworkConnectionSection] vm.merge({ :id => vapp[:href].split('/').last, :status => parser.human_status(vapp[:status]), :ip_address => network[:NetworkConnection][:IpAddress], :description => vapp[:Description], :cpu => get_hardware(vapp, 3), :memory => get_hardware(vapp, 4), :disks => get_disks(vapp), :links => [vapp[:GuestCustomizationSection][:Link]], }) end def get_hardware(vapp, resource_type) hardware = vapp[:"ovf:VirtualHardwareSection"][:"ovf:Item"] item = hardware.find {|h| h[:"rasd:ResourceType"].to_i == resource_type} if item and item.key? :"rasd:VirtualQuantity" item[:"rasd:VirtualQuantity"].to_i else nil end end def get_disks(vapp) hardware = vapp[:"ovf:VirtualHardwareSection"][:"ovf:Item"] disks = hardware.select {|h| h[:"rasd:ResourceType"].to_i == 17} disks.map {|d| {d[:"rasd:ElementName"] => d[:"rasd:HostResource"][:ns12_capacity].to_i}} end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/delete_vapp_template_metadata_item_metadata.rb0000644000004100000410000000157213171001215033662 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.42.0/lib/fog/vcloud_director/requests/compute/post_remove_all_snapshots.rb0000644000004100000410000000161313171001215030251 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.42.0/lib/fog/vcloud_director/requests/compute/post_reboot_vapp.rb0000644000004100000410000000207713171001215026347 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.42.0/lib/fog/vcloud_director/requests/compute/get_disks_rasd_items_list.rb0000644000004100000410000000527313171001215030204 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 class Mock def get_disks_rasd_items_list(id) type = 'application/vnd.vmware.vcloud.rasdItemsList+xml' unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end body = { :type => type, :href => make_href("vApp/#{id}/virtualHardwareSection/disks"), :Link => { :rel=>"edit", :type=>"application/vnd.vmware.vcloud.rasdItemsList+xml", :href=>make_href("vApp/#{id}/virtualHardwareSection/disks"), }, :Item => [ get_disks_rasd_items_list_body(id, vm), get_media_rasd_item_ide_controller_body(id, vm), ].flatten } Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => body ) end def get_disks_rasd_items_list_body(id, vm) [ { :"rasd:Address"=>"0", :"rasd:Description"=>"SCSI Controller", :"rasd:ElementName"=>"SCSI Controller 0", :"rasd:InstanceID"=>"2", :"rasd:ResourceSubType"=>"lsilogic", :"rasd:ResourceType"=>"6" }, # TODO: Add support for adding disks { :"rasd:AddressOnParent"=>"0", :"rasd:Description"=>"Hard disk", :"rasd:ElementName"=>"Hard disk 1", :"rasd:HostResource"=>{ :ns12_capacity=>"51200", :ns12_busSubType=>"lsilogic", :ns12_busType=>"6" }, :"rasd:InstanceID"=>"2000", :"rasd:Parent"=>"2", :"rasd:ResourceType"=>"17" }, ] end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/delete_vapp_metadata_item_metadata.rb0000644000004100000410000000175613171001215031773 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.42.0/lib/fog/vcloud_director/requests/compute/get_catalog_item_metadata.rb0000644000004100000410000000141313171001215030102 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.42.0/lib/fog/vcloud_director/requests/compute/get_allocated_ip_addresses.rb0000644000004100000410000000142213171001215030267 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.42.0/lib/fog/vcloud_director/requests/compute/get_guest_customization_system_section_vapp_template.rbfog-1.42.0/lib/fog/vcloud_director/requests/compute/get_guest_customization_system_section_vapp_temp0000644000004100000410000000150413171001215034533 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.42.0/lib/fog/vcloud_director/requests/compute/get_control_access_params_vapp.rb0000644000004100000410000000137513171001215031213 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.42.0/lib/fog/vcloud_director/requests/compute/get_serial_ports_items_list.rb0000644000004100000410000000144613171001215030562 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.42.0/lib/fog/vcloud_director/requests/compute/put_vapp_metadata_item_metadata.rb0000644000004100000410000000556413171001215031342 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 class Mock def put_vapp_metadata_item_metadata(id, key, value) unless vm_or_vapp = data[:vapps][id] || vm_or_vapp = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end owner = { :href => make_href("vApp/#{id}"), :type => 'application/vnd.vmware.vcloud.vm+xml' } task_id = enqueue_task( "Updating Virtual Machine #{vm_or_vapp[:name]}(#{id})", 'vappUpdateVm', owner, :on_success => lambda do vm_or_vapp[:metadata][key] = value 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.42.0/lib/fog/vcloud_director/requests/compute/get_vdc_metadata_item_metadata.rb0000644000004100000410000000164113171001215031107 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.42.0/lib/fog/vcloud_director/requests/compute/get_lease_settings_section_vapp_template.rb0000644000004100000410000000147113171001215033274 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.42.0/lib/fog/vcloud_director/requests/compute/get_virtual_hardware_section.rb0000644000004100000410000000175313171001215030710 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.42.0/lib/fog/vcloud_director/requests/compute/get_product_sections_vapp_template.rb0000644000004100000410000000150713171001215032126 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.42.0/lib/fog/vcloud_director/requests/compute/get_network_config_section_vapp.rb0000644000004100000410000000364113171001215031407 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 class Mock def get_network_config_section_vapp(id) type = 'application/vnd.vmware.vcloud.networkConfigSection+xml' unless vapp = data[:vapps][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => get_vapp_network_config_section_body(id, vapp) ) end def get_vapp_network_config_section_body(id, vapp) # TODO: This is effectively hardcoding a vAppNetwork configuration # into here, but this is sufficient for initial testing. # This network configuration has no networks. { :type => "application/vnd.vmware.vcloud.networkConfigSection+xml", :href => make_href("vApp/#{id}/networkConfigSection/"), :ovf_required => "false", :"ovf:Info" => "The configuration parameters for logical networks", :NetworkConfig => [], } end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_vm_disks.rb0000644000004100000410000000325313171001215025435 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 class Mock def get_vm_disks(id) disks = data[:disks].values.select {|d| d[:parent_vm] == id}.each_with_index.map do |disk, i| { :address => i, :description => disk[:description], :name => disk[:name], :id => (i+1)*1000, :resource_type => 17, :capacity => disk[:capacity], } end body = {:type => 'application/vnd.vmware.vcloud.rasditemslist+xml', :disks => disks} Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/post_reset_vapp.rb0000644000004100000410000000207113171001215026171 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.42.0/lib/fog/vcloud_director/requests/compute/get_cpu_rasd_item.rb0000644000004100000410000000370013171001215026431 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 class Mock def get_cpu_rasd_item(id) type = 'application/vnd.vmware.vcloud.rasdItem+xml' unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => get_cpu_rasd_item_body(id, vm) ) end def get_cpu_rasd_item_body(id, vm) { :ns12_href => make_href("vApp/#{id}/virtualHardwareSection/cpu"), :ns12_type => "application/vnd.vmware.vcloud.rasdItem+xml", :"rasd:AllocationUnits"=>"hertz * 10^6", :"rasd:Description"=>"Number of Virtual CPUs", :"rasd:ElementName"=>"#{vm[:cpu_count]} virtual CPU(s)", :"rasd:InstanceID"=>"4", :"rasd:Reservation"=>"0", :"rasd:ResourceType"=>"3", :"rasd:VirtualQuantity"=>"#{vm[:cpu_count]}", :"rasd:Weight"=>"0", } end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/post_upload_media.rb0000644000004100000410000001027213171001215026446 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].find {|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.42.0/lib/fog/vcloud_director/requests/compute/post_create_org_vdc_network.rb0000644000004100000410000001513513171001215030545 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.42.0/lib/fog/vcloud_director/requests/compute/get_vms_in_lease_from_query.rb0000644000004100000410000001476713171001215030546 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].find {|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 class Mock def get_vms_in_lease_from_query(options={}) if options.key?(:filter) && options[:filter] =~ /^href==([^;,]+)$/ href = $1 id = href.split('/').last else Fog::Mock.not_implemented("Filter by href is currently the only option implemented in get_vms_in_lease_from_query Mock") end vm = data[:vms][id] parent_vapp_id = vm[:parent_vapp] vdc_id = data[:vapps][parent_vapp_id][:vdc_id] body = { :xmlns=>xmlns, :xmlns_xsi=>xmlns_xsi, :href=>make_href('query'), :name=>"vm", :type=>"application/vnd.vmware.vcloud.query.records+xml", :xsi_schemaLocation=>xsi_schema_location, :total=>"1", :pageSize=>"25", :page=>"1", :Link=> [{:rel=>"alternate", :type=>"application/vnd.vmware.vcloud.query.references+xml", :href=>make_href('query')}, {:rel=>"alternate", :type=>"application/vnd.vmware.vcloud.query.idrecords+xml", :href=>make_href('query')}], :VMRecord=> [{:vdc=>make_href(vdc_id), :numberOfCpus=>vm[:cpu_count], :name=>vm[:name], :containerName=>data[:vapps][parent_vapp_id][:name], :memoryMB=>vm[:memory_in_mb], :isVAppTemplate=>"false", :href=>make_href(id), :taskStatus=>"success", :task=>make_href("task/#{uuid}"), :taskDetails=>" ", :taskStatusName=>"vappUpdateVm"}] } Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/post_exit_maintenance_mode.rb0000644000004100000410000000121113171001215030333 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.42.0/lib/fog/vcloud_director/requests/compute/get_vapp_template.rb0000644000004100000410000000133113171001215026452 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.42.0/lib/fog/vcloud_director/requests/compute/post_consolidate_vm_vapp_template.rb0000644000004100000410000000153713171001215031756 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.42.0/lib/fog/vcloud_director/requests/compute/get_execute_query.rb0000644000004100000410000010421513171001215026505 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 {|k, v| "#{k}=#{CGI.escape(v.to_s)}" }.join('&').gsub('%3D', '=').gsub('%3B', ';') ) 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].find {|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 type == 'vAppTemplate' && opts.key?(:filter) && opts[:filter] =~ /^name==([^;,]+);catalogName==([^;,]+)$/ #TODO also match in other order name = $1 catalog_name = $2 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, } records = [] record_type = nil if type == 'orgVdc' record_type = :OrgVdcRecord vdc_id = data[:vdcs].keys[0] vdc_name = data[:vdcs][vdc_id][:name] records = [{ :storageUsedMB=>"123967", :storageLimitMB=>"8388608", :storageAllocationMB=>"0", :status=>"READY", :orgName=>"orgName", :name=>vdc_name, :memoryUsedMB=>"0", :memoryLimitMB=>"0", :memoryAllocationMB=>"0", :isSystemVdc=>"false", :isEnabled=>"true", :isBusy=>"false", :href=>make_href("vdc/#{vdc_id}"), }] 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 elsif type == 'orgVdcNetwork' record_type = :OrgVdcNetworkRecords data_type = :networks 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 elsif type == 'edgeGateway' record_type = :EdgeGatewayRecord edge_gateway_id = data[:edge_gateways].keys[0] vdc_id = data[:edge_gateways][edge_gateway_id][:vdc] records = [{ :vdc=>make_href("vdc/#{vdc_id}"), :numberOfOrgNetworks=>"1", :numberOfExtNetworks=>"1", :name=>"Test EdgeGateway Name", :isBusy=>"false", :haStatus=>"DISABLED", :gatewayStatus=>"READY", :href=>make_href("edgeGateway/#{edge_gateway_id}"), :taskStatus=>"success", :taskOperation=>"networkConfigureEdgeGatewayServices", :task=>make_href("task/#{uuid}"), :taskDetails=>" " }] 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 elsif type == 'vAppTemplate' record_type = :VAappTemplateRecord records = [{ :vdcName=>"Bogus vDC", :vdc=>make_href("vdc/#{uuid}"), :storageProfileName=>"*", :status=>"RESOLVED", :ownerName=>"system", :org=> make_href("org/#{data[:org][:uuid]}"), :name=> name, :isPublished=>"true", :isGoldMaster=>"false", :isExpired=>"false", :isEnabled=>"true", :isDeployed=>"false", :isBusy=>"false", :creationDate=>"2013-09-19T22:55:30.257+01:00", :catalogName=> catalog_name, :href=> make_href("vAppTemplate/vappTemplate-#{uuid}"), :honorBootOrder=>"false", :isVdcEnabled=>"true", :isInCatalog=>"true", :cpuAllocationMhz=>"8", :cpuAllocationInMhz=>"16000", :storageKB=>"52428800", :numberOfShadowVMs=>"0", :numberOfVMs=>"1", :isAutoDeleteNotified=>"false", :numberOfCpus=>"8", :isAutoUndeployNotified=>"false", :memoryAllocationMB=>"32768" }] 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 elsif type == 'vApp' record_type = :VAppRecord all_records = data[:vapps].map do |vapp_id, vapp| { :vdcName => data.fetch(:vdcs).fetch(vapp[:vdc_id]).fetch(:name), :vdc => make_href("vdc/#{vapp[:vdc_id]}"), :storageProfileName => "*", :ownerName => "system", :name => vapp.fetch(:name), :status => 'POWERED_OFF', :isInMaintenanceMode=> 'false', :isPublic => 'false', :isExpired =>"false", :isEnabled =>"true", :isDeployed =>"false", :isBusy => "false", :pvdcHighestSupportedHardwareVersion => '8', :lowestHardwareVersionInVApp => '8', :creationDate => "2013-09-19T22:55:30.257+01:00", :href => make_href("vApp/#{vapp_id}"), :honorBootOrder => "false", :isVdcEnabled => "true", :cpuAllocationMhz => "8", :cpuAllocationInMhz => "16000", :storageKB => "52428800", :numberOfVMs => "1", :isAutoDeleteNotified => "false", :numberOfCpus => "8", :isAutoUndeployNotified => "false", :memoryAllocationMB => "32768", :task => make_href("task/#{uuid}"), :taskStatusName => 'vdcInstantiateVapp', :taskStatus => 'success', :taskDetails => " ", } end records = all_records.select do |record| record[:name] == name 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 elsif type == 'task' record_type = :TaskRecord data_type = :tasks data[data_type].each do |id, dr| r = {} if name.nil? || dr.fetch(:operation_name) == name r[:name] = dr.fetch(:operation_name) r[:href] = make_href("task/#{id}") if dr.key?(:end_time) r[:endDate] = dr.fetch(:end_time).strftime('%Y-%m-%dT%H:%M:%S%z') else r[:endDate] = nil end if dr.key?(:start_time) r[:startDate] = dr.fetch(:start_time).strftime('%Y-%m-%dT%H:%M:%S%z') else r[:startDate] = nil end r[:status] = dr.fetch(:status) r[:serviceNamespace] = 'com.vmware.vcloud' r[:ownerName] = '000.0.000000' r[:orgName] = data.fetch(:org).fetch(:name) r[:org] = make_href("org/#{data[:org][:uuid]}") r[:objectType] = dr.fetch(:owner).fetch(:type).split(/\./).last.split(/\+/).first r[:objectName] = dr.fetch(:owner).fetch(:name, '') # objectName is optional r[:object] = dr.fetch(:owner).fetch(:href) r[:details] = '! []' records << r end end else Fog::Mock.not_implemented("No 'get by name' get_execute_query Mock for #{type} (#{name})") 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 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.42.0/lib/fog/vcloud_director/requests/compute/get_network_section_vapp.rb0000644000004100000410000000137013171001215030057 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.42.0/lib/fog/vcloud_director/requests/compute/put_media_metadata_item_metadata.rb0000644000004100000410000000353313171001215031445 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.42.0/lib/fog/vcloud_director/requests/compute/get_vapps_in_lease_from_query.rb0000644000004100000410000001116113171001215031053 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].find {|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.42.0/lib/fog/vcloud_director/requests/compute/get_request.rb0000644000004100000410000000057013171001215025305 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.42.0/lib/fog/vcloud_director/requests/compute/put_vm_capabilities.rb0000644000004100000410000000306713171001215027005 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.42.0/lib/fog/vcloud_director/requests/compute/get_snapshot_section.rb0000644000004100000410000000311613171001215027177 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 class Mock def get_snapshot_section(id) type = 'application/vnd.vmware.vcloud.snapshotSection+xml' unless data[:vms][id] || data[:vapps][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => get_snapshot_section_body(id) ) end def get_snapshot_section_body(id) { :type => "application/vnd.vmware.vcloud.snapshotSection+xml", :href => make_href("vApp/#{id}/snapshotSection"), :ovf_required => "false", :"ovf:Info" => "Snapshot information section" } end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_current_session.rb0000644000004100000410000000631513171001215027045 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.42.0/lib/fog/vcloud_director/requests/compute/get_vdc_storage_class_metadata_item_metadata.rb0000644000004100000410000000154513171001215034023 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.42.0/lib/fog/vcloud_director/requests/compute/post_update_disk_metadata.rb0000644000004100000410000000354513171001215030164 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.42.0/lib/fog/vcloud_director/requests/compute/get_entity.rb0000644000004100000410000000271513171001215025134 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.42.0/lib/fog/vcloud_director/requests/compute/put_metadata_value.rb0000644000004100000410000000163313171001215026623 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.42.0/lib/fog/vcloud_director/requests/compute/delete_vapp_template.rb0000644000004100000410000000147613171001215027147 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.42.0/lib/fog/vcloud_director/requests/compute/get_template_vm.rb0000644000004100000410000000472713171001215026142 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 => "vAppTemplate/#{id}" ) end end class Mock def get_vm(id) vapp = get_vapp(id).body vm = parse_vapp_to_vm(vapp) body = {:type => vapp[:type], :vm => vm} Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end # Mock equivalent of Fog::Parsers::Compute::VcloudDirector::Vm def parse_vapp_to_vm(vapp) parser = Fog::Parsers::Compute::VcloudDirector::Vm.new vm = vapp.select {|k| [:href, :name, :status, :type].include? k} network = vapp[:NetworkConnectionSection] vm.merge({ :id => vapp[:href].split('/').last, :status => parser.human_status(vapp[:status]), :ip_address => network[:NetworkConnection][:IpAddress], :description => vapp[:Description], :cpu => get_hardware(vapp, 3), :memory => get_hardware(vapp, 4), :disks => get_disks(vapp), :links => [vapp[:GuestCustomizationSection][:Link]], }) end def get_hardware(vapp, resource_type) hardware = vapp[:"ovf:VirtualHardwareSection"][:"ovf:Item"] item = hardware.find {|h| h[:"rasd:ResourceType"].to_i == resource_type} if item and item.key? :"rasd:VirtualQuantity" item[:"rasd:VirtualQuantity"].to_i else nil end end def get_disks(vapp) hardware = vapp[:"ovf:VirtualHardwareSection"][:"ovf:Item"] disks = hardware.select {|h| h[:"rasd:ResourceType"].to_i == 17} disks.map {|d| {d[:"rasd:ElementName"] => d[:"rasd:HostResource"][:ns12_capacity].to_i}} end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/post_compose_vapp.rb0000644000004100000410000000411413171001215026514 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/generators/compute/compose_vapp' # Compose a vApp from existing virtual machines. # # 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 vdc. # @param [Hash] options # @option options [Boolean] :powerOn Used to specify whether to power # on vApp on deployment, if not set default value is true. # @option options [Boolean] :deploy Used to specify whether to deploy # the vApp, if not set default value is true. # @option options [String] :name Used to identify the vApp. # @option options [String] :networkName Used to conect the vApp and VMs to a VDC network, which has # to exist beforehand. # @option options [String] :networkHref Used to conect the vApp and VMs to a VDC network, which has # to exist beforehand. # @option options [String] :fenceMode Used to configure the network Mode (briged, isolated). # @option options [String] :source_vms Array with VMs to be used to compose the vApp, each containing - # :name, :href, :isGuestCustomizationEnabled, :computer_name and :ipAllocationMode (e.g. 'DHCP'). # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-ComposeVApp.html # @since vCloud API version 0.9 def post_compose_vapp(id, options={}) body = Fog::Generators::Compute::VcloudDirector::ComposeVapp.new(options).generate_xml request( :body => body, :expects => 201, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.composeVAppParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vdc/#{id}/action/composeVApp" ) end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_vms_by_metadata.rb0000644000004100000410000000107713171001215026757 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.42.0/lib/fog/vcloud_director/requests/compute/get_vm_customization.rb0000644000004100000410000000202013171001215027217 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.42.0/lib/fog/vcloud_director/requests/compute/get_network.rb0000644000004100000410000000442413171001215025310 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/parsers/compute/network' # Retrieve an organization network. # # @deprecated Use {#get_network_complete} instead # # @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) Fog::Logger.deprecation("#{self} => #get_network is deprecated, use #get_network_complete instead [light_black](#{caller.first})[/]") 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) Fog::Logger.deprecation("#{self} => #get_network is deprecated, use #get_network_complete instead [light_black](#{caller.first})[/]") 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.42.0/lib/fog/vcloud_director/requests/compute/post_capture_vapp.rb0000644000004100000410000000560113171001215026514 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. # @option options [Hash] :LeaseSettingsSection # * :StorageLeaseInSeconds<~Integer> - Storage lease in seconds. # @option options [Hash] :CustomizationSection # * :goldMaster<~Boolean> - True if this template is a gold master. # * :CustomizeOnInstantiate<~Boolean> - True if instantiating this # template applies customization settings. Otherwise, instantiation # creates an identical copy. # @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', 'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1', :name => name } CaptureVAppParams(attrs) { if options.key?(:Description) Description options[:Description] end Source(:href => "#{end_point}vApp/#{source_id}") if section = options[:LeaseSettingsSection] LeaseSettingsSection { self['ovf'].Info 'Lease settings section' if section.key?(:StorageLeaseInSeconds) StorageLeaseInSeconds section[:StorageLeaseInSeconds] end } end if section = options[:CustomizationSection] attrs = {} attrs[:goldMaster] = section[:goldMaster] if section.key?(:goldMaster) CustomizationSection(attrs) { self['ovf'].Info 'VApp template customization section' CustomizeOnInstantiate section[:CustomizeOnInstantiate] } end } 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.42.0/lib/fog/vcloud_director/requests/compute/post_deploy_vapp.rb0000644000004100000410000000411713171001215026346 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' } attrs[:deploymentLeaseSeconds] = options[:deploymentLeaseSeconds] if options.key?(:deploymentLeaseSeconds) attrs[:forceCustomization] = options[:forceCustomization] if options.key?(:forceCustomization) attrs[: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.42.0/lib/fog/vcloud_director/requests/compute/post_power_off_vapp.rb0000644000004100000410000000225213171001215027036 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.42.0/lib/fog/vcloud_director/requests/compute/get_vapp_templates_from_query.rb0000644000004100000410000001124113171001215031106 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].find {|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.42.0/lib/fog/vcloud_director/requests/compute/put_network.rb0000644000004100000410000001401013171001215025331 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/generators/compute/org_vdc_network' # Update 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: # TaskType # # @param [String] id Object identifier of the network # @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 put_network(id, name, options={}) body = Fog::Generators::Compute::VcloudDirector::OrgVdcNetwork.new(options.merge(:name => name)).generate_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.orgVdcNetwork+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "admin/network/#{id}" ) end end class Mock def put_network(id, name, options={}) original_network = data[:networks][id] unless original_network raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.orgVdcNetwork:#{id})\"." ) end type = 'network' # Description # Configuration # IpScopes # IpScope # IsInherited # Gateway # Netmask # Dns1 # Dns2 # DnsSuffix # IsEnabled # IpRanges # IpRange # StartAddress # EndAddress # FenceMode # EdgeGateway # IsShared # vdc_id = original_network[:vdc], 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( "Updating #{type} #{name} (#{id})", 'networkUpdateNetwork', owner, :on_success => lambda do data[:networks][id] = network_body end ) task = task_body(task_id) task.delete(:Owner) #known-bug: admin-api does not return owner. body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location, }.merge(task) Excon::Response.new( :status => 202, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootfog-1.42.0/lib/fog/vcloud_director/requests/compute/get_vapp_template_customization_system_section.rbfog-1.42.0/lib/fog/vcloud_director/requests/compute/get_vapp_template_customization_system_section.r0000644000004100000410000000150313171001215034431 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.42.0/lib/fog/vcloud_director/requests/compute/get_users_from_query.rb0000644000004100000410000001124113171001215027223 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].find {|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.42.0/lib/fog/vcloud_director/requests/compute/post_upgrade_hw_version.rb0000644000004100000410000000167213171001215027721 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.42.0/lib/fog/vcloud_director/requests/compute/get_vcloud.rb0000644000004100000410000000606213171001215025113 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.42.0/lib/fog/vcloud_director/requests/compute/post_update_vapp_metadata.rb0000644000004100000410000000567313171001215030204 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 class Mock def post_update_vapp_metadata(id, metadata={}) unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end owner = { :href => make_href("vApp/#{id}"), :type => 'application/vnd.vmware.vcloud.vApp+xml' } task_id = enqueue_task( "Updating Virtual Machine #{data[:vms][id][:name]}(#{id})", 'vappUpdateVm', owner, :on_success => lambda do metadata.each do |k,v| data[:tags][id] ||= {} data[:tags][id][k] = v end 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.42.0/lib/fog/vcloud_director/requests/compute/post_attach_disk.rb0000644000004100000410000000361513171001215026304 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.42.0/lib/fog/vcloud_director/requests/compute/get_startup_section.rb0000644000004100000410000000355413171001215027050 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 class Mock def get_startup_section(id) type = 'application/vnd.vmware.vcloud.startupSection+xml' unless vapp = data[:vapps][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => get_vapp_ovf_startup_section_body(id, vapp) ) end def get_vapp_ovf_startup_section_body(id, vapp) { :xmlns_ns12 => "http://www.vmware.com/vcloud/v1.5", :ns12_href => make_href("vApp/#{id}"), :ns12_type => "application/vnd.vmware.vcloud.startupSection+xml", :"ovf:Info" => "VApp startup section", :"ovf:Item" => { :ovf_stopDelay => "0", :ovf_stopAction => "powerOff", :ovf_startDelay => "0", :ovf_startAction => "powerOn", :ovf_order => "0", :ovf_id => vapp[:name], }, } end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_network_metadata_item_metadata.rb0000644000004100000410000000155713171001215032032 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.42.0/lib/fog/vcloud_director/requests/compute/get_network_config_section_vapp_template.rb0000644000004100000410000000147513171001215033305 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.42.0/lib/fog/vcloud_director/requests/compute/get_disk_metadata.rb0000644000004100000410000000134313171001215026406 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.42.0/lib/fog/vcloud_director/requests/compute/get_vapp_metadata_item_metadata.rb0000644000004100000410000000154613171001215031305 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.42.0/lib/fog/vcloud_director/requests/compute/get_network_cards_items_list.rb0000644000004100000410000000437413171001215030724 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 class Mock def get_network_cards_items_list(id) type = 'application/vnd.vmware.vcloud.rasdItemsList+xml' unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end body = { :type => type, :href => make_href("vApp/#{id}/virtualHardwareSection/networkCards"), :Link => { :rel=>"edit", :type=>"application/vnd.vmware.vcloud.rasdItemsList+xml", :href=>make_href("vApp/#{id}/virtualHardwareSection/networkCards"), }, :Item => get_network_cards_rasd_items_list_body(id, vm) } Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => body ) end def get_network_cards_rasd_items_list_body(id, vm) [{ :"rasd:Address" => vm[:nics][0][:mac_address], :"rasd:AddressOnParent" => "0", :"rasd:AutomaticAllocation" => "true", :"rasd:Connection" => vm[:nics][0][:network_name], :"rasd:Description" => "E1000 ethernet adapter", :"rasd:ElementName" => "Network adapter 0", :"rasd:InstanceID" => "1", :"rasd:ResourceSubType" => "E1000", :"rasd:ResourceType" => "10" }] end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_vm_pending_question.rb0000644000004100000410000000226413171001215027674 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.42.0/lib/fog/vcloud_director/requests/compute/get_vdcs_from_query.rb0000644000004100000410000001113613171001215027024 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].find {|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.42.0/lib/fog/vcloud_director/requests/compute/delete_disk.rb0000644000004100000410000000333713171001215025236 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.42.0/lib/fog/vcloud_director/requests/compute/post_recompose_vapp.rb0000644000004100000410000000121613171001215027043 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/generators/compute/recompose_vapp' def post_recompose_vapp(id, options={}) body = Fog::Generators::Compute::VcloudDirector::RecomposeVapp.new(options).generate_xml request( :body => body, :expects => 202, :headers => { 'Content-Type' => 'application/vnd.vmware.vcloud.recomposeVAppParams+xml' }, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/action/recomposeVApp" ) end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/post_enable_nested_hv.rb0000644000004100000410000000155113171001215027310 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.42.0/lib/fog/vcloud_director/requests/compute/get_vm_capabilities.rb0000644000004100000410000000364613171001215026757 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 class Mock def get_vm_capabilities(id) type = 'application/vnd.vmware.vcloud.vmCapabilitiesSection+xml' unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => get_vm_capabilities_section_body(id, vm) ) end def get_vm_capabilities_section_body(id, vm) { :type => "application/vnd.vmware.vcloud.vmCapabilitiesSection+xml", :href => make_href("vApp/#{id}/vmCapabilities/"), :MemoryHotAddEnabled => "false", :CpuHotAddEnabled => "false", } end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_catalogs_from_query.rb0000644000004100000410000001116613171001215027665 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].find {|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.42.0/lib/fog/vcloud_director/requests/compute/get_template_vms.rb0000644000004100000410000000227013171001215026314 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_template_vms(id) request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::Parsers::Compute::VcloudDirector::Vms.new, :path => "vAppTemplate/#{id}" ) end end class Mock def get_vms(id) vapptemplate = get_vapp(id).body parser = Fog::Parsers::Compute::VcloudDirector::Vms.new vms = vapp[:Children][:Vm].map {|child| parse_vapp_to_vm(child) } body = {:type => vapp[:type], :vms => vms} Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/post_login_session.rb0000644000004100000410000000302113171001215026670 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.42.0/lib/fog/vcloud_director/requests/compute/get_supported_versions.rb0000644000004100000410000021240413171001215027573 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.42.0/lib/fog/vcloud_director/requests/compute/post_cancel_task.rb0000644000004100000410000000231213171001215026266 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.42.0/lib/fog/vcloud_director/requests/compute/put_disks.rb0000644000004100000410000000247213171001215024766 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.42.0/lib/fog/vcloud_director/requests/compute/post_create_snapshot.rb0000644000004100000410000000122313171001215027201 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/generators/compute/create_snapshot' def post_create_snapshot(id, options={}) body = Fog::Generators::Compute::VcloudDirector::CreateSnapshot.new(options).generate_xml request( :body => body, :expects => 202, :headers => { 'Content-Type' => 'application/vnd.vmware.vcloud.createSnapshotParams+xml' }, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/action/createSnapshot" ) end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_vdc.rb0000644000004100000410000001540013171001215024367 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 => { :ResourceEntity => [] }, :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[:ResourceEntities][:ResourceEntity] += get_vapps_in_this_vdc(vdc_id).map do |vapp_id, vapp| {:type => "application/vnd.vmware.vcloud.vApp+xml", :name => vapp[:name], :href => make_href("vApp/#{vapp_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 def get_vapps_in_this_vdc(vdc_id) data[:vapps].select do |vapp_id, vapp| vapp[:vdc_id] == vdc_id end end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_thumbnail.rb0000644000004100000410000000156013171001215025600 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.42.0/lib/fog/vcloud_director/requests/compute/post_instantiate_vapp_template.rb0000644000004100000410000001762713171001215031302 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 class Mock def post_instantiate_vapp_template(vdc_id, vapp_template_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 = 'vApp' vapp_id = "vapp-#{uuid}" vm_id = "vm-#{uuid}" data[:vapps][vapp_id] = { :name => name, :vdc_id => vdc_id, :description => options.fetch(:description, "vApp created from #{vapp_template_id}"), :networks => [], :metadata => {:'vapp_key' => 'vapp_value'}, :status => "0", } data[:vms][vm_id] = { :name => 'vm-template-name', :parent_vapp => vapp_id, :memory_in_mb => "1024", :cpu_count => "2", :metadata => {:'vm_key' => 'vm_value'}, :nics => [ { :network_name => 'Default Network', :mac_address => "00:50:56:00:00:00", :ip_address => "192.168.0.1", } ], } owner = { :href => make_href("#{type}/#{vapp_id}"), :type => "application/vnd.vmware.vcloud.#{type}+xml" } task_id = enqueue_task( "Creating Virtual Application #{name}(#{vapp_id})", 'vdcInstantiateVapp', owner, :on_success => lambda do data[:vapps][vapp_id][:status] = "8" end ) body = get_vapp(vapp_id).body 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.42.0/lib/fog/vcloud_director/requests/compute/get_shadow_vm.rb0000644000004100000410000000124113171001215025600 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.42.0/lib/fog/vcloud_director/requests/compute/get_catalog_metadata_item_metadata.rb0000644000004100000410000000155113171001215031745 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.42.0/lib/fog/vcloud_director/requests/compute/get_disks_from_query.rb0000644000004100000410000001113513171001215027201 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].find {|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.42.0/lib/fog/vcloud_director/requests/compute/post_check_vm_compliance.rb0000644000004100000410000000163513171001215027777 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.42.0/lib/fog/vcloud_director/requests/compute/get_vapp_template_owner.rb0000644000004100000410000000136713171001215027675 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.42.0/lib/fog/vcloud_director/requests/compute/post_install_vmware_tools.rb0000644000004100000410000000153213171001215030271 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.42.0/lib/fog/vcloud_director/requests/compute/get_media.rb0000644000004100000410000000671113171001215024677 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.42.0/lib/fog/vcloud_director/requests/compute/get_medias_from_query.rb0000644000004100000410000001114713171001215027331 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].find {|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.42.0/lib/fog/vcloud_director/requests/compute/put_catalog_item_metadata_item_metadata.rb0000644000004100000410000000355613171001215033023 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.42.0/lib/fog/vcloud_director/requests/compute/post_upload_vapp_template.rb0000644000004100000410000000332413171001215030230 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.uploadVAppTemplateParams+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vdc/#{vdc_id}/action/uploadVAppTemplate" ) end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/post_shutdown_vapp.rb0000644000004100000410000000211613171001215026722 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.42.0/lib/fog/vcloud_director/requests/compute/put_cpu.rb0000644000004100000410000000662213171001215024441 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 class Mock def put_cpu(id, num_cpus) unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end owner = { :href => make_href("vApp/#{id}"), :type => 'application/vnd.vmware.vcloud.vm+xml' } task_id = enqueue_task( "Updating Virtual Machine #{data[:vms][id][:name]}(#{id})", 'vappUpdateVm', owner, :on_success => lambda do data[:vms][id][:cpu_count] = num_cpus 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.42.0/lib/fog/vcloud_director/requests/compute/post_eject_cd_rom.rb0000644000004100000410000000246213171001215026442 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.42.0/lib/fog/vcloud_director/requests/compute/put_guest_customization_section_vapp.rb0000644000004100000410000001415613171001215032544 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 # Don't add AdminPassword if AdminPasswordAuto is true if options.key?(:AdminPassword) and !options[:AdminPasswordAuto] 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.42.0/lib/fog/vcloud_director/requests/compute/get_catalog.rb0000644000004100000410000000372213171001215025231 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 items = data[:catalog_items].select {|_,v| v[:catalog] == id} body = { :href => make_href("catalog/#{id}"), :type => 'application/vnd.vmware.vcloud.catalog+xml', :id => id, :name => catalog[:name], :CatalogItems => { :CatalogItem => items.map do |uuid,item| { :href => make_href("catalogItem/#{uuid}"), :id => uuid, :name => item[:name], :type => 'application/vnd.vmware.vcloud.catalogItem+xml' } end }, } Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_vms_disk_attached_to.rb0000644000004100000410000000220713171001215027772 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.42.0/lib/fog/vcloud_director/requests/compute/get_vapp_template_metadata.rb0000644000004100000410000000143313171001215030315 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.42.0/lib/fog/vcloud_director/requests/compute/delete_logout.rb0000644000004100000410000000066213171001215025613 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.42.0/lib/fog/vcloud_director/requests/compute/post_suspend_vapp.rb0000644000004100000410000000210513171001215026526 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.42.0/lib/fog/vcloud_director/requests/compute/get_vapp_ovf_descriptor.rb0000644000004100000410000000132013171001215027665 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.42.0/lib/fog/vcloud_director/requests/compute/get_product_sections_vapp.rb0000644000004100000410000000142213171001215030227 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.42.0/lib/fog/vcloud_director/requests/compute/post_undeploy_vapp.rb0000644000004100000410000000523613171001215026714 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.42.0/lib/fog/vcloud_director/requests/compute/get_disk.rb0000644000004100000410000001041113171001215024542 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.42.0/lib/fog/vcloud_director/requests/compute/delete_catalog_item.rb0000644000004100000410000000114213171001215026724 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.42.0/lib/fog/vcloud_director/requests/compute/get_vms.rb0000644000004100000410000000223713171001215024424 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 class Mock def get_vms(id) vapp = get_vapp(id).body parser = Fog::Parsers::Compute::VcloudDirector::Vms.new vms = vapp[:Children][:Vm].map {|child| parse_vapp_to_vm(child) } body = {:type => vapp[:type], :vms => vms} Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/post_enable_vapp_template_download.rb0000644000004100000410000000134313171001215032060 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.42.0/lib/fog/vcloud_director/requests/compute/post_create_catalog_item.rb0000644000004100000410000000410713171001215027776 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Add an item to a catalog. # # @param [String] id Object identifier of the catalog. # @param [String] name The name of the entity. # @param [Hash] entity A reference to a VAppTemplate or Media object. # * href<~String> - Contains the URI to the entity. # @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::DuplicateName # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/POST-CreateCatalogItem.html # @since vCloud API version 0.9 def post_create_catalog_item(id, name, entity, options={}) body = Nokogiri::XML::Builder.new do attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', :name => name, } attrs[:operationKey] = options[:operationKey] if options.key?(:operationKey) CatalogItem(attrs) { if options.key?(:Description) Description options[:Description] end Entity(entity) } end.to_xml begin request( :body => body, :expects => 201, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.catalogItem+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "catalog/#{id}/catalogItems" ) 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.42.0/lib/fog/vcloud_director/requests/compute/put_network_connection_system_section_vapp.rb0000644000004100000410000001447213171001215033742 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 class Mock def put_network_connection_system_section_vapp(id, options={}) unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end owner = { :href => make_href("vApp/#{id}"), :type => 'application/vnd.vmware.vcloud.vApp+xml' } task_id = enqueue_task( "Updating Virtual Machine #{data[:vms][id][:name]}(#{id})", 'vappUpdateVm', owner, :on_success => lambda do data[:vms][id][:nics].first[:network_name] = options[:network] 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.42.0/lib/fog/vcloud_director/requests/compute/get_network_section_vapp_template.rb0000644000004100000410000000144313171001215031753 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.42.0/lib/fog/vcloud_director/requests/compute/get_supported_systems_info.rb0000644000004100000410000002446313171001215030453 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.42.0/lib/fog/vcloud_director/requests/compute/get_media_metadata_item_metadata.rb0000644000004100000410000000155513171001215031416 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.42.0/lib/fog/vcloud_director/requests/compute/get_vapp.rb0000644000004100000410000001415213171001215024564 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 class Mock def get_vapp(id) # Retrieve a vApp or VM. # case id when /^vapp-/ body = get_mock_vapp_body(id) when /^vm-/ body = get_mock_vm_body(id) else raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end def get_mock_vm_body(id) unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end body = { :name => vm[:name], :href => make_href("vApp/#{id}"), :type => "application/application/vnd.vmware.vcloud.vm+xml", :status => vm[:status], :deployed => vm[:deployed], :needsCustomization => vm[:needs_customization], :Description => vm[:description], :"ovf:VirtualHardwareSection" => get_vm_virtual_hardware_section_body(id, vm), :"ovf:OperatingSystemSection" => get_vm_operating_system_section_body(id, vm), :NetworkConnectionSection => get_vm_network_connection_section_body(id, vm), :GuestCustomizationSection => get_vm_guest_customization_section_body(id, vm), :RuntimeInfoSection => get_vm_runtime_info_section_body(id, vm), :SnapshotSection => get_snapshot_section_body(id), :DateCreated => vm[:date_created], # eg "2014-03-16T10:52:31.874Z" :VAppScopedLocalId => vm[:parent_vapp].split('-').last, # strip the vapp- prefix :"ovfenv:Environment" => get_vm_ovfenv_environment_section_body(id, vm), :VmCapabilities => get_vm_capabilities_section_body(id, vm), :StorageProfile => get_vm_storage_profile_section_body(id, vm), } body end def get_mock_vapp_body(id) unless vapp = data[:vapps][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end body = { :deployed => "true", :status => vapp[:status], :name => vapp[:name], :type => "application/vnd.vmware.vcloud.vApp+xml", :href => make_href("vApp/#{id}"), :LeaseSettingsSection => get_vapp_lease_settings_section_body(id), :"ovf:StartupSection" => get_vapp_ovf_startup_section_body(id, vapp), :"ovf:NetworkSection" => get_vapp_ovf_network_section_body(id, vapp), :NetworkConfigSection => get_vapp_network_config_section_body(id, vapp), :SnapshotSection => get_snapshot_section_body(id), :DateCreated => vapp[:date_created], # eg "2014-03-16T10:52:31.874Z" :Owner => get_owner_section_body(id), :InMaintenanceMode => "false", :Children => { :Vm => get_vapp_children_vms_body(id) }, } body end def get_vapp_ovf_network_section_body(id, vapp) {} end def get_vapp_children_vms_body(id) child_vms = data[:vms].select do |vm_id, vm_details| vm_details[:parent_vapp] == id end if RUBY_VERSION.to_f < 1.9 # 1.8 Hash.select returns an Array of [k,v] pairs. child_vms = Hash[child_vms] end child_vms.keys.collect do |vm_id| get_mock_vm_body(vm_id) end end def get_vm_ovfenv_environment_section_body(id, vm) # TODO: I'm pretty sure this is just repeating info in other # sections, and the OVF part of VMs is extremely verbose. It's # likely to not be needed in Mock mode {} end def get_vm_storage_profile_section_body(id, vm) { :type => "application/vnd.vmware.vcloud.vdcStorageProfile+xml", :name => "Mock Storage Profile", :href => make_href("vdcStorageProfile/12345678-1234-1234-1234-1234500e49a8"), } end def get_vm_virtual_hardware_section_body(id, vm) {:xmlns_ns12=>"http://www.vmware.com/vcloud/v1.5", :ovf_transport=>"", :ns12_href => make_href("vApp/#{id}/virtualHardwareSection/"), :ns12_type=>"application/vnd.vmware.vcloud.virtualHardwareSection+xml", :"ovf:Info"=>"Virtual hardware requirements", :"ovf:System"=>{ :"vssd:ElementName"=>"Virtual Hardware Family", :"vssd:InstanceID"=>"0", :"vssd:VirtualSystemIdentifier" => vm[:name], :"vssd:VirtualSystemType"=>"vmx-08" }, :"ovf:Item" => get_vm_ovf_item_list(id, vm), } end def get_vm_ovf_item_list(id, vm) [ get_network_cards_rasd_items_list_body(id, vm), get_disks_rasd_items_list_body(id, vm), get_media_rasd_item_cdrom_body(id, vm), get_media_rasd_item_floppy_body(id, vm), get_cpu_rasd_item_body(id, vm), get_memory_rasd_item_body(id, vm), ].compact.flatten end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/post_upload_disk.rb0000644000004100000410000001236513171001215026326 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].find {|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.42.0/lib/fog/vcloud_director/requests/compute/get_vapp_metadata.rb0000644000004100000410000000550613171001215026427 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 class Mock def get_vapp_metadata(id) unless vm_or_vapp = data[:vapps][id] || vm_or_vapp = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end body = { :xmlns=>xmlns, :xmlns_xsi=>xmlns_xsi, :type=>"application/vnd.vmware.vcloud.metadata+xml", :href=>make_href("vApp/#{id}/metadata"), :xsi_schemaLocation=>xsi_schema_location, :Link=> [{:rel=>"up", :type=>"application/vnd.vmware.vcloud.vApp+xml", :href=>make_href("/vApp/#{id}")}, {:rel=>"add", :type=>"application/vnd.vmware.vcloud.metadata+xml", :href=>make_href("vApp/#{id}/metadata")}], :MetadataEntry=>get_metadata_entries(vm_or_vapp[:metadata], id) } Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end private def get_metadata_entries(metadata, id) metadata_entries = [] for key, value in metadata do metadata_entries << {:type=>"application/vnd.vmware.vcloud.metadata.value+xml", :href=>make_href("vApp/#{id}/metadata/#{key}"), :Link=> [{:rel=>"up", :type=>"application/vnd.vmware.vcloud.metadata+xml", :href=>make_href("vApp/#{id}/metadata")}, {:rel=>"edit", :type=>"application/vnd.vmware.vcloud.metadata.value+xml", :href=>make_href("vApp/#{id}/metadata/#{key}")}, {:rel=>"remove", :href=>make_href("vApp/#{id}/metadata/#{key}")}], :Key=>"#{key}", :TypedValue=>{:xsi_type=>"MetadataStringValue", :Value=>"#{metadata[key]}"}} end metadata_entries end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_organizations.rb0000644000004100000410000000334113171001215026503 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.42.0/lib/fog/vcloud_director/requests/compute/instantiate_vapp_template.rb0000644000004100000410000001415213171001215030223 0ustar www-datawww-datarequire 'builder' module Fog module Compute class VcloudDirector class Real require 'fog/vcloud_director/generators/compute/instantiate_vapp_template_params' # 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_uri] = network_end_point(options[:network_id]) if 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 ={}) #overriding some params so they work with new standardised generator options[:InstantiationParams] = { :NetworkConfig => [{ :networkName => options[:network_name], :networkHref => options[:network_uri], :fenceMode => 'bridged' }] } unless options[:InstantiationParams] options[:name] = options.delete(:vapp_name) if options[:vapp_name] options[:Description] = options.delete(:description) unless options[:Description] if options[:vms_config] then options[:source_vms] = options.delete(:vms_config) options[:source_vms].each_with_index {|vm, i|options[:source_vms][i][:StorageProfileHref] = options[:source_vms][i].delete(:storage_profile_href) } end options[:Source] = options.delete(:template_uri) if options[:template_uri] Fog::Generators::Compute::VcloudDirector::InstantiateVappTemplateParams.new(options).generate_xml 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 class Mock # Assume the template is a single VM with one network interface and one disk. def instantiate_vapp_template(vapp_name, template_id, options={}) unless data[:catalog_items].values.find {|i| i[:template_id] == template_id} raise Fog::Compute::VcloudDirector::Forbidden.new( 'No such template.' ) end unless vdc = data[:vdcs][options[:vdc_id]] raise Fog::Compute::VcloudDirector::Forbidden.new( 'No such VDC.' ) end vapp_uuid = uuid vapp_id = "vapp-#{vapp_uuid}" owner = { :href => make_href("vApp/#{vapp_id}"), :type => 'application/vnd.vmware.vcloud.vm+xml' } task_id = enqueue_task( "Creating Virtual Application #{vapp_name}(#{vapp_uuid})", 'vdcInstantiateVapp', owner, :on_success => lambda do # Add to the VDC data[:vapps][vapp_id] = { :name => vapp_name, :vdc_id => options[:vdc_id], :description => 'From Template', :networks => [ {:parent_id => default_network_uuid } ] } vm_id = "vm-#{uuid}" data[:vms][vm_id] = { :name => vapp_name, :parent_vapp => vapp_id, :nics => [ { :network_name => 'Default Network', :mac_address => '7d:68:a2:a0:a4:f8', :ip_address => nil } ] } data[:disks][uuid] = { :name => 'Hard Disk 1', :capacity => 10240, :parent_vm => vm_id } end ) body = { :href => make_href("vApp/#{vapp_id}"), :Tasks => { :Task => { :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.42.0/lib/fog/vcloud_director/requests/compute/post_reconfigure_vm.rb0000644000004100000410000001012313171001215027030 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # Updates VM configuration. # # 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 [String] :name Change the VM's name [required]. # @option options [String] :description VM description # @option options [Integer] :cpu Number of CPUs # @option options [Integer] :memory Memory in MB # # @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/POST-ReconfigureVm.html # @since vCloud API version 5.1 def post_reconfigure_vm(id, options={}) body = Nokogiri::XML::Builder.new do |xml| attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1', 'xmlns:rasd' => 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData', :name => options[:name] } xml.Vm(attrs) do xml.Description options[:description] if options[:description] virtual_hardware_section(xml, options) end end.to_xml request( :body => body, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.vm+xml'}, :method => 'POST', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/action/reconfigureVm" ) end private def virtual_hardware_section(xml, options) return unless options[:cpu] or options[:memory] xml['ovf'].VirtualHardwareSection do xml['ovf'].Info 'Virtual Hardware Requirements' cpu_section(xml, options[:cpu]) if options[:cpu] memory_section(xml, options[:memory]) if options[:memory] end end def cpu_section(xml, cpu) xml['ovf'].Item do xml['rasd'].AllocationUnits 'hertz * 10 ^ 6' xml['rasd'].InstanceID 5 xml['rasd'].ResourceType 3 xml['rasd'].VirtualQuantity cpu.to_i end end def memory_section(xml, memory) xml['ovf'].Item do xml['rasd'].AllocationUnits 'byte * 2^20' xml['rasd'].InstanceID 6 xml['rasd'].ResourceType 4 xml['rasd'].VirtualQuantity memory.to_i end end end class Mock def post_reconfigure_vm(id, options={}) unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end owner = { :href => make_href("vApp/#{id}"), :type => 'application/vnd.vmware.vcloud.vApp+xml' } task_id = enqueue_task( "Updating Virtual Machine #{data[:vms][id][:name]}(#{id})", 'vappUpdateVm', owner, :on_success => lambda do data[:vms][id][:name] = options[:name] data[:vms][id][:description] = options[:description] if options[:description] data[:vms][id][:cpu_count] = options[:cpu] if options[:cpu] data[:vms][id][:memory_in_mb] = options[:memory] if options[:memory] 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.42.0/lib/fog/vcloud_director/requests/compute/post_insert_cd_rom.rb0000644000004100000410000000246613171001215026660 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.42.0/lib/fog/vcloud_director/requests/compute/post_detach_disk.rb0000644000004100000410000000244313171001215026266 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.42.0/lib/fog/vcloud_director/requests/compute/post_consolidate_vm_vapp.rb0000644000004100000410000000150613171001215030057 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.42.0/lib/fog/vcloud_director/requests/compute/get_vdc_storage_class.rb0000644000004100000410000000665013171001215027307 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.42.0/lib/fog/vcloud_director/requests/compute/get_runtime_info_section_type.rb0000644000004100000410000000333413171001215031101 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 class Mock def get_runtime_info_section_type(id) type = 'application/vnd.vmware.vcloud.virtualHardwareSection+xml' unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => get_vm_runtime_info_section_body(id, vm) ) end def get_vm_runtime_info_section_body(id, vm) { :xmlns_ns12 => "http://www.vmware.com/vcloud/v1.5", :ns12_href => make_href("vApp/#{id}/runtimeInfoSection"), :ns12_type => "application/vnd.vmware.vcloud.virtualHardwareSection+xml", :"ovf:Info" => "Specifies Runtime info", :VMWareTools => { :version => "9282", } } end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/delete_network.rb0000644000004100000410000000354113171001215025772 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.42.0/lib/fog/vcloud_director/requests/compute/get_disk_metadata_item_metadata.rb0000644000004100000410000000153213171001215031264 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.42.0/lib/fog/vcloud_director/requests/compute/get_vapp_template_metadata_item_metadata.rb0000644000004100000410000000163313171001215033175 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.42.0/lib/fog/vcloud_director/requests/compute/get_metadata.rb0000644000004100000410000000246113171001215025376 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 class Mock def get_metadata(id) tags = data[:tags][id] || {} body = {:type => 'application/vnd.vmware.vcloud.metadata+xml', :metadata => tags} Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_network_metadata.rb0000644000004100000410000000136213171001215027146 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.42.0/lib/fog/vcloud_director/requests/compute/post_clone_vapp_template.rb0000644000004100000410000000367313171001215030053 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.42.0/lib/fog/vcloud_director/requests/compute/get_network_connection_system_section_vapp_template.rbfog-1.42.0/lib/fog/vcloud_director/requests/compute/get_network_connection_system_section_vapp_templ0000644000004100000410000000150413171001215034500 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.42.0/lib/fog/vcloud_director/requests/compute/put_product_sections.rb0000644000004100000410000000352113171001215027234 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 # @param [Array] sections List of sections hashes # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.doc_51/GUID-E13A5613-8A41-46E3-889B-8E1EAF10ABBE.html # @since vCloud API version 1.5 def put_product_sections(id, sections) xml = '' xml += '' xml += 'Global vApp Custom Properties' xml += 'Global' sections.each do |section| section[:user_configurable] ||= true section[:type] ||= "string" section[:password] ||= false xml += "" xml += "#{section[:id]}" xml += "" end xml += '' xml += "" request( :body => xml, :expects => 202, :headers => {'Content-Type' => 'application/vnd.vmware.vcloud.productSections+xml'}, :method => 'PUT', :parser => Fog::ToHashDocument.new, :path => "vApp/#{id}/productSections" ) end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_groups_from_query.rb0000644000004100000410000001124213171001215027402 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].find {|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.42.0/lib/fog/vcloud_director/requests/compute/get_control_access_params_catalog.rb0000644000004100000410000000156313171001215031656 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.42.0/lib/fog/vcloud_director/requests/compute/get_org_settings.rb0000644000004100000410000000254613171001215026331 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.42.0/lib/fog/vcloud_director/requests/compute/get_catalog_metadata.rb0000644000004100000410000000134213171001215027065 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.42.0/lib/fog/vcloud_director/requests/compute/get_lease_settings_section_vapp.rb0000644000004100000410000000332113171001215031375 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 class Mock def get_lease_settings_section_vapp(id) type = 'application/vnd.vmware.vcloud.leaseSettingsSection+xml' unless vapp = data[:vapps][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => get_vapp_lease_settings_section_body(id) ) end def get_vapp_lease_settings_section_body(id) { :type => "application/vnd.vmware.vcloud.leaseSettingsSection+xml", :href => make_href("vApp/#{id}/leaseSettingsSection/"), :ovf_required=>"false", :"ovf:Info"=>"Lease settings section", :DeploymentLeaseInSeconds=>"0", :StorageLeaseInSeconds=>"0", } end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_media_drives_rasd_items_list.rb0000644000004100000410000000543413171001215031521 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 class Mock def get_media_drives_rasd_items_list(id) type = 'application/vnd.vmware.vcloud.rasdItemsList+xml' unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end body = { :type => type, :href => make_href("vApp/#{id}/virtualHardwareSection/media"), :Item => [ get_media_rasd_item_ide_controller_body(id, vm), get_media_rasd_item_cdrom_body(id, vm), get_media_rasd_item_floppy_body(id, vm), ] } Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => body ) end def get_media_rasd_item_ide_controller_body(id, vm) { :"rasd:Address"=>"0", :"rasd:Description"=>"IDE Controller", :"rasd:ElementName"=>"IDE Controller 0", :"rasd:InstanceID"=>"3", :"rasd:ResourceType"=>"5" } end def get_media_rasd_item_cdrom_body(id, vm) { :"rasd:AddressOnParent"=>"1", :"rasd:AutomaticAllocation"=>"true", :"rasd:Description"=>"CD/DVD Drive", :"rasd:ElementName"=>"CD/DVD Drive 1", :"rasd:HostResource"=>"", :"rasd:InstanceID"=>"3000", :"rasd:Parent"=>"3", :"rasd:ResourceType"=>"15" } end def get_media_rasd_item_floppy_body(id, vm) { :"rasd:AddressOnParent"=>"0", :"rasd:AutomaticAllocation"=>"false", :"rasd:Description"=>"Floppy Drive", :"rasd:ElementName"=>"Floppy Drive 1", :"rasd:HostResource"=>"", :"rasd:InstanceID"=>"8000", :"rasd:ResourceType"=>"14" } end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_organizations_from_query.rb0000644000004100000410000001124013171001215030750 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].find {|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.42.0/lib/fog/vcloud_director/requests/compute/get_vapp_template_ovf_descriptor.rb0000644000004100000410000000136113171001215031565 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.42.0/lib/fog/vcloud_director/requests/compute/post_update_catalog_item_metadata.rb0000644000004100000410000000362013171001215031654 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.42.0/lib/fog/vcloud_director/requests/compute/get_vm_compliance_results.rb0000644000004100000410000000132013171001215030204 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.42.0/lib/fog/vcloud_director/requests/compute/put_vm.rb0000644000004100000410000000451413171001215024272 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 class Mock def put_vm(id, name, options) unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end owner = { :href => make_href("vApp/#{id}"), :type => 'application/vnd.vmware.vcloud.vm+xml' } task_id = enqueue_task( "Updating Virtual Machine #{data[:vms][id][:name]}(#{id})", 'vappUpdateVm', owner, :on_success => lambda do data[:vms][id][:name] = name 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.42.0/lib/fog/vcloud_director/requests/compute/get_catalog_item_metadata_item_metadata.rb0000644000004100000410000000160013171001215032756 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.42.0/lib/fog/vcloud_director/requests/compute/get_organization_metadata.rb0000644000004100000410000000140213171001215030154 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.42.0/lib/fog/vcloud_director/requests/compute/post_clone_vapp.rb0000644000004100000410000000466413171001215026161 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.42.0/lib/fog/vcloud_director/requests/compute/get_network_connection_system_section_vapp.rb0000644000004100000410000000440513171001215033704 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 class Mock def get_network_connection_system_section_vapp(id) type = 'application/vnd.vmware.vcloud.networkConnectionSection+xml' unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => get_vm_network_connection_section_body(id, vm) ) end def get_vm_network_connection_section_body(id, vm) # TODO: Needs work - does not handle multiple NIC case yet, or # DHCP/POOL allocations { :type => "application/vnd.vmware.vcloud.networkConnectionSection+xml", :href => make_href("vApp/#{id}/networkConnectionSection/"), :ovf_required => "false", :"ovf:Info" => "Specifies the available VM network connections", :PrimaryNetworkConnectionIndex => "0", :NetworkConnection => { :network => vm[:nics][0][:network_name], :needsCustomization => "false", :NetworkConnectionIndex => "0", :IpAddress => vm[:nics][0][:ip_address], :IsConnected => "true", :MACAddress => vm[:nics][0][:mac_address], :IpAddressAllocationMode => "MANUAL" } } end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_guest_customization_system_section_vapp.rb0000644000004100000410000000460413171001215034114 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 class Mock def get_guest_customization_system_section_vapp(id) type = 'application/vnd.vmware.vcloud.guestCustomizationSection+xml' unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => get_vm_guest_customization_section_body(id, vm) ) end def get_vm_guest_customization_section_body(id, vm) { :type => "application/vnd.vmware.vcloud.guestCustomizationSection+xml", :href => make_href("vApp/#{id}/guestCustomizationSection/"), :ovf_required => "false", :"ovf:Info" => "Specifies Guest OS Customization Settings", :Enabled => "true", :ChangeSid => "false", :VirtualMachineId => id.split('-').last, # strip the 'vm-' prefix :JoinDomainEnabled => "false", :UseOrgSettings => "false", :AdminPasswordEnabled => "false", :AdminPasswordAuto => "true", :ResetPasswordRequired => "false", :CustomizationScript => vm[:customization_script] || "", :ComputerName => vm[:computer_name] || vm[:name], :Link => { :rel=>"edit", :type=>"application/vnd.vmware.vcloud.guestCustomizationSection+xml", :href=>make_href("vApp/#{id}"), }, } end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_organization_metadata_item_metadata.rb0000644000004100000410000000173313171001215033041 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.42.0/lib/fog/vcloud_director/requests/compute/post_disable_nested_hv.rb0000644000004100000410000000155413171001215027470 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.42.0/lib/fog/vcloud_director/requests/compute/put_vapp_name_and_description.rb0000644000004100000410000000242413171001215031041 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.42.0/lib/fog/vcloud_director/requests/compute/delete_shadow_vm.rb0000644000004100000410000000164013171001215026266 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.42.0/lib/fog/vcloud_director/requests/compute/post_acquire_ticket.rb0000644000004100000410000000154513171001215027022 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.42.0/lib/fog/vcloud_director/requests/compute/get_vdc_metadata.rb0000644000004100000410000000133513171001215026231 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.42.0/lib/fog/vcloud_director/requests/compute/get_network_complete.rb0000644000004100000410000000512213171001215027174 0ustar www-datawww-datamodule Fog module Compute class VcloudDirector class Real # 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_complete(id) response = request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => "admin/network/#{id}" ) ensure_list! response.body[:Configuration][:IpScopes][:IpScope], :IpRanges, :IpRange response end end class Mock def get_network_complete(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 => network[:Description], :Configuration => { :IpScopes => { :IpScope => { :IsInherited => network[:IsInherited].to_s, :Gateway => network[:Gateway], :Netmask => network[:Netmask], :Dns1 => network[:Dns1], :Dns2 => network[:Dns2], :DnsSuffix => network[:DnsSuffix], :IsEnabled => true.to_s, :IpRanges => { :IpRange => [], }, } }, :FenceMode => network[:FenceMode], :RetainNetInfoAcrossDeployments => false.to_s, }, :IsShared => network[:IsShared].to_s, } body[:Configuration][:IpScopes][:IpScope][:IpRanges][:IpRange] = network[:IpRanges].map do |ip_range| {:StartAddress => ip_range[:StartAddress], :EndAddress => 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.42.0/lib/fog/vcloud_director/requests/compute/post_power_on_vapp.rb0000644000004100000410000000440713171001215026704 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 class Mock def post_power_on_vapp(id) unless vapp = data[:vapps][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end owner = { :href => make_href("vApp/#{id}"), :type => 'application/vnd.vmware.vcloud.vApp+xml' } task_id = enqueue_task( "Starting Virtual Application #{data[:vapps][id]} vapp(#{id})", 'vappDeploy', owner, :on_success => lambda do data[:vms].values.each do |vm| if vm[:parent_vapp] == id vm[:status] = '4' # on end end 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.42.0/lib/fog/vcloud_director/requests/compute/post_disable_vapp_template_download.rb0000644000004100000410000000134713171001215032241 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.42.0/lib/fog/vcloud_director/requests/compute/get_vm_network.rb0000644000004100000410000000404213171001215026006 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 class Mock def get_vm_network(id) vapp = get_vapp(id).body network = vapp[:NetworkConnectionSection] connection = network[:NetworkConnection] body = { :type => network[:type], :id => network[:href].split('/')[-2], :href => network[:href], :info => network[:"ovf:Info"], :primary_network_connection_index => network[:PrimaryNetworkConnectionIndex], :network => connection[:network], :needs_customization => connection[:needsCustomization], :network_connection_index => connection[:NetworkConnectionIndex], :is_connected => connection[:IsConnected], :mac_address => connection[:MACAddress], :ip_address_allocation_mode => connection[:IpAddressAllocationMode] } Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/delete_media_metadata_item_metadata.rb0000644000004100000410000000151413171001215032074 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.42.0/lib/fog/vcloud_director/requests/compute/delete_vapp.rb0000644000004100000410000000343313171001215025247 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 class Mock def delete_vapp(id) unless vapp = data[:vapps][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end owner = { :href => make_href("vApp/#{id}"), :type => 'application/vnd.vmware.vcloud.vApp+xml' } task_id = enqueue_task( "Deleting Virtual Application (#{id})", 'vdcDeleteVapp', owner, :on_success => lambda do data[:vapps].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.42.0/lib/fog/vcloud_director/requests/compute/post_update_vapp_template_metadata.rb0000644000004100000410000000360713171001215032072 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.42.0/lib/fog/vcloud_director/requests/compute/post_configure_edge_gateway_services.rb0000644000004100000410000000556313171001215032423 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 => make_href("admin/edgeGateway/#{id}"), :type => 'application/vnd.vmware.vcloud.gateway+xml' } task_id = enqueue_task( "Configuring edgegateway(#{id})", 'networkConfigureEdgeGatewayServices', owner, :on_success => lambda do data[:edge_gateways][id][:Configuration][:EdgeGatewayServiceConfiguration] = configuration end ) task = task_body(task_id) task.delete(:Owner) # known bug - admin tasks do not return Owner body = { :xmlns => xmlns, :xmlns_xsi => xmlns_xsi, :xsi_schemaLocation => xsi_schema_location, }.merge(task) Excon::Response.new( :status => 202, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/delete_disk_metadata_item_metadata.rb0000644000004100000410000000147113171001215031751 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.42.0/lib/fog/vcloud_director/requests/compute/delete_media.rb0000644000004100000410000001316213171001215025360 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.42.0/lib/fog/vcloud_director/requests/compute/get_memory_rasd_item.rb0000644000004100000410000000372313171001215027157 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 class Mock def get_memory_rasd_item(id) type = 'application/vnd.vmware.vcloud.rasdItem+xml' unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => get_memory_rasd_item_body(id, vm) ) end def get_memory_rasd_item_body(id, vm) { :ns12_href => make_href("vApp/#{id}/virtualHardwareSection/memory"), :ns12_type=>"application/vnd.vmware.vcloud.rasdItem+xml", :"rasd:AllocationUnits"=>"byte * 2^20", :"rasd:Description"=>"Memory Size", :"rasd:ElementName"=>"#{vm[:memory_in_mb]} MB of memory", :"rasd:InstanceID"=>"5", :"rasd:Reservation"=>"0", :"rasd:ResourceType"=>"4", :"rasd:VirtualQuantity"=>"#{vm[:memory_in_mb]}", :"rasd:Weight"=>"0", } end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/get_operating_system_section.rb0000644000004100000410000000360713171001215030741 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 class Mock def get_operating_system_section(id) type = 'application/vnd.vmware.vcloud.operatingSystemSection+xml' unless vm = data[:vms][id] raise Fog::Compute::VcloudDirector::Forbidden.new( 'This operation is denied.' ) end Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{type};version=#{api_version}"}, :body => get_vm_operating_system_section_body(id, vm) ) end def get_vm_operating_system_section_body(id, vm) { :xmlns_ns12=>"http://www.vmware.com/vcloud/v1.5", :ovf_id => "94", # TODO: What is this? :ns12_href => make_href("vApp/#{id}/operatingSystemSection/"), :ns12_type => "application/vnd.vmware.vcloud.operatingSystemSection+xml", :vmw_osType => vm[:guest_os_type], # eg "ubuntu64Guest" :"ovf:Info"=>"Specifies the operating system installed", :"ovf:Description"=> vm[:guest_os_description], # eg "Ubuntu Linux (64-bit)", } end end end end end fog-1.42.0/lib/fog/vcloud_director/requests/compute/post_revert_snapshot.rb0000644000004100000410000000161013171001215027245 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.42.0/lib/fog/vcloud_director/requests/compute/post_discard_vapp_state.rb0000644000004100000410000000174013171001215027662 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.42.0/lib/fog/vcloud_director/requests/compute/get_disk_owner.rb0000644000004100000410000000436113171001215025763 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.42.0/lib/fog/vcloud_director/requests/compute/get_edge_gateway.rb0000644000004100000410000001070513171001215026243 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.42.0/lib/fog/vcloud_director/requests/compute/get_vdc_storage_class_metadata.rb0000644000004100000410000000156513171001215031147 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.42.0/lib/fog/vcloud_director/requests/compute/post_enter_maintenance_mode.rb0000644000004100000410000000156713171001215030515 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.42.0/lib/fog/vcloud_director/requests/compute/put_vapp_template_metadata_item_metadata.rb0000644000004100000410000000356213171001215033231 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.42.0/lib/fog/vcloud_director/requests/compute/delete_catalog_item_metadata_item_metadata.rb0000644000004100000410000000153713171001215033452 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.42.0/lib/fog/vcloud_director/requests/compute/get_catalog_item.rb0000644000004100000410000000300513171001215026241 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 class Mock def get_catalog_item(id) unless item = data[:catalog_items][id] raise Fog::Compute::VcloudDirector::Forbidden.new( "No access to entity \"(com.vmware.vcloud.entity.catalogItem:#{id})\"." ) end body = { :href => make_href("catalogItem/#{id}"), :id => id, :name => item[:name], :type => 'application/vnd.vmware.vcloud.catalogItem+xml', :Entity => { :href => make_href("vAppTemplate/#{item[:template_id]}") } } Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end fog-1.42.0/lib/fog/vcloud_director/parsers/0000755000004100000410000000000013171001215020557 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud_director/parsers/compute/0000755000004100000410000000000013171001215022233 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud_director/parsers/compute/metadata.rb0000644000004100000410000000661013171001215024343 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.42.0/lib/fog/vcloud_director/parsers/compute/vm_parser_helper.rb0000644000004100000410000000371113171001215026117 0ustar www-datawww-datamodule Fog module Parsers module Compute module VcloudDirector module VmParserHelper def parse_end_element(name, vm) 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 'Connection' vm[:network_adapters] ||= [] vm[:network_adapters] << { :ip_address => @current_network_connection[:ipAddress], :primary => (@current_network_connection[:primaryNetworkConnection] == 'true'), :ip_allocation_mode => @current_network_connection[:ipAddressingMode], :network => value } when 'Link' vm[:links] = @links end end def parse_start_element(name, attributes, vm) case name when 'OperatingSystemSection' @in_operating_system = true when 'HostResource' @current_host_resource = extract_attributes(attributes) when 'Connection' @current_network_connection = extract_attributes(attributes) when 'Link' @links << extract_attributes(attributes) end end end end end end end fog-1.42.0/lib/fog/vcloud_director/parsers/compute/network.rb0000644000004100000410000001103513171001215024251 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.42.0/lib/fog/vcloud_director/parsers/compute/vms_by_metadata.rb0000644000004100000410000000275613171001215025731 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.42.0/lib/fog/vcloud_director/parsers/compute/vm_customization.rb0000644000004100000410000000410213171001215026167 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") @response[:admin_password] = '' unless @response[:admin_password_enabled] 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.42.0/lib/fog/vcloud_director/parsers/compute/vm_network.rb0000644000004100000410000001145413171001215024760 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.42.0/lib/fog/vcloud_director/parsers/compute/vm.rb0000644000004100000410000000546713171001215023216 0ustar www-datawww-datarequire 'fog/vcloud_director/parsers/compute/vm_parser_helper' module Fog module Parsers module Compute module VcloudDirector class Vm < VcloudDirectorParser include VmParserHelper def reset @in_operating_system = false @in_children = false @resource_type = nil @response = { :vm => { :ip_address => '' } } @links = [] end def start_element(name, attributes) super if name == 'Vm' vm_attrs = extract_attributes(attributes) @response[:vm].merge!(vm_attrs.reject {|key,value| ![:href, :name, :status, :type, :deployed].include?(key)}) @response[:vm][:id] = @response[:vm][:href].split('/').last @response[:vm][:status] = human_status(@response[:vm][:status]) @response[:vm][:deployed] = @response[:vm][:deployed] == 'true' else parse_start_element name, attributes, @response[:vm] end end def end_element(name) parse_end_element name, @response[:vm] 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' case @resource_type when '17' # disk @response[:vm][:disks] ||= [] @response[:vm][:disks] << { @element_name => @current_host_resource[:capacity].to_i } when '10' # nic @response[:vm][:network_adapters] ||= [] @response[:vm][:network_adapters] << { :ip_address => @current_network_connection[:ipAddress], :primary => (@current_network_connection[:primaryNetworkConnection] == 'true'), :ip_allocation_mode => @current_network_connection[:ipAddressingMode] } 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.42.0/lib/fog/vcloud_director/parsers/compute/disks.rb0000644000004100000410000000302313171001215023673 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.42.0/lib/fog/vcloud_director/parsers/compute/vms.rb0000644000004100000410000000367413171001215023377 0ustar www-datawww-datarequire 'fog/vcloud_director/parsers/compute/vm_parser_helper' module Fog module Parsers module Compute module VcloudDirector class Vms < VcloudDirectorParser include VmParserHelper 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 'Vm' vapp = extract_attributes(attributes) @vm.merge!(vapp.reject {|key,value| ![:href, :name, :status, :type, :deployed].include?(key)}) @vm[:deployed] = response[:deployed] == 'true' @vm[:id] = @vm[:href].split('/').last @vm[:vapp_id] = @response[:id] @vm[:vapp_name] = @response[:name] @vm[:status] = human_status(@vm[:status]) 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 'Children' @in_children = true else parse_start_element name, attributes, @vm end end def end_element(name) if @in_children if name == 'Vm' @response[:vms] << @vm @vm = {} else parse_end_element name, @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.42.0/lib/fog/vcloud_director/query.rb0000644000004100000410000000335013171001215020573 0ustar www-datawww-datarequire 'pp' module Fog module VcloudDirector module Query def find_by_query(options={}) type = options.fetch(:type) { self.query_type } results = get_all_results(type, options) data = results.map do |query_record| model_data = {} model_data[:id] = query_record[:href].split('/').last model_data[:name] = query_record.fetch(:name) if query_record.key?(:name) if self.methods.include?(:populate_model_from_query_record) model_data.merge(self.populate_model_from_query_record(query_record)) else model_data end end load(data) end private def get_all_results(type, options) results = [] if options.key?(:page) page_range = [ Integer(options[:page]) ] else page_range = (1..get_num_pages(type, options)) end page_range.each do |page| results += get_results_page(page, type, options) || [] end results end def get_num_pages(type, options) body = service.get_execute_query(type, options) last_page = body[:lastPage] || 1 raise "Invalid lastPage (#{last_page}) in query results" unless last_page.is_a? Integer last_page.to_i end def get_results_page(page, type, options) body = service.get_execute_query(type, options.merge({:page=>page})).body record_key = key_of_first_record_or_reference(body) body[record_key] = [body[record_key]] if body[record_key].is_a?(Hash) body[record_key] end def key_of_first_record_or_reference(body) body.keys.detect { |key| key.to_s =~ /Record|Reference$/ } end end end end fog-1.42.0/lib/fog/vcloud_director/generators/0000755000004100000410000000000013171001215021251 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud_director/generators/compute/0000755000004100000410000000000013171001215022725 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud_director/generators/compute/recompose_vapp.rb0000644000004100000410000000155013171001215026275 0ustar www-datawww-datarequire 'fog/vcloud_director/generators/compute/compose_common' module Fog module Generators module Compute module VcloudDirector # @see http://pubs.vmware.com/vcd-51/index.jsp#types/RecomposeVAppParamsType.html class RecomposeVapp include ComposeCommon def generate_xml Nokogiri::XML::Builder.new do |xml| xml.RecomposeVAppParams(vapp_attrs) { if has_source_items? build_vapp_instantiation_params(xml) build_source_items(xml) end build_delete_items(xml) } end.to_xml end private def build_delete_items(xml) @configuration[:vms_to_delete].each { |vm| xml.DeleteItem(:href => vm.href) } end end end end end endfog-1.42.0/lib/fog/vcloud_director/generators/compute/instantiate_vapp_template_params.rb0000644000004100000410000000141413171001215032061 0ustar www-datawww-datarequire 'fog/vcloud_director/generators/compute/compose_common' module 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 InstantiateVappTemplateParams attr_reader :options include ComposeCommon def generate_xml Nokogiri::XML::Builder.new do |xml| xml.InstantiateVAppTemplateParams((vapp_attrs)) { build_vapp_instantiation_params(xml) build_source_template(xml) build_source_items(xml) } end.to_xml end end end end end end fog-1.42.0/lib/fog/vcloud_director/generators/compute/metadata.rb0000644000004100000410000000643713171001215025044 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.42.0/lib/fog/vcloud_director/generators/compute/compose_vapp.rb0000644000004100000410000000113213171001215025742 0ustar www-datawww-datarequire 'fog/vcloud_director/generators/compute/compose_common' module Fog module Generators module Compute module VcloudDirector # @see http://pubs.vmware.com/vcd-51/index.jsp#types/ComposeVAppParamsType.html class ComposeVapp include ComposeCommon def generate_xml Nokogiri::XML::Builder.new do |xml| xml.ComposeVAppParams(vapp_attrs) { build_vapp_instantiation_params(xml) build_source_items(xml) } end.to_xml end end end end end endfog-1.42.0/lib/fog/vcloud_director/generators/compute/vm_network.rb0000644000004100000410000001135213171001215025447 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.42.0/lib/fog/vcloud_director/generators/compute/compose_common.rb0000644000004100000410000001347313171001215026277 0ustar www-datawww-datamodule Fog module Generators module Compute module VcloudDirector module ComposeCommon def initialize(configuration={}) @configuration = configuration end private def vapp_attrs attrs = { :xmlns => 'http://www.vmware.com/vcloud/v1.5', 'xmlns:ovf' => 'http://schemas.dmtf.org/ovf/envelope/1' } [:deploy, :powerOn, :name].each do |a| attrs[a] = @configuration[a] if @configuration.key?(a) end attrs end def has_source_items? (@configuration[:source_vms] && (@configuration[:source_vms].size > 0)) || (@configuration[:source_templates] && (@configuration[:source_templates].size > 0)) end def build_vapp_instantiation_params(xml) xml.Description @configuration[:Description] if @configuration[:Description] vapp = @configuration[:InstantiationParams] if vapp xml.InstantiationParams { xml.DefaultStorageProfileSection { xml.StorageProfile vapp[:DefaultStorageProfile] } if (vapp.key? :DefaultStorageProfile) xml.NetworkConfigSection { xml['ovf'].Info vapp[:NetworkConfig].each do |network| xml.NetworkConfig(:networkName => network[:networkName]) { xml.Configuration { xml.ParentNetwork(:href => network[:networkHref]) xml.FenceMode network[:fenceMode] } } end if vapp[:NetworkConfig] } } end end def build_source_template(xml) xml.Source(:href => @configuration[:Source]) end def build_source_items(xml) vms = @configuration[:source_vms] vms.each do |vm| xml.SourcedItem { xml.Source(:name =>vm[:name], :href => vm[:href]) xml.VmGeneralParams { xml.Name vm[:name] xml.Description vm[:Description] if vm[:Description] xml.NeedsCustomization if vm[:NeedsCustomization] } if vm[:name] xml.InstantiationParams { if vm[:networks] xml.NetworkConnectionSection(:href => "#{vm[:href]}/networkConnectionSection/", :type => "application/vnd.vmware.vcloud.networkConnectionSection+xml", 'xmlns:ovf' => "http://schemas.dmtf.org/ovf/envelope/1", "ovf:required" => "false") { xml['ovf'].Info xml.PrimaryNetworkConnectionIndex 0 vm[:networks].each_with_index do |network, i| xml.NetworkConnection(:network => network[:networkName]) { xml.NetworkConnectionIndex i xml.IpAddress network[:IpAddress] if (network.key? :IpAddress) xml.ExternalIpAddress network[:ExternalIpAddress] if (network.key? :ExternalIpAddress) xml.IsConnected network[:IsConnected] xml.MACAddress network[:MACAddress] if (network.key? :MACAddress) xml.IpAddressAllocationMode network[:IpAddressAllocationMode] } end } end if customization = vm[:guest_customization] xml.GuestCustomizationSection(:xmlns => "http://www.vmware.com/vcloud/v1.5", 'xmlns:ovf' => "http://schemas.dmtf.org/ovf/envelope/1") { xml['ovf'].Info xml.Enabled (customization[:Enabled] || false) xml.ChangeSid customization[:ChangeSid] if (customization.key? :ChangeSid) xml.JoinDomainEnabled customization[:JoinDomainEnabled] if (customization.key? :JoinDomainEnabled) xml.UseOrgSettings customization[:UseOrgSettings] if (customization.key? :UseOrgSettings) xml.DomainName customization[:DomainName] if (customization.key? :DomainName) xml.DomainUserName customization[:DomainUserName] if (customization.key? :DomainUserName) xml.DomainUserPassword customization[:DomainUserPassword] if (customization.key? :DomainUserPassword) xml.MachineObjectOU customization[:MachineObjectOU] if (customization.key? :MachineObjectOU) xml.AdminPasswordEnabled customization[:AdminPasswordEnabled] if (customization.key? :AdminPasswordEnabled) xml.AdminPasswordAuto customization[:AdminPasswordAuto] if (customization.key? :AdminPasswordAuto) xml.AdminPassword customization[:AdminPassword] if (customization.key? :AdminPassword) xml.ResetPasswordRequired customization[:ResetPasswordRequired] if (customization.key? :ResetPasswordRequired) xml.CustomizationScript CGI::escapeHTML(customization[:CustomizationScript]).gsub(/\r/, " ") if (customization.key? :CustomizationScript) xml.ComputerName customization[:ComputerName] } end } xml.StorageProfile(:href => vm[:StorageProfileHref]) if (vm.key? :StorageProfileHref) } end if vms templates = @configuration[:source_templates] templates.each do |template| xml.SourcedItem { xml.Source(:href => template[:href]) } end if templates xml.AllEULAsAccepted (@configuration[:AllEULAsAccepted] || true) end end end end end end fog-1.42.0/lib/fog/vcloud_director/generators/compute/create_snapshot.rb0000644000004100000410000000135613171001215026441 0ustar www-datawww-datamodule Fog module Generators module Compute module VcloudDirector # @see http://pubs.vmware.com/vcd-56/topic/com.vmware.ICbase/PDF/vcd_56_api_guide.pdf @page 121 class CreateSnapshot attr_reader :attrs def initialize(attrs={}) @attrs = attrs end def generate_xml attrs = @attrs Nokogiri::XML::Builder.new do CreateSnapshotParams('xmlns' => 'http://www.vmware.com/vcloud/v1.5', 'memory' => attrs[:memory], 'name' => attrs[:name], 'quiesce' => attrs[:quiesce]) { Description attrs[:Description] if attrs.key?(:Description) } end.to_xml end end end end end end fog-1.42.0/lib/fog/vcloud_director/generators/compute/org_vdc_network.rb0000644000004100000410000000730413171001215026452 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.42.0/lib/fog/vcloud_director/generators/compute/vm.rb0000644000004100000410000000174613171001215023704 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.42.0/lib/fog/vcloud_director/generators/compute/edge_gateway_service_configuration.rb0000644000004100000410000002460613171001215032356 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) build_vpn(xml) build_dhcp(xml) build_static_routing_service(xml) } end.to_xml end private def build_dhcp(xml) dhcp_config = @configuration[:GatewayDhcpService] return unless dhcp_config xml.GatewayDhcpService { xml.IsEnabled dhcp_config[:IsEnabled] if dhcp_config.key?(:IsEnabled) dhcp_config[:pools].each do |pool| xml.Pool { xml.IsEnabled pool[:IsEnabled] xml.Network pool[:Network] xml.DefaultLeaseTime pool[:DefaultLeaseTime] xml.MaxLeaseTime pool[:MaxLeaseTime] xml.LowIpAddress pool[:LowIpAddress] xml.HighIpAddress pool[:HighIpAddress] } end } end def build_vpn(xml) vpn_config = @configuration[:GatewayIpsecVpnService] return unless vpn_config xml.GatewayIpsecVpnService { xml.IsEnabled vpn_config[:IsEnabled] if vpn_config.key?(:IsEnabled) vpn_config[:Tunnel].each do |tunnel_config| xml.Tunnel { xml.Name tunnel_config[:Name] xml.Description tunnel_config[:Description] xml.IpsecVpnLocalPeer { xml.Id tunnel_config[:IpsecVpnLocalPeerId] xml.Name tunnel_config[:IpsecVpnLocalPeerName] } xml.PeerIpAddress tunnel_config[:PeerIpAddress] xml.PeerId tunnel_config[:PeerId] xml.LocalIpAddress tunnel_config[:LocalIpAddress] xml.LocalId tunnel_config[:LocalId] tunnel_config[:LocalSubnet].each do |subnet| xml.LocalSubnet { xml.Name subnet[:Name] xml.Gateway subnet[:Gateway] xml.Netmask subnet[:Netmask] } end tunnel_config[:PeerSubnet].each do |subnet| xml.PeerSubnet { xml.Name subnet[:Name] xml.Gateway subnet[:Gateway] xml.Netmask subnet[:Netmask] } end xml.SharedSecret tunnel_config[:SharedSecret] xml.SharedSecretEncrypted tunnel_config[:SharedSecretEncrypted] if tunnel_config.key?(:SharedSecretEncrypted) xml.EncryptionProtocol tunnel_config[:EncryptionProtocol] xml.Mtu tunnel_config[:Mtu] xml.IsEnabled tunnel_config[:IsEnabled] } end } end 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_static_routing_service(xml) routing_config = @configuration[:StaticRoutingService] return unless routing_config xml.StaticRoutingService { xml.IsEnabled routing_config[:IsEnabled] routing_config[:StaticRoute].each do |rule| xml.StaticRoute{ xml.Name rule[:Name] xml.Network rule[:Network] xml.NextHopIp rule[:NextHopIp] xml.GatewayInterface( :type => rule[:GatewayInterface][:type], :name => rule[:GatewayInterface][:name], :href => rule[:GatewayInterface][:href] ) } 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.42.0/lib/fog/vcloud_director/generators/compute/disks.rb0000644000004100000410000001611013171001215024366 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.find{|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.42.0/lib/fog/vcloud_director/generators/compute/vapp.rb0000644000004100000410000000136413171001215024224 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.42.0/lib/fog/vcloud_director/generators/compute/customization.rb0000644000004100000410000001102413171001215026160 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.42.0/lib/fog/vcloud_director/core.rb0000644000004100000410000000477513171001215020372 0ustar www-datawww-datarequire 'fog/core' require 'fog/xml' module Fog module VcloudDirector extend Fog::Provider module Errors class ServiceError < Fog::Errors::Error attr_reader :minor_error_code attr_reader :major_error_code attr_reader :stack_trace attr_reader :status_code attr_reader :vendor_specific_error_code def self.slurp(error, service=nil) major_error_code = nil message = nil minor_error_code = nil stack_trace = nil status_code = nil vendor_specific_error_code = nil if error.response status_code = error.response.status unless error.response.body.empty? _, media_type = error.response.headers.find {|k,v| k.downcase == 'content-type'} if media_type =~ /vnd\.vmware\.vcloud\.error\+xml/i begin document = Fog::ToHashDocument.new Nokogiri::XML::SAX::Parser.new(document).parse_memory(error.response.body) major_error_code = document.body[:majorErrorCode] message = document.body[:message] minor_error_code = document.body[:minorErrorCode] stack_trace = document.body[:stackTrace] vendor_specific_error_code = document.body[:vendorSpecificErrorCode] rescue => e Fog::Logger.warning("Received exception '#{e}' while decoding>> #{error.response.body}") message = error.response.body end else message = CGI::unescapeHTML(error.response.body) end end end new_error = super(error, message) new_error.instance_variable_set(:@major_error_code, major_error_code) new_error.instance_variable_set(:@minor_error_code, minor_error_code) new_error.instance_variable_set(:@stack_trace, stack_trace) new_error.instance_variable_set(:@status_code, status_code) new_error.instance_variable_set(:@vendor_specific_error_code, vendor_specific_error_code) new_error end end class BadRequest < ServiceError; end class Unauthorized < ServiceError; end class Forbidden < ServiceError; end class Conflict < ServiceError; end class MalformedResponse < ServiceError; end class DuplicateName < ServiceError; end class TaskError < ServiceError; end end service(:compute, 'Compute') end end fog-1.42.0/lib/fog/vcloud_director/models/0000755000004100000410000000000013171001215020363 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud_director/models/compute/0000755000004100000410000000000013171001215022037 5ustar www-datawww-datafog-1.42.0/lib/fog/vcloud_director/models/compute/media.rb0000644000004100000410000000113313171001215023441 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.42.0/lib/fog/vcloud_director/models/compute/task.rb0000644000004100000410000000340713171001215023332 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' || status == 'queued' Fog::Formatador.redisplay_progressbar(progress, 100, :label => operation_name, :started_at => start_time) @last_progress = progress elsif status == 'success' Fog::Formatador.redisplay_progressbar(100, 100, :label => operation_name, :started_at => start_time) @last_progress = 100 end end ! %w(running queued).include?(status) end def cancel service.post_cancel_task(id) end end end end end fog-1.42.0/lib/fog/vcloud_director/models/compute/vapp_templates.rb0000644000004100000410000000206013171001215025406 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/vapp' module Fog module Compute class VcloudDirector class VappTemplates < Collection include Fog::VcloudDirector::Query model Fog::Compute::VcloudDirector::VappTemplate attribute :vdc def query_type "vAppTemplate" end private def get_by_id(item_id) item = service.get_vapp_template(item_id).body %w(:Link).each {|key_to_delete| item.delete(key_to_delete) } service.add_id_from_href!(item) item[:Description] ||= "" 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.vAppTemplate+xml" } items.each{|item| service.add_id_from_href!(item) } items end end end end end fog-1.42.0/lib/fog/vcloud_director/models/compute/medias.rb0000644000004100000410000000447313171001215023636 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].find {|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.42.0/lib/fog/vcloud_director/models/compute/organization.rb0000644000004100000410000000136613171001215025076 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.42.0/lib/fog/vcloud_director/models/compute/custom_fields.rb0000644000004100000410000000375613171001215025237 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/custom_field' module Fog module Compute class VcloudDirector class CustomFields < Collection model Fog::Compute::VcloudDirector::CustomField attribute :vapp def get_by_id(item_id) item_list.detect{|i| i[:id] == item_id} end def [](key) get key.to_s end def set(key, value, opts={:type => 'string', :password => 'false', :user_configurable => 'true'}) new_items = item_list.each.reject{|item| item[:id] == key} new_items << { :id => key, :value => value, :type => opts[:type], :password => opts[:password], :user_configurable => opts[:user_configurable] } response = service.put_product_sections(vapp.id, new_items) service.process_task(response.body) end def []=(key,value) set(key,value) end def delete(item_id) id = item_id.to_s new_items = item_list.each.reject{|item| item[:id] == id} response = service.put_product_sections(vapp.id, new_items) service.process_task(response.body) end def item_list return @items if @items resp = service.get_product_sections_vapp(vapp.id).body collection = resp["ovf:ProductSection".to_sym]["ovf:Property".to_sym] rescue [] collection = [collection] if collection.is_a?(Hash) @items = collection.collect do |property| { :id => property[:ovf_key], :value => property[:ovf_value], :type => property[:ovf_type], :password => property[:ovf_password], :user_configurable => property[:ovf_userConfigurable] } end rescue [] end end end end end fog-1.42.0/lib/fog/vcloud_director/models/compute/vdc.rb0000644000004100000410000000255513171001215023147 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 def vapp_templates requires :id service.vapp_templates(:vdc => self) end def networks requires :available_networks service.networks(:vdc => self) end end end end end fog-1.42.0/lib/fog/vcloud_director/models/compute/custom_field.rb0000644000004100000410000000042613171001215025043 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class VcloudDirector class CustomField < Model identity :id attribute :value attribute :type attribute :password attribute :user_configurable end end end end fog-1.42.0/lib/fog/vcloud_director/models/compute/template_vm.rb0000644000004100000410000000230313171001215024677 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/vcloud_director/models/compute/vm_customization' module Fog module Compute class VcloudDirector class TemplateVm < Model identity :id attribute :vapp_template_id attribute :vapp_template_name attribute :name attribute :type attribute :href def reload #Parent vapp_name & id are nil on a template_vm. Adding them from the collection parent self.vapp_template_id = collection.vapp_template.id self.vapp_template_name = collection.vapp_template.name 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 vapp_template service.vapp_templates.get(vapp_template_id) end end end end end fog-1.42.0/lib/fog/vcloud_director/models/compute/catalogs.rb0000644000004100000410000000146613171001215024170 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.42.0/lib/fog/vcloud_director/models/compute/network.rb0000644000004100000410000000102213171001215024050 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 :is_shared attribute :fence_mode attribute :gateway attribute :netmask attribute :dns1 attribute :dns2 attribute :dns_suffix attribute :ip_ranges, :type => :array end end end end fog-1.42.0/lib/fog/vcloud_director/models/compute/vm_customizations.rb0000644000004100000410000000147413171001215026167 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 private def get_by_id(item_id) item = service.get_vm_customization(item_id).body add_id_from_href!(item) item end # The HREF returned for a VM customization object is actually the VM # HREF suffixed with '/guestCustomizationSection/' so we cannot use # service.add_id_from_href! like all other collections. def add_id_from_href!(item={}) item[:id] = item[:href].gsub('/guestCustomizationSection/', '').split('/').last end end end end end fog-1.42.0/lib/fog/vcloud_director/models/compute/catalog.rb0000644000004100000410000000073413171001215024002 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.42.0/lib/fog/vcloud_director/models/compute/vm_customization.rb0000644000004100000410000000210013171001215025767 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.42.0/lib/fog/vcloud_director/models/compute/vm_network.rb0000644000004100000410000000123313171001215024556 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.42.0/lib/fog/vcloud_director/models/compute/vm_networks.rb0000644000004100000410000000057713171001215024753 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.42.0/lib/fog/vcloud_director/models/compute/vm.rb0000644000004100000410000001333713171001215023015 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 :description attribute :href attribute :status attribute :deployed attribute :operating_system attribute :ip_address attribute :cpu, :type => :integer attribute :memory, :type => :integer attribute :hard_disks, :aliases => :disks attribute :network_adapters 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 def undeploy requires :id begin response = service.post_undeploy_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 # Reconfigure a VM using any of the options documented in # post_reconfigure_vm def reconfigure(options) options[:name] ||= name # name has to be sent # Delete those things that are not changing for performance [:cpu, :memory, :description].each do |k| options.delete(k) if options.key? k and options[k] == attributes[k] end response = service.post_reconfigure_vm(id, options) service.process_task(response.body) options.each {|k,v| attributes[k] = v} 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.42.0/lib/fog/vcloud_director/models/compute/vapp_template.rb0000644000004100000410000000135513171001215025231 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class VcloudDirector class VappTemplate < Model identity :id attribute :name attribute :type attribute :href attribute :description, :aliases => :Description 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 def vms requires :id service.template_vms(:vapp_template => self) end end end end endfog-1.42.0/lib/fog/vcloud_director/models/compute/tag.rb0000644000004100000410000000134413171001215023141 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.42.0/lib/fog/vcloud_director/models/compute/tags.rb0000644000004100000410000000163213171001215023324 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.find{ |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.42.0/lib/fog/vcloud_director/models/compute/catalog_items.rb0000644000004100000410000000165713171001215025210 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.42.0/lib/fog/vcloud_director/models/compute/disks.rb0000644000004100000410000000233213171001215023501 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.find{ |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 # Returns only disk drives (OVF resource type 17) and not controllers, # etc. See def storage_only select {|d| d.resource_type == 17} end end end end end fog-1.42.0/lib/fog/vcloud_director/models/compute/vapp.rb0000644000004100000410000001105013171001215023327 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 def custom_fields requires :id service.custom_fields( :vapp => 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.42.0/lib/fog/vcloud_director/models/compute/template_vms.rb0000644000004100000410000000147713171001215025075 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/vm' module Fog module Compute class VcloudDirector class TemplateVms < Collection include Fog::VcloudDirector::Query model Fog::Compute::VcloudDirector::TemplateVm attribute :vapp_template def get_single_vm(vm_id) item = service.get_template_vm(vm_id).body return nil unless item new(item[:vm]) end def query_type "vm" end private def get_by_id(item_id) item = item_list.find{ |vm| vm[:id] == item_id } item end def item_list data = service.get_template_vms(vapp_template.id).body # vapp.id items = data[:vms] items end end end end end fog-1.42.0/lib/fog/vcloud_director/models/compute/catalog_item.rb0000644000004100000410000000143413171001215025016 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 vapp_template requires :id service.vapp_templates.get(self.vapp_template_id) end 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.42.0/lib/fog/vcloud_director/models/compute/vms.rb0000644000004100000410000000166713171001215023203 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/vm' module Fog module Compute class VcloudDirector class Vms < Collection include Fog::VcloudDirector::Query 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 def query_type "vm" end private def get_by_id(item_id) item = item_list.find{ |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.42.0/lib/fog/vcloud_director/models/compute/vdcs.rb0000644000004100000410000000162413171001215023326 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/vdc' module Fog module Compute class VcloudDirector class Vdcs < Collection include Fog::VcloudDirector::Query model Fog::Compute::VcloudDirector::Vdc attribute :organization def query_type "orgVdc" end 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.42.0/lib/fog/vcloud_director/models/compute/vapps.rb0000644000004100000410000000200713171001215023514 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/vapp' module Fog module Compute class VcloudDirector class Vapps < Collection include Fog::VcloudDirector::Query model Fog::Compute::VcloudDirector::Vapp attribute :vdc def query_type "vApp" end 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[:Description] ||= "" 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.42.0/lib/fog/vcloud_director/models/compute/disk.rb0000644000004100000410000000304413171001215023317 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.42.0/lib/fog/vcloud_director/models/compute/organizations.rb0000644000004100000410000000121013171001215025245 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.42.0/lib/fog/vcloud_director/models/compute/tasks.rb0000644000004100000410000000137513171001215023517 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/task' module Fog module Compute class VcloudDirector class Tasks < Collection include Fog::VcloudDirector::Query model Fog::Compute::VcloudDirector::Task attribute :organization def query_type "task" end def get(id) data = service.get_task(id).body return nil unless data data[:id] = data[:href].split('/').last data[:progress] ||= 0 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.42.0/lib/fog/vcloud_director/models/compute/networks.rb0000644000004100000410000000373713171001215024252 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/vcloud_director/models/compute/network' module Fog module Compute class VcloudDirector class Networks < Collection include Fog::VcloudDirector::Query model Fog::Compute::VcloudDirector::Network attribute :organization attribute :vdc def query_type "orgVdcNetwork" end private def get_by_id(item_id) raw_network = service.get_network_complete(item_id).body data = {} data[:type] = raw_network[:type] data[:href] = raw_network[:href] service.add_id_from_href!(data) data[:name] = raw_network[:name] data[:description] = raw_network[:Description] data[:is_shared] = raw_network[:IsShared] net_config = raw_network[:Configuration] data[:fence_mode] = net_config[:FenceMode] ip_scope = net_config[:IpScopes][:IpScope] data[:is_inherited] = ip_scope[:IsInherited] data[:gateway] = ip_scope[:Gateway] data[:netmask] = ip_scope[:Netmask] data[:dns1] = ip_scope[:Dns1] data[:dns2] = ip_scope[:Dns2] data[:dns_suffix] = ip_scope[:DnsSuffix] data[:ip_ranges] = [] raw_ip_ranges = ip_scope[:IpRanges][:IpRange] data[:ip_ranges] = raw_ip_ranges.map do |ip_range| { :start_address => ip_range[:StartAddress], :end_address => ip_range[:EndAddress] } end data end def item_list items = if vdc vdc.available_networks.select {|link| link[:type] == "application/vnd.vmware.vcloud.network+xml"} else data = service.get_organization(organization.id).body data[:Link].select { |link| link[:type] == "application/vnd.vmware.vcloud.orgNetwork+xml" } end items.each{|item| service.add_id_from_href!(item) } items end end end end end fog-1.42.0/lib/fog/vcloud_director/README.md0000644000004100000410000006552113171001215020370 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 vapp_templates -> vms -> vm networks -> network catalogs -> catalog -> catalog_items -> catalog_item -> instantiate_vapp -> vapp_template -> vms -> vm 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.42.0/lib/fog/vcloud_director/compute.rb0000644000004100000410000007735713171001215021124 0ustar www-datawww-datarequire 'fog/vcloud_director/core' require 'fog/vcloud_director/query' 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' OMIT_DEFAULT_PORT = true 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 MalformedResponse < Fog::VcloudDirector::Errors::MalformedResponse; 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, :path, :vcloud_token secrets :vcloud_director_password model_path 'fog/vcloud_director/models/compute' model :catalog collection :catalogs model :organization collection :organizations model :catalog_item collection :vapp_templates model :vapp_template collection :template_vms model :template_vm collection :catalog_items model :custom_field collection :custom_fields 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_complete 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_template_vm request :get_template_vms 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_catalog_item request :post_create_org_vdc_network request :post_deploy_vapp request :post_compose_vapp request :post_recompose_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_reconfigure_vm 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 :post_create_snapshot 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 request :put_network_connection_system_section_vapp request :put_product_sections 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.find {|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] || {} @connection_options[:omit_default_port] = Fog::Compute::VcloudDirector::Defaults::OMIT_DEFAULT_PORT unless @connection_options[:omit_default_port] @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::XML::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? @vcloud_token = options[:vcloud_token] 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) rescue EOFError # This error can occur if Vcloud receives a request from a network # it deems to be unauthorized; no HTTP response is sent, but the # connection is sent a signal to terminate early. raise( MalformedResponse, "Connection unexpectedly terminated by vcloud" ) # 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 @vcloud_token ||= ENV['FOG_VCLOUD_TOKEN'] if @vcloud_token response = get_current_session session_org = response.body[:org] session_user = response.body[:user] check_session_matches_credentials(session_org, session_user) else response = post_login_session x_vcloud_authorization = response.headers.keys.find do |key| key.downcase == 'x-vcloud-authorization' end @vcloud_token = response.headers[x_vcloud_authorization] end @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 def check_session_matches_credentials(session_org, session_user) fog_credential_org = @vcloud_director_username.split('@').last fog_credential_user = @vcloud_director_username.split('@')[0...-1].join('@') if session_org != fog_credential_org raise Fog::Errors::Error.new "FOG_CREDENTIAL specified is for vCloud organisation '#{fog_credential_org}' but " + "your current session is for '#{session_org}'. You should generate a new FOG_VCLOUD_TOKEN." end if session_user != fog_credential_user raise Fog::Errors::Error.new "FOG_CREDENTIAL specified is for user '#{fog_credential_user}' but " + "your current session is for '#{session_user}'. You should generate a new FOG_VCLOUD_TOKEN." end end end class Mock attr_reader :end_point, :api_version # This is used in some mocks so it's a method rather than a variable def default_network_uuid @default_network_uuid ||= uuid end def data @@data ||= Hash.new do |hash, key| vdc1_uuid = uuid vdc2_uuid = uuid uplink_network_uuid = uuid isolated_vdc1_network_uuid = uuid isolated_vdc2_network_uuid = uuid vapp1_id = "vapp-#{uuid}" vapp2_id = "vapp-#{uuid}" vapp1vm1_id = "vm-#{uuid}" vapp2vm1_id = "vm-#{uuid}" vapp2vm2_id = "vm-#{uuid}" catalog_uuid = uuid template_uuid = uuid hash[key] = { :catalogs => { catalog_uuid => { :name => 'Default Catalog' } }, :catalog_items => { uuid => { :type => 'vAppTemplate', :name => 'vAppTemplate 1', :catalog => catalog_uuid, :template_id => template_uuid } }, :disks => { uuid => { :name => 'Hard Disk 1', :capacity => 10240, :parent_vm => vapp1vm1_id } }, :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 => 'vDC1 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 }, :tags => {}, :tasks => {}, :vapps => { vapp1_id => { :name => 'mock-vapp-1', :vdc_id => vdc1_uuid, :description => "Mock vApp 1", :networks => [ { :parent_id => default_network_uuid, }, ], }, vapp2_id => { :name => 'mock-vapp-2', :vdc_id => vdc2_uuid, :description => "Mock vApp 2", :networks => [ { :parent_id => default_network_uuid }, ] }, }, :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' }, }, :vms => { vapp1vm1_id => { :name => 'mock-vm-1-1', :parent_vapp => vapp1_id, :nics => [ { :network_name => 'Default Network', :mac_address => "00:50:56:aa:bb:01", :ip_address => "192.168.1.33", }, ], }, vapp2vm1_id => { :name => 'mock-vm-2-1', :parent_vapp => vapp2_id, :nics => [ { :network_name => 'Default Network', :mac_address => "00:50:56:aa:bb:02", :ip_address => "192.168.1.34", }, ], }, vapp2vm2_id => { :name => 'mock-vm-2-2', :parent_vapp => vapp2_id, :nics => [ { :network_name => 'Default Network', :mac_address => "00:50:56:aa:bb:03", :ip_address => "192.168.1.35", }, ], }, }, } 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::XML::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 @vcloud_token = options[:vcloud_token] 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, :end_time => now + 86400, :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.42.0/lib/fog/go_grid.rb0000644000004100000410000000003613171001215015647 0ustar www-datawww-datarequire 'fog/go_grid/compute' fog-1.42.0/lib/fog/ibm/0000755000004100000410000000000013171001215014460 5ustar www-datawww-datafog-1.42.0/lib/fog/ibm/requests/0000755000004100000410000000000013171001215016333 5ustar www-datawww-datafog-1.42.0/lib/fog/ibm/requests/storage/0000755000004100000410000000000013171001215017777 5ustar www-datawww-datafog-1.42.0/lib/fog/ibm/requests/storage/create_volume.rb0000644000004100000410000000525713171001215023167 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.42.0/lib/fog/ibm/requests/storage/delete_volume.rb0000644000004100000410000000174213171001215023161 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.42.0/lib/fog/ibm/requests/storage/list_offerings.rb0000644000004100000410000000476113171001215023351 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.42.0/lib/fog/ibm/requests/storage/get_volume.rb0000644000004100000410000000405413171001215022475 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.42.0/lib/fog/ibm/requests/storage/list_volumes.rb0000644000004100000410000000251113171001215023050 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.42.0/lib/fog/ibm/requests/compute/0000755000004100000410000000000013171001215020007 5ustar www-datawww-datafog-1.42.0/lib/fog/ibm/requests/compute/get_location.rb0000644000004100000410000000312713171001215023006 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.42.0/lib/fog/ibm/requests/compute/create_key.rb0000644000004100000410000000365713171001215022462 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.42.0/lib/fog/ibm/requests/compute/get_image_manifest.rb0000644000004100000410000000234413171001215024146 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.42.0/lib/fog/ibm/requests/compute/create_image.rb0000644000004100000410000000320613171001215022742 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.42.0/lib/fog/ibm/requests/compute/delete_address.rb0000644000004100000410000000212113171001215023277 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.42.0/lib/fog/ibm/requests/compute/delete_key.rb0000644000004100000410000000164313171001215022452 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.42.0/lib/fog/ibm/requests/compute/get_request.rb0000644000004100000410000000566013171001215022672 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.42.0/lib/fog/ibm/requests/compute/modify_instance.rb0000644000004100000410000000466713171001215023524 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.42.0/lib/fog/ibm/requests/compute/get_instance_logs.rb0000644000004100000410000000107313171001215024024 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.42.0/lib/fog/ibm/requests/compute/list_images.rb0000644000004100000410000000404513171001215022637 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.42.0/lib/fog/ibm/requests/compute/get_key.rb0000644000004100000410000000231013171001215021757 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.42.0/lib/fog/ibm/requests/compute/delete_instance.rb0000644000004100000410000000275313171001215023471 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.42.0/lib/fog/ibm/requests/compute/create_address.rb0000644000004100000410000000277213171001215023314 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.42.0/lib/fog/ibm/requests/compute/list_vlans.rb0000644000004100000410000000231613171001215022514 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.42.0/lib/fog/ibm/requests/compute/clone_image.rb0000644000004100000410000000245213171001215022601 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.42.0/lib/fog/ibm/requests/compute/get_image_agreement.rb0000644000004100000410000000652713171001215024316 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.42.0/lib/fog/ibm/requests/compute/get_instance.rb0000644000004100000410000000535613171001215023010 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.42.0/lib/fog/ibm/requests/compute/list_keys.rb0000644000004100000410000000402413171001215022342 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.42.0/lib/fog/ibm/requests/compute/get_image.rb0000644000004100000410000000424113171001215022256 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.42.0/lib/fog/ibm/requests/compute/list_addresses.rb0000644000004100000410000000325713171001215023353 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.42.0/lib/fog/ibm/requests/compute/delete_image.rb0000644000004100000410000000212513171001215022740 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.42.0/lib/fog/ibm/requests/compute/list_instances.rb0000644000004100000410000000405713171001215023364 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.42.0/lib/fog/ibm/requests/compute/list_locations.rb0000644000004100000410000000143513171001215023365 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.42.0/lib/fog/ibm/requests/compute/create_instance.rb0000644000004100000410000000742413171001215023472 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.42.0/lib/fog/ibm/requests/compute/list_address_offerings.rb0000644000004100000410000000342713171001215025064 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.42.0/lib/fog/ibm/requests/compute/modify_key.rb0000644000004100000410000000257213171001215022501 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.42.0/lib/fog/ibm/core.rb0000644000004100000410000001237313171001215015743 0ustar www-datawww-datarequire 'fog/core' require 'fog/json' module Fog module IBM extend Fog::Provider service(:compute, 'Compute') service(: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::XML::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_method :instance_id, :id alias_method :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.42.0/lib/fog/ibm/models/0000755000004100000410000000000013171001215015743 5ustar www-datawww-datafog-1.42.0/lib/fog/ibm/models/storage/0000755000004100000410000000000013171001215017407 5ustar www-datawww-datafog-1.42.0/lib/fog/ibm/models/storage/volume.rb0000644000004100000410000000522613171001215021250 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.42.0/lib/fog/ibm/models/storage/offerings.rb0000644000004100000410000000046513171001215021723 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.42.0/lib/fog/ibm/models/storage/offering.rb0000644000004100000410000000062613171001215021537 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.42.0/lib/fog/ibm/models/storage/volumes.rb0000644000004100000410000000074413171001215021433 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.42.0/lib/fog/ibm/models/compute/0000755000004100000410000000000013171001215017417 5ustar www-datawww-datafog-1.42.0/lib/fog/ibm/models/compute/address.rb0000644000004100000410000000266613171001215021403 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.42.0/lib/fog/ibm/models/compute/addresses.rb0000644000004100000410000000110313171001215021714 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.42.0/lib/fog/ibm/models/compute/vlan.rb0000644000004100000410000000030713171001215020704 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.42.0/lib/fog/ibm/models/compute/location.rb0000644000004100000410000000041213171001215021551 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.42.0/lib/fog/ibm/models/compute/images.rb0000644000004100000410000000073413171001215021215 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.42.0/lib/fog/ibm/models/compute/servers.rb0000644000004100000410000000075213171001215021441 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.42.0/lib/fog/ibm/models/compute/instance-type.rb0000644000004100000410000000034713171001215022533 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.42.0/lib/fog/ibm/models/compute/instance-types.rb0000644000004100000410000000035613171001215022716 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.42.0/lib/fog/ibm/models/compute/locations.rb0000644000004100000410000000076413171001215021746 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.42.0/lib/fog/ibm/models/compute/keys.rb0000644000004100000410000000117013171001215020716 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.42.0/lib/fog/ibm/models/compute/key.rb0000644000004100000410000000150313171001215020533 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.42.0/lib/fog/ibm/models/compute/server.rb0000644000004100000410000001310013171001215021245 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_method :create_image, :to_image end end end end fog-1.42.0/lib/fog/ibm/models/compute/image.rb0000644000004100000410000000333713171001215021034 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.42.0/lib/fog/ibm/models/compute/vlans.rb0000644000004100000410000000102513171001215021065 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.42.0/lib/fog/ibm/compute.rb0000644000004100000410000002176013171001215016467 0ustar www-datawww-datarequire 'fog/ibm/core' 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.42.0/lib/fog/ibm/storage.rb0000644000004100000410000000323213171001215016451 0ustar www-datawww-datarequire 'fog/ibm/core' 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.42.0/lib/fog/ibm.rb0000644000004100000410000000006413171001215015005 0ustar www-datawww-datarequire 'fog/ibm/compute' require 'fog/ibm/storage' fog-1.42.0/lib/fog/fogdocker.rb0000644000004100000410000000004013171001215016173 0ustar www-datawww-datarequire 'fog/fogdocker/compute' fog-1.42.0/lib/fog/ovirt/0000755000004100000410000000000013171001215015054 5ustar www-datawww-datafog-1.42.0/lib/fog/ovirt/requests/0000755000004100000410000000000013171001215016727 5ustar www-datawww-datafog-1.42.0/lib/fog/ovirt/requests/compute/0000755000004100000410000000000013171001215020403 5ustar www-datawww-datafog-1.42.0/lib/fog/ovirt/requests/compute/deactivate_volume.rb0000644000004100000410000000125013171001215024426 0ustar www-datawww-datamodule Fog module Compute class Ovirt class Real def deactivate_volume(id, options) raise ArgumentError, "instance id is a required parameter" unless id raise ArgumentError, "volume id is a required parameter for deactivate-volume" unless options.key? :id client.deactivate_volume(id, options[:id]) end end class Mock def deactivate_volume(id, options) raise ArgumentError, "instance id is a required parameter" unless id raise ArgumentError, "volume id is a required parameter for deactivate-volume" unless options.key? :id true end end end end end fog-1.42.0/lib/fog/ovirt/requests/compute/activate_volume.rb0000644000004100000410000000123613171001215024121 0ustar www-datawww-datamodule Fog module Compute class Ovirt class Real def activate_volume(id, options) raise ArgumentError, "instance id is a required parameter" unless id raise ArgumentError, "volume id is a required parameter for activate-volume" unless options.key? :id client.activate_volume(id, options[:id]) end end class Mock def activate_volume(id, options) raise ArgumentError, "instance id is a required parameter" unless id raise ArgumentError, "volume id is a required parameter for activate-volume" unless options.key? :id true end end end end end fog-1.42.0/lib/fog/bluebox.rb0000644000004100000410000000012213171001215015671 0ustar www-datawww-datarequire 'fog/bluebox/blb' require 'fog/bluebox/compute' require 'fog/bluebox/dns' fog-1.42.0/lib/fog/clodo.rb0000644000004100000410000000003413171001215015333 0ustar www-datawww-datarequire 'fog/clodo/compute' fog-1.42.0/lib/fog/zerigo.rb0000644000004100000410000000003113171001215015527 0ustar www-datawww-datarequire 'fog/zerigo/dns' fog-1.42.0/lib/fog/cloudstack.rb0000644000004100000410000000004113171001215016365 0ustar www-datawww-datarequire 'fog/cloudstack/compute' fog-1.42.0/lib/fog/glesys.rb0000644000004100000410000000003513171001215015542 0ustar www-datawww-datarequire 'fog/glesys/compute' fog-1.42.0/lib/fog/rage4.rb0000644000004100000410000000003013171001215015231 0ustar www-datawww-datarequire 'fog/rage4/dns' fog-1.42.0/lib/fog/dnsmadeeasy/0000755000004100000410000000000013171001215016206 5ustar www-datawww-datafog-1.42.0/lib/fog/dnsmadeeasy/requests/0000755000004100000410000000000013171001215020061 5ustar www-datawww-datafog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/0000755000004100000410000000000013171001215020645 5ustar www-datawww-datafog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/delete_secondary.rb0000644000004100000410000000114613171001215024505 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Deletes the specified secondary entry. # # ==== Parameters # * secondary_name<~String> - secondary domain name # # ==== Returns # * response<~Excon::Response>: # * status<~Integer> 200 - OK, 404 - specified secondary entry name is not found def delete_secondary(secondary_name) request( :expects => 200, :method => 'DELETE', :path => "/V1.2/secondary/#{secondary_name}" ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/list_records.rb0000644000004100000410000000362413171001215023673 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Returns a list of record objects containing all records for the specified domain # # ==== Parameters # * domain<~String> # * options<~Hash> # * gtdLocation<~String> Global Traffic Director location. Values: DEFAULT, US_EAST, US_WEST, EUROPE # * type<~String> Record type. Values: A, AAAA, CNAME, HTTPRED, MX, NS, PTR, SRV, TXT # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * id<~Integer> Unique record identifier # * name<~String> Record name. # * type<~String> Record type. Values: A, AAAA, CNAME, HTTPRED, MX, NS, PTR, SRV, TXT # * data<~String> # * ttl<~Integer> Time to live. The amount of time a record will be cached before being refreshed. # * gtdLocation<~String> Global Traffic Director location. Values: DEFAULT, US_EAST, US_WEST, EUROPE # * password<~String> For A records. Password used to authenticate for dynamic DNS. # * description<~String> For HTTPRED records. A description of the HTTPRED record. # * keywords<~String> For HTTPRED records. Keywords associated with the HTTPRED record. # * title<~String> For HTTPRED records. The title of the HTTPRED record. # * redirectType<~String> For HTTPRED records. Type of redirection performed. Values: Hidden Frame Masked, Standard - 302, Standard - 301 # * hardLink<~Boolean> For HTTPRED records. # * status<~Integer> - 200 - OK, 404 - specified domain name is not found def list_records(domain, options = {}) request( :expects => 200, :method => "GET", :path => "/V1.2/domains/#{domain}/records", :query => options ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/delete_all_secondary.rb0000644000004100000410000000067613171001215025344 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Deletes all secondary entries for your account. # # ==== Returns # * response<~Excon::Response>: # * status<~Integer> 200 - OK def delete_all_secondary request( :expects => 200, :method => 'DELETE', :path => '/V1.2/secondary' ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/get_domain.rb0000644000004100000410000000161213171001215023300 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Get the details for a specific domain in your account. # # ==== Parameters # * domain<~String> - domain name # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * name<~String> The domain name. # * nameServer<~Array> List of strings, Name servers associated with this domain e.g. ["ns1.dnsmadeeasy.com", "ns2.dnsmadeeasy.com"] # * gtdEnabled<~Boolean> Indicator of whether or not this domain uses the Global Traffic Director. # * status<~Integer> 200 - OK, 404 - specified domain name is not found def get_domain(domain) request( :expects => 200, :method => "GET", :path => "/V1.2/domains/#{domain}" ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/create_secondary.rb0000644000004100000410000000243613171001215024511 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Creates a secondary entry with the specified name. Returns errors if name is not valid or conflicts with another domain. # # ==== Parameters # * secondary_name<~String> - secondary name # * ip_addresses<~Array> - List of secondary ip addresses # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * name<~String> Secondary name. # * ip<~Array> List of strings, IP addresses for your master nameserver associated with this secondary entry. e.g. ["10.10.10.10", "10.10.10.11"] # * gtdLocation<~String> Global Traffic Director location. Values: DEFAULT, US_EAST, US_WEST, EUROPE # * status<~Integer> - 201 - secondary entry successfully created or modified, 400 - secondary entry name or IP addresses not valid, see errors in response content def create_secondary(secondary_name, ip_addresses) body = { "ip" => [*ip_addresses] } request( :expects => 201, :method => 'PUT', :path => "/V1.2/secondary/#{secondary_name}", :body => Fog::JSON.encode(body) ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/create_record.rb0000644000004100000410000000511013171001215023770 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Creates a record with the representation specified in the request content. Returns errors if record is not valid. # Note that a record ID will be generated by the system with this request and any ID that is sent will be ignored. Records are not modifiable for domains that are locked to a template. # # ==== Parameters # * domain<~String> Domain name. # * name<~String> Record name. # * type<~String> Record type. Values: A, AAAA, CNAME, HTTPRED, MX, NS, PTR, SRV, TXT # * data<~String> Record data # * options<~Hash> - optional # * ttl<~Integer> Time to live. The amount of time a record will be cached before being refreshed. Default: 1800 (30 mins) # * gtdLocation<~String> Global Traffic Director location. Values: DEFAULT, US_EAST, US_WEST, EUROPE # * password<~String> For A records. Password used to authenticate for dynamic DNS. # * description<~String> For HTTPRED records. A description of the HTTPRED record. # * keywords<~String> For HTTPRED records. Keywords associated with the HTTPRED record. # * title<~String> For HTTPRED records. The title of the HTTPRED record. # * redirectType<~String> For HTTPRED records. Type of redirection performed. Values: Hidden Frame Masked, Standard - 302, Standard - 301 # * hardLink<~Boolean> For HTTPRED records. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * id<~Integer> Unique record identifier # * name<~String> # * type<~String> # * data<~String> # * ttl<~Integer> # * gtdLocation<~String> # * password<~String> # * description<~String> # * keywords<~String> # * title<~String> # * redirectType<~String> # * hardLink<~Boolean> # * 'status'<~Integer> - 201 - record successfully created, 400 - record not valid, see errors in response content, 404 - domain not found def create_record(domain, name, type, data, options = {}) body = { "name" => name, "type" => type, "data" => data, "ttl" => 1800 } body.merge!(options) request( :expects => 201, :method => "POST", :path => "/V1.2/domains/#{domain}/records", :body => Fog::JSON.encode(body) ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/get_secondary.rb0000644000004100000410000000174013171001215024022 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Returns the secondary entry object representation of the specified secondary entry. # # ==== Parameters # * secondary_name<~String> - secondary name # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * name<~String> Secondary name. # * ip<~Array> List of strings, IP addresses for your master nameserver associated with this secondary entry. e.g. ["10.10.10.10", "10.10.10.11"] # * gtdLocation<~String> Global Traffic Director location. Values: DEFAULT, US_EAST, US_WEST, EUROPE # * status<~Integer> - 200 - OK, 404 - specified secondary entry name is not found def get_secondary(secondary_name) request( :expects => 200, :method => "GET", :path => "/V1.2/secondary/#{secondary_name}" ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/create_domain.rb0000644000004100000410000000201113171001215023756 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Creates a domain entry with the specified name. Returns errors if name is not valid or conflicts with another domain. # # ==== Parameters # * domain<~String> - domain name # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * name<~String> The domain name. # * nameServer<~Array> List of strings, Name servers associated with this domain e.g. ["ns1.dnsmadeeasy.com", "ns2.dnsmadeeasy.com"] # * gtdEnabled<~Boolean> true | false - Indicator of whether or not this domain uses the Global Traffic Director. # * status<~Integer> - 201 - domain successfully created, 400 - domain name not valid, see errors in response content def create_domain(domain) request( :expects => 201, :method => 'PUT', :path => "/V1.2/domains/#{domain}" ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/update_secondary.rb0000644000004100000410000000243713171001215024531 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Modifies a secondary entry with the specified name. Returns errors if name is not valid or conflicts with another domain. # # ==== Parameters # * secondary_name<~String> - secondary name # * ip_addresses<~Array> - List of secondary ip addresses # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * name<~String> Secondary name. # * ip<~Array> List of strings, IP addresses for your master nameserver associated with this secondary entry. e.g. ["10.10.10.10", "10.10.10.11"] # * gtdLocation<~String> Global Traffic Director location. Values: DEFAULT, US_EAST, US_WEST, EUROPE # * status<~Integer> - 201 - secondary entry successfully created or modified, 400 - secondary entry name or IP addresses not valid, see errors in response content def update_secondary(secondary_name, ip_addresses) body = { "ip" => [*ip_addresses] } request( :expects => 201, :method => 'PUT', :path => "/V1.2/secondary/#{secondary_name}", :body => Fog::JSON.encode(body) ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/delete_record.rb0000644000004100000410000000134113171001215023771 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Deletes the record with the specified id. Note that records are not modifiable for domains that are locked to a template. # # ==== Parameters # * domain<~String> - domain name # * record_id<~String> - record id # # ==== Returns # * response<~Excon::Response>: # * status<~Integer> 200 - OK, 404 - specified domain name or record id is not found def delete_record(domain, record_id) request( :expects => 200, :method => 'DELETE', :path => "/V1.2/domains/#{domain}/records/#{record_id}" ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/update_record.rb0000644000004100000410000000542613171001215024021 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Updates a record with the representation specified in the request content. Returns errors if record is not valid. # Note that a record ID will be generated by the system with this request and any ID that is sent will be ignored. Records are not modifiable for domains that are locked to a template. # # DNS Made Easy has no update record method but they plan to add it in the next update! # They sent a reponse suggesting, there going to internaly delete/create a new record when we make update record call, so I've done the same here for now! # If want to update a record, it might be better to manually destroy and then create a new record # # ==== Parameters # * domain<~String> Domain name. # * record_id<~Integer> Record id. # * options<~Hash> # * name<~String> Record name. # * type<~String> Record type. Values: A, AAAA, CNAME, HTTPRED, MX, NS, PTR, SRV, TXT # * ttl<~Integer> Time to live. The amount of time a record will be cached before being refreshed. Default: 1800 (30 mins) # * gtdLocation<~String> Global Traffic Director location. Values: DEFAULT, US_EAST, US_WEST, EUROPE # * password<~String> For A records. Password used to authenticate for dynamic DNS. # * description<~String> For HTTPRED records. A description of the HTTPRED record. # * keywords<~String> For HTTPRED records. Keywords associated with the HTTPRED record. # * title<~String> For HTTPRED records. The title of the HTTPRED record. # * redirectType<~String> For HTTPRED records. Type of redirection performed. Values: Hidden Frame Masked, Standard - 302, Standard - 301 # * hardLink<~Boolean> For HTTPRED records. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * id<~Integer> Unique record identifier # * name<~String> # * type<~String> # * data<~String> # * ttl<~Integer> # * gtdLocation<~String> # * password<~String> # * description<~String> # * keywords<~String> # * title<~String> # * redirectType<~String> # * hardLink<~Boolean> # * 'status'<~Integer> - 201 - record successfully created, 400 - record not valid, see errors in response content, 404 - domain not found def update_record(domain, record_id, options = {}) request( :expects => 200, :method => "PUT", :path => "/V1.2/domains/#{domain}/records/#{record_id}", :body => Fog::JSON.encode(options) ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/get_record.rb0000644000004100000410000000330313171001215023306 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Returns a record object representing the record with the specified id. # # ==== Parameters # * domain<~String> # * record_id<~Integer> # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * id<~Integer> Unique record identifier # * name<~String> Record name. # * type<~String> Record type. Values: A, AAAA, CNAME, HTTPRED, MX, NS, PTR, SRV, TXT # * data<~String> Record data # * ttl<~Integer> Time to live. The amount of time a record will be cached before being refreshed. Default: 1800 # * gtdLocation<~String> Global Traffic Director location. Values: DEFAULT, US_EAST, US_WEST, EUROPE # * password<~String> For A records. Password used to authenticate for dynamic DNS. # * description<~String> For HTTPRED records. A description of the HTTPRED record. # * keywords<~String> For HTTPRED records. Keywords associated with the HTTPRED record. # * title<~String> For HTTPRED records. The title of the HTTPRED record. # * redirectType<~String> For HTTPRED records. Type of redirection performed. Values: Hidden Frame Masked, Standard - 302, Standard - 301 # * hardLink<~Boolean> For HTTPRED records. # * status<~Integer> - 200 - OK, 404 - specified domain name or record id is not found def get_record(domain, record_id) request( :expects => 200, :method => "GET", :path => "/V1.2/domains/#{domain}/records/#{record_id}" ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/list_secondary.rb0000644000004100000410000000104513171001215024214 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Returns a list of all secondary entry names for your account. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * list<~Array> e.g. ["xxx.domain.com", "xxx.domain.com"] # * status<~Integer> 200 - OK def list_secondary request( :expects => 200, :method => 'GET', :path => '/V1.2/secondary' ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/list_domains.rb0000644000004100000410000000104213171001215023654 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Returns a list of all domain names for your account. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * list<~Array> e.g. ["domain1.com","domain2.com", "domain3.com"] # * status<~Integer> - 200 - OK def list_domains request( :expects => 200, :method => 'GET', :path => '/V1.2/domains' ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/delete_domain.rb0000644000004100000410000000107213171001215023763 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Delete the given domain from your account. # # ==== Parameters # * domain<~String> - domain name # # ==== Returns # * response<~Excon::Response>: # * status<~Integer> 200 - OK, 404 - specified domain name is not found def delete_domain(domain) request( :expects => 200, :method => 'DELETE', :path => "/V1.2/domains/#{domain}" ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/requests/dns/delete_all_domains.rb0000644000004100000410000000071513171001215025001 0ustar www-datawww-datamodule Fog module DNS class DNSMadeEasy class Real # Deletes all domains for your account. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * status<~Integer> - 200 - OK def delete_all_domains request( :expects => 200, :method => 'DELETE', :path => '/V1.2/domains' ) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/dns.rb0000644000004100000410000000747413171001215017333 0ustar www-datawww-datarequire 'fog/dnsmadeeasy/core' module Fog module DNS class DNSMadeEasy < Fog::Service requires :dnsmadeeasy_api_key, :dnsmadeeasy_secret_key recognizes :host, :path, :port, :scheme, :persistent model_path 'fog/dnsmadeeasy/models/dns' model :record collection :records model :zone collection :zones request_path 'fog/dnsmadeeasy/requests/dns' request :list_domains request :get_domain request :create_domain request :delete_domain request :delete_all_domains request :list_records request :create_record request :update_record request :get_record request :delete_record request :list_secondary request :delete_all_secondary request :get_secondary request :create_secondary request :update_secondary request :delete_secondary class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = {} end end def self.reset @data = nil end def initialize(options={}) @dnsmadeeasy_api_key = options[:dnsmadeeasy_api_key] @dnsmadeeasy_secret_key = options[:dnsmadeeasy_secret_key] end def data self.class.data[@dnsmadeeasy_api_key] end def reset_data self.class.data.delete(@dnsmadeeasy_api_key) end end class Real # Initialize connection to DNS Made Easy # # ==== Notes # options parameter must include values for :dnsmadeeasy_api_key and # :dnsmadeeasy_secret_key in order to create a connection # # ==== Examples # dns = Fog::DNS::DNSMadeEasy.new( # :dnsmadeeasy_api_key => your_dnsmadeeasy_api_key, # :dnsmadeeasy_secret_key => your_dnsmadeeasy_secret_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # # ==== Returns # * dns object with connection to aws. def initialize(options={}) @dnsmadeeasy_api_key = options[:dnsmadeeasy_api_key] @dnsmadeeasy_secret_key = options[:dnsmadeeasy_secret_key] @connection_options = options[:connection_options] || {} @host = options[:host] || 'api.dnsmadeeasy.com' @persistent = options.fetch(:persistent, true) @port = options[:port] || 80 #443 Not yet @scheme = options[:scheme] || 'http' #'https Not yet @connection = Fog::XML::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def reload @connection.reset end private def request(params) params[:headers] ||= {} params[:headers]['x-dnsme-apiKey'] = @dnsmadeeasy_api_key params[:headers]['x-dnsme-requestDate'] = Fog::Time.now.to_date_header params[:headers]['x-dnsme-hmac'] = signature(params) params[:headers]['Accept'] = 'application/json' params[:headers]['Content-Type'] = 'application/json' begin response = @connection.request(params) rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::DNS::DNSMadeEasy::NotFound.slurp(error) else error end end unless response.body.empty? response.body = Fog::JSON.decode(response.body) end response end def signature(params) string_to_sign = params[:headers]['x-dnsme-requestDate'] OpenSSL::HMAC.hexdigest('sha1', @dnsmadeeasy_secret_key, string_to_sign) end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/core.rb0000644000004100000410000000020413171001215017457 0ustar www-datawww-datarequire 'fog/core' require 'fog/json' module Fog module DNSMadeEasy extend Fog::Provider service(:dns, 'DNS') end end fog-1.42.0/lib/fog/dnsmadeeasy/models/0000755000004100000410000000000013171001215017471 5ustar www-datawww-datafog-1.42.0/lib/fog/dnsmadeeasy/models/dns/0000755000004100000410000000000013171001215020255 5ustar www-datawww-datafog-1.42.0/lib/fog/dnsmadeeasy/models/dns/zones.rb0000644000004100000410000000107713171001215021745 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/dnsmadeeasy/models/dns/zone' module Fog module DNS class DNSMadeEasy class Zones < Fog::Collection model Fog::DNS::DNSMadeEasy::Zone def all clear data = service.list_domains.body['list'].map{|domain| {:id => domain}} load(data) end def get(zone_id) data = service.get_domain(zone_id).body data.merge!(:id => data['name']) new(data) rescue Fog::Service::NotFound nil end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/models/dns/record.rb0000644000004100000410000000365013171001215022064 0ustar www-datawww-datarequire 'fog/core/model' module Fog module DNS class DNSMadeEasy class Record < Fog::Model extend Fog::Deprecation deprecate :ip, :value deprecate :ip=, :value= identity :id attribute :name attribute :type attribute :ttl attribute :gtd_location, :aliases => "gtdLocation" attribute :password attribute :description attribute :keywords attribute :title attribute :redirect_type, :aliases => "redirectType" attribute :hard_link, :aliases => "hardLink" attribute :value, :aliases => "data" def initialize(attributes={}) super end def destroy service.delete_record(zone.id, identity) true end def zone @zone end def save self.ttl ||= 1800 requires :name, :type, :value, :ttl options = {} options[:ttl] = ttl if ttl options[:gtdLocation] = gtd_location if gtd_location if type.upcase == 'A' options[:password] = password if password end if type.upcase == 'HTTPRED' options[:description] = description if description options[:keywords] = keywords if keywords options[:title] = title if title options[:redirectType] = redirect_type if redirect_type options[:hardLink] = hard_link if hard_link end if id.nil? data = service.create_record(zone.domain, name, type, value, options).body merge_attributes(data) else options.merge!(:name => name, :type => type, :data => value) service.update_record(zone.domain, id, options).body end true end private def zone=(new_zone) @zone = new_zone end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/models/dns/zone.rb0000644000004100000410000000156413171001215021563 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/dnsmadeeasy/models/dns/records' module Fog module DNS class DNSMadeEasy class Zone < Fog::Model identity :id attribute :domain, :aliases => 'name' attribute :gtd_enabled, :aliases => 'gtdEnabled' attribute :nameservers, :aliases => 'nameServer' def destroy requires :identity service.delete_domain(identity) true end def records @records ||= begin Fog::DNS::DNSMadeEasy::Records.new( :zone => self, :service => service ) end end def save requires :domain data = service.create_domain(domain).body self.identity = data['name'] merge_attributes(data) true end end end end end fog-1.42.0/lib/fog/dnsmadeeasy/models/dns/records.rb0000644000004100000410000000126513171001215022247 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/dnsmadeeasy/models/dns/record' module Fog module DNS class DNSMadeEasy class Records < Fog::Collection attribute :zone model Fog::DNS::DNSMadeEasy::Record def all requires :zone data = service.list_records(zone.identity).body load(data) end def get(record_id) data = service.get_record(zone.identity, 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.42.0/lib/fog/dnsmadeeasy.rb0000644000004100000410000000003613171001215016532 0ustar www-datawww-datarequire 'fog/dnsmadeeasy/dns' fog-1.42.0/lib/fog/version.rb0000644000004100000410000000004413171001215015721 0ustar www-datawww-datamodule Fog VERSION = '1.42.0' end fog-1.42.0/lib/fog/glesys/0000755000004100000410000000000013171001215015217 5ustar www-datawww-datafog-1.42.0/lib/fog/glesys/requests/0000755000004100000410000000000013171001215017072 5ustar www-datawww-datafog-1.42.0/lib/fog/glesys/requests/compute/0000755000004100000410000000000013171001215020546 5ustar www-datawww-datafog-1.42.0/lib/fog/glesys/requests/compute/template_list.rb0000644000004100000410000000024713171001215023744 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def template_list request("/server/templates") end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/destroy.rb0000644000004100000410000000040413171001215022562 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def destroy(options) if options[:keepip].nil? options[:keepip] = 0 end request("/server/destroy", options) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/start.rb0000644000004100000410000000025113171001215022226 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def start(param) request("/server/start", param) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/stop.rb0000644000004100000410000000024713171001215022063 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def stop(param) request("/server/stop", param) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/server_status.rb0000644000004100000410000000031213171001215024000 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def server_status(serverid) request("/server/status", { :serverid => serverid } ) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/ip_details.rb0000644000004100000410000000025613171001215023213 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def ip_details(params) request("/ip/details", params) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/ssh_key_add.rb0000644000004100000410000000026013171001215023346 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def ssh_key_add(options) request("sshkey/add", options) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/ip_list_own.rb0000644000004100000410000000026613171001215023425 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def ip_list_own(options = {}) request("/ip/listown", options) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/ip_remove.rb0000644000004100000410000000025413171001215023061 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def ip_remove(params) request("/ip/remove", params) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/edit.rb0000644000004100000410000000025713171001215022024 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def edit(options = {}) request('server/edit/',options) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/list_servers.rb0000644000004100000410000000044013171001215023615 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def list_servers(serverid = nil, options = {}) unless serverid.nil? options[:serverid] = serverid end request("/server/list", options) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/ip_add.rb0000644000004100000410000000024613171001215022315 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def ip_add(params) request("/ip/add", params) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/reboot.rb0000644000004100000410000000025313171001215022365 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def reboot(param) request("/server/reboot", param) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/ssh_key_list.rb0000644000004100000410000000026713171001215023600 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def ssh_key_list(options = {}) request("sshkey/list", options) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/ip_list_free.rb0000644000004100000410000000027013171001215023536 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def ip_list_free(options = {}) request("/ip/listfree", options) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/create.rb0000644000004100000410000000026313171001215022337 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def create(options = {}) request('server/create/',options) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/server_details.rb0000644000004100000410000000035213171001215024106 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def server_details(serverid, options = {}) request("/server/details", { :serverid => serverid }.merge!(options) ) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/ssh_key_remove.rb0000644000004100000410000000026613171001215024121 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def ssh_key_remove(options) request("sshkey/remove", options) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/ip_release.rb0000644000004100000410000000025613171001215023206 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def ip_release(params) request("/ip/release", params) end end end end end fog-1.42.0/lib/fog/glesys/requests/compute/ip_take.rb0000644000004100000410000000025013171001215022504 0ustar www-datawww-datamodule Fog module Compute class Glesys class Real def ip_take(params) request("/ip/take", params) end end end end end fog-1.42.0/lib/fog/glesys/core.rb0000644000004100000410000000020713171001215016473 0ustar www-datawww-datarequire 'fog/core' require 'fog/json' module Fog module Glesys extend Fog::Provider service(:compute, 'Compute') end end fog-1.42.0/lib/fog/glesys/models/0000755000004100000410000000000013171001215016502 5ustar www-datawww-datafog-1.42.0/lib/fog/glesys/models/compute/0000755000004100000410000000000013171001215020156 5ustar www-datawww-datafog-1.42.0/lib/fog/glesys/models/compute/ips.rb0000644000004100000410000000550613171001215021304 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/glesys/models/compute/ip' module Fog module Compute class Glesys class Ips < Fog::Collection model Fog::Compute::Glesys::Ip attribute :serverid attribute :server def all attributes = {} attributes[:serverid] = serverid unless serverid.nil? ips = service.ip_list_own(attributes).body['response']['iplist'] load(ips) end def get(ip) data = service.ip_details( :ipaddress => ip).body['response']['details'] new data end def attached all.select { |ip| !ip.serverid.nil? } end def available all.select { |ip| ip.serverid.nil? } end def free(options = {}) default_options = { :version => 4 } if !server.nil? default_options[:datacenter] = server.datacenter default_options[:platform] = server.platform end options = default_options.merge!(options) %w{platform datacenter version}.each do |attr| raise Fog::Errors::Error.new("You need to specify ':#{attr}'") if !options.key?(attr.to_sym) end options[:ipversion] = options[:version] options.delete(:version) service.ip_list_free(options).body["response"]["iplist"]["ipaddresses"] end def take(ip, options = {}) default_options = { :attach => false } options = default_options.merge!(options) data = service.ip_take( :ipaddress => ip_from_object(ip) ).body["response"]["details"] ip = new data if options[:attach] && serverid server.ips.attach ip, serverid ip.serverid = serverid end ip end def release(ip) service.ip_release( :ipaddress => ip_from_object(ip) ) end def attach(ip, server_id=nil) if server_id.nil? server_id = serverid end if server_id.nil? raise Fog::Errors::Error.new("You need to specify a server id") end server_id = server_id.serverid if server_id.is_a?(Fog::Compute::Glesys::Server) service.ip_add( :ipaddress => ip_from_object(ip), :serverid => server_id ) if server.nil? true else server.reload end end def remove(ip, options = {}) new service.ip_remove({:ipaddress => ip_from_object(ip)}.merge!(options)).data.body["response"]["details"] end private def ip_from_object(ip) ip.is_a?(Fog::Compute::Glesys::Ip) ? ip.ip : ip end end end end end fog-1.42.0/lib/fog/glesys/models/compute/servers.rb0000644000004100000410000000205613171001215022177 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/glesys/models/compute/server' module Fog module Compute class Glesys class Servers < Fog::Collection model Fog::Compute::Glesys::Server def all data = service.list_servers.body['response']['servers'] load(data) end def get(identifier) return nil if identifier.nil? || identifier == "" begin details = service.server_details(identifier).body['response'] status = service.server_status(identifier).body['response'] if details.empty? || status.empty? nil else details['server']['usage'] = Hash.new %w|cpu memory disk transfer|.each do |attr| details['server']['usage'][attr] = status['server'].delete(attr) end details['server'].merge!(status['server']) new(details['server']) end rescue return nil end end end end end end fog-1.42.0/lib/fog/glesys/models/compute/ssh_key.rb0000644000004100000410000000113313171001215022146 0ustar www-datawww-datamodule Fog module Compute class Glesys class SshKey < Fog::Model identity :id attribute :description attribute :data def save requires :description, :data merge_attributes(service.ssh_key_add(:description => description, :sshkey => data ).body["response"]["sshkey"]) true end def destroy requires :id service.ssh_key_remove(:sshkeyids => id) true end end end end end fog-1.42.0/lib/fog/glesys/models/compute/ip.rb0000644000004100000410000000400513171001215021112 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Glesys class Ip < Fog::Model extend Fog::Deprecation identity :ip attribute :ip, :aliases => "ipaddress" attribute :datacenter attribute :version, :aliases => "ipversion" attribute :platform attribute :netmask attribute :broadcast attribute :gateway attribute :nameservers attribute :serverid attribute :reserved attribute :ptr attribute :cost def attached? !serverid.nil? end # Return an unused ip-address to the pool of free ips. def release requires :ip raise Fog::Errors::Error.new('You can\'t release a ip that is attached to a server') if attached? service.ip_release( :ipaddress => identity ) end # Add an ip-adress to the server. def attach(server) requires :ip server = server.serverid if server.is_a?(Fog::Compute::Glesys::Server) raise Fog::Errors::Error.new("Ip is already attached to a server, #{serverid}") unless serverid.nil? data = service.ip_add( :ipaddress => identity, :serverid => server ).body["response"]["details"] merge_attributes data end # Remove an ip from the server def remove(options = {}) requires :ip raise Fog::Errors::Error.new('Ip is not attached to a server.') if serverid.nil? data = service.ip_remove({:ipaddress => ip}.merge!(options)).body["response"]["details"] merge_attributes data end # Remove the ip from a server and release it def destroy requires :ip remove(:release => true) end def take requires :ip data = service.ip_take( :ipaddress => ip ).body["response"]["details"] merge_attributes data end end end end end fog-1.42.0/lib/fog/glesys/models/compute/ssh_keys.rb0000644000004100000410000000073413171001215022337 0ustar www-datawww-datarequire "fog/glesys/models/compute/ssh_key" module Fog module Compute class Glesys class SshKeys < Fog::Collection model Fog::Compute::Glesys::SshKey def all data = service.ssh_key_list.body["response"]["sshkeys"] load(data) end def get(id) hash = service.ssh_key_list.body["response"]["sshkeys"].find{|a| a["id"] == id} hash.nil? ? nil : new(hash) end end end end end fog-1.42.0/lib/fog/glesys/models/compute/templates.rb0000644000004100000410000000164313171001215022505 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/glesys/models/compute/template' module Fog module Compute class Glesys class Templates < Fog::Collection model Fog::Compute::Glesys::Template def all # Only select OpenVZ and Xen platforms # Glesys only offers Xen and OpenVZ but they have other platforms in the list images = platform :openvz, :xen load(images) end def openvz images = platform :openvz load(images) end def xen images = platform :xen load(images) end private def platform(*platforms) images = service.template_list.body['response']['templates'] images.select do |platform, images| platforms.include?(platform.downcase.to_sym) end.map{|platform, images| images}.flatten end end end end end fog-1.42.0/lib/fog/glesys/models/compute/server.rb0000644000004100000410000001041413171001215022011 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class Glesys class Server < Fog::Compute::Server extend Fog::Deprecation identity :serverid attribute :hostname attribute :datacenter attribute :cpucores attribute :memorysize attribute :disksize attribute :transfer attribute :bandwidth attribute :uptime attribute :templatename attribute :managedhosting attribute :platform attribute :cost attribute :rootpassword attribute :state attribute :iplist attribute :description attribute :usage attribute :glera_enabled, :aliases => "gleraenabled" attribute :supported_features, :aliases => "supportedfeatures" def ready? state == 'running' end def start requires :identity service.start(:serverid => identity) end def stop requires :identity service.stop(:serverid => identity) end def reboot requires :identity service.reboot(:serverid => identity) end def destroy(options = {}) requires :identity service.destroy(options.merge!({:serverid => identity})) end def save if self.identity options = { :serverid => self.identity, :disksize => disksize, :memorysize => memorysize, :cpucores => cpucores, :hostname => hostname, :bandwidth => bandwidth } data = service.edit(options) else requires :hostname, :rootpassword options = { :datacenter => datacenter || "Falkenberg", :platform => platform || "OpenVz", :hostname => hostname, :templatename => templatename || "Debian 7.0 64-bit", :disksize => disksize || "10", :memorysize => memorysize || "512", :cpucores => cpucores || "1", :rootpassword => rootpassword } # optional options when creating a server: [:description, :ip, :ipv6, :transfer, :bandwidth, :campaigncode, :sshkeyids, :sshkey].each do |k| options[k] = attributes[k] if attributes[k] end data = service.create(options) end merge_attributes(data.body['response']['server']) data.status == 200 ? true : false end def setup(credentials = {}) requires :ssh_ip_address, :username attrs = attributes.dup attrs.delete(:rootpassword) commands = [ %{mkdir -p .ssh}, %{echo "#{Fog::JSON.encode(Fog::JSON.sanitize(attrs))}" >> ~/attributes.json} ] if public_key commands << %{echo "#{public_key}" >> ~/.ssh/authorized_keys} end if credentials[:password].nil? && !rootpassword.nil? credentials[:password] = rootpassword end # wait for glesys to be ready wait_for { sshable?(credentials) } Fog::SSH.new(ssh_ip_address, username, credentials).run(commands) end def ssh(command, options={}, &block) if options[:password].nil? && !rootpassword.nil? options[:password] = rootpassword end super(command, options, &block) end def ips Fog::Compute::Glesys::Ips.new(:serverid => identity, :server => self, :service => service).all end def ip(ip) Fog::Compute::Glesys::Ips.new(:serverid => identity, :server => self, :service => service).get(ip) end def public_ip_address(options = {}) return nil if iplist.nil? type = options[:type] || nil ips = case type when :ipv4 then iplist.select { |ip| ip["version"] == 4 } when :ipv6 then iplist.select { |ip| ip["version"] == 6 } else iplist.sort_by { |ip| ip["version"] } end if ips.empty? nil else ips.first["ipaddress"] end end end end end end fog-1.42.0/lib/fog/glesys/models/compute/template.rb0000644000004100000410000000077713171001215022331 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Glesys class Template < Fog::Model identity :name attribute :platform attribute :operating_system, :aliases => "operatingsystem" attribute :minimum_memory_size, :aliases => "minimummemorysize" attribute :minimum_disk_size, :aliases => "minimumdisksize" attribute :instance_cost, :aliases => "instancecost" attribute :license_cost, :aliases => "licensecost" end end end end fog-1.42.0/lib/fog/glesys/compute.rb0000644000004100000410000000676213171001215017233 0ustar www-datawww-datarequire 'fog/glesys/core' module Fog module Compute class Glesys < Fog::Service requires :glesys_username, :glesys_api_key API_URL = "https://api.glesys.com" model_path 'fog/glesys/models/compute' collection :servers model :server collection :templates model :template collection :ips model :ip collection :ssh_keys model :ssh_key request_path 'fog/glesys/requests/compute' # Server request :create request :edit request :destroy request :list_servers request :server_details request :server_status request :start request :reboot request :stop # Templates request :template_list # IP request :ip_list_free request :ip_list_own request :ip_details request :ip_take request :ip_release request :ip_add request :ip_remove # SSH keys request :ssh_key_list request :ssh_key_add request :ssh_key_remove class Mock def initialize(options={}) @api_url = options[:glesys_api_url] || API_URL @glesys_username = options[:glesys_username] @glesys_api_key = options[:glesys_api_key] @connection_options = options[:connection_options] || {} end def self.data @data ||= { } end def self.reset @data = nil end def data self.class.data end def reset_data self.class.reset end end class Real def initialize(options) require 'base64' @api_url = options[:glesys_api_url] || API_URL @glesys_username = options[:glesys_username] @glesys_api_key = options[:glesys_api_key] @connection_options = options[:connection_options] || {} @persistent = options[:persistent] || false @connection = Fog::XML::Connection.new(@api_url, @persistent, @connection_options) end def request(method_name, options = {}) options.merge!( {:format => 'json'}) begin parser = options.delete(:parser) data = @connection.request( :expects => 200, :method => "POST", :body => urlencode(options), :parser => parser, :path => method_name, :headers => { 'Authorization' => "Basic #{encoded_api_auth}", 'Content-Type' => 'application/x-www-form-urlencoded' } ) data.body = Fog::JSON.decode(data.body) response_code = data.body['response']['status']['code'] unless response_code.to_i == 200 raise Fog::Compute::Glesys::Error, "#{data.body['response']['status']['text']}" end data rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Compute::Glesys::NotFound.slurp(error) else error end end end private def encoded_api_auth token = [@glesys_username, @glesys_api_key].join(':') Base64.encode64(token).delete("\r\n") end def urlencode(hash) hash.to_a.map! { |k, v| "#{k}=#{CGI.escape(v.to_s)}" }.join("&") end end end end end fog-1.42.0/lib/fog/bare_metal_cloud.rb0000644000004100000410000000004713171001215017520 0ustar www-datawww-datarequire 'fog/bare_metal_cloud/compute' fog-1.42.0/lib/fog/linode.rb0000644000004100000410000000006613171001215015512 0ustar www-datawww-datarequire 'fog/linode/compute' require 'fog/linode/dns' fog-1.42.0/lib/fog/openvz.rb0000644000004100000410000000003513171001215015555 0ustar www-datawww-datarequire 'fog/openvz/compute' fog-1.42.0/lib/fog/rage4/0000755000004100000410000000000013171001215014713 5ustar www-datawww-datafog-1.42.0/lib/fog/rage4/requests/0000755000004100000410000000000013171001215016566 5ustar www-datawww-datafog-1.42.0/lib/fog/rage4/requests/dns/0000755000004100000410000000000013171001215017352 5ustar www-datawww-datafog-1.42.0/lib/fog/rage4/requests/dns/list_records.rb0000644000004100000410000000134413171001215022375 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Get the list of records for the specific domain. # # ==== Parameters # * id<~Integer> # ==== Returns # * response<~Excon::Response>: # * records # * name<~String> # * ttl<~Integer> # * updated_at<~String> # * domain_id<~Integer> # * id<~Integer> # * content<~String> # * record_type<~String> # * priority<~Integer> def list_records(id) request( :expects => 200, :method => "GET", :path => "/rapi/getrecords/#{id}" ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/get_domain.rb0000644000004100000410000000125313171001215022006 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Get the details for a specific domain in your account. # ==== Parameters # * id<~Integer> - numeric ID # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'id'<~Integer> # * 'name'<~String> # * 'owner_email'<~String> # * 'type'<~Integer> # * 'subnet_mask'<~Integer> def get_domain(id) request( :expects => 200, :method => 'GET', :path => "/rapi/getdomain/#{id}" ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/create_reverse_domain_4.rb0000644000004100000410000000152613171001215024453 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Create a reverse domain for an ipv4 address . # ==== Parameters # * name<~String> - expects an ipv5 address # * subnet<~Integer> - subnet ie: 9 for /9, range is /8 to /30 # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'status'<~Boolean> # * 'id'<~Integer> # * 'error'<~String> def create_reverse_domain_4(name, subnet, options = {}) email = options[:email] || @rage4_email request( :expects => 200, :method => 'GET', :path => "/rapi/createreversedomain4/?name=#{name}&email=#{email}" + "&subnet=#{subnet}" ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/update_domain.rb0000644000004100000410000000245113171001215022512 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Update an existing domain # ==== Parameters # * id<~Integer> - domain integer value # * email <~String> - email of domain owner # * nsprefix<~String> - vanity ns prefix (nullable) # * nsname<~String> - vanity ns domain name (nullable) # * enablevanity<~String> - activate/deactivate # * failover<~Boolean> - failover enable # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'status'<~Boolean> # * 'id'<~Integer> # * 'error'<~String> def update_domain(id, options = {}) email = options[:email] || @rage4_email path = "/rapi/updatedomain/#{id}?email=#{email}" path << "&nsname=#{options[:nsname]}" if options[:nsname] path << "&nsprefix=#{options[:nsprefix]}" if options[:nsprefix] path << "&enablevanity=#{options[:enablevanity]}" if options[:enablevanity] path << "&failover=#{options[:failover]}" if options[:failover] request( :expects => 200, :method => 'GET', :path => path ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/create_record.rb0000644000004100000410000000437313171001215022507 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Create a record # ==== Parameters # * domain id <~Integer> The id of the domain you wish to create a record for # * name <~String> Name of record, include domain name # * content <~String> IP address or Domain name # * type <~Integer> The type of record to create see list_record_types # * priority <~Integer> - Record prioirity (nullable) # * failover <~Boolean> Enable/disable failover default false # * failovercontent <~String> Failover value, only valid for A/AAAA records # * ttl <~Integer> - Time to live # * geozone <~Long> Geo region id, see list_geo_regions # * geolock <~Boolean> Lock geo coordinates, default false # * geolat <~Double> Geo latitude, (nullable) # * geolong <~Double> Geo longitude, (nullable) # * udplimit <~Boolean> Limit number of records returned, (nullable, default false) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'status'<~Boolean> # * 'id'<~Integer> # * 'error'<~String> # https://secure.rage4.com/rapi/createrecord/ def create_record(domain_id, name, content, type, options = {}) path = "/rapi/createrecord/#{domain_id}" path << "?name=#{name}&content=#{content}&type=#{type}" path << "&priority=#{options[:priority]}" if options[:priority] failover = options[:failover] || 'false' path << "&failover=#{failover}" path << "&failovercontent=#{options[:failovercontent]}" if options[:failovercontent] ttl = options[:ttl] || 3600 path << "&ttl=#{ttl}" path << "&geozone=#{options[:geozone]}" if options[:geozone] path << "&geolock=#{options[:geolock]}" if options[:geolock] path << "&geolat=#{options[:geolat]}" if options[:geolat] path << "&geolong=#{options[:geolong]}" if options[:geolong] path << "&udplimit=#{options[:udplimit]}" if options[:udplimit] request( :expects => 200, :method => 'GET', :path => path ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/list_geo_regions.rb0000644000004100000410000000115113171001215023230 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # List all the geo regions available # ==== Parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * 'record types'<~Hash> # *'name' <~String> geo record name # *'value' <~Integer> Integer value of the type def list_geo_regions request( :expects => 200, :method => 'GET', :path => '/rapi/listgeoregions' ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/show_current_usage.rb0000644000004100000410000000100313171001215023577 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Shows current usage for a single domain # ==== Parameters # * id<~Integer> - domain name numeric ID # # ==== Returns # * response<~Excon::Response>: # * body<~Array> def show_current_usage(id) request( :expects => 200, :method => 'GET', :path => "/rapi/showcurrentusage/#{id}" ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/set_record_failover.rb0000644000004100000410000000122713171001215023721 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Set a failover to on or off # ==== Parameters # * id<~Integer> - numeric ID # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'status'<~Boolean> # * 'id'<~Integer> # * 'error'<~String> def set_record_failover(id, active, failover) request( :expects => 200, :method => 'GET', :path => "/rapi/setrecordfailover/#{id}&active=#{active}&failover=#{failover}" ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/create_domain.rb0000644000004100000410000000141413171001215022471 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Create a domain. # ==== Parameters # * name<~String> - domain name # * email<~String> - email of owner of domain, defaults to email of credentials # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'status'<~Boolean> # * 'id'<~Integer> # * 'error'<~String> # def create_domain(name, options = {}) email = options[:email] || @rage4_email request( :expects => 200, :method => 'GET', :path => "/rapi/createregulardomain/?name=#{name}&email=#{email}" ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/show_global_usage.rb0000644000004100000410000000071113171001215023362 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Shows global usage for all domains # ==== Parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Array> def show_global_usage request( :expects => 200, :method => 'GET', :path => "/rapi/showcurrentglobalusage/" ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/bulk_update_records.rb0000644000004100000410000000233513171001215023722 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Updates existing records in bulk # ==== Parameters # * zone_id <~Integer> Need to specify the zone id # * options <~Hash> Options should contain the body for the post # in the following format. # data = [{:id=>, :priority=>2}, {:id=>, :priority=>2}] # options => { :body => data.to_json } # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'status'<~Boolean> # * 'id'<~Integer> # * 'error'<~String> # https://secure.rage4.com//rapi/SetRecordState// def bulk_update_records(zone_id, options = {}) path = "/rapi/SetRecordState/#{zone_id}" body = options[:body] if options[:body].present? request( :expects => 200, :method => 'POST', :body => body, :path => path, :headers => { 'Content-Type' => "application/json; charset=UTF-8", }, ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/delete_record.rb0000644000004100000410000000111413171001215022474 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Delete a specific record # ==== Parameters # * id<~Integer> - numeric record ID # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'status'<~Boolean> # * 'id'<~Integer> # * 'error'<~String> def delete_record(id) request( :expects => 200, :method => 'GET', :path => "/rapi/deleterecord/#{id}" ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/update_record.rb0000644000004100000410000000437113171001215022524 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Updates an existing record # ==== Parameters # * record_id <~Integer> The id of the record you wish to update # * name <~String> Name of record, include domain name # * content <~String> IP address or Domain name # * type <~Integer> The type of record to create see list_record_types # * priority <~Integer> - Record prioirity (nullable) # * failover <~Boolean> Enable/disable failover default false # * failovercontent <~String> Failover value, only valid for A/AAAA records # * ttl <~Integer> - Time to live # * geozone <~Long> Geo region id, see list_geo_regions # * geolock <~Boolean> Lock geo coordinates, default false # * geolat <~Double> Geo latitude, (nullable) # * geolong <~Double> Geo longitude, (nullable) # * udplimit <~Boolean> Limit number of records returned, (nullable, default false) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'status'<~Boolean> # * 'id'<~Integer> # * 'error'<~String> # https://secure.rage4.com/rapi/createrecord/ def update_record(record_id, name, content, type, options = {}) path = "/rapi/updaterecord/#{record_id}" path << "?name=#{name}&content=#{content}&type=#{type}" path << "&priority=#{options[:priority]}" if options[:priority] failover = options[:failover] || 'false' path << "&failover=#{failover}" path << "&failovercontent=#{options[:failovercontent]}" if options[:failovercontent] ttl = options[:ttl] || 3600 path << "&ttl=#{ttl}" path << "&geozone=#{options[:geozone]}" if options[:geozone] path << "&geolock=#{options[:geolock]}" if options[:geolock] path << "&geolat=#{options[:geolat]}" if options[:geolat] path << "&geolong=#{options[:geolong]}" if options[:geolong] path << "&udplimit=#{options[:udplimit]}" if options[:udplimit] request( :expects => 200, :method => 'GET', :path => path ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/create_domain_vanity.rb0000644000004100000410000000170513171001215024066 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Create a domain with a vanity name server. # ==== Parameters # * name<~String> - domain name # * nsname<~String> - vanity ns domain name # * nsprefix<~String> - prefix for the domain name, defaults to 'ns' # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'status'<~Boolean> # * 'id'<~Integer> # * 'error'<~String> def create_domain_vanity(name, nsname, options = {}) email = options[:email] || @rage4_email nsprefix = options[:nsprefix] || 'ns' request( :expects => 200, :method => 'GET', :path => "/rapi/createregulardomainext/?name=#{name}&email=#{email}" + "&nsname=#{nsname}&nsprefix=#{nsprefix}" ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/list_domains.rb0000644000004100000410000000157113171001215022370 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Get the lsit of all domains for your account. # ==== Parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * 'domains'<~Hash> # * 'id'<~Integer> # * 'name'<~String> # * 'owner_email'<~String> # * 'type'<~Integer> # * 'subnet_mask'<~Integer> def list_domains request( :expects => 200, :method => 'GET', :path => '/rapi/getdomains' ) 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.42.0/lib/fog/rage4/requests/dns/list_record_types.rb0000644000004100000410000000115313171001215023434 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # List all the record types available # ==== Parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * 'record types'<~Hash> # *'name' <~String> record type name # *'value' <~Integer> Integer value of the type def list_record_types request( :expects => 200, :method => 'GET', :path => '/rapi/listrecordtypes' ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/delete_domain.rb0000644000004100000410000000110513171001215022465 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Delete a specific domain # ==== Parameters # * id<~Integer> - numeric ID # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'status'<~Boolean> # * 'id'<~Integer> # * 'error'<~String> def delete_domain(id) request( :expects => 200, :method => 'GET', :path => "/rapi/deletedomain/#{id}" ) end end end end end fog-1.42.0/lib/fog/rage4/requests/dns/get_domain_by_name.rb0000644000004100000410000000130713171001215023500 0ustar www-datawww-datamodule Fog module DNS class Rage4 class Real # Get the details for a specific domain in your account. # ==== Parameters # * name<~String> - name of domain # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'id'<~Integer> # * 'name'<~String> # * 'owner_email'<~String> # * 'type'<~Integer> # * 'subnet_mask'<~Integer> def get_domain_by_name(name) request( :expects => 200, :method => 'GET', :path => "/rapi/getdomainbyname/?name=#{name}") end end end end end fog-1.42.0/lib/fog/rage4/dns.rb0000644000004100000410000000431713171001215016031 0ustar www-datawww-datarequire 'fog/rage4/core' module Fog module DNS class Rage4 < Fog::Service requires :rage4_email, :rage4_api_key recognizes :rage4_url, :host, :path, :port, :scheme, :persistent model_path 'fog/rage4/models/dns' model :record collection :records model :zone collection :zones request_path 'fog/rage4/requests/dns' request :list_domains request :create_domain request :create_domain_vanity request :create_reverse_domain_4 request :get_domain request :get_domain_by_name request :update_domain request :delete_domain request :show_current_usage request :show_global_usage request :list_record_types request :list_geo_regions request :create_record request :update_record request :bulk_update_records request :list_records request :delete_record request :set_record_failover class Real def initialize(options={}) @rage4_email = options[:rage4_email] @rage4_password = options[:rage4_api_key] @connection_options = options[:connection_options] || {} if options[:rage4_url] uri = URI.parse(options[:rage4_url]) options[:host] = uri.host options[:port] = uri.port options[:scheme] = uri.scheme end @host = options[:host] || "secure.rage4.com" @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::XML::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def reload @connection.reset end def request(params) params[:headers] ||= {} key = "#{@rage4_email}:#{@rage4_password}" params[:headers].merge!({ "Authorization" => "Basic " + Base64.encode64(key).gsub("\n",'')}) response = @connection.request(params) unless response.body.empty? response.body = Fog::JSON.decode(response.body) end response end end end end end fog-1.42.0/lib/fog/rage4/core.rb0000644000004100000410000000017613171001215016174 0ustar www-datawww-datarequire 'fog/core' require 'fog/json' module Fog module Rage4 extend Fog::Provider service(:dns, 'DNS') end end fog-1.42.0/lib/fog/rage4/models/0000755000004100000410000000000013171001215016176 5ustar www-datawww-datafog-1.42.0/lib/fog/rage4/models/dns/0000755000004100000410000000000013171001215016762 5ustar www-datawww-datafog-1.42.0/lib/fog/rage4/models/dns/zones.rb0000644000004100000410000000111013171001215020436 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rage4/models/dns/zone' module Fog module DNS class Rage4 class Zones < Fog::Collection model Fog::DNS::Rage4::Zone def all clear data = service.list_domains.body load(data) end def get(zone_name) data = service.get_domain_by_name(zone_name).body if data["status"] && !data["status"] nil else new(data) end rescue Excon::Errors::NotFound nil end end end end end fog-1.42.0/lib/fog/rage4/models/dns/record.rb0000644000004100000410000000351413171001215020570 0ustar www-datawww-datarequire 'fog/core/model' module Fog module DNS class Rage4 class Record < Fog::Model identity :id attribute :name attribute :value, :aliases => "content" attribute :ttl attribute :zone_id, :aliases => "domain_id" attribute :type, :aliases => "record_type" attribute :priority, :aliases => "priority" attribute :domain_id attribute :geo_region_id attribute :failover_enabled attribute :failover_content attribute :geo_lat attribute :geo_long attribute :geo_lock attribute :is_active attribute :udp_limit def initialize(attributes={}) super end def domain name end def destroy service.delete_record(id) true end def zone @zone end def save requires :name, :type, :value options = {} options[:priority] = priority if priority options[:ttl] = ttl if ttl options[:geozone] = geo_region_id if geo_region_id options[:geolock] = geo_lock if geo_lock options[:geolat] = geo_lat if geo_lat options[:geolong] = geo_long if geo_long options[:udplimit] = udp_limit if udp_limit # decide whether its a new record or update of an existing if id.nil? data = service.create_record(zone.id, name, value, type, options) else data = service.update_record(id, name, value, type, options) end merge_attributes(options) merge_attributes(:name => name, :value => value, :type => type) true end private def zone=(new_zone) @zone = new_zone end end end end end fog-1.42.0/lib/fog/rage4/models/dns/zone.rb0000644000004100000410000000143313171001215020263 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rage4/models/dns/records' module Fog module DNS class Rage4 class Zone < Fog::Model identity :id attribute :domain, :aliases => 'name' def destroy service.delete_domain(id) true end def records @records ||= begin Fog::DNS::Rage4::Records.new( :zone => self, :service => service ) end end def nameservers [ "ns1.r4ns.com", "ns2.r4ns.com", ] end def save requires :domain data = service.create_domain(domain).body["id"] merge_attributes(data) true end end end end end fog-1.42.0/lib/fog/rage4/models/dns/records.rb0000644000004100000410000000145713171001215020757 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rage4/models/dns/record' module Fog module DNS class Rage4 class Records < Fog::Collection attribute :zone model Fog::DNS::Rage4::Record def all requires :zone clear data = service.list_records(zone.id).body load(data) end def get(record_id) requires :zone data = service.list_records(zone.id).select {|record| record['id'] == record_id } if !data.empty? new(data.first) 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.42.0/lib/fog/linode/0000755000004100000410000000000013171001215015163 5ustar www-datawww-datafog-1.42.0/lib/fog/linode/requests/0000755000004100000410000000000013171001215017036 5ustar www-datawww-datafog-1.42.0/lib/fog/linode/requests/dns/0000755000004100000410000000000013171001215017622 5ustar www-datawww-datafog-1.42.0/lib/fog/linode/requests/dns/domain_resource_update.rb0000644000004100000410000000350613171001215024673 0ustar www-datawww-datamodule Fog module DNS class Linode class Real # Updates a resource record in a domain # # ==== Parameters # * domain_id<~Integer>: limit the list to the domain ID specified # * resource_id<~Integer>: id of resouce to delete # * options<~Hash> # * type<~String>: One of: NS, MX, A, AAAA, CNAME, TXT, or SRV # * name<~String>: The hostname or FQDN. When Type=MX the subdomain to delegate to the # Target MX server # * target<~String> When Type=MX the hostname. When Type=CNAME the target of the alias. # When Type=TXT the value of the record. When Type=A or AAAA the token # of '[remote_addr]' will be substituted with the IP address of the request. # * priority<~Integer>: priority for MX and SRV records, 0-255 - default: 10 # * weight<~Integer>: default: 5 # * port<~Integer>: default: 80 # * protocol<~String>: The protocol to append to an SRV record. Ignored on other record # types. default: udp # * ttl_sec<~Integer>: note, Linode will round the input to set values (300, 3600, 7200, etc) # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * DATA<~Hash>: # * 'ResourceID'<~Integer>: ID of the resource record updated def domain_resource_update(domain_id, resource_id, options = {}) query= {} request( :expects => 200, :method => 'GET', :query => { :api_action => 'domain.resource.update', :domainID => domain_id, :resourceID => resource_id, }.merge!( options) ) end end end end end fog-1.42.0/lib/fog/linode/requests/dns/domain_list.rb0000644000004100000410000000215513171001215022454 0ustar www-datawww-datamodule Fog module DNS class Linode class Real # List of domains (you have access to) # # ==== Parameters # * domain_id<~Integer>: limit the list to the domain ID specified # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * DATA<~Array> # * 'DOMAINID'<~Interger> # * 'SOA_EMAIL'<~String> # * 'DESCRIPTION'<~String> # * 'TTL_SEC'<~String> # * 'EXPIRE_SEC'<~Integer> # * 'RETRY_SEC'<~Integer> # * 'DOMAIN'<~String> # * 'STATUS'<~Integer> # * 'MASTER_IPS'<~String> # * 'REFRESH_SEC'<~Integer> # * 'TYPE'<~String> def domain_list(domain_id = nil) options = {} if domain_id options.merge!(:domainId => domain_id) end request( :expects => 200, :method => 'GET', :query => { :api_action => 'domain.list' }.merge!(options) ) end end end end end fog-1.42.0/lib/fog/linode/requests/dns/domain_resource_delete.rb0000644000004100000410000000141613171001215024651 0ustar www-datawww-datamodule Fog module DNS class Linode class Real # Delete the given resource from a domain # # ==== Parameters # * domain_id<~Integer>: id of domain resource belongs to # * resource_id<~Integer>: id of resouce to delete # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * DATA<~Hash>: # * resource_id<~Integer>: resource id that was deleted def domain_resource_delete(domain_id, resource_id) request( :expects => 200, :method => 'GET', :query => { :api_action => 'domain.resource.delete', :domainId => domain_id, :resourceID => resource_id } ) end end end end end fog-1.42.0/lib/fog/linode/requests/dns/domain_delete.rb0000644000004100000410000000114713171001215022743 0ustar www-datawww-datamodule Fog module DNS class Linode class Real # Delete the given domain from the list Linode hosts # # ==== Parameters # * domain_id<~Integer>: id of domain to delete # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * DATA<~Hash>: # TODO: docs def domain_delete(domain_id) request( :expects => 200, :method => 'GET', :query => { :api_action => 'domain.delete', :domainId => domain_id } ) end end end end end fog-1.42.0/lib/fog/linode/requests/dns/domain_resource_create.rb0000644000004100000410000000336513171001215024657 0ustar www-datawww-datamodule Fog module DNS class Linode class Real # Creates a resource record in a domain # # ==== Parameters # * domain_id<~Integer>: limit the list to the domain ID specified # * type<~String>: One of: NS, MX, A, AAAA, CNAME, TXT, or SRV # * options<~Hash> # * name<~String>: The hostname or FQDN. When Type=MX the subdomain to delegate to the # Target MX server # * target<~String> When Type=MX the hostname. When Type=CNAME the target of the alias. # When Type=TXT the value of the record. When Type=A or AAAA the token # of '[remote_addr]' will be substituted with the IP address of the request. # * priority<~Integer>: priority for MX and SRV records, 0-255 - default: 10 # * weight<~Integer>: default: 5 # * port<~Integer>: default: 80 # * protocol<~String>: The protocol to append to an SRV record. Ignored on other record # types. default: udp # * ttl_sec<~Integer>: note, Linode will round the input to set values (300, 3600, 7200, etc) # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * DATA<~Hash>: # * 'ResourceID'<~Integer>: ID of the resource record created def domain_resource_create(domain_id, type, options = {}) query= {} request( :expects => 200, :method => 'GET', :query => { :api_action => 'domain.resource.create', :domainID => domain_id, :type => type }.merge!( options) ) end end end end end fog-1.42.0/lib/fog/linode/requests/dns/domain_update.rb0000644000004100000410000000242613171001215022764 0ustar www-datawww-datamodule Fog module DNS class Linode class Real # Update a domain record # # ==== Parameters # * domain_id<~Integer>: The ID to identify the zone # * options<~Hash> # * domain<~String>: The zone's name. # * type<~String>: master or slave # * description<~String> Currently undisplayed # * SOA_email<~String> Required when type=master # * refresh_sec<~Integer> numeric, default: '0' # * retry_sec<~Integer> numeric, default: '0' # * expire_sec<~Integer> numeric, default: '0' # * ttl_sec<~String> numeric, default: '0' # * status<~Integer> 0, 1, or 2 (disabled, active, edit mode), default: 1 # * master_ips<~String> When type=slave, the zone's master DNS servers list, semicolon separated # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * DATA<~Hash>: # * 'DomainID'<~Integer>: domain ID def domain_update(domain_id, options = {}) request( :expects => 200, :method => 'GET', :query => { :api_action => 'domain.update', :domainId => domain_id }.merge!(options) ) end end end end end fog-1.42.0/lib/fog/linode/requests/dns/domain_create.rb0000644000004100000410000000264313171001215022746 0ustar www-datawww-datamodule Fog module DNS class Linode class Real # Creates a domain record # # ==== Parameters # * domain<~String>: The zone's name. Note, if master zone, SOA_email is required and if slave # master_ips is/are required # * type<~String>: master or slave # * options<~Hash> # * description<~String> Currently undisplayed # * SOA_email<~String> Required when type=master # * refresh_sec<~Integer> numeric, default: '0' # * retry_sec<~Integer> numeric, default: '0' # * expire_sec<~Integer> numeric, default: '0' # * ttl_sec<~String> numeric, default: '0' # * status<~Integer> 0, 1, or 2 (disabled, active, edit mode), default: 1 # * master_ips<~String> When type=slave, the zone's master DNS servers list, semicolon separated # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * DATA<~Hash>: # * 'DomainID'<~Integer>: domain ID def domain_create(domain, type, options = {}) query= {} request( :expects => 200, :method => 'GET', :query => { :api_action => 'domain.create', :domain => domain, :type => type }.merge!( options) ) end end end end end fog-1.42.0/lib/fog/linode/requests/dns/domain_resource_list.rb0000644000004100000410000000331513171001215024362 0ustar www-datawww-datamodule Fog module DNS class Linode class Real # List of resource records for a domain # # ==== Parameters # * domain_id<~Integer>: limit the list to the domain ID specified # * resource_id<~Integer>: optional. use if want only a specific resource record # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * DATA<~Array> # * 'PROTOCOL'<~String>: for SRV records. default is UDP # * 'TTL_SEC'<~Interger>: # * 'PRIORITY'<~Interger>: for MX and SRV records # * 'TYPE'<~String>: One of: NS, MX, A, AAAA, CNAME, TXT, or SRV # * 'TARGET'<~String>: When Type=MX the hostname. When Type=CNAME the target of the alias. # When Type=TXT the value of the record. When Type=A or AAAA the token # of '[remote_addr]' will be substituted with the IP address of the request. # * 'WEIGHT'<~Interger>: # * 'RESOURCEID'<~Interger>: ID of the resource record # * 'PORT'<~Interger>: # * 'DOMAINID'<~Interger>: ID of the domain that this record belongs to # * 'NAME'<~Interger>: The hostname or FQDN. When Type=MX, the subdomain to delegate to def domain_resource_list(domain_id, resource_id = nil) query = { :api_action => 'domain.resource.list', :domainID => domain_id } if resource_id query[:resourceID] = resource_id end request( :expects => 200, :method => 'GET', :query => query ) end end end end end fog-1.42.0/lib/fog/linode/requests/compute/0000755000004100000410000000000013171001215020512 5ustar www-datawww-datafog-1.42.0/lib/fog/linode/requests/compute/linode_config_update.rb0000644000004100000410000000161113171001215025177 0ustar www-datawww-datamodule Fog module Compute class Linode class Real # api docs say LinodeID is optional, turns out its required def linode_config_update(linode_id, config_id, options={}) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.config.update', :configId => config_id, :linodeID => linode_id }.merge!(options) ) end end class Mock def linode_config_update(linode_id, config_id, options={}) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.config.update", "DATA" => { "ConfigID" => rand(10000..99999) } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/image_delete.rb0000644000004100000410000000252413171001215023446 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def image_delete(image_id) request( :expects => 200, :method => 'GET', :query => { :api_action => 'image.delete', :imageId => image_id } ) end end class Mock def image_delete(image_id, status='available') size = rand(1..999999) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "image.delete", "DATA" => { "LAST_USED_DT" => "2014-07-21 12:31:54.0", "DESCRIPTION" => "Fog Mock Linode Image #{image_id}", "LABEL" => "test_#{image_id}_image", "STATUS" => status, "SIZE" => size, "ISPUBLIC" => rand(0..1), "CREATE_DT" => "2014-06-23 13:45:12.0", "USED" => rand(1..size), "FS_TYPE" => "ext4", "USERID" => Fog::Mock.random_numbers(4), "IMAGEID" => image_id } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_disk_createfromstackscript.rb0000644000004100000410000000130013171001215027777 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_disk_createfromstackscript(linode_id, script_id, distro_id, name, size, password, options={}) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.disk.createfromstackscript', :linodeId => linode_id, :stackScriptID => script_id, :distributionId => distro_id, :label => name, :size => size, :rootPass => password, :stackScriptUDFResponses => Fog::JSON.encode(options) } ) end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_reboot.rb0000644000004100000410000000206713171001215023670 0ustar www-datawww-datamodule Fog module Compute class Linode class Real # Issues a shutdown, and then a boot job for a given linode # # ==== Parameters # * linode_id<~Integer>: id of linode to reboot # * options<~Hash>: # * configId<~Boolean>: id of config to boot server with # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def linode_reboot(linode_id, options={}) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.reboot', :linodeId => linode_id }.merge!(options) ) end end class Mock def linode_reboot(linode_id, options={}) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.reboot", "DATA" => { "JobID" => rand(1000..9999) } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_config_create.rb0000644000004100000410000000157013171001215025164 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_config_create(linode_id, kernel_id, name, disk_list) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.config.create', :linodeId => linode_id, :kernelId => kernel_id, :label => name, :diskList => disk_list } ) end end class Mock def linode_config_create(linode_id, kernel_id, name, disk_list) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.boot", "DATA" => { "ConfigID" => rand(10000..99999) } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/avail_kernels.rb0000644000004100000410000000350013171001215023654 0ustar www-datawww-datamodule Fog module Compute class Linode class Real # Get available kernels # # ==== Parameters # * options<~Hash> # * isXen<~Boolean> Show or hide Xen compatible kernels # * isKVM<~Boolean> Show or hide KVM compatible kernels # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def avail_kernels(options={}) # avail.kernels used to accept a kernelId parameter (now removed) raise Fog::Errors::Error.new('avail_kernels no longer accepts a kernelId parameter') unless !options || options.is_a?(Hash) request( :expects => 200, :method => 'GET', :query => { :api_action => 'avail.kernels' }.merge!(options || {}) ) end end class Mock def avail_kernels(options={}) # avail.kernels used to accept a kernelId parameter (now removed) raise Fog::Errors::Error.new('avail_kernels no longer accepts a kernelId parameter') unless !options || options.is_a?(Hash) response = Excon::Response.new response.status = 200 body = { "ERRORARRAY" => [], "ACTION" => "avail.kernels" } mock_kernels = [] 10.times do kernel_id = rand(1..200) mock_kernels << create_mock_kernel(kernel_id) end response.body = body.merge("DATA" => mock_kernels) response end private def create_mock_kernel(kernel_id) { "ISPVOPS" => 1, "ISXEN" => 1, "ISKVM" => 1, "KERNELID" => kernel_id, "LABEL" => "Latest 3.0 (3.0.18-linode43)" } end end end end end fog-1.42.0/lib/fog/linode/requests/compute/avail_nodebalancers.rb0000644000004100000410000000211013171001215025005 0ustar www-datawww-datamodule Fog module Compute class Linode class Real # Get NodeBalancer pricing information. # # ==== Parameters # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * 'MONTHLY'<~Float> - Monthly price # * 'HOURLY'<~Float>: - Hourly price # * 'CONNECTIONS'<~Integer>: - Maximum concurrent connections def avail_nodebalancers request( :expects => 200, :method => 'GET', :query => { :api_action => 'avail.nodebalancers' } ) end end class Mock def avail_nodebalancers response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "avail.nodebalancers", "DATA" => [{ "MONTHLY" => 20.0, "HOURLY" => 0.03, "CONNECTIONS" => 10000 }] } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_config_delete.rb0000644000004100000410000000143313171001215025161 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_config_delete(linode_id, config_id) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.config.delete', :linodeId => linode_id, :configId => config_id } ) end end class Mock def linode_config_delete(linode_id, config_id) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.config.delete", "DATA" => { "ConfigID" => rand(10000..99999) } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_ip_list.rb0000644000004100000410000000304313171001215024034 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_ip_list(linode_id, ip_id=nil) options = {} if ip_id options.merge!(:ipaddressId => ip_id) end request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.ip.list', :linodeId => linode_id }.merge!(options) ) end end class Mock def linode_ip_list(linode_id, ip_id=nil) response = Excon::Response.new response.status = 200 body = { "ERRORARRAY" => [], "ACTION" => "linode.ip.list" } if ip_id # one IP mock_ip = create_mock_ip(ip_id) response.body = body.merge("DATA" => [mock_ip]) else # all IPs mock_ips = [] ip_id = rand(10000..99999) mock_ips << create_mock_ip(linode_id, ip_id) ip_id = rand(10000..99999) mock_ips << create_mock_ip(linode_id, ip_id, false) response.body = body.merge("DATA" => mock_ips) end response end private def create_mock_ip(linode_id, ip_id, is_public=true) { "IPADDRESSID" => ip_id, "RDNS_NAME" => "li-test.members.linode.com", "LINODEID" => linode_id, "ISPUBLIC" => is_public ? 1 : 0, "IPADDRESS" => is_public ? "1.2.3.4" : "192.168.1.2" } end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_disk_delete.rb0000644000004100000410000000147113171001215024650 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_disk_delete(linode_id, disk_id) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.disk.delete', :linodeId => linode_id, :diskId => disk_id } ) end end class Mock def linode_disk_delete(linode_id, disk_id) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.disk.delete", "DATA" => { "JobID" => rand(1000..9999), "DiskID" => disk_id } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_disk_imagize.rb0000644000004100000410000000172213171001215025032 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_disk_imagize(linode_id, disk_id, description, label) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.disk.imagize', :linodeId => linode_id, :diskId => disk_id, :description => description, :label => label } ) end end class Mock def linode_disk_imagize(linode_id, disk_id, description, label) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.disk.imagize", "DATA" => { "JobID" => Fog::Mock.random_numbers(4), "ImageID" => Fog::Mock.random_numbers(4) } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/avail_stackscripts.rb0000644000004100000410000000342213171001215024731 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def avail_stackscripts(options={}) result = request( :expects => 200, :method => 'GET', :query => { :api_action => 'avail.stackscripts' }.merge!(options) ) result.body['DATA'].each { |r| r['DISTRIBUTIONIDLIST'] = r['DISTRIBUTIONIDLIST'].to_s } result end end class Mock def avail_stackscripts(options={}) response = Excon::Response.new response.status = 200 body = { "ERRORARRAY" => [], "ACTION" => "avail.stackscripts" } mock_stackscripts = [] 10.times do stackscript_id = rand(1..200) mock_stackscripts << create_mock_stackscript(stackscript_id) end response.body = body.merge("DATA" => mock_stackscripts) response end private def create_mock_stackscript(stackscript_id) { "CREATE_DT" => "2011-10-07 00:28:13.0", "DEPLOYMENTSACTIVE" => 0, "DEPLOYMENTSTOTAL" => 1, "DESCRIPTION" => "Prints 'foobar' to the screen. Magic!", "DISTRIBUTIONIDLIST" => "77,78,64,65,82,83,50,51,73,74,41,42", "ISPUBLIC" => 1, "LABEL" => "foobar", "LATESTREV" => 15149, "REV_DT" => "2011-10-07 00:33:58.0", "REV_NOTE" => "Updated update_rubygems_install function.", "SCRIPT" => "#!/bin/bash\n#\n#\n\necho \"foobar\"", "STACKSCRIPTID" => stackscript_id, "USERID" => 1 } end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_disk_duplicate.rb0000644000004100000410000000154513171001215025362 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_disk_duplicate(linode_id, disk_id) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.disk.duplicate', :linodeId => linode_id, :diskID => disk_id, } ) end end class Mock def linode_disk_duplicate(linode_id, disk_id) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.disk.duplicate", "DATA" => { "JobID" => Fog::Mock.random_numbers(4), "DiskID" => Fog::Mock.random_numbers(5) } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_disk_createfromdistribution.rb0000644000004100000410000000203613171001215030173 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_disk_createfromdistribution(linode_id, distro_id, name, size, password) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.disk.createfromdistribution', :linodeId => linode_id, :distributionId => distro_id, :label => name, :size => size, :rootPass => password } ) end end class Mock def linode_disk_createfromdistribution(linode_id, distro_id, name, size, password) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.disk.createFromDistribution", "DATA" => { "JobID" => rand(1000..9999), "DiskID" => rand(10000..99999) } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_list.rb0000644000004100000410000000474413171001215023355 0ustar www-datawww-datamodule Fog module Compute class Linode class Real # List all linodes user has access or delete to # # ==== Parameters # * linodeId<~Integer>: Limit the list to the specified LinodeID # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def linode_list(linode_id=nil) options = {} if linode_id options.merge!(:linodeId => linode_id) end request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.list' }.merge!(options) ) end end class Mock def linode_list(linode_id=nil) body = { "ERRORARRAY" => [], "ACTION" => "linode.list" } response = Excon::Response.new response.status = 200 if linode_id # one server mock_server = create_mock_server(linode_id) response.body = body.merge("DATA" => [mock_server]) else # all servers mock_servers = [] 5.times do linode_id = rand(100000..999999) mock_servers << create_mock_server(linode_id) end response.body = body.merge("DATA" => mock_servers) end response end private def create_mock_server(linode_id) { "ALERT_CPU_ENABLED" => 1, "ALERT_BWIN_ENABLED" => 1, "BACKUPSENABLED" => 0, "ALERT_CPU_THRESHOLD" => 90, "ALERT_BWQUOTA_ENABLED" => 1, "LABEL" => "test_#{linode_id}", "ALERT_DISKIO_THRESHOLD" => 1000, "BACKUPWEEKLYDAY" => 0, "BACKUPWINDOW" => 0, "WATCHDOG" => 1, "DATACENTERID" => 6, "STATUS" => 1, "ALERT_DISKIO_ENABLED" => 1, "TOTALHD" => 40960, "LPM_DISPLAYGROUP" => "", "TOTALXFER" => 400, "ALERT_BWQUOTA_THRESHOLD" => 80, "TOTALRAM" => 1024, "LINODEID" => linode_id, "ALERT_BWIN_THRESHOLD" => 5, "ALERT_BWOUT_THRESHOLD" => 5, "ALERT_BWOUT_ENABLED" => 1 } end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_disk_list.rb0000644000004100000410000000313313171001215024356 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_disk_list(linode_id, disk_id=nil) options = {} if disk_id options.merge!(:diskId => disk_id) end request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.disk.list', :linodeId => linode_id }.merge!(options) ) end end class Mock def linode_disk_list(linode_id, disk_id=nil) response = Excon::Response.new response.status = 200 body = { "ERRORARRAY" => [], "ACTION" => "linode.disk.list" } if disk_id mock_disk = create_mock_disk(linode_id, disk_id) response.body = body.merge("DATA" => [mock_disk]) else mock_disks = [] 2.times do disk_id = rand(10000..99999) mock_disks << create_mock_disk(linode_id, disk_id) end response.body = body.merge("DATA" => mock_disks) end response end private def create_mock_disk(linode_id, disk_id) { "CREATE_DT" => "2012-02-29 12:55:29.0", "DISKID" => disk_id, "ISREADONLY" => 0, "LABEL" => "test_#{linode_id}_main", "LINODEID" => linode_id, "SIZE" => 39936, "STATUS" => 1, "TYPE" => "ext3", "UPDATE_DT" => "2012-02-29 12:55:53.0" } end end end end end fog-1.42.0/lib/fog/linode/requests/compute/stackscript_list.rb0000644000004100000410000000145113171001215024425 0ustar www-datawww-datamodule Fog module Compute class Linode class Real # Get available stack scripts # # ==== Parameters # * scriptId<~Integer>: id to limit results to # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def stackscript_list(script_id=nil) options = {} if script_id options.merge!(:stackScriptID => script_id) end result = request( :expects => 200, :method => 'GET', :query => { :api_action => 'stackscript.list' }.merge!(options) ) result.body['DATA'].each { |r| r['DISTRIBUTIONIDLIST'] = r['DISTRIBUTIONIDLIST'].to_s } result end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_shutdown.rb0000644000004100000410000000123013171001215024240 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_shutdown(linode_id) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.shutdown', :linodeId => linode_id } ) end end class Mock def linode_shutdown(linode_id) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.shutdown", "DATA" => { "JobID" => rand(1000..9999) } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_create.rb0000644000004100000410000000241613171001215023637 0ustar www-datawww-datamodule Fog module Compute class Linode class Real # Creates a linode and assigns you full privileges # # ==== Parameters # * datacenter_id<~Integer>: id of datacenter to place new linode in # * plan_id<~Integer>: id of plan to boot new linode with # * payment_term<~Integer>: Subscription term in months, in [1, 12, 24] # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def linode_create(datacenter_id, plan_id, payment_term) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.create', :datacenterId => datacenter_id, :paymentTerm => payment_term, :planId => plan_id } ) end end class Mock def linode_create(datacenter_id, plan_id, payment_term) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.create", "DATA" => { "LinodeID" => rand(1000..9999) } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/avail_linodeplans.rb0000644000004100000410000000353513171001215024531 0ustar www-datawww-datamodule Fog module Compute class Linode class Real # Get available plans # # ==== Parameters # * linodeplanId<~Integer>: id to limit results to # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def avail_linodeplans(linodeplan_id = nil) options = {} if linodeplan_id options.merge!(:planId => linodeplan_id) end result = request( :expects => 200, :method => 'GET', :query => { :api_action => 'avail.linodeplans' }.merge!(options) ) result end end class Mock def avail_linodeplans(linodeplan_id = nil) response = Excon::Response.new response.status = 200 body = { "ERRORARRAY" => [], "ACTION" => "avail.linodeplans" } if linodeplan_id mock_plan = create_mock_linodeplan(linodeplan_id) response.body = body.merge("DATA" => [mock_plan]) else mock_plans = [] 10.times do plan_id = rand(1..99) mock_plans << create_mock_linodeplan(plan_id) end response.body = body.merge("DATA" => mock_plans) end response end private def create_mock_linodeplan(linodeplan_id) { "PRICE" => 19.95, "RAM" => 512, "XFER" => 200, "PLANID" => linodeplan_id, "LABEL" => "Linode #{linodeplan_id}", "DISK" => 20, "CORES" => 1, "AVAIL" => { "2" => 500, "3" => 500, "4" => 500, "6" => 500, "7" => 500, "8" => 500, "9" => 500, "10" => 500 }, "HOURLY" => 0.03 } end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_config_list.rb0000644000004100000410000000430113171001215024667 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_config_list(linode_id, config_id=nil, options={}) if config_id options.merge!(:configid => config_id) end request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.config.list', :linodeId => linode_id }.merge!(options) ) end end class Mock def linode_config_list(linode_id, config_id=nil, options={}) response = Excon::Response.new response.status = 200 body = { "ERRORARRAY" => [], "ACTION" => "linode.config.list" } if config_id mock_config = create_mock_config(linode_id, config_id) response.body = body.merge("DATA" => [mock_config]) else mock_configs = [] 5.times do linode_id = rand(10000..99999) config_id = rand(10000..99999) mock_configs << create_mock_config(linode_id, config_id) end response.body = body.merge("DATA" => mock_configs) end response end private def create_mock_config(linode_id, config_id) { "Comments" => "", "ConfigID" => config_id, "DiskList" => "839421,839420,,,,,,,", "KernelID" => 137, "Label" => "test_#{linode_id}", "LinodeID" => linode_id, "RAMLimit" => 0, "RootDeviceCustom" => "", "RootDeviceNum" => 1, "RootDeviceRO" => true, "RunLevel" => "default", "__validationErrorArray" => [], "apiColumnFilterStruct" => "", "devtmpfs_automount" => true, "helper_depmod" => 1, "helper_disableUpdateDB" => 1, "helper_libtls" => 0, "helper_xen" => 1, "isRescue" => 0 } end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_ip_addprivate.rb0000644000004100000410000000051213171001215025202 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_ip_addprivate(linode_id) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.ip.addprivate', :linodeId => linode_id } ) end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_disk_update.rb0000644000004100000410000000160013171001215024662 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_disk_update(linode_id, disk_id, label, isreadonly) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.disk.update', :linodeId => linode_id, :diskId => disk_id, :label => label, :isReadOnly => isreadonly } ) end end class Mock def linode_disk_update(linode_id, disk_id, label, isreadonly) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.disk.update", "DATA" => { "DiskID" => Fog::Mock.random_numbers(5) } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_disk_resize.rb0000644000004100000410000000160413171001215024705 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_disk_resize(linode_id, disk_id, size) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.disk.resize', :linodeId => linode_id, :diskId => disk_id, :size => size } ) end end class Mock def linode_disk_resize(linode_id, disk_id, size) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.disk.resize", "DATA" => { "JobID" => Fog::Mock.random_numbers(4), "DiskID" => Fog::Mock.random_numbers(4) } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/avail_distributions.rb0000644000004100000410000000353213171001215025120 0ustar www-datawww-datamodule Fog module Compute class Linode class Real # Get available distributions # # ==== Parameters # * distributionId<~Integer>: id to limit results to # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def avail_distributions(distribution_id=nil) options = {} if distribution_id options.merge!(:distributionId => distribution_id) end request( :expects => 200, :method => 'GET', :query => { :api_action => 'avail.distributions' }.merge!(options) ) end end class Mock def avail_distributions(distribution_id=nil) response = Excon::Response.new response.status = 200 body = { "ERRORARRAY" => [], "ACTION" => "avail.distributions" } if distribution_id mock_distribution = create_mock_distribution(distribution_id) response.body = body.merge("DATA" => [mock_distribution]) else mock_distributions = [] 10.times do distribution_id = rand(1..99) mock_distributions << create_mock_distribution(distribution_id) end response.body = body.merge("DATA" => mock_distributions) end response end private def create_mock_distribution(distribution_id) { "CREATE_DT" => "2012-04-26 17:25:16.0", "DISTRIBUTIONID" => distribution_id, "IS64BIT" => 0, "LABEL" => "Ubuntu 12.04 LTS", "MINIMAGESIZE" => 600, "REQUIRESPVOPSKERNEL" => 1 } end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_delete.rb0000644000004100000410000000205713171001215023637 0ustar www-datawww-datamodule Fog module Compute class Linode class Real # List all linodes user has access or delete to # # ==== Parameters # * linode_id<~Integer>: id of linode to delete # * options<~Hash>: # * skipChecks<~Boolean>: skips safety checks and always deletes # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def linode_delete(linode_id, options={}) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.delete', :linodeId => linode_id }.merge!(options) ) end end class Mock def linode_delete(linode_id, options={}) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.delete", "DATA" => { "LinodeID" => linode_id } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_update.rb0000644000004100000410000000130113171001215023646 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_update(linode_id, options={}) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.update', :linodeId => linode_id }.merge!(options) ) end end class Mock def linode_update(linode_id, options={}) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.update", "DATA" => { "LinodeID" => rand(1000..9999) } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_disk_create.rb0000644000004100000410000000161413171001215024650 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_disk_create(linode_id, name, type, size) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.disk.create', :linodeId => linode_id, :label => name, :type => type, :size => size } ) end end class Mock def linode_disk_create(linode_id, name, type, size) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.disk.create", "DATA" => { "JobID" => rand(1000..9999), "DiskID" => rand(10000..99999) } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_boot.rb0000644000004100000410000000126613171001215023341 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_boot(linode_id, config_id) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.boot', :linodeId => linode_id, :configId => config_id } ) end end class Mock def linode_boot(linode_id, config_id) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.boot", "DATA" => { "JobID" => rand(1000..9999) } } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/avail_datacenters.rb0000644000004100000410000000301413171001215024506 0ustar www-datawww-datamodule Fog module Compute class Linode class Real # Get available data centers # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO: docs def avail_datacenters request( :expects => 200, :method => 'GET', :query => { :api_action => 'avail.datacenters' } ) end end class Mock def avail_datacenters response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "DATA" => [ { "LOCATION" => "Dallas, TX, USA", "DATACENTERID" => 2, "ABBR" => "dallas" }, { "LOCATION" => "Fremont, CA, USA", "DATACENTERID" => 3, "ABBR" => "fremont" }, { "LOCATION" => "Atlanta, GA, USA", "DATACENTERID" => 4, "ABBR" => "atlanta" }, { "LOCATION" => "Newark, NJ, USA", "DATACENTERID" => 6, "ABBR" => "newark" }, { "LOCATION" => "London, England, UK", "DATACENTERID" => 7, "ABBR" => "london" }, { "LOCATION" => "Tokyo, JP", "DATACENTERID" => 8, "ABBR" => "tokyo" }, { "LOCATION" => "Singapore, SGP", "DATACENTERID" => 9, "ABBR" => "singapore" }, { "LOCATION" => "Frankfurt, DE", "DATACENTERID" => 10, "ABBR" => "frankfurt" }, ], "ACTION" => "avail.datacenters" } response end end end end end fog-1.42.0/lib/fog/linode/requests/compute/image_list.rb0000644000004100000410000000352013171001215023154 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def image_list(pending=nil, image_id=nil) options = {} if pending options.merge!(:pending => pending) end if image_id options.merge!(:imageId => image_id) end request( :expects => 200, :method => 'GET', :query => { :api_action => 'image.list' }.merge!(options) ) end end class Mock def image_list(pending=nil, image_id=nil) response = Excon::Response.new response.status = 200 body = { "ERRORARRAY" => [], "ACTION" => "image.list" } if image_id mock_image = create_mock_image(image_id) response.body = body.merge("DATA" => [mock_image]) else mock_images = [] rand(1..3).times do image_id = Fog::Mock.random_numbers(5) mock_images << create_mock_image(image_id) end response.body = body.merge("DATA" => mock_images) end response end private def create_mock_image(image_id, status='available') size = rand(1...999999) { "LAST_USED_DT" => "2014-07-29 12:55:29.0", "DESCRIPTION" => "Fog Mock Linode Image #{image_id}", "LABEL" => "test_#{image_id}_image", "STATUS" => status, "TYPE" => "manual", "ISPUBLIC" => rand(0...1), "CREATE_DT" => "2014-06-29 5:39:19.0", "MINSIZE" => Fog::Mock.random_numbers(5), "FS_TYPE" => "ext4", "CREATOR" => "test_username", "IMAGEID" => image_id } end end end end end fog-1.42.0/lib/fog/linode/requests/compute/linode_disk_createfromimage.rb0000644000004100000410000000210413171001215026532 0ustar www-datawww-datamodule Fog module Compute class Linode class Real def linode_disk_createfromimage(linode_id, image_id, label, size, password, sshkey) request( :expects => 200, :method => 'GET', :query => { :api_action => 'linode.disk.createfromimage', :linodeId => linode_id, :imageId => image_id, :label => label, :size => size, :rootPass => password, :rootSSHKey => sshkey } ) end end class Mock def linode_disk_createfromimage(linode_id, image_id, label, size, password, sshkey) response = Excon::Response.new response.status = 200 response.body = { "ERRORARRAY" => [], "ACTION" => "linode.disk.createfromimage", "DATA" => { "JobID" => Fog::Mock.random_numbers(4), "DiskID" => Fog::Mock.random_numbers(5) } } response end end end end end fog-1.42.0/lib/fog/linode/dns.rb0000644000004100000410000000444513171001215016303 0ustar www-datawww-datarequire 'fog/linode/core' module Fog module DNS class Linode < Fog::Service requires :linode_api_key recognizes :port, :scheme, :persistent model_path 'fog/linode/models/dns' model :record collection :records model :zone collection :zones request_path 'fog/linode/requests/dns' request :domain_create request :domain_delete request :domain_list request :domain_update request :domain_resource_create request :domain_resource_delete request :domain_resource_list request :domain_resource_update class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = {} end end def self.reset @data = nil end def initialize(options={}) @linode_api_key = options[:linode_api_key] end def data self.class.data[@linode_api_key] end def reset_data self.class.data.delete(@linode_api_key) end end class Real def initialize(options={}) @connection_options = options[:connection_options] || {} @host = options[:host] || "api.linode.com" @linode_api_key = options[:linode_api_key] @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::XML::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def reload @connection.reset end def request(params) params[:query] ||= {} params[:query].merge!(:api_key => @linode_api_key) response = @connection.request(params) unless response.body.empty? response.body = Fog::JSON.decode(response.body) if data = response.body['ERRORARRAY'].first error = case data['ERRORCODE'] when 5 Fog::DNS::Linode::NotFound else Fog::DNS::Linode::Error end raise error.new(data['ERRORMESSAGE']) end end response end end end end end fog-1.42.0/lib/fog/linode/core.rb0000644000004100000410000000024313171001215016437 0ustar www-datawww-datarequire 'fog/core' require 'fog/json' module Fog module Linode extend Fog::Provider service(:compute, 'Compute') service(:dns, 'DNS') end end fog-1.42.0/lib/fog/linode/models/0000755000004100000410000000000013171001215016446 5ustar www-datawww-datafog-1.42.0/lib/fog/linode/models/dns/0000755000004100000410000000000013171001215017232 5ustar www-datawww-datafog-1.42.0/lib/fog/linode/models/dns/zones.rb0000644000004100000410000000074313171001215020721 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/linode/models/dns/zone' module Fog module DNS class Linode class Zones < Fog::Collection model Fog::DNS::Linode::Zone def all data = service.domain_list.body['DATA'] load(data) end def get(zone_id) if data = service.domain_list(zone_id).body['DATA'].first new(data) else nil end end end end end end fog-1.42.0/lib/fog/linode/models/dns/record.rb0000644000004100000410000000353013171001215021036 0ustar www-datawww-datarequire 'fog/core/model' module Fog module DNS class Linode class Record < Fog::Model extend Fog::Deprecation deprecate :ip, :value deprecate :ip=, :value= identity :id, :aliases => ['ResourceID', 'RESOURCEID'] attribute :value, :aliases => 'TARGET' attribute :name, :aliases => 'NAME' attribute :priority, :aliases => 'PRIORITY' attribute :ttl, :aliases => 'TTL_SEC' attribute :type, :aliases => 'TYPE' attribute :zone_id, :aliases => 'DOMAINID' # "PROTOCOL":"", # "WEIGHT":0, # "PORT":0, def initialize(attributes={}) super end def destroy requires :identity, :zone service.domain_resource_delete(zone.id, identity) true end def zone @zone end def save requires :type, :zone options = {} # * options<~Hash> # * weight<~Integer>: default: 5 # * port<~Integer>: default: 80 # * protocol<~String>: The protocol to append to an SRV record. Ignored on other record # types. default: udp options[:name] = name if name options[:priority] = priority if priority options[:target] = value if value options[:ttl_sec] = ttl if ttl response = unless identity service.domain_resource_create(zone.identity, type, options) else options[:type] = type if type service.domain_resource_update(zone.identity, identity, options) end merge_attributes(response.body['DATA']) true end private def zone=(new_zone) @zone = new_zone end end end end end fog-1.42.0/lib/fog/linode/models/dns/zone.rb0000644000004100000410000000442313171001215020535 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/linode/models/dns/records' module Fog module DNS class Linode class Zone < Fog::Model identity :id, :aliases => ['DomainID', 'DOMAINID', 'ResourceID'] attribute :description, :aliases => 'DESCRIPTION' attribute :domain, :aliases => 'DOMAIN' attribute :email, :aliases => 'SOA_EMAIL' attribute :ttl, :aliases => 'TTL_SEC' attribute :type, :aliases => 'TYPE' # "STATUS":1, # "RETRY_SEC":0, # "MASTER_IPS":"", # "EXPIRE_SEC":0, # "REFRESH_SEC":0, # "TTL_SEC":0 def initialize(attributes={}) self.type ||= 'master' super end def destroy requires :identity service.domain_delete(identity) true end def records @records ||= begin Fog::DNS::Linode::Records.new( :zone => self, :service => service ) end end def nameservers [ 'ns1.linode.com', 'ns2.linode.com', 'ns3.linode.com', 'ns4.linode.com', 'ns5.linode.com' ] end def save requires :domain, :type requires :email if type == 'master' options = {} # * options<~Hash> # * refresh_sec<~Integer> numeric, default: '0' # * retry_sec<~Integer> numeric, default: '0' # * expire_sec<~Integer> numeric, default: '0' # * status<~Integer> 0, 1, or 2 (disabled, active, edit mode), default: 1 # * master_ips<~String> When type=slave, the zone's master DNS servers list, semicolon separated options[:description] = description if description options[:soa_email] = email if email options[:ttl_sec] = ttl if ttl response = unless identity service.domain_create(domain, type, options) else options[:domain] = domain if domain options[:type] = type if type service.domain_update(identity, options) end merge_attributes(response.body['DATA']) true end end end end end fog-1.42.0/lib/fog/linode/models/dns/records.rb0000644000004100000410000000130013171001215021212 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/linode/models/dns/record' module Fog module DNS class Linode class Records < Fog::Collection attribute :zone model Fog::DNS::Linode::Record def all requires :zone data = service.domain_resource_list(zone.id).body['DATA'] load(data) end def get(record_id) if data = service.domain_resource_list(zone.id, record_id).body['DATA'].first new(data) else nil end end def new(attributes = {}) requires :zone super({ :zone => zone }.merge!(attributes)) end end end end end fog-1.42.0/lib/fog/linode/models/compute/0000755000004100000410000000000013171001215020122 5ustar www-datawww-datafog-1.42.0/lib/fog/linode/models/compute/images.rb0000644000004100000410000000171013171001215021713 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/linode/models/compute/image' module Fog module Compute class Linode class Images < Fog::Collection model Fog::Compute::Linode::Image def all load images end def get(id) new images(id).first rescue Fog::Compute::Linode::NotFound nil end private def images(id=nil) service.avail_distributions(id).body['DATA'].map { |image| map_image image } end def map_image(image) image = image.each_with_object({}) { |(k, v), h| h[k.downcase.to_sym] = v } image.merge!(:id => image[:distributionid], :name => image[:label], :image_size => image[:minimagesize], :requires_pvops_kernel => image[:requirespvopskernel], :bits => ((image[:is64bit] == 1) ? 64 : 32 ), :created_at => image[:create_dt]) end end end end end fog-1.42.0/lib/fog/linode/models/compute/ips.rb0000644000004100000410000000172313171001215021245 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/linode/models/compute/ip' module Fog module Compute class Linode class Ips < Fog::Collection model Fog::Compute::Linode::Ip attribute :server def all requires :server load ips(server.id) end def get(id) requires :server new ips(server.id, id).first rescue Fog::Compute::Linode::NotFound nil end def new(attributes = {}) requires :server super({ :server => server }.merge!(attributes)) end private def ips(linode_id, id=nil) service.linode_ip_list(linode_id, id).body['DATA'].map { |ip| map_ip ip } end def map_ip(ip) ip = ip.each_with_object({}) { |(k, v), h| h[k.downcase.to_sym] = v } ip.merge! :id => ip[:ipaddressid], :ip => ip[:ipaddress], :public => ip[:ispublic]==1 end end end end end fog-1.42.0/lib/fog/linode/models/compute/servers.rb0000644000004100000410000000135713171001215022146 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/linode/models/compute/server' module Fog module Compute class Linode class Servers < Fog::Collection model Fog::Compute::Linode::Server def all load servers end def get(id) new servers(id).first rescue Fog::Compute::Linode::NotFound nil end private def servers(id=nil) service.linode_list(id).body['DATA'].map { |server| map_server server } end def map_server(server) server = server.each_with_object({}) { |(k, v), h| h[k.downcase.to_sym] = v } server.merge! :id => server[:linodeid], :name => server[:label] end end end end end fog-1.42.0/lib/fog/linode/models/compute/stack_script.rb0000644000004100000410000000032413171001215023137 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Linode class StackScript < Fog::Model attr_accessor :options identity :id attribute :name end end end end fog-1.42.0/lib/fog/linode/models/compute/node_balancer_flavors.rb0000644000004100000410000000156513171001215024766 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/linode/models/compute/node_balancer_flavor' module Fog module Compute class Linode class NodeBalancerFlavors < Fog::Collection model Fog::Compute::Linode::NodeBalancerFlavor def all load node_balancer_flavors end private def node_balancer_flavors service.avail_nodebalancers.body['DATA'].map { |node_balancer_flavor| map_node_balancer_flavor node_balancer_flavor } end def map_node_balancer_flavor(node_balancer_flavor) node_balancer_flavor = node_balancer_flavor.each_with_object({}) { |(k, v), h| h[k.downcase.to_sym] = v } node_balancer_flavor.merge! :price_monthly => node_balancer_flavor[:monthly], :price_hourly => node_balancer_flavor[:hourly] end end end end end fog-1.42.0/lib/fog/linode/models/compute/ip.rb0000644000004100000410000000112213171001215021053 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Linode class Ip < Fog::Model identity :id attribute :ip attribute :public def save requires :server raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? service.linode_ip_addprivate server.id server.ips.all.find { |ip| !ip.public } end def server @server end private def server=(server) @server = server end end end end end fog-1.42.0/lib/fog/linode/models/compute/flavors.rb0000644000004100000410000000205513171001215022125 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/linode/models/compute/flavor' module Fog module Compute class Linode class Flavors < Fog::Collection model Fog::Compute::Linode::Flavor def all load flavors end def get(id) new flavors(id).first rescue Fog::Compute::Linode::NotFound nil end private def flavors(id=nil) service.avail_linodeplans(id).body['DATA'].map { |flavor| map_flavor flavor } end def map_flavor(flavor) flavor = flavor.each_with_object({}) { |(k, v), h| h[k.downcase.to_sym] = v } flavor.merge! :id => flavor[:planid], :name => flavor[:label], :transfer => flavor[:xfer], :price_hourly => flavor[:hourly], :available => map_available(flavor[:avail]) end def map_available(available) return nil unless available available.each_with_object({}) { |(k, v), h| h[k.to_i] = v } end end end end end fog-1.42.0/lib/fog/linode/models/compute/data_center.rb0000644000004100000410000000032013171001215022713 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Linode class DataCenter < Fog::Model identity :id attribute :location attribute :abbr end end end end fog-1.42.0/lib/fog/linode/models/compute/node_balancer_flavor.rb0000644000004100000410000000035713171001215024601 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Linode class NodeBalancerFlavor < Fog::Model attribute :price_monthly attribute :price_hourly attribute :connections end end end end fog-1.42.0/lib/fog/linode/models/compute/disks.rb0000644000004100000410000000176013171001215021570 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/linode/models/compute/disk' module Fog module Compute class Linode class Disks < Fog::Collection model Fog::Compute::Linode::Disk attribute :server def all requires :server load disks(server.id) end def get(id) requires :server new disks(server.id, id).first rescue Fog::Compute::Linode::NotFound nil end def new(attributes = {}) requires :server super({ :server => server }.merge!(attributes)) end private def disks(linode_id, id=nil) service.linode_disk_list(linode_id, id).body['DATA'].map { |disk| map_disk disk } end def map_disk(disk) disk = disk.each_with_object({}) { |(k, v), h| h[k.downcase.to_sym] = v } disk.merge! :id => disk[:diskid], :name => disk[:label], :server_id => disk[:linodeid] end end end end end fog-1.42.0/lib/fog/linode/models/compute/kernel.rb0000644000004100000410000000040013171001215021721 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Linode class Kernel < Fog::Model identity :id attribute :name attribute :is_xen attribute :is_kvm attribute :is_pvops end end end end fog-1.42.0/lib/fog/linode/models/compute/kernels.rb0000644000004100000410000000231413171001215022112 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/linode/models/compute/kernel' module Fog module Compute class Linode class Kernels < Fog::Collection model Fog::Compute::Linode::Kernel # Returns an Array of the available kernels. # # The list of kernels can be filtered by support for KVM or Xen by # specifying kvm: true or xen: true respectively as options. def all(options={}) [[:kvm, :isKVM], [:xen, :isXen]].each do |type, param| options[param] = options[type] ? 1 : 0 if options.has_key?(type) end load kernels(options) end def get(id) new kernels.select {|kernel| kernel[:id] == id }.first end private def kernels(options={}) service.avail_kernels(options).body['DATA'].map { |kernel| map_kernel kernel } end def map_kernel(kernel) kernel = kernel.each_with_object({}) { |(k, v), h| h[k.downcase.to_sym] = v } kernel.merge! :id => kernel[:kernelid], :name => kernel[:label], :is_xen => kernel[:isxen], :is_kvm => kernel[:iskvm], :is_pvops => kernel[:ispvops] end end end end end fog-1.42.0/lib/fog/linode/models/compute/stack_scripts.rb0000644000004100000410000000144213171001215023324 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/linode/models/compute/stack_script' module Fog module Compute class Linode class StackScripts < Fog::Collection model Fog::Compute::Linode::StackScript def all load stackscripts end def get(id) new stackscripts(id).first rescue Fog::Compute::Linode::NotFound nil end private def stackscripts(id=nil) service.stackscript_list(id).body['DATA'].map { |script| map_stackscript script } end def map_stackscript(script) script = script.each_with_object({}) { |(k, v), h| h[k.downcase.to_sym] = v } script.merge! :id => script[:stackscriptid], :name => script[:label] end end end end end fog-1.42.0/lib/fog/linode/models/compute/disk.rb0000644000004100000410000000342713171001215021407 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Linode class Disk < Fog::Model identity :id attribute :name attribute :type def save requires :server raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? @type, @image, @stack_script, @name, @password, @size = attributes.values_at :type, :image, :stack_script, :name, :password, :size create_disk end def destroy requires :identity, :server service.linode_disk_delete server.id, id end def server @server end private def server=(server) @server = server end def create_disk case when @image && @stack_script then create_disk_from_stack_script when @image then create_disk_from_image when @type then create_disk_type else raise 'disk cannot be created' end end def create_disk_type self.id = service.linode_disk_create(server.id, "#{@name}_#{@type}", @type, @size).body['DATA']['DiskID'] reload end def create_disk_from_image disk = service.linode_disk_createfromdistribution server.id, @image.id, "#{@name}_main", @size, @password self.id = disk.body['DATA']['DiskID'] reload end def create_disk_from_stack_script disk = service.linode_disk_createfromstackscript(server.id, @stack_script.id, @image.id, "#{@name}_main", @size, @password, @stack_script.options) self.id = disk.body['DATA']['DiskID'] reload end end end end end fog-1.42.0/lib/fog/linode/models/compute/flavor.rb0000644000004100000410000000072113171001215021740 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Linode class Flavor < Fog::Model identity :id attribute :disk attribute :name attribute :ram attribute :transfer attribute :price attribute :price_hourly attribute :cores attribute :available def bits 0 # these are determined by images you select not the hardware end end end end end fog-1.42.0/lib/fog/linode/models/compute/server.rb0000644000004100000410000000527413171001215021765 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class Linode class Server < Fog::Compute::Server attr_reader :stack_script identity :id attribute :name attribute :status def initialize(attributes={}) super self.username = 'root' end def ips Fog::Compute::Linode::Ips.new :server => self, :service => service end def public_ip_address ips.find{|ip| ip.ip !~ /^192\.168\./}.ip end def disks Fog::Compute::Linode::Disks.new :server => self, :service => service end def disks? not disks.empty? end def reboot service.linode_reboot id end def shutdown service.linode_shutdown id end def boot service.linode_boot id, config end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? @data_center, @flavor, @image, @kernel, @type, @payment_terms, @stack_script, @name, @password, @callback = attributes.values_at :data_center, :flavor, :image, :kernel, :type, :payment_terms, :stack_script, :name, :password, :callback create_linode @callback.call self if @callback create_disks create_config boot_linode self rescue Exception => ex destroy if id raise ex end def destroy requires :identity service.linode_shutdown id disks.each { |disk| disk.destroy } wait_for { not disks? } service.linode_delete id end def ready? status == 1 end private def config service.linode_config_list(id).body['DATA'].first['ConfigID'] end def create_linode self.id = service.linode_create(@data_center.id, @flavor.id, @payment_terms).body['DATA']['LinodeID'] service.linode_update id, :label => @name ips.create reload end def create_disks @swap = disks.create :type => :swap, :name => @name, :size => 256 @disk = disks.create(:type => @type, :image => @image, :stack_script => @stack_script, :password => @password, :name => @name, :size => (@flavor.disk*1024)-256) end def create_config @config = service.linode_config_create(id, @kernel.id, @name, "#{@disk.id},#{@swap.id},,,,,,,").body['DATA']['ConfigID'] end def boot_linode service.linode_boot id, @config end end end end end fog-1.42.0/lib/fog/linode/models/compute/data_centers.rb0000644000004100000410000000127013171001215023103 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/linode/models/compute/data_center' module Fog module Compute class Linode class DataCenters < Fog::Collection model Fog::Compute::Linode::DataCenter def all load datacenters end private def datacenters(id=nil) service.avail_datacenters.body['DATA'].map { |datacenter| map_datacenter datacenter } end def map_datacenter(datacenter) datacenter = datacenter.each_with_object({}) { |(k, v), h| h[k.downcase.to_sym] = v } datacenter.merge! :id => datacenter[:datacenterid], :name => datacenter[:location] end end end end end fog-1.42.0/lib/fog/linode/models/compute/image.rb0000644000004100000410000000047313171001215021535 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Linode class Image < Fog::Model identity :id attribute :name attribute :bits attribute :image_size attribute :created_at, types: 'time' attribute :requires_pvops_kernel end end end end fog-1.42.0/lib/fog/linode/compute.rb0000644000004100000410000000646213171001215017174 0ustar www-datawww-datarequire 'fog/linode/core' module Fog module Compute class Linode < Fog::Service requires :linode_api_key recognizes :port, :scheme, :persistent model_path 'fog/linode/models/compute' model :flavor collection :flavors model :image collection :images model :server collection :servers model :kernel collection :kernels model :data_center collection :data_centers model :stack_script collection :stack_scripts model :ip collection :ips model :disk collection :disks model :node_balancer_flavor collection :node_balancer_flavors request_path 'fog/linode/requests/compute' request :avail_datacenters request :avail_distributions request :avail_kernels request :avail_linodeplans request :avail_nodebalancers request :avail_stackscripts request :linode_disk_create request :linode_disk_list request :linode_disk_delete request :linode_disk_resize request :linode_disk_update request :linode_disk_imagize request :linode_disk_duplicate request :linode_disk_createfromdistribution request :linode_disk_createfromstackscript request :linode_disk_createfromimage request :image_list request :image_delete request :linode_ip_list request :linode_ip_addprivate request :linode_config_list request :linode_config_create request :linode_config_delete request :linode_config_update request :linode_create request :linode_delete request :linode_list request :linode_boot request :linode_reboot request :linode_shutdown request :linode_update request :stackscript_list # request :linode_resize class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = {} end end def self.reset @data = nil end def initialize(options={}) @linode_api_key = options[:linode_api_key] end def data self.class.data[@linode_api_key] end def reset_data self.class.data.delete(@linode_api_key) end end class Real def initialize(options={}) @linode_api_key = options[:linode_api_key] @host = options[:host] || "api.linode.com" @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::XML::Connection.new("#{@scheme}://#{@host}:#{@port}", options[:persistent]) end def reload @connection.reset end def request(params) params[:query] ||= {} params[:query].merge!(:api_key => @linode_api_key) response = @connection.request(params) unless response.body.empty? response.body = Fog::JSON.decode(response.body) if data = response.body['ERRORARRAY'].first error = case data['ERRORCODE'] when 5 Fog::Compute::Linode::NotFound else Fog::Compute::Linode::Error end raise error.new(data['ERRORMESSAGE']) end end response end end end end end fog-1.42.0/lib/fog/fogdocker/0000755000004100000410000000000013171001215015654 5ustar www-datawww-datafog-1.42.0/lib/fog/fogdocker/errors.rb0000644000004100000410000000030213171001215017510 0ustar www-datawww-datamodule Fog module Errors module Fogdocker class ServiceError < Fog::Errors::Error; end class AuthenticationError < Fog::Errors::Fogdocker::ServiceError; end end end end fog-1.42.0/lib/fog/fogdocker/requests/0000755000004100000410000000000013171001215017527 5ustar www-datawww-datafog-1.42.0/lib/fog/fogdocker/requests/compute/0000755000004100000410000000000013171001215021203 5ustar www-datawww-datafog-1.42.0/lib/fog/fogdocker/requests/compute/container_action.rb0000644000004100000410000000471313171001215025054 0ustar www-datawww-datamodule Fog module Compute class Fogdocker class Real def container_action(options = {}) raise ArgumentError, "instance id is a required parameter" unless options.key? :id raise ArgumentError, "action is a required parameter" unless options.key? :action result = Docker::Container.get(options[:id], {}, @connection).send(options[:action], options[:options] || {}) if result.is_a?(Hash) downcase_hash_keys(result) else result end rescue Docker::Error::NotFoundError => e raise Fog::Errors::NotFound.new(e.message) rescue Docker::Error::TimeoutError => e raise Fog::Errors::TimeoutError.new(e.message) rescue Docker::Error::UnauthorizedError => e raise Fog::Errors::Fogdocker::AuthenticationError.new(e.message) rescue Docker::Error::DockerError => e raise Fog::Errors::Fogdocker::ServiceError.new(e.message) end end class Mock def container_action(options = {}) raise ArgumentError, "id is a required parameter" unless options.key? :id raise ArgumentError, "action is a required parameter" unless options.key? :action response_matcher(options[:action]) end private def response_matcher(action) send("#{action}_response".to_sym) rescue NoMethodError default_response end def default_response { 'id' => 'a6b02c7ca29a22619f7d0e59062323247739bc0cd375d619f305f0b519af4ef3', 'state_running' => false } end def start_response default_response.merge({ 'state_running' => true }) end def top_response [ { 'UID' => 'root', 'PID' => '15306', 'PPID' => '13567', 'C' => '0', 'STIME' => 'Oct15', 'TTY' => '?', 'TIME' => '00:00:11', 'CMD' => 'ping theforeman.org' } ] end # Sample response from a ping def logs_response "\u0001\u0000\u0000\u0000\u0000\u0000\u0000]64 bytes from fra07s30-in-f6.1e100.net (173.194.112.102): icmp_req=35272 ttl=52 time=36.9 ms\n\u0001\u0000\u0000\u0000\u0000\u0000\u0000]64 bytes from fra07s30-in-f6.1e100.net (173.194.112.102): icmp_req=35273 ttl=52 time=35.3 ms\n" end end end end end fog-1.42.0/lib/fog/fogdocker/requests/compute/image_delete.rb0000644000004100000410000000112213171001215024130 0ustar www-datawww-datamodule Fog module Compute class Fogdocker class Real def image_delete(options = {}) raise ArgumentError, "instance id is a required parameter" unless options.key? :id image = Docker::Image.get(options[:id], {}, @connection) image.remove() end end class Mock def image_delete(options = {}) raise ArgumentError, "instance id is a required parameter" unless options.key? :id "[{'Deleted':'b15c1423ba157d0f7ac83cba178390c421bb8d536e7e7857580fc10f2d53e1b9'}]" end end end end end fog-1.42.0/lib/fog/fogdocker/requests/compute/container_get.rb0000644000004100000410000000461413171001215024356 0ustar www-datawww-datamodule Fog module Compute class Fogdocker class Real def container_get(id) raw_container = Docker::Container.get(id, {}, @connection).json processed_container = downcase_hash_keys(raw_container) processed_container['hostconfig_port_bindings'] = raw_container['HostConfig']['PortBindings'] processed_container['hostconfig_links'] = raw_container['HostConfig']['Links'] processed_container['config_exposed_ports'] = raw_container['Config']['ExposedPorts'] processed_container end end class Mock def container_get(id) {'id' => '2ce79789656e4f7474624be6496dc6d988899af30d556574389a19aade2f9650', 'image' => 'mattdm/fedora:f19', 'command' => '/bin/bash', 'created' => '1389876158', 'status' => 'Up 45 hours', 'state_running' => true, 'network_settings_ipaddress' => '172.17.0.2', 'config_memory' => '1024', 'config_cpu_sets' => '0-3', 'config_cpu_shares' => '20', 'config_hostname' => '21341234', 'config_attach_stdin' => true, 'config_attach_stdout' => true, 'config_attach_stderr' => true, 'ports' => nil, 'config_tty' => true, 'hostconfig_privileged' => true, 'hostconfig_links' => nil, 'hostconfig_port_bindings' => { "29321/tcp" => [{"HostIp"=>"", "HostPort"=>"3001"}], "39212/tcp" => [{"HostIp"=>"", "HostPort"=>"2030"}]}, 'state_exit_code' => 0, 'state_pid' => 2932, 'cpu_shares' => 0, 'volumes' => nil, 'config_exposed_ports' => { "29321/tcp" => {}, "39212/tcp" => {} }, 'sizerw' => 0, 'sizerootfs' => 0, 'environment_variables' => ["HOME=/mydir", "SAMPLEENV=samplevalue"], 'name' => '123123123', 'names' => ['/boring_engelbert']} end end end end end fog-1.42.0/lib/fog/fogdocker/requests/compute/container_all.rb0000644000004100000410000000255313171001215024347 0ustar www-datawww-datamodule Fog module Compute class Fogdocker class Real # filter options # all – true or false, Show all containers. Only running containers are shown by default # limit – Show limit last created containers, include non-running ones. # since – Show only containers created since Id, include non-running ones. # before – Show only containers created before Id, include non-running ones. # size – true or false, Show the containers sizes def container_all(filters = {}) Docker::Container.all(filters.merge(:all => true), @connection).map do |container| downcase_hash_keys(container.json) end end end class Mock def container_all(filters = {}) [ {'id' => '2ce79789656e4f7474624be6496dc6d988899af30d556574389a19aade2f9650', 'image' => 'mattdm/fedora:f19', 'command' => '/bin/bash', 'created' => '1389876158', 'status' => 'Up 45 hours', 'state_running' => true, 'ports' => nil, 'sizerw' => 0, 'sizerootfs' => 0, 'name' => '123123123', 'names' => ['/boring_engelbert'] } ] end end end end end fog-1.42.0/lib/fog/fogdocker/requests/compute/image_search.rb0000644000004100000410000000140413171001215024136 0ustar www-datawww-datamodule Fog module Compute class Fogdocker class Real def image_search(query = {}) Docker::Util.parse_json(@connection.get('/images/search', query)).map do |image| downcase_hash_keys(image) end end end class Mock def image_search(query = {}) [ {"description" => "", "is_official" => false, "is_automated" => false, "name" => "wma55/u1210sshd", "star_count" => 0}, {"description" => "", "is_official" => false, "is_automated" => false, "name" => "jdswinbank/sshd", "star_count" => 0} ] end end end end end fog-1.42.0/lib/fog/fogdocker/requests/compute/image_get.rb0000644000004100000410000000071513171001215023454 0ustar www-datawww-datamodule Fog module Compute class Fogdocker class Real def image_get(id) downcase_hash_keys Docker::Image.get(id, {}, @connection).json end end class Mock def image_get(id) {'id'=>'a6b02c7ca29a22619f7d0e59062323247739bc0cd375d619f305f0b519af4ef3', 'repotags' => ['repo/other'], 'created' => 1389877693, 'size' => 3265536} end end end end end fog-1.42.0/lib/fog/fogdocker/requests/compute/image_all.rb0000644000004100000410000000136413171001215023446 0ustar www-datawww-datamodule Fog module Compute class Fogdocker class Real def image_all(filters = {}) Docker::Image.all({}, @connection).map do |image| downcase_hash_keys(image.json) end end end class Mock def image_all(filters = {}) [ {'id'=>'a6b02c7ca29a22619f7d0e59062323247739bc0cd375d619f305f0b519af4ef2', 'repotags' => ['repo/one'], 'created' => 1389877693, 'size' => 3265536}, {'id'=>'a6b02c7ca29a22619f7d0e59062323247739bc0cd375d619f305f0b519af4ef3', 'repotags' => ['repo/other'], 'created' => 1389877693, 'size' => 3265536} ] end end end end end fog-1.42.0/lib/fog/fogdocker/requests/compute/container_delete.rb0000644000004100000410000000104713171001215025036 0ustar www-datawww-datamodule Fog module Compute class Fogdocker class Real def container_delete(options = {}) raise ArgumentError, "instance id is a required parameter" unless options.key? :id container = Docker::Container.get(options[:id], {}, @connection) container.delete() true end end class Mock def container_delete(options = {}) raise ArgumentError, "instance id is a required parameter" unless options.key? :id true end end end end end fog-1.42.0/lib/fog/fogdocker/requests/compute/api_version.rb0000644000004100000410000000040513171001215024045 0ustar www-datawww-datamodule Fog module Compute class Fogdocker class Real def api_version Docker.version(@connection) end end class Mock def api_version {'Version' => '1.6'} end end end end end fog-1.42.0/lib/fog/fogdocker/requests/compute/container_commit.rb0000644000004100000410000000122513171001215025062 0ustar www-datawww-datamodule Fog module Compute class Fogdocker class Real def container_commit(options) raise ArgumentError, "instance id is a required parameter" unless options.key? :id container = Docker::Container.get(options[:id], {}, @connection) downcase_hash_keys container.commit(camelize_hash_keys(options)).json end end class Mock def container_commit(options) {'id'=>'a6b02c7ca29a22619f7d0e59062323247739bc0cd375d619f305f0b519af4ef3', 'repotags' => ['repo/other'], 'created' => 1389877693, 'size' => 3265536} end end end end end fog-1.42.0/lib/fog/fogdocker/requests/compute/container_create.rb0000644000004100000410000000261213171001215025036 0ustar www-datawww-datamodule Fog module Compute class Fogdocker # Create attributes #'Hostname' => '', #'User' => '', #'Memory' => 0, #'MemorySwap' => 0, #'AttachStdin' => false, #'AttachStdout' => true, #'AttachStderr' => true, #'PortSpecs' => nil, #'Tty' => false, #'OpenStdin' => false, #'StdinOnce' => false, #'Env' => nil, #'Cmd' => ['date'], #'Dns' => nil, #'Image' => 'base', #'Volumes' => { # '/tmp' => {} #}, #'VolumesFrom' => '', #'WorkingDir' => '', #'ExposedPorts' => { # '22/tcp' => {} #} class Real def container_create(attrs) downcase_hash_keys Docker::Container.create(camelize_hash_keys(attrs), @connection).json end end class Mock def container_create(attrs) {'id' => '2ce79789656e4f7474624be6496dc6d988899af30d556574389a19aade2f9650', 'image' => 'mattdm/fedora:f19', 'command' => '/bin/bash', 'created' => '1389876158', 'status' => 'Up 45 hours', 'state' => {'running' => 'true'}, 'ports' => nil, 'sizerw' => 0, 'sizerootfs' => 0, 'name' => '123123123', 'names' => ['/boring_engelbert'] } end end end end end fog-1.42.0/lib/fog/fogdocker/requests/compute/image_create.rb0000644000004100000410000000056613171001215024144 0ustar www-datawww-datamodule Fog module Compute class Fogdocker class Real def image_create(attrs) downcase_hash_keys Docker::Image.create(attrs, nil, @connection).json end end class Mock def image_create(attrs) {'id'=>'a6b02c7ca29a22619f7d0e59062323247739bc0cd375d619f305f0b519af4ef2'} end end end end end fog-1.42.0/lib/fog/fogdocker/core.rb0000644000004100000410000000022513171001215017130 0ustar www-datawww-datarequire 'fog/core' require 'fog/fogdocker/errors' module Fog module Fogdocker extend Fog::Provider service(:compute, 'Compute') end end fog-1.42.0/lib/fog/fogdocker/models/0000755000004100000410000000000013171001215017137 5ustar www-datawww-datafog-1.42.0/lib/fog/fogdocker/models/compute/0000755000004100000410000000000013171001215020613 5ustar www-datawww-datafog-1.42.0/lib/fog/fogdocker/models/compute/images.rb0000644000004100000410000000073413171001215022411 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/fogdocker/models/compute/image' module Fog module Compute class Fogdocker class Images < Fog::Collection model Fog::Compute::Fogdocker::Image def all(filters = {}) load service.image_all(filters) end def get(id) new service.image_get(id) end def image_search(query = {}) service.image_search(query) end end end end end fog-1.42.0/lib/fog/fogdocker/models/compute/servers.rb0000644000004100000410000000100213171001215022622 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/fogdocker/models/compute/server' module Fog module Compute class Fogdocker class Servers < Fog::Collection model Fog::Compute::Fogdocker::Server def all(filters = {}) load service.container_all(filters) end def get(id) new service.container_get(id) end def bootstrap(new_attributes = {}) server = create(new_attributes) server end end end end end fog-1.42.0/lib/fog/fogdocker/models/compute/server.rb0000644000004100000410000001232713171001215022453 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class Fogdocker # fog server is a docker container class Server < Fog::Compute::Server identity :id attr_accessor :info attribute :name attribute :created attribute :path attribute :args attribute :hostname attribute :links, :aliases => 'hostconfig_links' attribute :privileged, :aliases => 'hostconfig_privileged' attribute :port_bindings, :aliases => 'hostconfig_port_bindings' attribute :ipaddress, :aliases => 'network_settings_ipaddress' attribute :bridge, :aliases => 'network_settings_bridge' attribute :state_running attribute :state_pid attribute :state_exit_code attribute :cores, :aliases => 'config_cpu_sets' attribute :cpu_shares, :aliases => 'config_cpu_shares' attribute :memory, :aliases => 'config_memory' attribute :hostname, :aliases => 'config_hostname' attribute :cmd, :aliases => 'config_cmd' attribute :entrypoint, :aliases => 'config_entrypoint' attribute :tty, :aliases => 'config_tty' attribute :attach_stdin, :aliases => 'config_attach_stdin' attribute :attach_stdout, :aliases => 'config_attach_stdout' attribute :attach_stderr, :aliases => 'config_attach_stderr' attribute :host attribute :image attribute :exposed_ports, :aliases => 'config_exposed_ports' attribute :volumes attribute :environment_variables, :aliases => 'config_env' #raw = {"ID"=>"2ce79789656e4f7474624be6496dc6d988899af30d556574389a19aade2f9650", # "Created"=>"2014-01-16T12:42:38.081665295Z", # "Path"=>"/bin/bash", # "Args"=>[], # "Config"=>{ # "Hostname"=>"2ce79789656e", # "Domainname"=>"", # "User"=>"", # "Memory"=>0, # "MemorySwap"=>0, # "CpuShares"=>0, # "AttachStdin"=>true, # "AttachStdout"=>true, # "AttachStderr"=>true, # "PortSpecs"=>nil, # "ExposedPorts"=>{}, # "Env": [ # "HOME=/mydir", # ], # "State"=>{ # "Running"=>true, # "Pid"=>1505, # "ExitCode"=>0, # "StartedAt"=>"2014-01-16T15:50:36.304626413Z", # "FinishedAt"=>"2014-01-16T15:50:36.238743161Z", # "Ghost"=>false}, # "Image"=>"7c8cf65e1efa9b55f9ba8c60a970fe41595e56b894c7fdb19871bd9b276ca9d3", # "NetworkSettings"=>{ # "IPAddress"=>"172.17.0.2", # "IPPrefixLen"=>16, # "Gateway"=>"172.17.42.1", # "Bridge"=>"docker0", # "PortMapping"=>nil, # "Ports"=>{}}, # "SysInitPath"=>"/var/lib/docker/init/dockerinit-0.7.2", # "ResolvConfPath"=>"/etc/resolv.conf", # "HostnamePath"=>"/var/lib/docker/containers/2ce79789656e4f7474624be6496dc6d988899af30d556574389a19aade2f9650/hostname", # "HostsPath"=>"/var/lib/docker/containers/2ce79789656e4f7474624be6496dc6d988899af30d556574389a19aade2f9650/hosts", # "Name"=>"/boring_engelbart", # "Driver"=>"devicemapper", # "Volumes"=>{}, # "VolumesRW"=>{}, # "HostConfig"=>{ # "Binds"=>nil, # "ContainerIDFile"=>"", # "LxcConf"=>[], # "Privileged"=>false, # "PortBindings"=>{}, # "Links"=>nil, # "PublishAllPorts"=>false} # } def ready? reload if state_running.nil? state_running end def stopped? !ready? end def mac # TODO end def start(options = {}) service.container_action(:id =>id, :action => :start!) reload end def stop(options = {}) action = options['force'] ? :kill : :stop service.container_action(:id =>id, :action => action) reload end def restart(options = {}) service.container_action(:id =>id, :action => :restart!) reload end def commit(options = {}) service.container_commit({:id=>id}.merge(options)) end def destroy(options = {}) service.container_action(:id =>id, :action => :kill) service.container_delete(:id => id) end def logs(options = { :stdout => 1, :stderr => 1 }) service.container_action(:id =>id, :action => :logs, :options => options) end def top(options = {}) service.container_action(:id =>id, :action => :top) end def save if persisted? service.container_update(attributes) else self.id = service.container_create(attributes)['id'] end reload end def to_s name end end end end end fog-1.42.0/lib/fog/fogdocker/models/compute/image.rb0000644000004100000410000000132013171001215022216 0ustar www-datawww-datamodule Fog module Compute class Fogdocker class Image < Fog::Model identity :id attr_accessor :info attribute :repo_tags attribute :created attribute :size attribute :virtual_size def name repo_tags.empty? ? id : repo_tags.first end def ready? !(status =~ /down/i) end def destroy(options = {}) service.image_delete(id) end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? service.image_create(attributes) end def to_s name end end end end end fog-1.42.0/lib/fog/fogdocker/compute.rb0000644000004100000410000000354213171001215017661 0ustar www-datawww-datarequire 'fog/fogdocker/core' module Fog module Compute class Fogdocker < Fog::Service requires :docker_url recognizes :docker_username, :docker_password, :docker_email model_path 'fog/fogdocker/models/compute' model :server collection :servers model :image collection :images request_path 'fog/fogdocker/requests/compute' request :api_version request :container_all request :container_create request :container_delete request :container_get request :container_action request :container_commit request :image_all request :image_create request :image_delete request :image_get request :image_search class Mock def initialize(options={}) end end class Real def initialize(options={}) require 'docker' username = options[:docker_username] password = options[:docker_password] email = options[:docker_email] url = options[:docker_url] connection_options = {:username => username, :password => password, :email => email} @connection = Docker::Connection.new(url, connection_options) Docker.authenticate!(connection_options, @connection) if username || email || password rescue Docker::Error::AuthenticationError => e raise Fog::Errors::Fogdocker::AuthenticationError.new(e.message) end def downcase_hash_keys(hash, k = []) return {k.join('_').gsub(/([a-z])([A-Z])/,'\1_\2').downcase => hash} unless hash.is_a?(Hash) hash.reduce({}){ |h, v| h.merge! downcase_hash_keys(v[-1], k + [v[0]]) } end def camelize_hash_keys(hash) Hash[ hash.map {|k, v| [k.to_s.split('_').map {|w| w.capitalize}.join, v] }] end end end end end fog-1.42.0/lib/fog/vcloud_director.rb0000644000004100000410000000004613171001215017425 0ustar www-datawww-datarequire 'fog/vcloud_director/compute' fog-1.42.0/lib/fog/bare_metal_cloud/0000755000004100000410000000000013171001215017172 5ustar www-datawww-datafog-1.42.0/lib/fog/bare_metal_cloud/requests/0000755000004100000410000000000013171001215021045 5ustar www-datawww-datafog-1.42.0/lib/fog/bare_metal_cloud/requests/compute/0000755000004100000410000000000013171001215022521 5ustar www-datawww-datafog-1.42.0/lib/fog/bare_metal_cloud/requests/compute/list_plans.rb0000644000004100000410000000143013171001215025214 0ustar www-datawww-datamodule Fog module Compute class BareMetalCloud class Real # List available plans # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'plan'<~Array> # * 'id'<~String> - Id of the plan # * 'name'<~String> - Name of the plan # * 'rate'<~String> - Cost per hour of the plan # * 'os'<~String> - Operating system of the plan # * 'config'<~String> - Configuration of the plan # def list_plans request( :expects => 200, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'api/listPlans' ) end end end end end fog-1.42.0/lib/fog/bare_metal_cloud/requests/compute/list_configurations.rb0000644000004100000410000000125513171001215027136 0ustar www-datawww-datamodule Fog module Compute class BareMetalCloud class Real # List Configurations # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * available-server<~Array>: # * 'configuration'<~String> - Hardware Configuration string # * 'quantity'<~String>: - quantity of servers to a certain configuration # def list_configurations request( :expects => 200, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'api/listConfigurations' ) end end end end end fog-1.42.0/lib/fog/bare_metal_cloud/requests/compute/cancel_server.rb0000644000004100000410000000131413171001215025660 0ustar www-datawww-datamodule Fog module Compute class BareMetalCloud class Real # Shutdown a running server # # ==== Parameters # * serverId<~String> - The id of the server to shutdown # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'server'<~Hash>: # * 'id'<~String> - Id of the image # def cancel_server(server_id) request( :expects => 200, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'api/cancelServer', :query => {'serverId' => server_id} ) end end end end end fog-1.42.0/lib/fog/bare_metal_cloud/requests/compute/add_server.rb0000644000004100000410000000162713171001215025172 0ustar www-datawww-datamodule Fog module Compute class BareMetalCloud class Real # Boot a new server # # ==== Parameters # * planId<~String> - The id of the plan to boot the server with # * options<~Hash>: optional extra arguments # * imageId<~String> - Optional image to boot server from # * name<~String> - Name to boot new server with # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'server'<~Hash>: # * 'id'<~String> - Id of the image # def add_server(plan_id, options = {}) request( :expects => 200, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'api/addServer', :query => {'planId' => plan_id}.merge!(options) ) end end end end end fog-1.42.0/lib/fog/bare_metal_cloud/requests/compute/get_server.rb0000644000004100000410000000241713171001215025217 0ustar www-datawww-datamodule Fog module Compute class BareMetalCloud class Real # List servers # # ==== Parameters # * serverId<~String> - Id of the server # # ==== Returns # * response<~Excon::Response>: # * body<~Has>: # * server<~Hash>: # * 'id'<~String> - Id of the server # * 'mac-address'<~String> - mac-address of the server # * 'ip'<~Hash>: # * 'address'<~String> - Address of the ip # * 'name'<~String> - Name of the ip # * 'login'<~Hash>: # * 'name'<~String> - Name of the login # * 'password'<~String> - Password of the login # * 'username'<~String> - Username of the login # * 'name'<~String> - Name of the server # * 'notes'<~String> - Notes about the server # * 'state'<~String> - State of the server # def get_server(server_id) request( :expects => 200, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'api/getServer', :query => {'serverId' => server_id} ) end end end end end fog-1.42.0/lib/fog/bare_metal_cloud/requests/compute/add_server_by_configuration.rb0000644000004100000410000000167613171001215030617 0ustar www-datawww-datamodule Fog module Compute class BareMetalCloud class Real # Boot a new server by configuration # # ==== Parameters # * config<~String> - The Hardware configuration string # * options<~Hash>: optional extra arguments # * imageName<~String> - Optional imageName to be installed # * name<~String> - Optional server Name # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'server'<~Hash>: # * 'id'<~String> - Id of the image # def add_server_by_configuration(config, options = {}) request( :expects => 200, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'api/addServerByConfiguration', :query => {'configuration' => config}.merge!(options) ) end end end end end fog-1.42.0/lib/fog/bare_metal_cloud/requests/compute/list_images.rb0000644000004100000410000000112113171001215025341 0ustar www-datawww-datamodule Fog module Compute class BareMetalCloud class Real # List images # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'image'<~Array> # * 'Size'<~String> - Size of the image # * 'Name'<~String> - Name of the image # def list_images request( :expects => 200, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'api/listImages' ) end end end end end fog-1.42.0/lib/fog/bare_metal_cloud/requests/compute/list_servers.rb0000644000004100000410000000207713171001215025600 0ustar www-datawww-datamodule Fog module Compute class BareMetalCloud class Real # List servers # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * server<~Array>: # * 'id'<~String> - Id of the server # * 'ip'<~Hash>: # * 'address'<~String> - Address of the ip # * 'name'<~String> - Name of the ip # * 'login'<~Hash>: # * 'name'<~String> - Name of the login # * 'password'<~String> - Password of the login # * 'username'<~String> - Username of the login # * 'name'<~String> - Name of the server # * 'notes'<~String> - Notes about the server # * 'state'<~String> - State of the server # def list_servers request( :expects => 200, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'api/listServers' ) end end end end end fog-1.42.0/lib/fog/bare_metal_cloud/requests/compute/reboot_server.rb0000644000004100000410000000102113171001215025720 0ustar www-datawww-datamodule Fog module Compute class BareMetalCloud class Real # Reboot a running server # # ==== Parameters # * serverId<~String> - The id of the server to reboot # def reboot_server(server_id) request( :expects => 200, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'api/rebootServer', :query => {'serverId' => server_id} ) end end end end end fog-1.42.0/lib/fog/bare_metal_cloud/core.rb0000644000004100000410000000021613171001215020446 0ustar www-datawww-datarequire 'fog/core' require 'fog/xml' module Fog module BareMetalCloud extend Fog::Provider service(:compute, 'Compute') end end fog-1.42.0/lib/fog/bare_metal_cloud/compute.rb0000644000004100000410000000520013171001215021170 0ustar www-datawww-datarequire 'fog/bare_metal_cloud/core' module Fog module Compute class BareMetalCloud < Fog::Service requires :bare_metal_cloud_password, :bare_metal_cloud_username recognizes :host, :port, :scheme, :persistent model_path 'fog/bare_metal_cloud/models/compute' request_path 'fog/bare_metal_cloud/requests/compute' request :add_server request :add_server_by_configuration request :cancel_server request :get_server request :list_images request :list_plans request :list_servers request :list_configurations request :reboot_server class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = {} end end def self.reset @data = nil end def initialize(options={}) @bare_metal_cloud_username = options[:bare_metal_cloud_username] end def data self.class.data[@bare_metal_cloud_username] end def reset_data self.class.data.delete(@bare_metal_cloud_username) end end class Real def initialize(options={}) @bare_metal_cloud_password = options[:bare_metal_cloud_password] @bare_metal_cloud_username = options[:bare_metal_cloud_username] @connection_options = options[:connection_options] || {} @host = options[:host] || "noc.newservers.com" @persistent = options[:persistent] || false @port = options[:port] || 443 @scheme = options[:scheme] || 'https' @connection = Fog::XML::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def reload @connection.reset end def request(params) params[:query] ||= {} params[:query].merge!({ :password => @bare_metal_cloud_password, :username => @bare_metal_cloud_username }) params[:headers] ||= {} 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) rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Compute::BareMetalCloud::NotFound.slurp(error) else error end end response end end end end end fog-1.42.0/lib/fog/opennebula.rb0000644000004100000410000000004113171001215016361 0ustar www-datawww-datarequire 'fog/opennebula/compute' fog-1.42.0/lib/fog/opennebula/0000755000004100000410000000000013171001215016041 5ustar www-datawww-datafog-1.42.0/lib/fog/opennebula/requests/0000755000004100000410000000000013171001215017714 5ustar www-datawww-datafog-1.42.0/lib/fog/opennebula/requests/compute/0000755000004100000410000000000013171001215021370 5ustar www-datawww-datafog-1.42.0/lib/fog/opennebula/requests/compute/vm_shutdown.rb0000644000004100000410000000050213171001215024267 0ustar www-datawww-datamodule Fog module Compute class OpenNebula class Real def vm_shutdown(id) vmpool = ::OpenNebula::VirtualMachinePool.new(client) vmpool.info!(-2,id,id,-1) vmpool.each do |vm| vm.shutdown end end #def vm_shutdown end end end end fog-1.42.0/lib/fog/opennebula/requests/compute/get_vnc_console.rb0000644000004100000410000000303213171001215025062 0ustar www-datawww-datarequire File.expand_path('../OpenNebulaVNC', __FILE__) module Fog module Compute class OpenNebula class Mock # 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 = { :type => "novnc", :proxy_port => "29876", :password => "null", :token => "3n32dtwpsdj5jkug3b4w", :proxy_host => "example.com" } end # def get_vnc_console end # class Real class Real def get_vnc_console(server_id, console_type, onevm_object) logger = Fog::Logger.new $conf = {"vnc_proxy_port" => "29876", "vnc_proxy_ipv6" => "", "vnc_proxy_support_wss" => "", "vnc_proxy_cert" => "", "vnc_proxy_key" => ""} $vnc = OpenNebulaVNC.new($conf, logger) ret = startvnc(onevm_object,$vnc) response = Excon::Response.new response.status = ret[0] response.body = ret[1] response end # def get_vnc_console def startvnc(onevm_object, vnc) return vnc.proxy(onevm_object) end #def startvnc end # class Mock end # class OpenNebula end # module Compute end # module Fog fog-1.42.0/lib/fog/opennebula/requests/compute/vm_stop.rb0000644000004100000410000000046313171001215023407 0ustar www-datawww-datamodule Fog module Compute class OpenNebula class Real def vm_stop(id) vmpool = ::OpenNebula::VirtualMachinePool.new(client) vmpool.info!(-2,id,id,-1) vmpool.each do |vm| vm.stop end end #def vm_stop end end end end fog-1.42.0/lib/fog/opennebula/requests/compute/vm_destroy.rb0000644000004100000410000000121213171001215024104 0ustar www-datawww-datamodule Fog module Compute class OpenNebula class Real def vm_destroy(id) vmpool = ::OpenNebula::VirtualMachinePool.new(client) vmpool.info!(-2,id,id,-1) vmpool.each do |vm| # true => delete and recreate vm vm.delete(false) end end end class Mock def vm_destroy(id) response = Excon::Response.new response.status = 200 self.data['vms'].each do |vm| if vm['id'] == id self.data['vms'].delete(vm) end end true end end end end end fog-1.42.0/lib/fog/opennebula/requests/compute/OpenNebulaVNC.rb0000644000004100000410000002174613171001215024326 0ustar www-datawww-data# -------------------------------------------------------------------------- # # Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs # # # # Licensed under the Apache License, Version 2.0 (the "License"); you may # # not use this file except in compliance with the License. You may obtain # # a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # #--------------------------------------------------------------------------- # # # This class provides support for launching and stopping a websockify proxy # require 'rubygems' require 'json' require 'opennebula' #if !ONE_LOCATION NOVNC_LOCK_FILE = "/var/lock/.novnc.lock" #else # NOVNC_LOCK_FILE= ONE_LOCATION + "/var/.novnc.lock" #end TOKEN_EXPIRE_SECONDS = 4 VNC_STATES = [ #0, #LCM_INIT #1, #PROLOG #2, #BOOT "3", #RUNNING "4", #MIGRATE #5, #SAVE_STOP #6, #SAVE_SUSPEND #7, #SAVE_MIGRATE #8, #PROLOG_MIGRATE #9, #PROLOG_RESUME #10, #EPILOG_STOP #11, #EPILOG "12", #SHUTDOWN "13", #CANCEL #14, #FAILURE #15, #CLEANUP_RESUBMIT "16", #UNKNOWN "17", #HOTPLUG "18", #SHUTDOWN_POWEROFF #19, #BOOT_UNKNOWN #20, #BOOT_POWEROFF #21, #BOOT_SUSPENDED #22, #BOOT_STOPPED #23, #CLEANUP_DELETE "24", #HOTPLUG_SNAPSHOT "25", #HOTPLUG_NIC "26", #HOTPLUG_SAVEAS "27", #HOTPLUG_SAVEAS_POWEROFF "28", #HOTPLUG_SAVEAS_SUSPENDED "29" #SHUTDOWN_UNDEPLOY #30, #EPILOG_UNDEPLOY #31, #PROLOG_UNDEPLOY #32 #BOOT_UNDEPLOY ] VAR_LOCATION = Dir.pwd + "/extras/noVNC" SHARE_LOCATION = Dir.pwd + "/extras/noVNC" class OpenNebulaVNC attr_reader :proxy_port def initialize(config, logger, options = {}) opts={ :json_errors => true, :token_folder_name => 'sunstone_vnc_tokens'}.merge(options) @pipe = nil @token_folder = File.join(VAR_LOCATION, opts[:token_folder_name]) @proxy_path = File.join(SHARE_LOCATION, "websockify/websocketproxy.py") @proxy_port = config[:vnc_proxy_port] @proxy_ipv6 = config[:vnc_proxy_ipv6] @wss = config[:vnc_proxy_support_wss] @lock_file = NOVNC_LOCK_FILE if (@wss == "yes") || (@wss == "only") || (@wss == true) @enable_wss = true @cert = config[:vnc_proxy_cert] @key = config[:vnc_proxy_key] else @enable_wss = false end @options = opts @logger = logger end def start if is_running? message="VNC server already running" STDERR.puts message @logger.info message return false end create_token_dir proxy_options = "--target-config=#{@token_folder} " if @enable_wss proxy_options << " --cert #{@cert}" proxy_options << " --key #{@key}" if @key && @key.size > 0 proxy_options << " --ssl-only" if @wss == "only" end if @proxy_ipv6 proxy_options << " -6" end cmd ="python #{@proxy_path} #{proxy_options} #{@proxy_port}" begin @logger.info { "Starting VNC proxy: #{cmd}" } pid=start_daemon(cmd, VNC_LOG) rescue Exception => e @logger.error e.message return false end File.open(@lock_file, "w") do |f| f.write(pid.to_s) end sleep 1 if !is_running? message="Error starting VNC proxy" STDERR.puts message @logger.error message File.delete(@lock_file) if File.exist?(@lock_file) return false end STDOUT.puts "VNC proxy started" true end def proxy(vm_resource) # Check configurations and VM attributes #if !is_running? # return error(400, "VNC Proxy is not running") #end if !VNC_STATES.include?(vm_resource['LCM_STATE']) return error(400,"Wrong state (#{vm_resource['LCM_STATE']}) to open a VNC session") end if vm_resource['TEMPLATE/GRAPHICS/TYPE'].nil? || vm_resource['TEMPLATE/GRAPHICS/TYPE'].downcase != "vnc" return error(400,"VM has no VNC configured") end # Proxy data host = vm_resource['HISTORY_RECORDS/HISTORY[last()]/HOSTNAME'] vnc_port = vm_resource['TEMPLATE/GRAPHICS/PORT'] vnc_pw = vm_resource['TEMPLATE/GRAPHICS/PASSWD'] # Generate token random_str: host:port random_str = rand(36**20).to_s(36) #random string a-z0-9 length 20 token = "#{random_str}: #{host}:#{vnc_port}" token_file = 'one-'+vm_resource['ID'] # Create token file begin f = File.open(File.join(@token_folder, token_file), 'w') f.write(token) f.close rescue Exception => e # @logger.error e.message return error(500, "Cannot create VNC proxy token") end info = { :proxy_port => "29876", :password => vnc_pw, :token => random_str, :vm_name => vm_resource['NAME'] } return [200, info] end # Delete proxy token file def delete_token(filename) begin File.delete(File.join(@token_folder, filename)) rescue => e @logger.error "Error deleting token file for VM #{vm_id}" @logger.error e.message end end def stop(force=false) pid=get_pid if pid @logger.info "Killing VNC proxy" signal=(force ? 'KILL' : 'TERM') Process.kill(signal ,pid) sleep 1 begin Process.getpgid(pid) Process.kill('KILL', pid) rescue end if is_running? message="VNC server is still running" STDERR.puts message logger.error message return false end delete_token_dir else message="VNC server is not running" @logger.info message STDERR.puts message end true end def status if is_running? STDOUT.puts "VNC is running" true else STDOUT.puts "VNC is NOT running" false end end private def error(code, msg) if @options[:json_errors] return [code,OpenNebula::Error.new(msg).to_json] else return [code,msg] end end def create_token_dir delete_token_dir begin Dir.mkdir(@token_folder) if !File.exist?(@token_folder) rescue Exception => e @logger.error "Cannot create token folder" @logger.error e.message end end def delete_token_dir if File.exist?(@token_folder) begin Dir.glob("#{@token_folder}/*").each do |file| File.delete(file) end rescue => e @logger.error "Error deleting token folder" @logger.error e.message end end end def is_running? if File.exist?(@lock_file) pid=File.read(@lock_file).strip if system("ps #{pid} 1> /dev/null") return pid.to_i end @logger.info "Deleting stale lock file" File.delete(@lock_file) end false end alias_method :get_pid, :is_running? if RUBY_VERSION<'1.9' def spawn(*args) fork { command=args[0..-2] # Close stdin and point out and err to log file $stdin.close $stdout.reopen(VNC_LOG, "a") $stderr.reopen(VNC_LOG, "a") # Detach process from the parent Process.setsid exec(*command) } end end def start_daemon(cmd, log) options={ :pgroup => true, :in => :close, [:out, :err] => [log, "a"], :close_others => true } params=cmd.split(" ")+[options] pid=spawn( *params ) Process.detach(pid) pid end end fog-1.42.0/lib/fog/opennebula/requests/compute/image_pool.rb0000644000004100000410000000123013171001215024024 0ustar www-datawww-datamodule Fog module Compute class OpenNebula class Real def image_pool(filter = { }) images = ::OpenNebula::ImagePool.new(client) if filter[:mine].nil? images.info! else images.info_mine! end # if filter[:mine].nil? if not filter[:id].nil? images.each do |i| if filter[:id] == i.id return [ i ] # return an array with only one element - found image end end end images end #def image_pool end #class Real end #class OpenNebula end #module Compute end #module Fog fog-1.42.0/lib/fog/opennebula/requests/compute/vm_allocate.rb0000644000004100000410000000643313171001215024211 0ustar www-datawww-datamodule Fog module Compute class OpenNebula class Real def vm_allocate(attr={ }) if(attr[:flavor].nil?) raise(ArgumentError.new("Attribute flavor is nil! #{attr.inspect}")) end if(attr[:name].nil? || attr[:name].empty?) raise(ArgumentError.new("Attribute name is nil or empty! #{attr.inspect}")) end xml = ::OpenNebula::VirtualMachine.build_xml vm = ::OpenNebula::VirtualMachine.new(xml, client) rc = vm.allocate(attr[:flavor].to_s + "\nNAME=\"" + attr[:name] + "\"") # irb(main):050:0> vm.allocate(s.flavor.to_s + "\nNAME=altest5") # => # # irb(main):051:0> a = vm.allocate(s.flavor.to_s + "\nNAME=altest5") # => # # irb(main):052:0> a.class if(rc.is_a? ::OpenNebula::Error) raise(rc) end # -1 - do not change the owner vm.chown(-1,attr[:gid].to_i) unless attr[:gid].nil? # TODO # check if vm is created vmid.class == One error class vm.info! one = vm.to_hash data = {} data["onevm_object"] = vm data["status"] = vm.state data["state"] = vm.lcm_state_str data["id"] = vm.id data["uuid"] = vm.id data["gid"] = vm.gid data["name"] = one["VM"]["NAME"] unless one["VM"]["NAME"].nil? data["user"] = one["VM"]["UNAME"] unless one["VM"]["UNAME"].nil? data["group"] = one["VM"]["GNAME"] unless one["VM"]["GNAME"].nil? unless ( one["VM"]["TEMPLATE"].nil? ) then temp = one["VM"]["TEMPLATE"] data["cpu"] = temp["VCPU"] unless temp["VCPU"].nil? data["memory"] = temp["MEMORY"] unless temp["MEMORY"].nil? unless (temp["NIC"].nil?) then if one["VM"]["TEMPLATE"]["NIC"].is_a?(Array) data["mac"] = temp["NIC"][0]["MAC"] unless temp["NIC"][0]["MAC"].nil? data["ip"] = temp["NIC"][0]["IP"] unless temp["NIC"][0]["IP"].nil? else data["mac"] = temp["NIC"]["MAC"] unless temp["NIC"]["MAC"].nil? data["ip"] = temp["NIC"]["IP"] unless temp["NIC"]["IP"].nil? end end end data rescue => err raise(err) end end class Mock def vm_allocate(attr={ }) response = Excon::Response.new response.status = 200 id = rand(1000) ids = [] self.data['vms'].each do |vm| ids << vm['id'] if vm['id'] == id while ids.include?(id) id = rand(1000) end break end end data = {} data['id'] = id data['flavor'] = attr[:flavor] data['name'] = attr[:name] data['state'] = 'RUNNING' data['status'] = 3 self.data['vms'] << data data end end end end end fog-1.42.0/lib/fog/opennebula/requests/compute/list_groups.rb0000644000004100000410000000376413171001215024301 0ustar www-datawww-datamodule Fog module Compute class OpenNebula class Real def list_groups(filter = {}) groups=[] grouppool = ::OpenNebula::GroupPool.new(client) grouppool.info # { # "GROUP"=>{ # "ID"=>"0", # "NAME"=>"oneadmin", # "USERS"=>{"ID"=>["0", "1"]}, # "DATASTORE_QUOTA"=>{}, # "NETWORK_QUOTA"=>{}, # "VM_QUOTA"=>{}, # "IMAGE_QUOTA"=>{} # } #} grouppool.each do |group| filter_missmatch = false unless (filter.empty?) filter.each do |k,v| if group["#{k.to_s.upcase}"] && group["#{k.to_s.upcase}"] != v.to_s filter_missmatch = true break end end next if filter_missmatch end groups << {:id => group["ID"], :name => group["NAME"]} end groups end end class Mock def list_groups(filter={}) groups = [] net1 = mock_group "1", 'net1' net2 = mock_group "2", 'fogtest' grouppool = [net1, net2] grouppool.each do |group| filter_missmatch = false unless (filter.empty?) filter.each do |k,v| if group["#{k.to_s.upcase}"] && group["#{k.to_s.upcase}"] != v.to_s filter_missmatch = true break end end next if filter_missmatch end groups << {:id => group["ID"], :name => group["NAME"]} end groups end def mock_group id, name { "ID" => id, "NAME" => name, "UID" => "5", "GID" => "5", "DESCRIPTION" => "netDescription", "VLAN" => "5" } end end end end end fog-1.42.0/lib/fog/opennebula/requests/compute/vm_suspend.rb0000644000004100000410000000114413171001215024100 0ustar www-datawww-datamodule Fog module Compute class OpenNebula class Real def vm_suspend(id) vmpool = ::OpenNebula::VirtualMachinePool.new(client) vmpool.info!(-2,id,id,-1) vmpool.each do |vm| vm.suspend end end end class Mock def vm_suspend(id) response = Excon::Response.new response.status = 200 self.data['vms'].each do |vm| if id == vm['id'] vm['state'] = 'LCM_INIT' vm['status'] = 5 end end end end end end end fog-1.42.0/lib/fog/opennebula/requests/compute/list_vms.rb0000644000004100000410000001146613171001215023565 0ustar www-datawww-data#{"VM"=>{"ID"=>"30", "UID"=>"0", "GID"=>"0", "UNAME"=>"oneadmin", "GNAME"=>"oneadmin", "NAME"=>"m1.small-30", "PERMISSIONS"=>{"OWNER_U"=>"1", "OWNER_M"=>"1", "OWNER_A"=>"0", "GROUP_U"=>"0", "GROUP_M"=>"0", "GROUP_A"=>"0", "OTHER_U"=>"0", "OTHER_M"=>"0", "OTHER_A"=>"0"}, "LAST_POLL"=>"0", "STATE"=>"1", "LCM_STATE"=>"0", "RESCHED"=>"0", "STIME"=>"1395937874", "ETIME"=>"0", "DEPLOY_ID"=>{}, "MEMORY"=>"0", "CPU"=>"0", "NET_TX"=>"0", "NET_RX"=>"0", "TEMPLATE"=>{"AUTOMATIC_REQUIREMENTS"=>"!(PUBLIC_CLOUD = YES)", "CONTEXT"=>{"DISK_ID"=>"2", "EC2_KEYNAME"=>"foreman-1b028a80e-2c8e-4582-a718-960ab6531eb3", "EC2_PUBLIC_KEY"=>"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDN/8DRFSrYoox1wqZfOUGpDxP4C906kgaHEQ3UEV0536VCBmGgG4flQ3C4Smf9zYrWPuQNqLt7KHzODlrWcSj9Bo98u7HbSUW386A3mIXJ8ujUxTQsIoKb0U+/eKjTCB21mjr8RFKAADRKtCQQkNMvJxrZ3/05QDvproprukyFY5R8se6EMTLit46s33QJaVF82q/Bbhzqd2cfx72TusXUp8bo/w5SBgr4VjFewke82VD6flBMLACkAQhDh200fwsjaEb4NUuUSvS5gfha3okjlVvcSLBaDkQftW0/VuUTjDi7wZbBKeu1SS2MpKTYBDrsi+bcmlJmvbwadBncCbGh foreman-1b028a80e-2c8e-4582-a718-960ab6531eb3", "ETH0_IP"=>"192.168.17.0", "ETH0_MAC"=>"02:00:c0:a8:11:00", "ETH0_MASK"=>"255.255.255.0", "ETH0_NETWORK"=>"192.168.17.0", "NETWORK"=>"YES", "TARGET"=>"hdb"}, "CPU"=>"1", "DISK"=>[{"CLONE"=>"YES", "CLONE_TARGET"=>"SYSTEM", "DATASTORE"=>"default", "DATASTORE_ID"=>"1", "DEV_PREFIX"=>"hd", "DISK_ID"=>"0", "DRIVER"=>"qcow2", "IMAGE"=>"testimage", "IMAGE_ID"=>"0", "LN_TARGET"=>"NONE", "READONLY"=>"NO", "SAVE"=>"NO", "SIZE"=>"218", "SOURCE"=>"/var/lib/one//datastores/1/5c3ff6087ee30b4f5ac7626ed66cfcc6", "TARGET"=>"hda", "TM_MAD"=>"shared", "TYPE"=>"FILE"}, {"CLONE"=>"YES", "CLONE_TARGET"=>"SYSTEM", "DATASTORE"=>"default", "DATASTORE_ID"=>"1", "DEV_PREFIX"=>"hd", "DISK_ID"=>"1", "IMAGE"=>"ec2-c29e8235-249e-4a1e-b818-5703140a1133", "IMAGE_ID"=>"2", "IMAGE_UNAME"=>"oneadmin", "LN_TARGET"=>"NONE", "READONLY"=>"NO", "SAVE"=>"NO", "SIZE"=>"1024", "SOURCE"=>"/var/lib/one//datastores/1/346ee4cb31e9a3a6d119add759cf2824", "TARGET"=>"hdc", "TM_MAD"=>"shared", "TYPE"=>"FILE"}], "MEMORY"=>"512", "NIC"=>{"BRIDGE"=>"br0", "IP"=>"192.168.17.0", "IP6_LINK"=>"fe80::400:c0ff:fea8:1100", "MAC"=>"02:00:c0:a8:11:00", "NETWORK"=>"vlan17", "NETWORK_ID"=>"0", "NETWORK_UNAME"=>"oneadmin", "NIC_ID"=>"0", "VLAN"=>"YES", "VLAN_ID"=>"17"}, "TEMPLATE_ID"=>"3", "VMID"=>"30"}, "USER_TEMPLATE"=>{"EC2_INSTANCE_TYPE"=>"m1.small", "EC2_TAGS"=>{"NAME"=>"test.example.com"}, "SCHED_MESSAGE"=>"Tue Apr 1 15:01:22 2014 : No host with enough capacity to deploy the VM"}, "HISTORY_RECORDS"=>{}}} module Fog module Compute class OpenNebula class Real def list_vms(filter={}) vms=[] vmpool = ::OpenNebula::VirtualMachinePool.new(client) if filter[:id].nil? vmpool.info!(-2,-1,-1,-1) elsif filter[:id] filter[:id] = filter[:id].to_i if filter[:id].is_a?(String) vmpool.info!(-2, filter[:id], filter[:id], -1) end # filter[:id].nil? vmpool.each do |vm| one = vm.to_hash data = {} data["onevm_object"] = vm data["status"] = vm.state data["state"] = vm.lcm_state_str data["id"] = vm.id data["gid"] = vm.gid data["uuid"] = vm.id data["name"] = one["VM"]["NAME"] unless one["VM"]["NAME"].nil? data["user"] = one["VM"]["UNAME"] unless one["VM"]["UNAME"].nil? data["group"] = one["VM"]["GNAME"] unless one["VM"]["GNAME"].nil? unless ( one["VM"]["TEMPLATE"].nil? ) then data["cpu"] = one["VM"]["TEMPLATE"]["VCPU"] unless one["VM"]["TEMPLATE"]["VCPU"].nil? data["memory"] = one["VM"]["TEMPLATE"]["MEMORY"] unless one["VM"]["TEMPLATE"]["MEMORY"].nil? unless (one["VM"]["TEMPLATE"]["NIC"].nil?) then if one["VM"]["TEMPLATE"]["NIC"].is_a?(Array) data["ip"]=one["VM"]["TEMPLATE"]["NIC"][0]["IP"] data["mac"]=one["VM"]["TEMPLATE"]["NIC"][0]["MAC"] else data["ip"]=one["VM"]["TEMPLATE"]["NIC"]["IP"] unless one["VM"]["TEMPLATE"]["NIC"]["IP"].nil? data["mac"]=one["VM"]["TEMPLATE"]["NIC"]["MAC"] unless one["VM"]["TEMPLATE"]["NIC"]["MAC"].nil? end end # unless (one["VM"]["TEMPLATE"]["NIC"].nil?) then end # unless ( one["VM"]["TEMPLATE"].nil? ) then vms << data end # vmpool.each vms end # def list_vms end # class Real module Shared private end class Mock def list_vms(filter = {}) vms = [] self.data['vms'].each do |vm| if filter[:id].nil? vms << vm elsif filter[:id] == vm['id'] vms << vm end end vms end end end end end fog-1.42.0/lib/fog/opennebula/requests/compute/vm_resume.rb0000644000004100000410000000102513171001215023715 0ustar www-datawww-datamodule Fog module Compute class OpenNebula class Real def vm_resume(id) vmpool = ::OpenNebula::VirtualMachinePool.new(client) vmpool.info!(-2,id,id,-1) vmpool.each do |vm| vm.resume end end end class Mock def vm_resume(id) self.data['vms'].each do |vm| if id == vm['id'] vm['state'] = 'RUNNING' vm['status'] = 3 end end end end end end end fog-1.42.0/lib/fog/opennebula/requests/compute/list_networks.rb0000644000004100000410000000551713171001215024634 0ustar www-datawww-data#1.9.3-p545 :017 > netpool.entries.first.to_hash # => {"VNET"=>{"ID"=>"4", "UID"=>"0", "GID"=>"0", "UNAME"=>"oneadmin", "GNAME"=>"oneadmin", "NAME"=>"vlan116", "PERMISSIONS"=>{"OWNER_U"=>"1", "OWNER_M"=>"1", "OWNER_A"=>"0", "GROUP_U"=>"0", "GROUP_M"=>"0", "GROUP_A"=>"0", "OTHER_U"=>"0", "OTHER_M"=>"0", "OTHER_A"=>"0"}, "CLUSTER_ID"=>"-1", "CLUSTER"=>{}, "TYPE"=>"0", "BRIDGE"=>"br116", "VLAN"=>"0", "PHYDEV"=>{}, "VLAN_ID"=>{}, "GLOBAL_PREFIX"=>{}, "SITE_PREFIX"=>{}, "RANGE"=>{"IP_START"=>"192.168.0.1", "IP_END"=>"192.168.0.254"}, "TOTAL_LEASES"=>"6", "TEMPLATE"=>{"NETWORK_MASK"=>"255.255.0.0"}}} # module Fog module Compute class OpenNebula class Real def list_networks(filter = { }) networks=[] netpool = ::OpenNebula::VirtualNetworkPool.new(client) if filter[:id].nil? netpool.info!(-2,-1,-1) elsif filter[:id] filter[:id] = filter[:id].to_i if filter[:id].is_a?(String) netpool.info!(-2, filter[:id], filter[:id]) end # if filter[:id].nil? netpool.each do |network| if filter[:network] && filter[:network].is_a?(String) && !filter[:network].empty? next if network.to_hash["VNET"]["NAME"] != filter[:network] end if filter[:network_uname] && filter[:network_uname].is_a?(String) && !filter[:network_uname].empty? next if network.to_hash["VNET"]["UNAME"] != filter[:network_uname] end if filter[:network_uid] && filter[:network_uid].is_a?(String) && !filter[:network_uid].empty? next if network.to_hash["VNET"]["UID"] != filter[:network_uid] end networks << network_to_attributes(network.to_hash) end networks end def network_to_attributes(net) return if net.nil? h = { :id => net["VNET"]["ID"], :name => net["VNET"]["NAME"], :uid => net["VNET"]["UID"], :uname => net["VNET"]["UNAME"], :gid => net["VNET"]["GID"], } h[:description] = net["VNET"]["TEMPLATE"]["DESCRIPTION"] unless net["VNET"]["TEMPLATE"]["DESCRIPTION"].nil? h[:vlan] = net["VNET"]["VLAN_ID"] unless (net["VNET"]["VLAN_ID"].nil? || net["VNET"]["VLAN_ID"].empty?) return h end end class Mock def list_networks(filters={}) net1 = mock_network 'fogtest' net2 = mock_network 'net2' [net1, net2] end def mock_network name { :id => "5", :name => name, :uid => "5", :uname => "mock", :gid => "5", :description => "netDescription", :vlan => "5" } end end end end end fog-1.42.0/lib/fog/opennebula/requests/compute/template_pool.rb0000644000004100000410000001024413171001215024562 0ustar www-datawww-data# t.template_str # CPU="0.2" # VCPU="2" # MEMORY="2048" # SCHED_REQUIREMENTS="NFS=\"true\"" # SCHED_DS_REQUIREMENTS="NAME=\"local\"" # DISK=[ # DEV_PREFIX="vd", # DRIVER="qcow2", # IMAGE="base", # IMAGE_ID="355", # IMAGE_UNAME="oneadmin", # TARGET="vda" ] # GRAPHICS=[ # LISTEN="0.0.0.0", # TYPE="VNC" ] # NIC=[ # MODEL="virtio", # NETWORK="vlan2-2", # NETWORK_UNAME="oneadmin" ] # OS=[ # ARCH="x86_64", # BOOT="network,hd" ] # RAW=[ # DATA="core2duo", # TYPE="kvm" ] module Fog module Compute class OpenNebula class Real def template_pool(filter = { }) templates = ::OpenNebula::TemplatePool.new(client) if filter[:id].nil? templates.info!(-2,-1,-1) elsif filter[:id] filter[:id] = filter[:id].to_i if filter[:id].is_a?(String) templates.info!(-2, filter[:id], filter[:id]) end # if filter[:id].nil? templates = templates.map do |t| # filtering by name # done here, because OpenNebula:TemplatePool does not support something like .delete_if if filter[:name] && filter[:name].is_a?(String) && !filter[:name].empty? next if t.to_hash["VMTEMPLATE"]["NAME"] != filter[:name] end if filter[:uname] && filter[:uname].is_a?(String) && !filter[:uname].empty? next if t.to_hash["VMTEMPLATE"]["UNAME"] != filter[:uname] end if filter[:uid] && filter[:uid].is_a?(String) && !filter[:uid].empty? next if t.to_hash["VMTEMPLATE"]["UID"] != filter[:uid] end h = Hash[ :id => t.to_hash["VMTEMPLATE"]["ID"], :name => t.to_hash["VMTEMPLATE"]["NAME"], :content => t.template_str, :USER_VARIABLES => "" # Default if not set in template ] h.merge! t.to_hash["VMTEMPLATE"]["TEMPLATE"] # h["NIC"] has to be an array of nic objects nics = h["NIC"] unless h["NIC"].nil? h["NIC"] = [] # reset nics to a array if nics.is_a? Array nics.each do |n| if n["NETWORK_ID"] vnet = networks.get(n["NETWORK_ID"].to_s) elsif n["NETWORK"] vnet = networks.get_by_name(n["NETWORK"].to_s) else next end h["NIC"] << interfaces.new({ :vnet => vnet, :model => n["MODEL"] || "virtio" }) end elsif nics.is_a? Hash nics["model"] = "virtio" if nics["model"].nil? #nics["uuid"] = "0" if nics["uuid"].nil? # is it better is to remove this NIC? n = networks.get_by_filter({ :id => nics["NETWORK_ID"], :network => nics["NETWORK"], :network_uname => nics["NETWORK_UNAME"], :network_uid => nics["NETWORK_UID"] }) n.each do |i| h["NIC"] << interfaces.new({ :vnet => i }) end else # should i break? end # every key should be lowercase ret_hash = {} h.each_pair do |k,v| ret_hash.merge!({k.downcase => v}) end ret_hash end templates.delete nil raise Fog::Compute::OpenNebula::NotFound, "Flavor/Template not found" if templates.empty? templates end #def template_pool end #class Real class Mock def template_pool(filter = { }) nic1 = Mock_nic.new nic1.vnet = networks.first self.data['template_pool'] self.data['template_pool'].each do |tmpl| tmpl['nic'][0] = nic1 end self.data['template_pool'] end class Mock_nic attr_accessor :vnet def id 2 end def name "fogtest" end def model "virtio-net" end end end #class Mock end #class OpenNebula end #module Compute end #module Fog fog-1.42.0/lib/fog/opennebula/requests/compute/vm_disk_snapshot.rb0000644000004100000410000000113013171001215025263 0ustar www-datawww-datamodule Fog module Compute class OpenNebula class Real def vm_disk_snapshot(id, disk_id, image_name) vmpool = ::OpenNebula::VirtualMachinePool.new(client) vmpool.info!(-2,id,id,-1) rc = 0 vmpool.each do |vm| rc = vm.disk_snapshot_create(disk_id, image_name) if(rc.is_a? ::OpenNebula::Error) raise(rc) end end rc end #def vm_disk_snapshot end class Mock def vm_disk_snapshot(id, disk_id, image_name) end end end end end fog-1.42.0/lib/fog/opennebula/core.rb0000644000004100000410000000016713171001215017322 0ustar www-datawww-datarequire 'fog/core' module Fog module OpenNebula extend Fog::Provider service(:compute, 'Compute') end end fog-1.42.0/lib/fog/opennebula/models/0000755000004100000410000000000013171001215017324 5ustar www-datawww-datafog-1.42.0/lib/fog/opennebula/models/compute/0000755000004100000410000000000013171001215021000 5ustar www-datawww-datafog-1.42.0/lib/fog/opennebula/models/compute/interface.rb0000644000004100000410000000121413171001215023263 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class OpenNebula class Interface < Fog::Model identity :id attribute :vnet attribute :model attribute :name attribute :mac def save raise Fog::Errors::Error.new('Creating a new interface is not yet implemented. Contributions welcome!') end def vnetid return vnet end def persisted? mac end def destroy raise Fog::Errors::Error.new('Destroying an interface is not yet implemented. Contributions welcome!') end end end end end fog-1.42.0/lib/fog/opennebula/models/compute/servers.rb0000644000004100000410000000101213171001215023010 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/opennebula/models/compute/server' module Fog module Compute class OpenNebula class Servers < Fog::Collection model Fog::Compute::OpenNebula::Server def all(filter={}) load(service.list_vms(filter)) end def get(id) data = service.list_vms({:id => id}) new data.first unless data.empty? end def shutdown(id) service.vm_shutdown(id) end end end end end fog-1.42.0/lib/fog/opennebula/models/compute/network.rb0000644000004100000410000000165513171001215023025 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class OpenNebula class Network < Fog::Model identity :id attribute :name attribute :uname attribute :uid attribute :gid attribute :description attribute :vlan def description attributes[:description] || "" end def vlan attributes[:vlan] || "" end def save raise Fog::Errors::Error.new('Creating a new network is not yet implemented. Contributions welcome!') end def shutdown raise Fog::Errors::Error.new('Shutting down a new network is not yet implemented. Contributions welcome!') end def to_label ret = "" ret += "#{description} - " unless description.empty? ret += "VLAN #{vlan} - " unless vlan.empty? ret += "#{name}" end end end end end fog-1.42.0/lib/fog/opennebula/models/compute/interfaces.rb0000644000004100000410000000037113171001215023451 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/opennebula/models/compute/interface' module Fog module Compute class OpenNebula class Interfaces < Fog::Collection model Fog::Compute::OpenNebula::Interface end end end end fog-1.42.0/lib/fog/opennebula/models/compute/flavors.rb0000644000004100000410000000162213171001215023002 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/opennebula/models/compute/flavor' module Fog module Compute class OpenNebula class Flavors < Fog::Collection model Fog::Compute::OpenNebula::Flavor def all data = service.template_pool load(data) end def get(flavor_id) data = service.template_pool({:id => flavor_id}) load(data).first rescue Fog::Compute::OpenNebula::NotFound nil end def get_by_name(flavor_name) data = service.template_pool({:name => flavor_name}) load(data) rescue Fog::Compute::OpenNebula::NotFound nil end def get_by_filter(flavor_filter) data = service.template_pool(flavor_filter) load(data) rescue Fog::Compute::OpenNebula::NotFound nil end end end end end fog-1.42.0/lib/fog/opennebula/models/compute/group.rb0000644000004100000410000000056213171001215022464 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class OpenNebula class Group < Fog::Model identity :id attribute :name def save raise Fog::Errors::Error.new('Creating a new group is not yet implemented. Contributions welcome!') end def to_label name end end end end end fog-1.42.0/lib/fog/opennebula/models/compute/groups.rb0000644000004100000410000000122313171001215022642 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/opennebula/models/compute/group' module Fog module Compute class OpenNebula class Groups < Fog::Collection model Fog::Compute::OpenNebula::Group def all(filter={}) load(service.list_groups(filter)) end def get(id) group = self.all({:id => id}) if group.length > 1 raise Fog::Errors::Error.new("groups.get should return only one group, not #{group.length}!") end group.first end def get_by_name(str) self.all({:name => str}) end end end end end fog-1.42.0/lib/fog/opennebula/models/compute/flavor.rb0000644000004100000410000001054613171001215022624 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class OpenNebula class Flavor < Fog::Model identity :id attribute :name attribute :content attribute :cpu attribute :vcpu attribute :memory attribute :sched_requirements attribute :sched_rank attribute :sched_ds_requirements attribute :sched_ds_rank attribute :disk attribute :nic attribute :os attribute :graphics attribute :raw attribute :context attribute :user_variables def to_label "#{name} -- #{vcpu} VCPU - #{memory}MB Mem" end def to_s "" + get_cpu \ + get_vcpu \ + get_memory \ + get_disk \ + get_nic \ + get_os \ + get_graphics \ + get_raw \ + get_sched_requirements \ + get_sched_ds_requirements \ + get_sched_rank \ + get_sched_ds_rank \ + get_context \ + get_user_variables end def get_cpu return "CPU=#{vcpu.to_f/10}\n" unless cpu return "CPU=#{vcpu}\n" if cpu.to_i > vcpu.to_i "CPU=#{cpu}\n" end def get_vcpu self.vcpu = 1 unless vcpu "VCPU=#{vcpu}\n" end def get_memory self.memory = 128 unless memory "MEMORY=#{memory}\n" end def get_raw return "" unless raw ret = "RAW=#{raw}\n" ret.gsub!(/\{/, '[') ret.gsub!(/\}/, ']') ret.gsub!(/=>/,'=') ret end def get_disk return "" unless disk ret = "" if disk.is_a? Array disk.each do |d| ret += "DISK=#{d}\n" end else ret = "DISK=#{disk}\n" end ret.gsub!(/\{/, '[') ret.gsub!(/\}/, ']') ret.gsub!(/>/,'') ret end def get_os return "" unless os ret = "OS=#{os}\n" ret.gsub!(/\{/, '[') ret.gsub!(/\}/, ']') ret.gsub!(/>/,'') ret end def get_graphics return "" unless graphics ret = "GRAPHICS=#{graphics}\n" ret.gsub!(/\{/, '[') ret.gsub!(/\}/, ']') ret.gsub!(/>/,'') ret end def get_nic # NIC=[MODEL="virtio",NETWORK="vlan17",NETWORK_UNAME="oneadmin"] return "" if nic.nil? ret = "" if nic.is_a? Array nic.each do |n| ret += %Q|NIC=[MODEL="#{n.model}",NETWORK_ID="#{n.vnet.id}"]\n| unless n.vnet.nil? end end #ret.gsub!(/\{/, '[') #ret.gsub!(/\}/, ']') #ret.gsub!(/>/,'') ret end def get_sched_ds_requirements return "" unless sched_ds_requirements %Q|SCHED_DS_REQUIREMENTS="#{sched_ds_requirements.gsub(/"/){ %q(\") }}"\n| end def get_sched_ds_rank return "" unless sched_ds_rank %Q|SCHED_DS_RANK="#{sched_ds_rank.gsub(/"/){ %q(\") }}"\n| end def get_sched_requirements return "" unless sched_requirements %Q|SCHED_REQUIREMENTS="#{sched_requirements.gsub(/"/){ %q(\") }}"\n| end def get_sched_rank return "" unless sched_rank %Q|SCHED_RANK="#{sched_rank.gsub(/"/){ %q(\") }}"\n| end def get_context return "" unless context if context.is_a? String return %Q|CONTEXT= [ #{context} ]\n| elsif context.is_a? Hash ret = "" context.each do |key, value| ret << %Q|"#{key}"="#{value}",| end ret.chop! if ret.end_with?(',') return %Q|CONTEXT=[ #{ret} ]\n| else return "" end end def get_user_variables return "" unless user_variables if user_variables.is_a? String return %Q|#{user_variables}\n| elsif user_variables.is_a? Hash ret = "" user_variables.each do |key, value| ret << %Q|#{key}="#{value}"\n| end return ret else return "" end end end end end end fog-1.42.0/lib/fog/opennebula/models/compute/server.rb0000644000004100000410000000376513171001215022646 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class OpenNebula class Server < Fog::Compute::Server identity :id attribute :template_str attribute :name attribute :uuid attribute :state attribute :status attribute :ip attribute :mac attribute :vcpu attribute :cpu attribute :memory attribute :user attribute :gid attribute :group attribute :onevm_object attribute :flavor def save merge_attributes(service.vm_allocate(attributes)) end # only for integration in foreman # needed by formbuilder # should be handled by foreman and not by fog def vminterfaces [] end # only for integration in foreman # needed by formbuilder # should be handled by foreman and not from by fog def vminterfaces_attributes=(attributes) true end def vm_ip_address ip end def private_ip_address ip end def public_ip_address ip end def vm_mac_address mac end def start if status == 4 service.vm_resume(id) end true end def stop Fog::Logger.warning("stop VM: ID:#{id}") service.vm_stop(id) end def suspend service.vm_suspend(id) end def resume service.vm_resume(id) end def destroy service.vm_destroy(id) end def ready? (status == 3) end # only for integration in foreman # needed by formbuilder # should be handled by foreman and not by fog def template_id "" end def console_output requires :id service.get_vnc_console(id, "vnc", onevm_object) end end end end end fog-1.42.0/lib/fog/opennebula/models/compute/networks.rb0000644000004100000410000000142513171001215023203 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/opennebula/models/compute/network' module Fog module Compute class OpenNebula class Networks < Fog::Collection model Fog::Compute::OpenNebula::Network def all(filter={}) self.get_by_filter(filter) end def get(id) data = service.list_networks({:id => id}) load(data).first rescue Fog::Compute::OpenNebula::NotFound nil end def get_by_name(network) data = service.list_networks({:network => network}) load(data).first rescue Fog::Compute::OpenNebula::NotFound nil end def get_by_filter(filter) load(service.list_networks(filter)) end end end end end fog-1.42.0/lib/fog/opennebula/README.md0000644000004100000410000000554513171001215017331 0ustar www-datawww-data# Getting started with OpenNebula (one) Fog provider [OpenNebula](http://www.opennebula.org) provides ruby bindings to access the xml-rpc The opennebula fog extensions provides examples for using Fog with OpenNebula (4.4). **Note:** This provider is under construction! This means everything that is provided should work without problems, but there are many features not available yet. Please contribute! ## Requirements For working with this provider the following pre-requisites are needed: * Ruby version 1.8.x or 1.9.x * `fog` gem * Working OpenNebula instance with XML-RPC and credentials * This version is tested with OpenNebula 4.4 and the opennebula gem dependency is hardcoded to this version. it should work with version 4.6, but is not tested. ## Examples General proceeding: * Connect to one-rpc * create new vm object * fetch a template/flavor from one (this template should be predefined) * assigne the flavor/template to the vm * change the attributes of this flavor/template (name, cpu, memory, nics....) * save/instantiate the vm ```ruby require 'fog' # connect to your one rpc con = Fog::Compute.new( { :provider => 'OpenNebula', :opennebula_username => 'user', :opennebula_password => 'password', :opennebula_endpoint => 'http://oned.domain:2633/RPC2' } ) # list all vms con.servers # list all flavors (templates in OpenNebula slang) con.flavors # get flavor with id 4 con.flavors.get 4 # list all Virtual Networks con.networks con.networks.get 2 # get all usergroups con.groups # create a new vm (creates the object, the vm is not instantiated yet) newvm = con.servers.new # set the flavor of the vm newvm.flavor = con.flavors.get 4 # set the name of the vm newvm.name = "FooBarVM" # set the groupid of the vm newvm.gid = 0 # set cores and memory (MB) newvm.flavor.vcpu = 2 newvm.flavor.memory = 256 # create a new network interface attached to the network with id 1 and virtio as driver/model network = client.networks.get(1) nic = con.interfaces.new({ :vnet => network, :model => "virtio"}) # Attach the new nic to our vm newvm.flavor.nic = [ nic ] # instantiat the new vm newvm.save ``` ## Features tbd ## not working yet * con.groups.get 4 _AND_ everything not mentioned in features or examples ;) ## Troubleshooting * ArgumentError: opennebula is not a recognized compute provider * is the correct gem version included? ## Additional Resources * [Fog cloud library](http://fog.io) * [Fog documentation](http://rubydoc.info/gems/fog) * [Fog Github repo](https://github.com/fog/fog) * [Fog Release Notes](https://github.com/fog/fog/blob/master/changelog.txt) * [Ruby OpenNebula Cloud API](http://docs.opennebula.org/stable/integration/system_interfaces/ruby.html) * [OpenNebula ruby bindings](http://docs.opennebula.org/doc/stable/oca/ruby/) ## Support and Feedback Please contribute and send feedback! Just do it here! fog-1.42.0/lib/fog/opennebula/compute.rb0000644000004100000410000000713013171001215020043 0ustar www-datawww-datarequire 'fog/opennebula/core' module Fog module Compute class OpenNebula < Fog::Service requires :opennebula_endpoint recognizes :opennebula_username, :opennebula_password model_path 'fog/opennebula/models/compute' model :server collection :servers model :network collection :networks model :flavor collection :flavors model :interface collection :interfaces model :group collection :groups request_path 'fog/opennebula/requests/compute' request :list_vms request :list_groups request :list_networks request :vm_allocate request :vm_destroy request :get_vnc_console request :vm_resume request :vm_suspend request :vm_stop request :template_pool request :vm_disk_snapshot request :vm_shutdown request :image_pool class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = { "vms" => [ { "onevm_object" => "", "status" => "RUNNING", "state" => "3", "id" => 4, "uuid" => "5", "gid" => "5", "name" => "MockVM", "user" => "MockUser", "group" => "MockGroup", "cpu" => "2", "memory" => "1024", "mac" => "00:01:02:03:04:05", "ip" => "1.1.1.1" } ], "image_pool" => [ {} ], "template_pool" => [ { "content" => %Q{ NAME = mock-vm MEMORY = 512 VCPU = 1 CPU = 1 }, "id" => 1, "name" => 'mock', "cpu" => 1, "vcpu" => 1, "memory" => 512, "sched_requirements" => 'CPUSPEED > 1000', "sched_rank" => 'FREECPU', "sched_ds_requirements" => "NAME=mock", "sched_ds_rank" => "FREE_MB", "disk" => {}, "nic" => {}, "os" => { 'ARCH' => 'x86_64' }, "graphics" => {}, "raw" => %|["DATA"=>"core2duo", "TYPE"=>"kvm"]|, "context" => {}, "user_variables" => {} } ] } end end def self.reset @data = nil end include Collections def initialize(options={}) @opennebula_endpoint = options[:opennebula_endpoint] @opennebula_username = options[:opennebula_username] @opennebula_password = options[:opennebula_password] require 'opennebula' end def client return @client end def data self.class.data[@opennebula_endpoint] end def reset_data self.class.data.delete(@opennebula_endpoint) end end class Real include Collections def client return @client end def initialize(options={}) require 'opennebula' @client = ::OpenNebula::Client.new("#{options[:opennebula_username]}:#{options[:opennebula_password]}", options[:opennebula_endpoint]) end end end end end fog-1.42.0/lib/fog/bluebox/0000755000004100000410000000000013171001215015351 5ustar www-datawww-datafog-1.42.0/lib/fog/bluebox/blb.rb0000644000004100000410000000446313171001215016444 0ustar www-datawww-datarequire 'fog/bluebox/core' module Fog module Bluebox class BLB < Fog::Service requires :bluebox_api_key, :bluebox_customer_id recognizes :bluebox_host, :bluebox_port, :bluebox_scheme, :persistent model_path 'fog/bluebox/models/blb' model :lb_application collection :lb_applications model :lb_service collection :lb_services model :lb_backend collection :lb_backends request_path 'fog/bluebox/requests/blb' request :get_lb_application request :get_lb_applications request :get_lb_service request :get_lb_services request :get_lb_backend request :get_lb_backends request :add_machine_to_lb_application request :add_machine_to_lb_backend request :remove_machine_from_lb_backend request :update_lb_backend_machine class Mock end class Real def initialize(options={}) @bluebox_api_key = options[:bluebox_api_key] @bluebox_customer_id = options[:bluebox_customer_id] @connection_options = options[:connection_options] || {} @host = options[:bluebox_host] || "boxpanel.bluebox.net" @persistent = options[:persistent] || false @port = options[:bluebox_port] || 443 @scheme = options[:bluebox_scheme] || 'https' @connection = Fog::XML::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def reload @connection.reset end def request(params) params[:headers] ||= {} params[:headers].merge!({ 'Authorization' => "Basic #{Base64.encode64([@bluebox_customer_id, @bluebox_api_key].join(':')).delete("\r\n")}" }) begin response = @connection.request(params) rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Compute::Bluebox::NotFound.slurp(error) else error end end unless response.body.empty? || params[:headers]['Accept'] == 'text/plain' response.body = Fog::JSON.decode(response.body) end response end end end end end fog-1.42.0/lib/fog/bluebox/requests/0000755000004100000410000000000013171001215017224 5ustar www-datawww-datafog-1.42.0/lib/fog/bluebox/requests/dns/0000755000004100000410000000000013171001215020010 5ustar www-datawww-datafog-1.42.0/lib/fog/bluebox/requests/dns/get_records.rb0000644000004100000410000000230713171001215022637 0ustar www-datawww-datamodule Fog module DNS class Bluebox class Real require 'fog/bluebox/parsers/dns/get_records' # Get all the DNS records across all the DNS zones for this account # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * 'addresses'<~Array> - Ip addresses for the slice # * 'backup-id'<~Integer> - Id of backup slice was booted from # * 'flavor_id'<~Integer> - Id of flavor slice was booted from # * 'id'<~Integer> - Id of the slice # * 'image-id'<~Integer> - Id of image slice was booted from # * 'name'<~String> - Name of the slice # * 'progress'<~Integer> - Progress of current action, in percentage # * 'status'<~String> - Current status of the slice def get_records(zone_id) request( :expects => 200, :method => 'GET', :parser => Fog::Parsers::DNS::Bluebox::GetRecords.new, :path => "/api/domains/#{zone_id}/records.xml" ) end end class Mock def get_records Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/bluebox/requests/dns/get_zone.rb0000644000004100000410000000236113171001215022151 0ustar www-datawww-datamodule Fog module DNS class Bluebox class Real require 'fog/bluebox/parsers/dns/get_zone' # Get details of a DNS zone # # ==== Parameters # * zone_id<~Integer> - Id of zone to lookup # # ==== Returns # * response<~Excon::Response>: # * hash<~Hash>: # * 'name'<~String> - The name of the zone # * 'serial'<~Integer> - Serial number of the zone # * 'ttl'<~Integer> - TimeToLive (ttl) for the domain, in seconds # * 'retry'<~Integer> - Retry interval for the domain, in seconds # * 'record-count'<~Integer> - Number of records in the zone # * 'id'<~String> - Id for the zone # * 'refresh'<~Integer> - Refresh interval for the zone # * 'minimum'<~Integer> - Minimum refresh interval for the zone def get_zone(zone_id) request( :expects => 200, :method => 'GET', :parser => Fog::Parsers::DNS::Bluebox::GetZone.new, :path => "/api/domains/#{zone_id}.xml" ) end end class Mock def get_zone(zone_id) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/bluebox/requests/dns/create_record.rb0000644000004100000410000000303613171001215023140 0ustar www-datawww-datamodule Fog module DNS class Bluebox class Real require 'fog/bluebox/parsers/dns/create_record' # Create a new record in a DNS zone # ==== Parameters # * type<~String> - type of DNS record to create (A, CNAME, etc) # * name<~String> - host name this DNS record is for # * content<~String> - data for the DNS record (ie for an A record, the IP address) # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'name'<~String> - as above # * 'id'<~Integer> - Id of zone/domain - used in future API calls for this zone # * 'ttl'<~Integer> - as above # * 'data'<~String> - as above # * 'active'<~String> - as above # * 'aux'<~String> - as above def create_record(zone_id, type, name, content, options={}) body = %Q{#{type}#{name}#{content}} options.each do |k,v| body += %Q{<#{k}>#{v}} end body += %Q{} request( :body => body, :expects => 202, :method => 'POST', :parser => Fog::Parsers::DNS::Bluebox::CreateRecord.new, :path => "/api/domains/#{zone_id}/records.xml" ) end end class Mock def create_record(zone_id, type, name, content) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/bluebox/requests/dns/get_zones.rb0000644000004100000410000000251013171001215022330 0ustar www-datawww-datamodule Fog module DNS class Bluebox class Real require 'fog/bluebox/parsers/dns/get_zones' # Get list of all DNS zones hosted on Bluebox (for this account) # # ==== Returns # * response<~Excon::Response>: # * 'records'<~Array> # * 'record' # * 'name'<~String> - name of the zone # * 'serial'<~Integer> - Serial # for the zone # * 'ttl'<~Integer> - TTL for the zone record in seconds # * 'retry'<~Integer> - Retry interval for the zone record in seconds # * 'expires'<~Integer> - Expiration interval for the zone record in seconds # * 'record-count'<~Integer> - # of records in this zone # * 'id'<~String> - Id for the zone record # * 'refresh'<~Integer> - default refresh interval for this zone, in seconds # * 'minimum'<~Integer> - minimum value for intervals for this zone, in seconds def get_zones request( :expects => 200, :method => 'GET', :parser => Fog::Parsers::DNS::Bluebox::GetZones.new, :path => '/api/domains.xml' ) end end class Mock def get_zones Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/bluebox/requests/dns/create_zone.rb0000644000004100000410000000366413171001215022644 0ustar www-datawww-datamodule Fog module DNS class Bluebox class Real require 'fog/bluebox/parsers/dns/create_zone' # Create a new DNS zone # ==== Parameters # * 'name'<~String> - The name of the zone # * 'ttl'<~Integer> - TimeToLive (ttl) for the domain, in seconds # * 'retry'<~Integer> - Retry interval for the domain, in seconds # * 'refresh'<~Integer> - Refresh interval for the zone # * 'minimum'<~Integer> - Minimum refresh interval for the zone # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'name'<~String> - The name of the zone # * 'serial'<~Integer> - Serial number of the zone # * 'ttl'<~Integer> - TimeToLive (ttl) for the domain, in seconds # * 'retry'<~Integer> - Retry interval for the domain, in seconds # * 'record-count'<~Integer> - Number of records in the zone # * 'id'<~String> - Id for the zone # * 'refresh'<~Integer> - Refresh interval for the zone # * 'minimum'<~Integer> - Minimum refresh interval for the zone def create_zone(options) body = %Q{#{options[:name]}#{options[:ttl]}} body += %Q{#{options[:retry]}} if options[:retry] body += %Q{#{options[:retry]}} if options[:refresh] body += %Q{#{options[:minimum]}} if options[:minimum] body += %Q{} request( :body => body, :expects => 202, :method => 'POST', :parser => Fog::Parsers::DNS::Bluebox::CreateZone.new, :path => "/api/domains.xml" ) end end class Mock def create_zone(options) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/bluebox/requests/dns/delete_zone.rb0000644000004100000410000000114313171001215022631 0ustar www-datawww-datamodule Fog module DNS class Bluebox class Real # Delete a zone from DNS # ==== Parameters # * zone_id<~Integer> - Id of zone to delete # # ==== Returns # * response<~Excon::Response>: - HTTP status code will be result def delete_zone(zone_id) request( :expects => 200, :method => 'DELETE', :path => "/api/domains/#{zone_id}.xml" ) end end class Mock def delete_zone(zone_id) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/bluebox/requests/dns/delete_record.rb0000644000004100000410000000125713171001215023142 0ustar www-datawww-datamodule Fog module DNS class Bluebox class Real # Delete a record from the specified DNS zone # ==== Parameters # * record_id<~Integer> - Id of DNS record to delete # # ==== Returns # * response<~Excon::Response>: - HTTP status code will be result def delete_record(zone_id, record_id) request( :expects => 200, :method => 'DELETE', :path => "/api/domains/#{zone_id}/records/#{record_id}.xml" ) end end class Mock def delete_record(zone_id, record_id) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/bluebox/requests/dns/update_record.rb0000644000004100000410000000164713171001215023165 0ustar www-datawww-datamodule Fog module Bluebox class DNS class Real # Updates an existing record in a DNS zone # ==== Parameters # * type<~String> - type of DNS record (A, CNAME, etc) # * name<~String> - host name for this DNS record # * content<~String> - data for the DNS record (ie for an A record, the IP address) def update_record(zone_id, record_id, options) body = %Q{} options.each {|k,v| body += "<#{k}>#{v}"} body += "" request( :body => body, :expects => 202, :method => 'PUT', :path => "/api/domains/#{zone_id}/records/#{record_id}.xml" ) end end class Mock def create_record(zone_id, type, domain, content) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/bluebox/requests/dns/update_zone.rb0000644000004100000410000000121213171001215022646 0ustar www-datawww-datamodule Fog module DNS class Bluebox class Real # Updates an existing DNS zone def update_zone(zone_id, options) body = %Q{} options.each {|k,v| body += "<#{k}>#{v}"} body += "" request( :body => body, :expects => 202, :method => 'PUT', :path => "/api/domains/#{zone_id}.xml" ) end end class Mock def create_record(zone_id, type, domain, content) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/bluebox/requests/dns/get_record.rb0000644000004100000410000000221513171001215022452 0ustar www-datawww-datamodule Fog module DNS class Bluebox class Real require 'fog/bluebox/parsers/dns/get_record' # Get an individual DNS record from the specified zone # # ==== Returns # * response<~Excon::Response>: # * hash<~Hash>: # * 'id'<~String> - The id of this record # * 'type'<~String> - type of DNS record to create (A, CNAME, etc) # * 'domain-id'<~Integer> - ID of the zone # * 'name'<~String> - empty? # * 'domain'<~String> - The domain name # * 'type'<~String> - The type of DNS record (e.g. A, MX, NS, etc.) # * 'content'<~String> - data for the DNS record (ie for an A record, the IP address) def get_record(zone_id, record_id) request( :expects => 200, :method => 'GET', :parser => Fog::Parsers::DNS::Bluebox::GetRecord.new, :path => "/api/domains/#{zone_id}/records/#{record_id}.xml" ) end end class Mock def get_record(record_id) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/bluebox/requests/compute/0000755000004100000410000000000013171001215020700 5ustar www-datawww-datafog-1.42.0/lib/fog/bluebox/requests/compute/get_location.rb0000644000004100000410000000104013171001215023667 0ustar www-datawww-datamodule Fog module Compute class Bluebox class Real # Get details of a location # # ==== Parameters # * location_id<~Integer> - Id of location to lookup # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO def get_location(location_id) request( :expects => 200, :method => 'GET', :path => "api/locations/#{location_id}.json" ) end end end end end fog-1.42.0/lib/fog/bluebox/requests/compute/destroy_block.rb0000644000004100000410000000101313171001215024063 0ustar www-datawww-datamodule Fog module Compute class Bluebox class Real # Destroy a block # # ==== Parameters # * block_id<~Integer> - Id of block to destroy # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # TODO def destroy_block(block_id) request( :expects => 200, :method => 'DELETE', :path => "api/blocks/#{block_id}.json" ) end end end end end fog-1.42.0/lib/fog/bluebox/requests/compute/reboot_block.rb0000644000004100000410000000117413171001215023674 0ustar www-datawww-datamodule Fog module Compute class Bluebox class Real # Reboot block # # ==== Parameters # * block_id<~String> - Id of block to reboot # * type<~String> - Type of reboot, must be in ['HARD', 'SOFT'] # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # TODO def reboot_block(block_id, type = 'SOFT') request( :expects => 200, :method => 'PUT', :path => "api/blocks/#{block_id}/#{'soft_' if type == 'SOFT'}reboot.json" ) end end end end end fog-1.42.0/lib/fog/bluebox/requests/compute/create_block.rb0000644000004100000410000000261113171001215023642 0ustar www-datawww-datamodule Fog module Compute class Bluebox class Real # Create a new block # # ==== Parameters # * product_id<~String> - ID of block product (size) # * template_id<~String> - ID of block OS/build template # * location_id<~String> - ID of deployment location # * options<~Hash>: # * password<~String> - Password for block # or # * ssh_public_key<~String> - SSH public key # * username<~String> - Defaults to deploy # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: def create_block(product_id, template_id, location_id, options = {}) unless options.key?('password') || options.key?('ssh_public_key') raise ArgumentError, 'Either password or public_key must be supplied' end query = { 'product' => product_id, 'template' => template_id, 'location' => location_id } query['ipv6_only'] = options.delete('ipv6_only') if options['ipv6_only'] request( :expects => 200, :method => 'POST', :path => '/api/blocks.json', :query => query, :body => options.map {|k,v| "#{CGI.escape(k)}=#{CGI.escape(v)}"}.join('&') ) end end end end end fog-1.42.0/lib/fog/bluebox/requests/compute/get_block.rb0000644000004100000410000000101313171001215023151 0ustar www-datawww-datamodule Fog module Compute class Bluebox class Real # Get details of a block. # # ==== Parameters # * block_id<~Integer> - Id of block to lookup # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # TODO def get_block(block_id) request( :expects => 200, :method => 'GET', :path => "api/blocks/#{block_id}.json" ) end end end end end fog-1.42.0/lib/fog/bluebox/requests/compute/get_locations.rb0000644000004100000410000000101313171001215024052 0ustar www-datawww-datamodule Fog module Compute class Bluebox class Real # Get list of locations # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * 'id'<~String> - UUID of the location # * 'description'<~String> - Description of the location def get_locations request( :expects => 200, :method => 'GET', :path => 'api/locations.json' ) end end end end end fog-1.42.0/lib/fog/bluebox/requests/compute/get_template.rb0000644000004100000410000000104613171001215023700 0ustar www-datawww-datamodule Fog module Compute class Bluebox class Real # Get details of a template # # ==== Parameters # * template_id<~Integer> - Id of template to lookup # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO def get_template(template_id) request( :expects => 200, :method => 'GET', :path => "api/block_templates/#{template_id}.json" ) end end end end end fog-1.42.0/lib/fog/bluebox/requests/compute/get_templates.rb0000644000004100000410000000123113171001215024057 0ustar www-datawww-datamodule Fog module Compute class Bluebox class Real # Get list of OS templates # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * 'id'<~String> - UUID of the image # * 'description'<~String> - Description of the image # * 'public'<~Boolean> - Public / Private image # * 'created'<~Datetime> - Timestamp of when the image was created def get_templates request( :expects => 200, :method => 'GET', :path => 'api/block_templates.json' ) end end end end end fog-1.42.0/lib/fog/bluebox/requests/compute/create_template.rb0000644000004100000410000000115413171001215024364 0ustar www-datawww-datamodule Fog module Compute class Bluebox class Real # Create a template from block # # ==== Parameters # * block_id<~Integer> - Id of block to create template from # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO def create_template(block_id, options={}) request( :expects => 202, :method => 'POST', :path => "api/block_templates.json", :query => {'id' => block_id}.merge!(options) ) end end end end end fog-1.42.0/lib/fog/bluebox/requests/compute/get_products.rb0000644000004100000410000000111213171001215023722 0ustar www-datawww-datamodule Fog module Compute class Bluebox class Real # Get list of products # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * 'id'<~String> - UUID of the product # * 'description'<~String> - Description of the product # * 'cost'<~Decimal> - Hourly cost of the product def get_products request( :expects => 200, :method => 'GET', :path => 'api/block_products.json' ) end end end end end fog-1.42.0/lib/fog/bluebox/requests/compute/get_product.rb0000644000004100000410000000103613171001215023544 0ustar www-datawww-datamodule Fog module Compute class Bluebox class Real # Get details of a product # # ==== Parameters # * product_id<~Integer> - Id of flavor to lookup # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO def get_product(product_id) request( :expects => 200, :method => 'GET', :path => "api/block_products/#{product_id}.json" ) end end end end end fog-1.42.0/lib/fog/bluebox/requests/compute/get_blocks.rb0000644000004100000410000000137613171001215023350 0ustar www-datawww-datamodule Fog module Compute class Bluebox class Real # Get list of blocks # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * 'ips'<~Array> - Ip addresses for the block # * 'id'<~String> - Id of the block # * 'storage'<~Integer> - Disk space quota for the block # * 'memory'<~Integer> - RAM quota for the block # * 'cpu'<~Float> - The fractional CPU quota for this block # * 'hostname'<~String> - The hostname for the block def get_blocks request( :expects => 200, :method => 'GET', :path => 'api/blocks.json' ) end end end end end fog-1.42.0/lib/fog/bluebox/requests/compute/destroy_template.rb0000644000004100000410000000102313171001215024605 0ustar www-datawww-datamodule Fog module Compute class Bluebox class Real # Create a template from block # # ==== Parameters # * id<~Integer> - Id of image to destroy # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # TODO def destroy_template(id) request( :expects => 200, :method => 'DELETE', :path => "api/block_templates/#{id}.json" ) end end end end end fog-1.42.0/lib/fog/bluebox/requests/blb/0000755000004100000410000000000013171001215017763 5ustar www-datawww-datafog-1.42.0/lib/fog/bluebox/requests/blb/update_lb_backend_machine.rb0000644000004100000410000000171213171001215025403 0ustar www-datawww-datamodule Fog module Bluebox class BLB class Real # change machine attributes (port &c) in a single backend # # === Parameters # * lb_backend_id<~String> - ID of backend # * lb_machine_id<~String> - ID of machine # * options<~Hash>: # * port<~Integer> - port machine listens on # * maxconn<~Integer> - maximum number of connections server can be sent # * backup<~Boolean> - only send traffic to machine if all others are down def update_lb_backend_machine(lb_backend_id, lb_machine_id, options = {}) # inconsistent, no? request( :expects => 202, :method => 'PUT', :path => "/api/lb_backends/#{lb_backend_id}/lb_machines/#{lb_machine_id}", :body => options.map {|k,v| "#{CGI.escape(k)}=#{CGI.escape(v.to_s)}"}.join('&') ) end end class Mock end end end end fog-1.42.0/lib/fog/bluebox/requests/blb/get_lb_applications.rb0000644000004100000410000000152413171001215024314 0ustar www-datawww-datamodule Fog module Bluebox class BLB class Real # Get list of applications # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * 'application'<~Hash>: # * 'id'<~String> - UUID of application # * 'ip_v4'<~Array> - IPv4 addresses # * 'ip_v6'<~String> - IPv6 address # * 'name'<~String> - The hostname # * 'lb_services'<~Array> - Listening services # * 'source_ip_v4'<~String> - address that application connects to pool members from (v1 only) def get_lb_applications request( :expects => 200, :method => 'GET', :path => 'api/lb_applications.json' ) end end class Mock end end end end fog-1.42.0/lib/fog/bluebox/requests/blb/add_machine_to_lb_backend.rb0000644000004100000410000000210513171001215025350 0ustar www-datawww-datamodule Fog module Bluebox class BLB class Real # Add machine to specified lb_backend # # === Parameters # * lb_backend_id<~String> - ID of backend # * lb_machine_id<~String> - ID of machine # * options<~Hash>: # * port<~Integer> - port machine listens on; defaults to service listening port # * maxconn<~Integer> - maximum number of connections server can be sent # * backup<~Boolean> - only send traffic to machine if all others are down def add_machine_to_lb_backend(lb_backend_id, lb_machine_id, options = {}) # convert to CGI array args body = Hash[options.map {|k,v| ["lb_options[#{k}]", v] }] body['lb_machine'] = lb_machine_id request( :expects => 200, :method => 'POST', :path => "/api/lb_backends/#{lb_backend_id}/lb_machines.json", :body => body.map {|k,v| "#{CGI.escape(k)}=#{CGI.escape(v.to_s)}"}.join('&') ) end end class Mock end end end end fog-1.42.0/lib/fog/bluebox/requests/blb/get_lb_service.rb0000644000004100000410000000232113171001215023262 0ustar www-datawww-datamodule Fog module Bluebox class BLB class Real # Get details of a lb_service. # # ==== Parameters # * lb_application_id<~String> - ID of application the service belongs to # * lb_service_id<~String> - ID of service to look up # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * name<~String> - service name # * port<~Integer> - port of load balanced service # * private<~Boolean> - whether service is only available internally # * status_username<~String> - HTTP basic auth username # * status_password<~String> - HTTP basic auth password # * status_url<~String> - URL of stats page # * service_type<~String> - proto being load balanced (e.g. 'http', 'tcp') # * created<~DateTime> - when service was created def get_lb_service(lb_application_id, lb_service_id) request( :expects => 200, :method => 'GET', :path => "api/lb_applications/#{lb_application_id}/lb_services/#{lb_service_id}.json", ) end end class Mock end end end end fog-1.42.0/lib/fog/bluebox/requests/blb/get_lb_application.rb0000644000004100000410000000166113171001215024133 0ustar www-datawww-datamodule Fog module Bluebox class BLB class Real # Get details of an lb_application. # # ==== Parameters # * lb_application_id<~Integer> - ID of application # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'id'<~String> - UUID of application # * 'ip_v4'<~Array> - IPv4 addresses # * 'ip_v6'<~String> - IPv6 address # * 'name'<~String> - The hostname # * 'lb_services'<~Array> - Listening services # * 'source_ip_v4'<~String> - address that application connects to pool members from (v1 only) def get_lb_application(lb_application_id) request( :expects => 200, :method => 'GET', :path => "api/lb_applications/#{lb_application_id}.json" ) end end class Mock end end end end fog-1.42.0/lib/fog/bluebox/requests/blb/get_lb_services.rb0000644000004100000410000000224513171001215023452 0ustar www-datawww-datamodule Fog module Bluebox class BLB class Real # Get list of load balancing services # # ==== Parameters # * lb_application_id<~String> - Id of application services to list # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * backend<~Hash>: # * name<~String> - service name # * port<~Integer> - port of load balanced service # * private<~Boolean> - whether service is only available internally # * status_username<~String> - HTTP basic auth username # * status_password<~String> - HTTP basic auth password # * status_url<~String> - URL of stats page # * service_type<~String> - proto being load balanced (e.g. 'http', 'tcp') # * created<~DateTime> - when service was created def get_lb_services(lb_application_id) request( :expects => 200, :method => 'GET', :path => "api/lb_applications/#{lb_application_id}/lb_services.json" ) end end class Mock end end end end fog-1.42.0/lib/fog/bluebox/requests/blb/get_lb_backends.rb0000644000004100000410000000210213171001215023371 0ustar www-datawww-datamodule Fog module Bluebox class BLB class Real # Get list of backends # # ==== Parameters # * lb_service_id<~String> - service containing backends # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * backend<~Hash>: # * id<~String> - backend ID # * backend_name<~String> # * lb_machines<~Array> - array of backend members # * acl_name<~String> - name of ACL for this backend # * acl_rule<~String> # * monitoring_url_hostname<~String> - HTTP host header for health check # * monitoring_url<~String> - URL for health check # * check_interval<~Integer> - time between checks, in milliseconds def get_lb_backends(lb_service_id) request( :expects => 200, :method => 'GET', :path => "api/lb_services/#{lb_service_id}/lb_backends.json" ) end end class Mock end end end end fog-1.42.0/lib/fog/bluebox/requests/blb/get_lb_backend.rb0000644000004100000410000000216013171001215023212 0ustar www-datawww-datamodule Fog module Bluebox class BLB class Real # Get details of an lb_backend. # # ==== Parameters # * lb_service_id<~String> - service backend belongs to # * lb_backend_id<~String> - backend to look up # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * id<~String> - backend ID # * backend_name<~String> # * lb_machines<~Array> - array of backend members # * acl_name<~String> - name of ACL for this backend # * acl_rule<~String> # * monitoring_url_hostname<~String> - HTTP host header for health check # * monitoring_url<~String> - URL for health check # * check_interval<~Integer> - time between checks, in milliseconds def get_lb_backend(lb_service_id, lb_backend_id) request( :expects => 200, :method => 'GET', :path => "api/lb_services/#{lb_service_id}/lb_backends/#{lb_backend_id}.json" ) end end class Mock end end end end fog-1.42.0/lib/fog/bluebox/requests/blb/get_lb_machine.rb0000644000004100000410000000221213171001215023225 0ustar www-datawww-datamodule Fog module Bluebox class BLB class Real # Get details of an lb_machine. # # ==== Parameters # * lb_backend_id<~String> - backend machine belongs to # * lb_machine_id<~String> - machine to look up # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * id<~String> - machine ID # * ip<~String> - machine IP address for this member (v4 or v6) # * port<~Integer> - service port for this member # * hostname<~String> - name as registered with Box Panel # * acl_name<~String> - name of ACL for this machine # * created<~DateTime> - when machine was added to load balancer backend # * maxconn<~Integer> - maximum concurrent connections for this member (BLBv2 only) def get_lb_machine(lb_backend_id, lb_machine_id) request( :expects => 200, :method => 'GET', :path => "api/lb_backends/#{lb_backend_id}/lb_machines/#{lb_machine_id}.json" ) end end class Mock end end end end fog-1.42.0/lib/fog/bluebox/requests/blb/get_lb_machines.rb0000644000004100000410000000213213171001215023411 0ustar www-datawww-datamodule Fog module Bluebox class BLB class Real # Get list of machines # # ==== Parameters # * lb_backend_id<~String> - backend containing machines # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * machine<~Hash>: # * id<~String> - machine ID # * ip<~String> - machine IP address for this member (v4 or v6) # * port<~Integer> - service port for this member # * hostname<~String> - name as registered with Box Panel # * acl_name<~String> - name of ACL for this machine # * created<~DateTime> - when machine was added to load balancer backend # * maxconn<~Integer> - maximum concurrent connections for this member (BLBv2 only) def get_lb_machines(lb_backend_id) request( :expects => 200, :method => 'GET', :path => "api/lb_backends/#{lb_backend_id}/lb_machines.json" ) end end class Mock end end end end fog-1.42.0/lib/fog/bluebox/requests/blb/remove_machine_from_lb_backend.rb0000644000004100000410000000135413171001215026443 0ustar www-datawww-datamodule Fog module Bluebox class BLB class Real # remove machine from single backend # # === Parameters # * lb_backend_id<~String> - ID of backend # * lb_machine_id<~String> - ID of machine # # ==== Returns # * response<~Excon::Response>: # * body<~String> - success or failure message def remove_machine_from_lb_backend(lb_backend_id, lb_machine_id) request( :expects => 200, :method => 'DELETE', :path => "/api/lb_backends/#{lb_backend_id}/lb_machines/#{lb_machine_id}", :headers => {"Accept" => "text/plain"}, ) end end class Mock end end end end fog-1.42.0/lib/fog/bluebox/requests/blb/add_machine_to_lb_application.rb0000644000004100000410000000222713171001215026271 0ustar www-datawww-datamodule Fog module Bluebox class BLB class Real # Add machine to default lb_backend for each lb_service # in the application. # # === Parameters # * lb_application_id<~String> - ID of application # * lb_machine_id<~String> - ID of machine # * options<~Hash>: # * port<~Integer> - port machine listens on; defaults to service listening port # * maxconn<~Integer> - maximum number of connections server can be sent # * backup<~Boolean> - only send traffic to machine if all others are down # def add_machine_to_lb_application(lb_application_id, lb_machine_id, options = {}) # convert to CGI array args body = Hash[options.map {|k,v| ["lb_options[#{k}]", v] }] body['lb_machine'] = lb_machine_id request( :expects => 200, :method => 'POST', :path => "/api/lb_applications/add_machine/#{lb_application_id}.json", :body => body.map {|k,v| "#{CGI.escape(k)}=#{CGI.escape(v.to_s)}"}.join('&') ) end end class Mock end end end end fog-1.42.0/lib/fog/bluebox/parsers/0000755000004100000410000000000013171001215017030 5ustar www-datawww-datafog-1.42.0/lib/fog/bluebox/parsers/dns/0000755000004100000410000000000013171001215017614 5ustar www-datawww-datafog-1.42.0/lib/fog/bluebox/parsers/dns/get_records.rb0000644000004100000410000000075213171001215022445 0ustar www-datawww-datamodule Fog module Parsers module DNS module Bluebox class GetRecords < Fog::Parsers::Base def reset @record = {} @response = { 'records' => [] } end def end_element(name) case name when 'record' @response['records'] << @record @record = {} else @record[name] = value end end end end end end end fog-1.42.0/lib/fog/bluebox/parsers/dns/get_zone.rb0000644000004100000410000000075713171001215021764 0ustar www-datawww-datamodule Fog module Parsers module DNS module Bluebox class GetZone < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'serial', 'ttl', 'retry', 'expires', 'record-count', 'refresh', 'minimum' @response[name] = value.to_i when 'name', 'id' @response[name] = value end end end end end end end fog-1.42.0/lib/fog/bluebox/parsers/dns/create_record.rb0000644000004100000410000000076413171001215022751 0ustar www-datawww-datamodule Fog module Parsers module DNS module Bluebox class CreateRecord < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'serial', 'ttl', 'retry', 'refresh', 'minimum', 'record-count', 'expires' @response[name] = value.to_i when 'name', 'id' @response[name] = value end end end end end end end fog-1.42.0/lib/fog/bluebox/parsers/dns/get_zones.rb0000644000004100000410000000115313171001215022136 0ustar www-datawww-datamodule Fog module Parsers module DNS module Bluebox class GetZones < Fog::Parsers::Base def reset @zone = {} @response = { 'zones' => [] } end def end_element(name) case name when 'serial', 'ttl', 'retry', 'expires', 'record-count', 'refresh', 'minimum' @zone[name] = value.to_i when 'name', 'id' @zone[name] = value when 'record' @response['zones'] << @zone @zone = {} end end end end end end end fog-1.42.0/lib/fog/bluebox/parsers/dns/create_zone.rb0000644000004100000410000000076213171001215022444 0ustar www-datawww-datamodule Fog module Parsers module DNS module Bluebox class CreateZone < Fog::Parsers::Base def reset @response = {} end def end_element(name) case name when 'serial', 'ttl', 'retry', 'refresh', 'minimum', 'record-count', 'expires' @response[name] = value.to_i when 'name', 'id' @response[name] = value end end end end end end end fog-1.42.0/lib/fog/bluebox/parsers/dns/get_record.rb0000644000004100000410000000044613171001215022262 0ustar www-datawww-datamodule Fog module Parsers module DNS module Bluebox class GetRecord < Fog::Parsers::Base def reset @response = { } end def end_element(name) @response[name] = value end end end end end end fog-1.42.0/lib/fog/bluebox/dns.rb0000644000004100000410000000532113171001215016463 0ustar www-datawww-datarequire 'fog/bluebox/core' module Fog module DNS class Bluebox < Fog::Service requires :bluebox_api_key, :bluebox_customer_id recognizes :bluebox_host, :bluebox_port, :bluebox_scheme, :persistent model_path 'fog/bluebox/models/dns' model :record collection :records model :zone collection :zones request_path 'fog/bluebox/requests/dns' request :create_record request :update_record request :delete_record request :create_zone request :update_zone request :delete_zone request :get_record request :get_records request :get_zone request :get_zones class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = {} end end def self.reset @data = nil end def initialize(options={}) @bluebox_customer_id = options[:bluebox_customer_id] @bluebox_api_key = options[:bluebox_api_key] end def data self.class.data[@bluebox_customer_id] end def reset_data self.class.data.delete(@bluebox_customer_id) end end class Real def initialize(options ={}) @bluebox_customer_id = options[:bluebox_customer_id] @bluebox_api_key = options[:bluebox_api_key] @connection_options = options[:connection_options] || {} @host = options[:bluebox_host] || "boxpanel.bluebox.net" @persistent = options[:persistent] || false @port = options[:bluebox_port] || 443 @scheme = options[:bluebox_scheme] || 'https' @connection = Fog::XML::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def reload @connection.reset end def request(params) params[:headers] ||= {} params[:headers]['Authorization'] = "Basic #{auth_header}" params[:headers]['Accept'] = 'application/xml' case params[:method] when 'POST', 'PUT' params[:headers]['Content-Type'] = 'application/xml' end begin response = @connection.request(params) rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::DNS::Bluebox::NotFound.slurp(error) else error end end response end protected def auth_header @auth_header ||= Base64.encode64("#{@bluebox_customer_id}:#{@bluebox_api_key}").gsub("\n",'') end end end end end fog-1.42.0/lib/fog/bluebox/core.rb0000644000004100000410000000030213171001215016621 0ustar www-datawww-datarequire 'fog/core' require 'fog/json' module Fog module Bluebox extend Fog::Provider service(:blb, 'BLB') service(:compute, 'Compute') service(:dns, 'DNS') end end fog-1.42.0/lib/fog/bluebox/models/0000755000004100000410000000000013171001215016634 5ustar www-datawww-datafog-1.42.0/lib/fog/bluebox/models/dns/0000755000004100000410000000000013171001215017420 5ustar www-datawww-datafog-1.42.0/lib/fog/bluebox/models/dns/zones.rb0000644000004100000410000000072613171001215021110 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/bluebox/models/dns/zone' module Fog module DNS class Bluebox class Zones < Fog::Collection model Fog::DNS::Bluebox::Zone def all data = service.get_zones.body['zones'] load(data) end def get(zone_id) data = service.get_zone(zone_id).body new(data) rescue Fog::Service::NotFound nil end end end end end fog-1.42.0/lib/fog/bluebox/models/dns/record.rb0000644000004100000410000000215413171001215021225 0ustar www-datawww-datarequire 'fog/core/model' module Fog module DNS class Bluebox class Record < Fog::Model extend Fog::Deprecation deprecate :ip, :value deprecate :ip=, :value= identity :id attribute :name attribute :domain_id, :aliases => 'domain-id' attribute :domain attribute :type attribute :value, :aliases => 'content' def initialize(attributes={}) super end def destroy requires :identity service.delete_record(@zone.identity, identity) true end def zone @zone end def save requires :zone, :type, :name, :value data = unless identity service.create_record(zone.identity, type, name, value) else service.update_record(zone.identity, identity, {:type => type, :name => name, :content => value}) end merge_attributes(data.body) true end private def zone=(new_zone) @zone = new_zone end end end end end fog-1.42.0/lib/fog/bluebox/models/dns/zone.rb0000644000004100000410000000265013171001215020723 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/bluebox/models/dns/records' module Fog module DNS class Bluebox class Zone < Fog::Model identity :id attribute :domain, :aliases => 'name' attribute :serial attribute :ttl attribute :retry attribute :expires attribute :record_count, :aliases => 'record-count' attribute :refresh attribute :minimum def initialize(attributes = {}) super(attributes) end def destroy raise Fog::Errors::Error.new('Not implemented') end def records @records ||= begin Fog::DNS::Bluebox::Records.new( :zone => self, :service => service ) end end def nameservers [ 'ns1.blueblxgrid.com', 'ns2.blueblxgrid.com', 'ns3.blueblxgrid.com' ] end def destroy requires :identity service.delete_zone(identity) true end def save self.ttl ||= 3600 requires :domain, :ttl options = attributes.dup options[:name] = options.delete(:domain) data = identity.nil? ? service.create_zone(options) : service.update_zone(identity, options) merge_attributes(data.body) true end end end end end fog-1.42.0/lib/fog/bluebox/models/dns/records.rb0000644000004100000410000000126313171001215021410 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/bluebox/models/dns/record' module Fog module DNS class Bluebox class Records < Fog::Collection attribute :zone model Fog::DNS::Bluebox::Record def all requires :zone data = service.get_records(zone.identity).body['records'] load(data) end def get(record_id) data = service.get_record(zone.identity, 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.42.0/lib/fog/bluebox/models/compute/0000755000004100000410000000000013171001215020310 5ustar www-datawww-datafog-1.42.0/lib/fog/bluebox/models/compute/location.rb0000644000004100000410000000027313171001215022447 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Bluebox class Location < Fog::Model identity :id attribute :description end end end end fog-1.42.0/lib/fog/bluebox/models/compute/images.rb0000644000004100000410000000077513171001215022113 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/bluebox/models/compute/image' module Fog module Compute class Bluebox class Images < Fog::Collection model Fog::Compute::Bluebox::Image def all data = service.get_templates.body load(data) end def get(template_id) response = service.get_template(template_id) new(response.body) rescue Fog::Compute::Bluebox::NotFound nil end end end end end fog-1.42.0/lib/fog/bluebox/models/compute/servers.rb0000644000004100000410000000134413171001215022330 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/bluebox/models/compute/server' module Fog module Compute class Bluebox class Servers < Fog::Collection model Fog::Compute::Bluebox::Server def all data = service.get_blocks.body load(data) end def bootstrap(new_attributes = {}) server = create(new_attributes) server.wait_for { ready? } server.setup(:key_data => [server.private_key]) server end def get(server_id) if server_id && server = service.get_block(server_id).body new(server) end rescue Fog::Compute::Bluebox::NotFound nil end end end end end fog-1.42.0/lib/fog/bluebox/models/compute/locations.rb0000644000004100000410000000100613171001215022625 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/bluebox/models/compute/location' module Fog module Compute class Bluebox class Locations < Fog::Collection model Fog::Compute::Bluebox::Location def all data = service.get_locations.body load(data) end def get(location_id) response = service.get_location(location_id) new(response.body) rescue Fog::Compute::Bluebox::NotFound nil end end end end end fog-1.42.0/lib/fog/bluebox/models/compute/flavors.rb0000644000004100000410000000077413171001215022321 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/bluebox/models/compute/flavor' module Fog module Compute class Bluebox class Flavors < Fog::Collection model Fog::Compute::Bluebox::Flavor def all data = service.get_products.body load(data) end def get(product_id) response = service.get_product(product_id) new(response.body) rescue Fog::Compute::Bluebox::NotFound nil end end end end end fog-1.42.0/lib/fog/bluebox/models/compute/flavor.rb0000644000004100000410000000143313171001215022127 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Bluebox class Flavor < Fog::Model identity :id attribute :name attribute :cost attribute :description def bits # 64 raise StandardError.new("Figure me out!?!") end def cores # # 2 quad-cores >= 2Ghz = 8 cores # 8 * case ram # when 256 # 1/64.0 # when 512 # 1/32.0 # when 1024 # 1/16.0 # when 2048 # 1/8.0 # when 4096 # 1/4.0 # when 8192 # 1/2.0 # when 15872 # 1 # end raise StandardError.new("Figure me out!?!") end end end end end fog-1.42.0/lib/fog/bluebox/models/compute/server.rb0000644000004100000410000000657513171001215022160 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class Bluebox class BlockInstantiationError < StandardError; end class Server < Fog::Compute::Server identity :id attribute :cpu attribute :description attribute :flavor_id, :aliases => :product, :squash => 'id' attribute :hostname attribute :image_id attribute :location_id attribute :ips attribute :memory attribute :state, :aliases => "status" attribute :storage attribute :template attribute :ipv6_only attribute :vsh_id attr_accessor :hostname, :password, :lb_applications, :lb_services, :lb_backends def initialize(attributes={}) self.flavor_id ||= '94fd37a7-2606-47f7-84d5-9000deda52ae' # Block 1GB Virtual Server self.image_id ||= 'a8f05200-7638-47d1-8282-2474ef57c4c3' # Scientific Linux 6 self.location_id ||= '37c2bd9a-3e81-46c9-b6e2-db44a25cc675' # Seattle, WA super end def destroy requires :id service.destroy_block(id) true end def flavor requires :flavor_id service.flavors.get(flavor_id) end def image requires :image_id service.images.get(image_id) end def location requires :location_id service.locations.get(location_id) end def private_ip_address nil end def public_ip_address if ip = ips.first ip['address'] end end def ready? self.state == 'running' end def reboot(type = 'SOFT') requires :id service.reboot_block(id, type) true end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :flavor_id, :image_id, :location_id options = {} unless persisted? # new record raise(ArgumentError, "password or public_key is required for this operation") if !password && !public_key options['ssh_public_key'] = public_key if public_key options['password'] = password if @password end if @lb_backends options['lb_backends'] = lb_backends elsif @lb_services options['lb_services'] = lb_services elsif @lb_applications options['lb_applications'] = lb_applications end options['username'] = username options['hostname'] = hostname if @hostname options['ipv6_only'] = ipv6_only if ipv6_only data = service.create_block(flavor_id, image_id, location_id, options) merge_attributes(data.body) true end def setup(credentials = {}) requires :identity, :ips, :public_key, :username Fog::SSH.new(ssh_ip_address, username, credentials).run([ %{mkdir .ssh}, %{echo "#{public_key}" >> ~/.ssh/authorized_keys}, %{passwd -l #{username}}, %{echo "#{Fog::JSON.encode(attributes)}" >> ~/attributes.json} ]) rescue Errno::ECONNREFUSED sleep(1) retry end def username @username ||= 'deploy' end end end end end fog-1.42.0/lib/fog/bluebox/models/compute/image.rb0000644000004100000410000000104313171001215021715 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Bluebox class Image < Fog::Model identity :id attribute :block_id attribute :description attribute :public attribute :created_at, :aliases => 'created' def save requires :block_id data = service.create_template(block_id, attributes) true end def destroy requires :id data = service.destroy_template(id) true end end end end end fog-1.42.0/lib/fog/bluebox/models/blb/0000755000004100000410000000000013171001215017373 5ustar www-datawww-datafog-1.42.0/lib/fog/bluebox/models/blb/lb_service.rb0000644000004100000410000000121713171001215022036 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Bluebox class BLB class LbService < Fog::Model identity :id attribute :name attribute :port attribute :service_type attribute :private attribute :status_url attribute :status_username attribute :status_password attribute :created, :aliases => 'created_at' def lb_application collection.lb_application end def lb_backends Fog::Bluebox::BLB::LbBackends.new({ :service => service, :lb_service => self }) end end end end end fog-1.42.0/lib/fog/bluebox/models/blb/lb_services.rb0000644000004100000410000000114613171001215022222 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/bluebox/models/blb/lb_service' module Fog module Bluebox class BLB class LbServices < Fog::Collection model Fog::Bluebox::BLB::LbService attr_accessor :lb_application def all data = service.get_lb_services(lb_application.id).body load(data) end def get(lb_service_id) if lb_service = service.get_lb_service(lb_application.id, lb_service_id).body new(lb_service) end rescue Fog::Bluebox::BLB::NotFound nil end end end end end fog-1.42.0/lib/fog/bluebox/models/blb/lb_applications.rb0000644000004100000410000000104513171001215023063 0ustar www-datawww-datarequire 'fog/bluebox/models/blb/lb_application' module Fog module Bluebox class BLB class LbApplications < Fog::Collection model Fog::Bluebox::BLB::LbApplication def all data = service.get_lb_applications.body load(data) end def get(application_id) if application_id && application = service.get_lb_application(application_id).body new(application) end rescue Fog::Bluebox::BLB::NotFound nil end end end end end fog-1.42.0/lib/fog/bluebox/models/blb/lb_application.rb0000644000004100000410000000120413171001215022675 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Bluebox class BLB class LbApplication < Fog::Model identity :id attribute :name attribute :ip_v4 attribute :ip_v6 attribute :description attribute :created, :aliases => 'created_at' def add_machine(lb_machine_id, options) requires :id service.add_machine_to_lb_application(id, lb_machine_id, options) end def lb_services Fog::Bluebox::BLB::LbServices.new({ :service => service, :lb_application => self }) end end end end end fog-1.42.0/lib/fog/bluebox/models/blb/lb_backend.rb0000644000004100000410000000056713171001215021774 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Bluebox class BLB class LbBackend < Fog::Model identity :id attribute :name attribute :lb_machines attribute :monitoring_url attribute :monitoring_url_hostname attribute :acl_name attribute :acl_rule attribute :check_interval end end end end fog-1.42.0/lib/fog/bluebox/models/blb/lb_backends.rb0000644000004100000410000000113613171001215022150 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/bluebox/models/blb/lb_backend' module Fog module Bluebox class BLB class LbBackends < Fog::Collection model Fog::Bluebox::BLB::LbBackend attr_accessor :lb_service def all data = service.get_lb_backends(lb_service.id).body load(data) end def get(lb_backend_id) if lb_backend = service.get_lb_backend(lb_service.id, lb_backend_id).body new(lb_backend) end rescue Fog::Compute::Bluebox::NotFound nil end end end end end fog-1.42.0/lib/fog/bluebox/compute.rb0000644000004100000410000000534113171001215017355 0ustar www-datawww-datarequire 'fog/bluebox/core' module Fog module Compute class Bluebox < Fog::Service requires :bluebox_api_key, :bluebox_customer_id recognizes :bluebox_host, :bluebox_port, :bluebox_scheme, :persistent model_path 'fog/bluebox/models/compute' model :flavor collection :flavors model :image collection :images model :server collection :servers model :location collection :locations request_path 'fog/bluebox/requests/compute' request :create_block request :destroy_block request :get_block request :get_blocks request :get_location request :get_locations request :get_product request :get_products request :get_template request :get_templates request :create_template request :destroy_template request :reboot_block class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = {} end end def self.reset @data = nil end def initialize(options={}) @bluebox_api_key = options[:bluebox_api_key] end def data self.class.data[@bluebox_api_key] end def reset_data self.class.data.delete(@bluebox_api_key) end end class Real def initialize(options={}) @bluebox_api_key = options[:bluebox_api_key] @bluebox_customer_id = options[:bluebox_customer_id] @connection_options = options[:connection_options] || {} @host = options[:bluebox_host] || "boxpanel.bluebox.net" @persistent = options[:persistent] || false @port = options[:bluebox_port] || 443 @scheme = options[:bluebox_scheme] || 'https' @connection = Fog::XML::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def reload @connection.reset end def request(params) params[:headers] ||= {} params[:headers].merge!({ 'Authorization' => "Basic #{Base64.encode64([@bluebox_customer_id, @bluebox_api_key].join(':')).delete("\r\n")}" }) begin response = @connection.request(params) rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Compute::Bluebox::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.42.0/lib/fog/ovirt.rb0000644000004100000410000000003413171001215015376 0ustar www-datawww-datarequire 'fog/ovirt/compute' fog-1.42.0/lib/fog/clodo/0000755000004100000410000000000013171001215015011 5ustar www-datawww-datafog-1.42.0/lib/fog/clodo/requests/0000755000004100000410000000000013171001215016664 5ustar www-datawww-datafog-1.42.0/lib/fog/clodo/requests/compute/0000755000004100000410000000000013171001215020340 5ustar www-datawww-datafog-1.42.0/lib/fog/clodo/requests/compute/delete_server.rb0000644000004100000410000000206013171001215023513 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real # Delete an existing server # # ==== Parameters # * id<~Integer> - Id of server to delete # 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'].find {|_| _['id'].to_i == server_id } if server['status'] == 'is_install' response.status = 405 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::Clodo::NotFound end end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/list_images.rb0000644000004100000410000000244613171001215023173 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real # List all images (IDs and names only) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'id'<~Integer> - Id of the image # * 'name'<~String> - Name of the image # * 'status'<~String> - Status of the image # * 'vps_type'<~String> - VirtualServer or ScaleServer def list_images request( :expects => [200, 203], :method => 'GET', :path => 'images' ) end end class Mock def list_images response = Excon::Response.new response.status = 200 response.body = { 'images' => [ { 'name' => 'Debian 6 64 bits', 'id' => "541", 'vps_type' => 'ScaleServer', 'status' => 'ACTIVE' }, { 'name' => 'CentOS 5.5 32 bits', 'id' => "31", 'vps_type' => 'VirtualServer', 'status' => 'ACTIVE' } ] } response end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/stop_server.rb0000644000004100000410000000051113171001215023235 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real def stop_server(id) body = {'stop' => {}} server_action(id, body) end end class Mock def stop_server(id) body = {'stop' => {}} server_action(id, body) end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/move_ip_address.rb0000644000004100000410000000147513171001215024037 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real # Move IP-address to specified server. # ==== Paramaters # * server_id<~Integer> - Id of server to move IP to # * ip<~String> - IP-address to move # # ==== Returns # * response<~Excon::Response> # def move_ip_address(server_id, ip) request( :expects => [204], :method => 'GET', :path => "servers/#{server_id}/ips/moveip", :body => Fog::JSON.encode({'ip'=>"#{ip}"}) ) end end class Mock def move_ip_address(server_id, ip) response = Excon::Response.new response.status = [204] response end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/list_servers_detail.rb0000644000004100000410000000246513171001215024742 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real # List all servers details # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'servers'<~Array>: # * 'id'<~Integer> - Id of server # * 'name<~String> - Name of server # * 'imageId'<~Integer> - Id of image used to boot server # * 'status'<~String> - Current server status # * 'addresses'<~Hash>: # * 'public'<~Array> - public address strings def list_servers_detail request( :expects => [200, 203], :method => 'GET', :path => 'servers/detail' ) end end class Mock def list_servers_detail response = Excon::Response.new servers = self.data[:servers].values for server in servers case server['status'] when 'is_install' if Time.now - self.data[:last_modified][:servers][server['id']] > Fog::Mock.delay * 2 server['status'] = 'is_running' end end end response.status = [200, 203][rand(1)] response.body = { 'servers' => servers } response end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/start_server.rb0000644000004100000410000000051513171001215023411 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real def start_server(id) body = {'start' => {}} server_action(id, body) end end class Mock def start_server(id) body = {'start' => {}} server_action(id, body) end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/list_images_detail.rb0000644000004100000410000000352313171001215024512 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real # List all images # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'os_type'<~String> - OS distribution # * 'os_bits'<~Integer> - OS bits # * 'os_hvm'<~Integer> - HVM flag # * '_attr'<~Hash>: # * 'id'<~Integer> - Id of the image # * 'name'<~String> - Name of the image # * 'status'<~String> - Status of the image # * 'vps_type'<~String> - VirtualServer or ScaleServer def list_images_detail request( :expects => [200, 203], :method => 'GET', :path => 'images/detail' ) end end class Mock def list_images_detail response = Excon::Response.new response.status = 200 response.body = { 'images' => [{ 'os_type' => 'debian', 'os_bits' => "64", 'os_hvm' => "0", '_attr' => { 'id' => "541", 'name' => 'Debian 6 64 bits', 'status' => 'ACTIVE', 'vps_type' => 'ScaleServer' }}, { 'os_type' => 'centos', 'os_bits' => "32", 'os_hvm' => "0", '_attr' => { 'name' => 'CentOS 5.5 32 bits', 'id' => "31", 'vps_type' => 'VirtualServer', 'status' => 'ACTIVE', }}] } response end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/list_servers.rb0000644000004100000410000000275013171001215023415 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real # List all servers (IDs and names only) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'servers'<~Array>: # * 'id'<~String> - Id of server # * 'name'<~String> - Name of server # * 'addresses'<~Hash>: # * 'public'<~Array>: # * 'dosprotect'<~Bool> - DDoS protection enabled # * 'primary_ip'<~Bool> - Is a primary IP-address # * 'isp'<~Bool> - ISPManager license enabled # * 'ip'<~String> - IP-address # * 'imageId'<~String> - ID of OS image installed # * 'type'<~String> - Type (ScaleServer or Virtual Server) # * 'status'<~String> - Server's status def list_servers request( :expects => [200, 203], :method => 'GET', :path => 'servers' ) end end class Mock def list_servers response = Excon::Response.new data = list_servers_detail.body['servers'] servers = [] for server in data servers << server.reject { |key, value| !['id', 'name', 'addresses', 'imageId', 'type', 'status', 'state'].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'servers' => servers } response end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/rebuild_server.rb0000644000004100000410000000104513171001215023701 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real def rebuild_server(id, image_id, vps_isp = nil) body = {'rebuild' => {'imageId' => image_id}} body['rebuild']['vps_isp'] = vps_isp if vps_isp server_action(id, body) end end class Mock def rebuild_server(id, image_id, vps_isp = nil) body = {'rebuild' => {'imageId' => image_id}} body['rebuild']['vps_isp'] = vps_isp if vps_isp server_action(id, body) end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/create_server.rb0000644000004100000410000000763313171001215023527 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real # Input: # vps_title - VDS title to display in VDS list # vps_type - VDS type (VirtualServer,ScaleServer) # vps_memory - memory size in megabytes (for ScaleServer - low limit) # vps_memory_max - maximum number of ScaleServer memory megabytes to scale up. # vps_hdd - Virtual HDD size im gigabytes. # vps_admin - support level (1 - usual&free, 2 - extended, 3 - VIP) # vps_os - OS ID to install # Output: # id - VDS ID # name - VDS title # imageId - OS ID # adminPass - root password def create_server(image_id, options = {}) data = { 'server' => { :vps_os => image_id, :vps_hdd => options[:vps_hdd]?options[:vps_hdd]:5, :vps_memory => options[:vps_memory]?options[:vps_memory]:256, :vps_memory_max => options[:vps_memory_max]?options[:vps_memory_max]:1024, :vps_admin => options[:vps_admin]?options[:vps_admin]:1 } } data['server'].merge! options if options request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'POST', :path => 'servers' ) end end class Mock def create_server(image_id, options = {}) raise Excon::Errors::BadRequest.new("Invalid image ID") unless image_id > 0 response = Excon::Response.new response.status = 202 id = Fog::Mock.random_numbers(6).to_i data = { 'id' => id, 'imageId' => "#{image_id}", 'name' => options['name'] || "VPS #{rand(999)}", 'adminPass' => '23ryh8udbcbyt' } self.data[:last_modified][:servers][id] = Time.now self.data[:servers][id] = { 'id' => "#{id}", 'imageId' => data['imageId'], 'name' => data['name'], 'vps_os_title' => "OSTitle", 'vps_root_pass' => data['adminPass'], 'status' => "is_running", 'addresses' => {'public' =>[{ 'primary_ip' => true, 'isp' => false, 'ip' => '66.6.6.66' }, { 'primary_ip' => false, 'isp' => false, 'ip' => '13.13.13.13' }]}, 'vps_createdate' => "#{Time.now}", 'vps_hdd_max' => "5", 'vps_traff' => nil, 'vps_mem_1h_max' => "0", 'vps_mem_load' => "0", 'vps_user_pass' => "wer45345ht", 'vps_vnc_pass' => "bi65tdfyb", 'vps_adddate' => "#{Time.now}", 'vps_update' => "#{Time.now}", 'vps_mem_1h_min' => "0", 'vps_mem_1h_avg' => nil, 'vps_memory_max' => options['vps_memory_max'] || "512", 'vps_os_version' => "6.6.6", 'vps_cpu_1h_max' => "0", 'vps_hdd_load' => "0", 'vps_disk_load' => "0", 'vps_os_type' => options['vps_os_type'] || "VirtualServer", 'type' => options['vps_os_type'] || "VirtualServer", 'vps_memory' => options['vps_memory'] || "512", 'vps_cpu_load' => "0", 'vps_update_days' => "0", 'vps_os_bits' => "64", 'vps_vnc' => "6.6.6.6:5900", 'vps_cpu_max' => "0", 'vps_cpu_1h_min' => "0", 'vps_cpu_1h_avg' => nil } response.body = { 'server' => data } response end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/add_ip_address.rb0000644000004100000410000000242313171001215023613 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real # Bye new IP-address for specified server # ==== Paramaters # * server_id<~Integer> - Id of server to bye IP for # # ==== Returns # * response<~Excon::Response> # def add_ip_address(server_id) request( :expects => [204], :method => 'PUT', :path => "servers/#{server_id}/ips" ) end end class Mock def add_ip_address(server_id) raise Excon::Errors::BadRequest.new( "Invalid image ID" ) unless server_id > 0 data = { 'primary_ip' => false, 'isp' => false, 'ip' => "66.6.#{rand(255)}.#{rand(255)}" } raise Excon::Errors::BadRequest unless self.data[:servers][server_id] raise Excon::Errors::BadRequest.new "No addresses" unless self.data[:servers][server_id]['addresses'] self.data[:servers][server_id]['addresses']['public'] << data response = Excon::Response.new response.status = 204 response end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/get_image_details.rb0000644000004100000410000000066613171001215024323 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real def get_image_details(image_id) request(:expects => [200,203], :method => 'GET', :path => "images/#{image_id}") end end class Mock def get_image_details(image_id) response = Excon::Response.new response.status = 404 response end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/reboot_server.rb0000644000004100000410000000053513171001215023550 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real def reboot_server(id, type) body = {'reboot' => {}} server_action(id, body) end end class Mock def reboot_server(id, type) body = {'reboot' => {}} server_action(id, body) end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/get_server_details.rb0000644000004100000410000000261413171001215024542 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real # Get details about a server # # ==== Parameters # * server_id<~Integer> - Id of server to get details for # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'server'<~Hash>: # * 'addresses'<~Hash>: # * 'public'<~Array> - public address strings # * 'private'<~Array> - private address strings # * 'id'<~Integer> - Id of server # * 'imageId'<~Integer> - Id of image used to boot server # * 'name<~String> - Name of server # * 'status'<~String> - Current server status def get_server_details(server_id) request( :expects => [200, 203], :method => 'GET', :path => "servers/#{server_id}" ) end end class Mock def get_server_details(server_id) response = Excon::Response.new if server = list_servers_detail.body['servers'].find {|_| _['id'] == "#{server_id}"} response.status = [200, 203][rand(1)] response.body = { 'server' => server } response.body['server']['id'] = server['id'].to_i response else raise Fog::Compute::Clodo::NotFound end end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/server_action.rb0000644000004100000410000000113113171001215023524 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real def server_action(id, action) request( :body => Fog::JSON.encode(action), :expects => [204], :method => 'POST', :path => "servers/#{id}/action") end end class Mock def server_action(id, action) raise Excon::Errors::BadRequest.new("Invalid server id #{id}.") unless id > 0 response = Excon::Response.new response.status = 204 response end end end end end fog-1.42.0/lib/fog/clodo/requests/compute/delete_ip_address.rb0000644000004100000410000000222513171001215024325 0ustar www-datawww-datamodule Fog module Compute class Clodo class Real # Delete IP-address from specified server # ==== Paramaters # * server_id<~Integer> - Id of server to delete IP from # * ip<~String> - IP-address to delete # # ==== Returns # * response<~Excon::Response> # def delete_ip_address(server_id, ip) data = {'ip' => ip} request( :expects => [204], :method => 'DELETE', :path => "servers/#{server_id}/ips", :body => Fog::JSON.encode(data) ) end end class Mock def delete_ip_address(server_id, ip) server = self.data[:servers][server_id] raise Excon::Errors::BadRequest.new "Server not found" unless server pa = server['addresses']['public'] raise Excon::Errors::BadRequest.new "Address not found" unless pa && pa.reject! {|addr| addr['ip'] == ip } response = Excon::Response.new response.status = 204 response end end end end end fog-1.42.0/lib/fog/clodo/core.rb0000644000004100000410000000205613171001215016271 0ustar www-datawww-datarequire 'fog/core' require 'fog/json' module Fog module Clodo extend Fog::Provider service(:compute, 'Compute') def self.authenticate(options) clodo_auth_url = options[:clodo_auth_url] || "api.clodo.ru" url = clodo_auth_url.match(/^https?:/) ? \ clodo_auth_url : 'https://' + clodo_auth_url uri = URI.parse(url) connection = Fog::XML::Connection.new(url) @clodo_api_key = options[:clodo_api_key] @clodo_username = options[:clodo_username] response = connection.request({ :expects => [200, 204], :headers => { 'X-Auth-Key' => @clodo_api_key, 'X-Auth-User' => @clodo_username }, :host => uri.host, :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 # authenticate end # module Clodo end # module Fog fog-1.42.0/lib/fog/clodo/models/0000755000004100000410000000000013171001215016274 5ustar www-datawww-datafog-1.42.0/lib/fog/clodo/models/compute/0000755000004100000410000000000013171001215017750 5ustar www-datawww-datafog-1.42.0/lib/fog/clodo/models/compute/images.rb0000644000004100000410000000101713171001215021541 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/clodo/models/compute/image' module Fog module Compute class Clodo class Images < Fog::Collection model Fog::Compute::Clodo::Image def all data = service.list_images_detail.body['images'] load(data) end def get(image_id) image = service.get_image_details(image_id).body['image'] new(image) if image rescue Fog::Compute::Clodo::NotFound nil end end end end end fog-1.42.0/lib/fog/clodo/models/compute/servers.rb0000644000004100000410000000136113171001215021767 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/clodo/models/compute/server' module Fog module Compute class Clodo class Servers < Fog::Collection model Fog::Compute::Clodo::Server def all data = service.list_servers_detail.body['servers'] load(data) end def bootstrap(new_attributes = {}) server = create(new_attributes) server.wait_for { ready? } server.setup(:password => server.password) server end def get(server_id) if server = service.get_server_details(server_id).body['server'] new(server) end rescue Fog::Compute::Clodo::NotFound nil end end end end end fog-1.42.0/lib/fog/clodo/models/compute/server.rb0000644000004100000410000000637513171001215021616 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class Clodo class Server < Fog::Compute::Server identity :id attribute :addresses attribute :name attribute :image_id, :aliases => 'imageId' attribute :type attribute :state, :aliases => 'status' attribute :type attribute :vps_memory attribute :vps_memory_max attribute :vps_os_title attribute :vps_os_bits attribute :vps_os_type attribute :vps_vnc attribute :vps_cpu_load attribute :vps_cpu_max attribute :vps_cpu_1h_min attribute :vps_cpu_1h_max attribute :vps_mem_load attribute :vps_mem_max attribute :vps_mem_1h_min attribute :vps_mem_1h_max attribute :vps_hdd_load attribute :vps_hdd_max attribute :vps_traf_rx attribute :vps_traf_tx attribute :vps_createdate attribute :vps_billingdate attribute :vps_update attribute :vps_update_days attribute :vps_root_pass, :aliases => ['adminPass','password'] attribute :vps_user_pass attribute :vps_vnc_pass def initialize(attributes={}) self.image_id ||= attributes[:vps_os] ? attributes[:vps_os] : 666 super attributes end def destroy requires :id service.delete_server(id) true end def image requires :image_id image_id # API does not support image details request. :-( end def private_ip_address nil end def public_ip_address pubaddrs = addresses && addresses['public'] ? addresses['public'].select {|ip| ip['primary_ip']} : nil pubaddrs && !pubaddrs.empty? ? pubaddrs.first['ip'] : nil end def add_ip_address service.add_ip_address(id) end def move_ip_address(ip_address) service.move_ip_address(id, ip_address) end def delete_ip_address(ip_address) service.delete_ip_address(id, ip_address) end def ready? self.state == 'is_running' end def reboot(type = 'SOFT') requires :id service.reboot_server(id, type) true end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :image_id data = service.create_server(image_id, attributes) merge_attributes(data.body['server']) true end def setup(credentials = {}) requires :ssh_ip_address, :identity, :public_key, :username Fog::SSH.new(ssh_ip_address, username, credentials).run([ %{mkdir .ssh}, %{echo "#{public_key}" >> ~/.ssh/authorized_keys}, %{passwd -l #{username}}, %{echo "#{Fog::JSON.encode(attributes)}" >> ~/attributes.json}, ]) rescue Errno::ECONNREFUSED sleep(1) retry end def ssh(commands) super(commands, password ? {:password => password} : {}) end def password vps_root_pass end private end end end end fog-1.42.0/lib/fog/clodo/models/compute/image.rb0000644000004100000410000000102513171001215021355 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Clodo class Image < Fog::Model identity :id attribute :name attribute :vps_type attribute :status attribute :os_type attribute :os_bits attribute :os_hvm def initialize(new_attributes) super(new_attributes) merge_attributes(new_attributes['_attr']) if new_attributes['_attr'] end def ready? status == 'ACTIVE' end end end end end fog-1.42.0/lib/fog/clodo/compute.rb0000644000004100000410000001062613171001215017017 0ustar www-datawww-datarequire 'fog/clodo/core' module Fog module Compute class Clodo < Fog::Service requires :clodo_api_key, :clodo_username recognizes :clodo_auth_url, :persistent recognizes :clodo_auth_token, :clodo_management_url model_path 'fog/clodo/models/compute' model :image collection :images model :server collection :servers request_path 'fog/clodo/requests/compute' request :create_server request :delete_server request :get_image_details # Not supported by API request :list_images request :list_images_detail request :list_servers request :list_servers_detail request :get_server_details request :server_action request :start_server request :stop_server request :reboot_server request :rebuild_server request :add_ip_address request :delete_ip_address request :move_ip_address # request :list_addresses # request :list_private_addresses # request :list_public_addresses # request :confirm_resized_server # request :revert_resized_server # request :resize_server # request :update_server class Mock def self.data @data ||= Hash.new do |hash, key| hash[key] = { :last_modified => { :images => {}, :servers => {} }, :images => {}, :servers => {} } end end def self.reset @data = nil end def initialize(options={}) @clodo_username = options[:clodo_username] end def data self.class.data[@clodo_username] end def reset_data self.class.data.delete(@clodo_username) end end class Real def initialize(options={}) @clodo_api_key = options[:clodo_api_key] @clodo_username = options[:clodo_username] @clodo_auth_url = options[:clodo_auth_url] @clodo_servicenet = options[:clodo_servicenet] @clodo_auth_token = options[:clodo_auth_token] @clodo_management_url = options[:clodo_management_url] @clodo_must_reauthenticate = false authenticate Excon.ssl_verify_peer = false if options[:clodo_servicenet] == true @connection = Fog::XML::Connection.new("#{@scheme}://#{@host}:#{@port}", options[:persistent]) 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] || {}), :host => @host, :path => "#{@path}/#{params[:path]}" })) rescue Excon::Errors::Unauthorized => error if error.response.body != 'Bad username or password' # token expiration @clodo_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::Clodo::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 @clodo_must_reauthenticate || @clodo_auth_token.nil? options = { :clodo_api_key => @clodo_api_key, :clodo_username => @clodo_username, :clodo_auth_url => @clodo_auth_url } credentials = Fog::Clodo.authenticate(options) @auth_token = credentials['X-Auth-Token'] uri = URI.parse(credentials['X-Server-Management-Url']) else @auth_token = @clodo_auth_token uri = URI.parse(@clodo_management_url) end @host = @clodo_servicenet == true ? "snet-#{uri.host}" : uri.host @path = uri.path @port = uri.port @scheme = uri.scheme end end end end end fog-1.42.0/lib/fog/openvz/0000755000004100000410000000000013171001215015232 5ustar www-datawww-datafog-1.42.0/lib/fog/openvz/requests/0000755000004100000410000000000013171001215017105 5ustar www-datawww-datafog-1.42.0/lib/fog/openvz/requests/compute/0000755000004100000410000000000013171001215020561 5ustar www-datawww-datafog-1.42.0/lib/fog/openvz/requests/compute/resume_server.rb0000644000004100000410000000050113171001215023770 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def resume_server(id, options = {}) vzctl("resume",{:ctid => id}.merge(options)) end end class Mock def resume_server(id, options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/restart_server.rb0000644000004100000410000000067513171001215024170 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def restart_server(id, options = {}) vzctl("restart",{:ctid => id}.merge(options)) end end class Mock def restart_server(id, options = {}) server = self.data[:servers].find { |s| s['ctid'] == id.to_s } unless server.nil? server['status'] = 'running' end end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/destroy_server.rb0000644000004100000410000000055113171001215024166 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def destroy_server(id, options = {}) vzctl("destroy",{:ctid => id}.merge(options)) end end class Mock def destroy_server(id , options = {}) self.data[:servers].reject! { |s| s['ctid'].to_s == id.to_s } end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/quotaon_server.rb0000644000004100000410000000050413171001215024161 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def quotaon_server(id, options = {}) vzctl("quotaon",{:ctid => id}.merge(options)) end end class Mock def quotaon_server(id, options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/quotainit_server.rb0000644000004100000410000000051213171001215024507 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def quotainit_server(id, options = {}) vzctl("quotainit",{:ctid => id}.merge(options)) end end class Mock def quotainit_server(id, options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/runscript_server.rb0000644000004100000410000000047013171001215024526 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def runscript_server(id,args = []) vzctl("runscript",{:ctid => id},args) end end class Mock def runscript_server(id,args = []) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/compact_server.rb0000644000004100000410000000050313171001215024120 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def compact_server(id,options = {}) vzctl("compact",{:ctid => id}.merge(options)) end end class Mock def compact_server(id, options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/status_server.rb0000644000004100000410000000050113171001215024013 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def status_server(id, options = {}) vzctl("status",{:ctid => id}.merge(options)) end end class Mock def status_server(id, options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/stop_server.rb0000644000004100000410000000070313171001215023461 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def stop_server(id, options = {}) vzctl("stop",{:ctid => id}.merge(options)) end end class Mock def stop_server(id, options = {}) server = self.data[:servers].find { |s| s['ctid'].to_s == id.to_s } unless server.nil? server['status'] = 'stopped' end end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/suspend_server.rb0000644000004100000410000000050413171001215024154 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def suspend_server(id, options = {}) vzctl("suspend",{:ctid => id}.merge(options)) end end class Mock def suspend_server(id, options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/snapshot_switch_server.rb0000644000004100000410000000053213171001215025714 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def snapshot_switch_server(id,options = {}) vzctl("snapshot-switch",{:ctid => id}.merge(options)) end end class Mock def snapshot_switch_server(id,options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/snapshot_delete_server.rb0000644000004100000410000000053213171001215025655 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def snapshot_delete_server(id,options = {}) vzctl("snapshot-delete",{:ctid => id}.merge(options)) end end class Mock def snapshot_delete_server(id,options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/snapshot_umount_server.rb0000644000004100000410000000053213171001215025742 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def snapshot_umount_server(id,options = {}) vzctl("snapshot-umount",{:ctid => id}.merge(options)) end end class Mock def snapshot_umount_server(id,options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/start_server.rb0000644000004100000410000000066613171001215023641 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def start_server(id,options={}) vzctl("start",{:ctid => id}.merge(options)) end end class Mock def start_server(id,options={}) server = self.data[:servers].find { |s| s['ctid'].to_s == id.to_s } unless server.nil? server['status'] = 'running' end end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/snapshot_mount_server.rb0000644000004100000410000000052713171001215025561 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def snapshot_mount_server(id,options = {}) vzctl("snapshot-mount",{:ctid => id}.merge(options)) end end class Mock def snapshot_mount_server(id,options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/set_server.rb0000644000004100000410000000073213171001215023271 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def set_server(id,options = {}) vzctl("set",{:ctid => id}.merge(options)) end end class Mock def set_server(id, options = {}) server = self.data[:servers].find { |s| s['ctid'].to_s == id.to_s } unless server.nil? options.each do |k,v| server[k] = v end end end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/list_servers.rb0000644000004100000410000000040113171001215023625 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def list_servers(options = {}) vzlist({}) end end class Mock def list_servers self.data[:servers] end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/mount_server.rb0000644000004100000410000000047613171001215023645 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def mount_server(id, options = {}) vzctl("mount",{:ctid => id}.merge(options)) end end class Mock def mount_server(id, options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/create_server.rb0000644000004100000410000000063413171001215023742 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def create_server(options = {}) vzctl("create",options) end end class Mock def create_server(options = {}) # When a new fake server is created we set the status to stopped options['status'] = 'stopped' self.data[:servers] << options end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/snapshot_server.rb0000644000004100000410000000050513171001215024333 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def snapshot_server(id,options = {}) vzctl("snapshot",{:ctid => id}.merge(options)) end end class Mock def snapshot_server(id,options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/quotaoff_server.rb0000644000004100000410000000051113171001215024315 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def quotaooff_server(id, options = {}) vzctl("quotaoff",{:ctid => id}.merge(options)) end end class Mock def quotaooff_server(id, options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/exec_server.rb0000644000004100000410000000045213171001215023421 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def exec_server(id,args = []) vzctl("exec",{:ctid => id},args) end end class Mock def exec_server(id, args = []) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/umount_server.rb0000644000004100000410000000050113171001215024017 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def umount_server(id, options = {}) vzctl("umount",{:ctid => id}.merge(options)) end end class Mock def umount_server(id, options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/convert_server.rb0000644000004100000410000000050313171001215024152 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def convert_server(id,options = {}) vzctl("convert",{:ctid => id}.merge(options)) end end class Mock def convert_server(id, options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/exec2_server.rb0000644000004100000410000000044313171001215023503 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def exec2_server(id,args) vzctl("exec2",{:ctid => id},args) end end class Mock def exec2_server(id, args) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/snapshot_list_server.rb0000644000004100000410000000052513171001215025370 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def snapshot_list_server(id,options = {}) vzctl("snapshot-list",{:ctid => id}.merge(options)) end end class Mock def snapshot_list_server(id, options = {}) Fog::Mock.not_implemented end end end end end fog-1.42.0/lib/fog/openvz/requests/compute/get_server_details.rb0000644000004100000410000000050613171001215024761 0ustar www-datawww-datamodule Fog module Compute class Openvz class Real def get_server_details(id) vzlist({:ctid => id}).first end end class Mock def get_server_details(id) return self.data[:servers].find { |s| s['ctid'].to_s == id.to_s } end end end end end fog-1.42.0/lib/fog/openvz/core.rb0000644000004100000410000000016313171001215016507 0ustar www-datawww-datarequire 'fog/core' module Fog module Openvz extend Fog::Provider service(:compute, 'Compute') end end fog-1.42.0/lib/fog/openvz/models/0000755000004100000410000000000013171001215016515 5ustar www-datawww-datafog-1.42.0/lib/fog/openvz/models/compute/0000755000004100000410000000000013171001215020171 5ustar www-datawww-datafog-1.42.0/lib/fog/openvz/models/compute/servers.rb0000644000004100000410000000074113171001215022211 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/openvz/models/compute/server' module Fog module Compute class Openvz class Servers < Fog::Collection model Fog::Compute::Openvz::Server def all(filters = {}) load service.list_servers end def get(id) if server = service.get_server_details(id) new server end rescue Fog::Errors::NotFound nil end end end end end fog-1.42.0/lib/fog/openvz/models/compute/server.rb0000644000004100000410000001143513171001215022030 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class Openvz class Server < Fog::Compute::Server identity :ctid attribute :ostemplate attribute :config attribute :layout attribute :hostname attribute :name attribute :ipadd attribute :diskspace attribute :private attribute :root attribute :local_uid attribute :local_gid attribute :veid attribute :vpsid attribute :private attribute :mount_opts attribute :origin_sample attribute :smart_name attribute :description attribute :nameserver attribute :searchdomain attribute :status attribute :simfs attribute :cpus attribute :vswap attribute :disabled attribute :ip # vzctl create [--ostemplate ] [--config ] # [--layout ploop|simfs] [--hostname ] [--name ] [--ipadd ] # [--diskspace ] [--private ] [--root ] # [--local_uid ] [--local_gid ] def save requires :ctid raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? meta_hash = {} create_options = { 'ctid' => ctid, 'ostemplate' => ostemplate, 'layout' => layout , 'hostname' => hostname, 'name' => name, 'ipadd' => ipadd, 'diskspace' => diskspace, 'private' => private, 'root' => root, 'local_uid' => local_uid, 'local_gid' => local_gid } data = service.create_server(create_options) reload end def persisted? ctid.nil? end def public_ip_addresses return ip end def public_ip_address if ip.nil? return nil else return ip.first end end def start data = service.start_server(ctid) end def destroy(options = {}) data = service.destroy_server(ctid, options) end def mount(options = {}) data = service.mount_server(ctid, options) end def umount(options = {}) data = service.umount_server(ctid, options) end def stop(options = {}) data = service.stop_server(ctid, options) end def reboot(options = {}) data = service.restart_server(ctid, options) end alias_method :restart, :reboot def convert(options = {}) data = service.convert_server(ctid, options) end def compact(options = {}) data = service.compact_server(ctid, options) end def snapshot(options = {}) data = service.snapshot_server(ctid, options) end def snapshot_switch(options = {}) data = service.snapshot_switch_server(ctid, options) end def snapshot_delete(options = {}) data = service.snapshot_delete_server(ctid, options) end def snapshot_mount(options = {}) data = service.snapshot_mount_server(ctid, options) end def snapshot_umount(options = {}) data = service.snapshot_umount_server(ctid, options) end def snapshot_list(options = {}) data = service.snapshot_list_server(ctid, options) end def quotaon(options = {}) data = service.quotaon_server(ctid, options) end def quotaoff(options = {}) data = service.quotaoff_server(ctid, options) end def quotainit(options = {}) data = service.quotainit_server(ctid, options) end def exec(args) if args.is_a?(String) data = service.exec_server(ctid,[ args ]) else data = service.exec_server(ctid,args) end end def exec2(args) if args.is_a?(String) data = service.exec2_server(ctid,[ args ]) else data = service.exec2_server(ctid,args) end end def runscript(args) if args.is_a?(String) data = service.runscript_server(ctid,[ args ]) else data = service.runscript_server(ctid,args) end end def suspend(options = {}) data = service.suspend_server(ctid, options) end def resume(options = {}) data = service.resume_server(ctid, options) end def set(options) data = service.set_server(ctid,options) end def ready? status == 'running' end end end end end fog-1.42.0/lib/fog/openvz/README.md0000644000004100000410000001474313171001215016522 0ustar www-datawww-data# Description The openvz provider implements a simple mapping between openvz commands and fog # Usage ## Establish a connection openvz = ::Fog::Compute.new( {:provider => 'openvz'}) Additional option is **:openvz_connect_command**: It allows you to specify connect command to connect to the openvz server, if it's not localhost. - This is specified as a string where the '@command@' placeholder will be replaced when the commands are executed - The @command@ will contain double quotes, therefore make sure you use single quotes only inside the placeholder To connect to a remote ssh server myopenvzserver and sudo excute the command openvz = ::Fog::Compute.new( { :provider => 'openvz', :openvz_connect_command => "ssh myopenvzserver 'sudo @command'" }) ## List servers openvz = ::Fog::Compute.new( {:provider => 'openvz'}) servers = openvz.servers.all servers.each do |s| puts c.ctid end ## Server Unique id Servers have the ctid as identity. ## Get a specific server openvz = ::Fog::Compute.new( {:provider => 'openvz'}) server = openvz.servers.get(104) ## Server lifecycle openvz = ::Fog::Compute.new( {:provider => 'openvz'}) # Create a server server = openvz.servers.create( :ctid => '104', :ostemplate => 'ubuntu-12.04-x86_64', :diskspace => 1024*1024 #in kbyte ) server.reload # Start a server unless server.status == 'running' server.start end server.set({ :nameserver => '8.8.8.8', :ipadd => '192.168.8.10', :ram => '380M', :hostname => 'wonderfullserver', :name => 'chef', :description => 'wonderfullserver', :save => true }) # Reboot a server server.reboot sleep 3 # Get the ipaddress puts "ipaddress: #{server.public_ip_address}" server.wait_for { status == 'running' } # Stop the server server.stop # Destroy the server server.destroy ## Models Both compute::server and computer::servers (collections) have been implemented Note: - server.save can only be called upon creation, use the server.set command to change the settings - server.public_ip_address will only return the first ip address - TODO: snapshots could be implemented as a collection - server.state has the standard openvz states. - server.ready? assumes server.status == 'running' ## Requests ### Passing parameters The server request are in essence a passthrough to __vzctl__. Just provide the options as a hash in key,value pairs. If it's just a switch (like --save), use a key and a boolean(true). The following command in plain cli-vzctl: vzctl set 104 --nameserver 8.8.8.8 --ipadd 192.168.8.10 --ram '380M' Would be in fog-speak: server = openvz.servers.get(104) server.set({ :nameserver => '8.8.8.8', :ipadd => '192.168.8.10', :ram => '380M', :save => true }) To specify multiple values for the same option pass an array server.set({ :nameserver => ['8.8.8.8','7.7.7.7'], :ipadd => ['192.168.8.10','192.168.4.10'], :ram => '380M', :save => true }) ### Passing arguments both exec, exec2 and runscript take no parameters just arguments server = openvz.servers.get(104) uname_output = server.exec("uname -a") ### Not implemented From all the options to vzctl (see below) the following commands have **NOT** been implemented: - console : as it requires direct input ## VZCTL commands the current version of the fog openvz driver is based on the following vzctl syntax vzctl version 4.3 Copyright (C) 2000-2012, Parallels, Inc. This program may be distributed under the terms of the GNU GPL License. Usage: vzctl [options] [parameters] vzctl create [--ostemplate ] [--config ] [--layout ploop|simfs] [--hostname ] [--name ] [--ipadd ] [--diskspace ] [--private ] [--root ] [--local_uid ] [--local_gid ] vzctl start [--force] [--wait] vzctl destroy | mount | umount | stop | restart | status vzctl convert [--layout ploop[:mode]] [--diskspace ] vzctl compact vzctl snapshot [--id ] [--name ] [--description ] [--skip-suspend] vzctl snapshot-switch | snapshot-delete --id vzctl snapshot-mount --id --target vzctl snapshot-umount --id vzctl snapshot-list [-H] [-o field[,field...]] [--id ] vzctl quotaon | quotaoff | quotainit vzctl console [ttyno] vzctl enter [--exec [arg ...]] vzctl exec | exec2 [arg ...] vzctl runscript