fog-google-0.5.3/0000755000004100000410000000000013145731036013577 5ustar www-datawww-datafog-google-0.5.3/Rakefile0000644000004100000410000000110013145731036015234 0ustar www-datawww-datarequire "rubygems" require "bundler/setup" # Immediately sync all stdout so that tools like buildbot can # immediately load in the output. $stdout.sync = true $stderr.sync = true # Load all the rake tasks from the "tasks" folder. This folder # allows us to nicely separate rake tasks into individual files # based on their role, which makes development and debugging easier # than one monolithic file. task_dir = File.expand_path("../tasks", __FILE__) Dir["#{task_dir}/**/*.rake"].each do |task_file| load task_file end desc "Default Task" task :default => "test:travis" fog-google-0.5.3/Gemfile0000644000004100000410000000013713145731036015073 0ustar www-datawww-datasource "https://rubygems.org" # Specify your gem's dependencies in fog-google.gemspec gemspec fog-google-0.5.3/examples/0000755000004100000410000000000013145731036015415 5ustar www-datawww-datafog-google-0.5.3/examples/l7_load_balance.rb0000644000004100000410000000567413145731036020744 0ustar www-datawww-data# This example assumes three instances have been created in the project. # They should each have Apache installed and distinct index.html files # in order to observe the results of the l7 load balancer. A firewall # rule should also have been created with a tag shared by the instances. # More info on Google's HTTP load balancing: # https://developers.google.com/compute/docs/load-balancing/http/ def test connection = Fog::Compute.new(:provider => "google") health = connection.http_health_checks.create(:name => "test-checks") instance1 = connection.servers.get("fog-l7-instance-1") instance2 = connection.servers.get("fog-l7-instance-2") instance3 = connection.servers.get("fog-l7-instance-3") resource_view1 = connection.resource_views.create( :name => "fog-l7-resource-view-1", :numMembers => 1, :members => [instance1.self_link], :zone => "us-central1-a") resource_view1.add_resources(instance1.self_link) resource_view2 = connection.resource_views.create( :name => "fog-l7-resource-view-2", :numMembers => 1, :members => [instance2.self_link], :zone => "us-central1-a") resource_view2.add_resources(instance2.self_link) resource_view3 = connection.resource_views.create( :name => "fog-l7-resource-view-3", :members => [instance3.self_link], :zone => "us-central1-b") resource_view3.add_resources(instance3.self_link) backend_service1 = connection.backend_services.create( :name => "fog-l7-backend-service-1", :health_checks => [health.self_link], :backends => [{ "balancingMode" => "RATE", "maxRate" => 100, "group" => resource_view1.self_link }]) backend_service2 = connection.backend_services.create( :name => "fog-l7-backend-service-2", :health_checks => [health.self_link], :backends => [{ "balancingMode" => "RATE", "maxRate" => 100, "group" => resource_view2.self_link }]) backend_service3 = connection.backend_services.create( :name => "fog-l7-backend-service-3", :health_checks => [health.self_link], :backends => [{ "balancingMode" => "RATE", "maxRate" => 100, "group" => resource_view3.self_link }]) url_map = connection.url_maps.create( :name => "fog-l7-url-map", :pathMatchers => [{ "name" => "pathmatcher", "defaultService" => backend_service1.self_link, "pathRules" => [ { "paths" => ["/one/*"], "service" => backend_service1.self_link }, { "paths" => ["/two/*"], "service" => backend_service2.self_link }, { "paths" => ["/three/*"], "service" => backend_service3.self_link } ] }], :hostRules => [{ "hosts" => ["*"], "pathMatcher" => "pathmatcher" }], :default_service => backend_service1.self_link) proxy = connection.target_http_proxies.create( :name => "fog-l7-proxy", :url_map => url_map.self_link) connection.global_forwarding_rules.create(:name => "fog-l7-fwd-rule", :target => proxy.self_link) end fog-google-0.5.3/examples/get_list_images.rb0000644000004100000410000000303113145731036021076 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # More info on it can be found here: http://fog.io/about/getting_started.html require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! def test connection = Fog::Compute.new(:provider => "Google") puts "Listing images in all projects..." puts "---------------------------------" images = connection.images.all raise "Could not LIST the images" unless images puts images.inspect puts "Listing current (non-deprecated) images in all projects..." puts "----------------------------------------------------------" images = connection.images.current raise "Could not LIST current images" unless images puts images.inspect puts "Fetching a single image from a global project..." puts "------------------------------------------------" img = connection.images.get("debian-8-jessie-v20161215") raise "Could not GET the image" unless img puts img.inspect # First, get the name of an image that is in the users 'project' (not global) custom_img_name = images.detect { |i| i.project.eql? i.service.project } # Run the next test only if there is a custom image available if custom_img_name puts "Fetching a single image from the custom project" puts "----------------------------------------------" img = connection.images.get(custom_img_name.name) raise "Could not GET the (custom) image" unless img puts img.inspect end end test fog-google-0.5.3/examples/bootstrap.rb0000644000004100000410000000105513145731036017760 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # More info on it can be found here: http://fog.io/about/getting_started.html require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! def test connection = Fog::Compute.new(:provider => "Google") server = connection.servers.bootstrap raise "Could not bootstrap sshable server." unless server.ssh("whoami") raise "Could not delete server." unless server.destroy end test fog-google-0.5.3/examples/get_list_snapshots.rb0000644000004100000410000000147213145731036021662 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # More info on it can be found here: http://fog.io/about/getting_started.html require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! def test connection = Fog::Compute.new(:provider => "Google") puts "Listing snapshots..." puts "---------------------------------" snapshots = connection.snapshots.all raise "Could not LIST the snapshots" unless snapshots puts snapshots.inspect puts "Fetching a single snapshot..." puts "---------------------------------" snap = snapshots.first unless snap.nil? snap = connection.snapshots.get(snap) raise "Could not GET the snapshot" unless snap puts snap.inspect end end test fog-google-0.5.3/examples/load-balance.rb0000644000004100000410000000516613145731036020254 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # More info on it can be found here: http://fog.io/about/getting_started.html require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! def test # Config name = "fog-lb-test-#{Time.now.to_i}" zone = "europe-west1-d" region = "europe-west1" # Setup gce = Fog::Compute.new :provider => "Google" servers = [] puts "Creating instances..." puts "--------------------------------" (1..3).each do |i| begin disk = gce.disks.create( :name => "#{name}-#{i}", :size_gb => 10, :zone_name => zone, :source_image => "debian-8-jessie-v20160718" ) disk.wait_for { disk.ready? } rescue puts "Failed to create disk #{name}-#{i}" end begin server = gce.servers.create( :name => "#{name}-#{i}", :disks => [disk.get_as_boot_disk(true, true)], :machine_type => "f1-micro", :zone_name => zone ) servers << server rescue puts "Failed to create instance #{name}-#{i}" end end puts "Creating health checks..." puts "--------------------------------" begin health = gce.http_health_checks.new(:name => name) health.save rescue puts "Failed to create health check #{name}" end puts "Creating a target pool..." puts "--------------------------------" begin pool = gce.target_pools.new( :name => name, :region => region, :health_checks => [health.self_link], :instances => servers.map(&:self_link) ) pool.save rescue puts "Failed to create target pool #{name}" end puts "Creating forwarding rules..." puts "--------------------------------" begin rule = gce.forwarding_rules.new( :name => name, :region => region, :port_range => "1-65535", :ip_protocol => "TCP", :target => pool.self_link ) rule.save rescue puts "Failed to create forwarding rule #{name}" end # TODO(bensonk): Install apache, create individualized htdocs, and run some # actual requests through the load balancer. # Cleanup puts "Cleaning up..." puts "--------------------------------" begin rule.destroy rescue puts "Failed to clean up forwarding rule." end begin pool.destroy rescue puts "Failed to clean up target pool." end begin health.destroy rescue puts "Failed to clean up health check." end begin servers.each(&:destroy) rescue puts "Failed to clean up instances." end end test fog-google-0.5.3/examples/metadata.rb0000644000004100000410000000210613145731036017521 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # More info on it can be found here: http://fog.io/about/getting_started.html require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! def test connection = Fog::Compute.new(:provider => "Google") name = "fog-smoke-test-#{Time.now.to_i}" disk = connection.disks.create( :name => name, :size_gb => 10, :zone_name => "us-central1-f", :source_image => "debian-8-jessie-v20161215" ) disk.wait_for { disk.ready? } server = connection.servers.create( :name => name, :disks => [disk], :machine_type => "n1-standard-1", :zone_name => "us-central1-f", :private_key_path => File.expand_path("~/.ssh/id_rsa"), :public_key_path => File.expand_path("~/.ssh/id_rsa.pub")) server.wait_for { ready? } server.metadata["test"] = "foo" raise "Metadata was not set." unless server.metadata["test"] == "foo" raise "Could not delete server." unless server.destroy end test fog-google-0.5.3/examples/network.rb0000644000004100000410000000320313145731036017431 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # More info on it can be found here: http://fog.io/about/getting_started.html require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! def test connection = Fog::Compute.new(:provider => "Google") puts "Creating a new private network..." puts "---------------------------------" network = connection.networks.create( :name => "test-private-network", :ipv4_range => "10.240.0.0/16" ) name = "fog-smoke-test-#{Time.now.to_i}" puts "Creating a disk for an instance..." puts "---------------------------------" disk = connection.disks.create( :name => name, :size_gb => 10, :zone_name => "us-central1-a", :source_image => "debian-8-jessie-v20161215" ) disk.wait_for { disk.ready? } puts "Spinning up an instance with private network config..." puts "------------------------------------------------------" server = connection.servers.create( :name => name, :disks => [disk], :machine_type => "n1-standard-1", :zone_name => "us-central1-a", :private_key_path => File.expand_path("~/.ssh/id_rsa"), :public_key_path => File.expand_path("~/.ssh/id_rsa.pub"), :network => network, :external_ip => false, :username => ENV["USER"] ) # The network won't have any firewall rules, so we won't be able to ssh in. server.wait_for { ready? } raise "Could not delete server." unless server.destroy raise "Could not delete network." unless network.destroy rescue StandardError => e p e.message end test fog-google-0.5.3/examples/dns/0000755000004100000410000000000013145731036016201 5ustar www-datawww-datafog-google-0.5.3/examples/dns/project.rb0000644000004100000410000000025513145731036020176 0ustar www-datawww-datadef test connection = Fog::DNS::Google.new puts "Get the Project limits..." puts "-------------------------" connection.projects.get(Fog::DNS[:google].project) end fog-google-0.5.3/examples/dns/zones.rb0000644000004100000410000000217613145731036017672 0ustar www-datawww-datadef test connection = Fog::DNS::Google.new puts "Create a Zone..." puts "----------------" zone = connection.zones.create(:name => "mytestdomain", :domain => "example.org.", :description => "This is my test domain") puts "List all Zones..." puts "-----------------" connection.zones.all puts "Get the Zone..." puts "---------------" zone = connection.zones.get(zone.id) puts 'Create an "A" Record...' puts "-----------------------" zone.records.create(:name => "test.example.org.", :type => "A", :ttl => 3600, :rrdatas => ["192.168.1.1"]) puts "Get the Zone Resource Record Sets..." puts "------------------------------------" zone.records puts "Get the Record..." puts "-----------------" record = connection.records(:zone => zone).get("test.example.org.", "A") puts 'Modify the "A" Record...' puts "------------------------" record.modify(:ttl => 2600) puts 'Delete the "A" Record...' puts "------------------------" record.destroy puts "Get the Zone Changes..." puts "-----------------------" zone.changes puts "Delete the Zone..." puts "------------------" zone.destroy end fog-google-0.5.3/examples/storage_json.rb0000644000004100000410000000230313145731036020435 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # More info on it can be found here: http://fog.io/about/getting_started.html require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! # This specific example needs google_storage_access_key_id: and google_storage_secret_access_key to be set in ~/.fog # One can request those keys via Google Developers console in: # Storage -> Storage -> Settings -> "Interoperability" tab -> "Create a new key" def test connection = Fog::Storage::Google.new puts "Put a bucket..." puts "----------------" connection.put_bucket("fog-smoke-test", options = { "predefinedAcl" => "publicReadWrite" }) puts "Get the bucket..." puts "-----------------" connection.get_bucket("fog-smoke-test") puts "Put a test file..." puts "---------------" connection.put_object("fog-smoke-test", "my file", "THISISATESTFILE") puts "Delete the test file..." puts "---------------" connection.delete_object("fog-smoke-test", "my file") puts "Delete the bucket..." puts "------------------" connection.delete_bucket("fog-smoke-test") end test fog-google-0.5.3/examples/backend_services.rb0000644000004100000410000000111113145731036021226 0ustar www-datawww-datarequire "rubygems" require "fog" def test connection = Fog::Compute.new(:provider => "google") health = connection.http_health_checks.create(:name => "test-checks") health.wait_for { health.ready? } backend = connection.backend_services.create( :name => "backend-test", :health_checks => [health.self_link], :port => 8080, :timeout_sec => 40, :backends => [{ "group" => "resource_view self_link" }] ) backend.get_health puts connection.backend_services.all backend = connection.backend_services.get("backend-test") backend.get_health end test fog-google-0.5.3/examples/sql/0000755000004100000410000000000013145731036016214 5ustar www-datawww-datafog-google-0.5.3/examples/sql/ssl_certs.rb0000644000004100000410000000156313145731036020547 0ustar www-datawww-datadef test connection = Fog::Google::SQL.new puts "Create a Instance..." puts "--------------------" instance = connection.instances.create(:instance => Fog::Mock.random_letters(16), :tier => "D1") instance.wait_for { ready? } puts "Create a SSL certificate..." puts "---------------------------" ssl_cert = connection.ssl_certs.create(:instance => instance.instance, :common_name => Fog::Mock.random_letters(16)) puts "Get the SSL certificate..." puts "--------------------------" connection.ssl_certs.get(instance.instance, ssl_cert.sha1_fingerprint) puts "List all SSL certificate..." puts "---------------------------" connection.ssl_certs.all(instance.instance) puts "Delete the SSL certificate..." puts "-----------------------------" ssl_cert.destroy puts "Delete the Instance..." puts "----------------------" instance.destroy end fog-google-0.5.3/examples/sql/flags.rb0000644000004100000410000000020113145731036017626 0ustar www-datawww-datadef test connection = Fog::Google::SQL.new puts "Listing all Flags..." puts "--------------------" connection.flags end fog-google-0.5.3/examples/sql/tiers.rb0000644000004100000410000000020113145731036017660 0ustar www-datawww-datadef test connection = Fog::Google::SQL.new puts "Listing all Tiers..." puts "--------------------" connection.tiers end fog-google-0.5.3/examples/sql/instances.rb0000644000004100000410000000202613145731036020530 0ustar www-datawww-datadef test connection = Fog::Google::SQL.new puts "Create a Instance..." puts "--------------------" instance = connection.instances.create(:instance => Fog::Mock.random_letters(16), :tier => "D1") instance.wait_for { ready? } puts "Get the Instance..." puts "----------------------" connection.instances.get(instance.instance) puts "List all Instances..." puts "---------------------" connection.instances.all puts "Update the Instance..." puts "----------------------" instance.activation_policy = "ALWAYS" instance.update instance.wait_for { ready? } puts "Reset the Instance SSL configuration..." puts "---------------------------------------" instance.reset_ssl_config puts "Restart the Instance..." puts "-----------------------" instance.restart puts "Set the Instance root password..." puts "---------------------------------" instance.set_root_password(Fog::Mock.random_letters_and_numbers(8)) puts "Delete the Instance..." puts "----------------------" instance.destroy end fog-google-0.5.3/examples/sql/operations.rb0000644000004100000410000000110613145731036020722 0ustar www-datawww-datadef test connection = Fog::Google::SQL.new puts "Create a Instance..." puts "--------------------" instance = connection.instances.create(:instance => Fog::Mock.random_letters(16), :tier => "D1") instance.wait_for { ready? } puts "Delete the Instance..." puts "----------------------" operation = instance.destroy puts "Get the Operation..." puts "--------------------" connection.operations.get(instance.identity, operation.identity) puts "Listing all Operations..." puts "-------------------------" connection.operations.all(instance.identity) end fog-google-0.5.3/examples/precreated_client.rb0000644000004100000410000000134713145731036021423 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # More info on it can be found here: http://fog.io/about/getting_started.html require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! # This example shows how to work with fog using a pre-created Google API client # with specific parameters, should you want to for any reason. def test client = Google::APIClient.new(:application_name => "supress") connection = Fog::Compute.new(:provider => "Google", :google_client => client) begin p connection.client.discovered_apis p connection.servers rescue StandardError => e p e.message end end test fog-google-0.5.3/examples/create_instance.rb0000644000004100000410000000327613145731036021101 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # More info on it can be found here: http://fog.io/about/getting_started.html require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! def test connection = Fog::Compute.new(:provider => "Google") disk = connection.disks.create( :name => "fog-smoke-test-#{Time.now.to_i}", :size_gb => 10, :zone_name => "us-central1-f", :source_image => "debian-8-jessie-v20161215" ) disk.wait_for { disk.ready? } server = connection.servers.create( :name => "fog-smoke-test-#{Time.now.to_i}", :disks => [disk], :machine_type => "n1-standard-1", :private_key_path => File.expand_path("~/.ssh/id_rsa"), :public_key_path => File.expand_path("~/.ssh/id_rsa.pub"), :zone_name => "us-central1-f", :username => ENV["USER"], :tags => ["fog"], :service_accounts => %w(sql-admin bigquery https://www.googleapis.com/auth/compute) ) # Wait_for routine copied here to show errors, if necessary. duration = 0 interval = 5 timeout = 600 start = Time.now until server.sshable? || duration > timeout # puts duration # puts " ----- " server.reload # p "ready?: #{server.ready?}" # p "public_ip_address: #{server.public_ip_address.inspect}" # p "public_key: #{server.public_key.inspect}" # p "metadata: #{server.metadata.inspect}" # p "sshable?: #{server.sshable?}" sleep(interval.to_f) duration = Time.now - start end raise "Could not bootstrap sshable server." unless server.ssh("whoami") raise "Could not delete server." unless server.destroy end test fog-google-0.5.3/examples/pubsub/0000755000004100000410000000000013145731036016715 5ustar www-datawww-datafog-google-0.5.3/examples/pubsub/topics.rb0000644000004100000410000000154713145731036020552 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # # More info on it can be found here: http://fog.io/about/getting_started.html # require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! def test connection = Fog::Google::Pubsub.new puts "Creating a topic" puts "----------------" topic = connection.topics.create(:name => "projects/#{connection.project}/topics/#{Fog::Mock.random_letters(16)}") puts "Getting a topic" puts "---------------" connection.topics.get(topic.name) puts "Listing all topics" puts "------------------" connection.topics.all puts "Publishing to topic" puts "-------------------" topic.publish(["test message"]) puts "Delete the topic" puts "----------------" topic.destroy end test fog-google-0.5.3/examples/pubsub/subscriptions.rb0000644000004100000410000000314513145731036022154 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # # More info on it can be found here: http://fog.io/about/getting_started.html # require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! def test connection = Fog::Google::Pubsub.new puts "Creating a topic to subscribe to" puts "--------------------------------" topic = connection.topics.create(:name => "projects/#{connection.project}/topics/#{Fog::Mock.random_letters(16)}") puts "Creating a subscription" puts "-----------------------" subscription = connection.subscriptions.create(:name => "projects/#{connection.project}/subscriptions/#{Fog::Mock.random_letters(16)}", :topic => topic) puts "Getting a subscription" puts "----------------------" connection.subscriptions.get(subscription.name) puts "Listing all subscriptions" puts "-------------------------" connection.subscriptions.all puts "Publishing to topic" puts "-------------------" topic.publish(["test message"]) puts "Pulling from subscription" puts "-------------------------" msgs = [] msgs = subscription.pull while msgs.empty? puts "Acknowledging pulled messages" puts "-----------------------------" subscription.acknowledge(msgs) # Alternatively, received messages themselves can be acknowledged msgs.each(&:acknowledge) puts "Deleting the subscription" puts "-------------------------" subscription.destroy puts "Deleting the topic subscribed to" puts "--------------------------------" topic.destroy end test fog-google-0.5.3/examples/image_create.rb0000644000004100000410000000115413145731036020350 0ustar www-datawww-datadef test connection = Fog::Compute.new(:provider => "Google") rawdisk = { :source => nil, # Google Cloud Storage URL pointing to the disk image. (e.g. http://storage.googleapis.com/test/test.tar.gz) :container_type => "TAR" } # Can't test this unless the 'source' points to a valid URL return if rawdisk[:source].nil? img = connection.images.create(:name => "test-image", :description => "Test image (via fog)", :raw_disk => rawdisk) img.reload # will raise if image was not saved correctly end fog-google-0.5.3/examples/monitoring/0000755000004100000410000000000013145731036017602 5ustar www-datawww-datafog-google-0.5.3/examples/monitoring/timeseries_descriptors.rb0000644000004100000410000000243013145731036024720 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # # More info on it can be found here: http://fog.io/about/getting_started.html # require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! def test connection = Fog::Google::Monitoring.new puts "Listing all TimeseriesDescriptors for the metric compute.googleapis.com/instance/uptime..." puts "------------------------------------------------------------------------------------------" td = connection.timeseries_descriptors.all("compute.googleapis.com/instance/uptime", DateTime.now.rfc3339) puts "Number of matches: #{td.length}" puts "Listing all TimeseriesDescriptors for the metric compute.googleapis.com/instance/uptime &" puts "the region us-central1..." puts "-----------------------------------------------------------------------------------------" td = connection.timeseries_descriptors.all("compute.googleapis.com/instance/uptime", DateTime.now.rfc3339, :labels => "cloud.googleapis.com/location=~us-central1.*") puts "Number of matches: #{td.length}" end test fog-google-0.5.3/examples/monitoring/metric_descriptors.rb0000644000004100000410000000147613145731036024043 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # # More info on it can be found here: http://fog.io/about/getting_started.html # require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! # def test connection = Fog::Google::Monitoring.new puts "Listing all MetricDescriptors..." puts "--------------------------------" md = connection.metric_descriptors puts "Number of all metric descriptors: #{md.length}" puts "\nListing all MetricDescriptors related to Google Compute Engine..." puts "-----------------------------------------------------------------" md = connection.metric_descriptors.all(:query => "compute") puts "Number of compute metric descriptors: #{md.length}" end test fog-google-0.5.3/examples/monitoring/timeseries_collection.rb0000644000004100000410000000235113145731036024514 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # # More info on it can be found here: http://fog.io/about/getting_started.html # require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! def test connection = Fog::Google::Monitoring.new puts "Listing all Timeseries for the metric compute.googleapis.com/instance/uptime..." puts "-------------------------------------------------------------------------------" tc = connection.timeseries_collection.all("compute.googleapis.com/instance/uptime", DateTime.now.rfc3339) puts "Number of matches: #{tc.length}" puts "\nListing all Timeseries for the metric compute.googleapis.com/instance/uptime &" puts "the region us-central1..." puts "------------------------------------------------------------------------------" tc = connection.timeseries_collection.all("compute.googleapis.com/instance/uptime", DateTime.now.rfc3339, :labels => "cloud.googleapis.com/location=~us-central1.*") puts "Number of matches: #{tc.length}" end test fog-google-0.5.3/examples/storage.rb0000644000004100000410000000271613145731036017414 0ustar www-datawww-data# All examples presume that you have a ~/.fog credentials file set up. # More info on it can be found here: http://fog.io/about/getting_started.html require "bundler" Bundler.require(:default, :development) # Uncomment this if you want to make real requests to GCE (you _will_ be billed!) # WebMock.disable! # This specific example needs google_storage_access_key_id: and google_storage_secret_access_key to be set in ~/.fog # One can request those keys via Google Developers console in: # Storage -> Storage -> Settings -> "Interoperability" tab -> "Create a new key" def test connection = Fog::Storage::Google.new puts "Put a bucket..." puts "----------------" connection.put_bucket("fog-smoke-test") puts "Get the bucket..." puts "-----------------" connection.get_bucket("fog-smoke-test") puts "Put a test file..." puts "---------------" connection.put_object("fog-smoke-test", "my file", "THISISATESTFILE") puts "Get the test file..." puts "---------------" connection.get_object("fog-smoke-test", "my file") puts "Head file..." puts "---------------" connection.head_object("fog-smoke-test", "my file") puts "Get file ACL..." puts "---------------" connection.get_object_acl("fog-smoke-test", "my file") puts "Delete the test file..." puts "---------------" connection.delete_object("fog-smoke-test", "my file") puts "Delete the bucket..." puts "------------------" connection.delete_bucket("fog-smoke-test") end test fog-google-0.5.3/tests/0000755000004100000410000000000013145731036014741 5ustar www-datawww-datafog-google-0.5.3/tests/helper.rb0000644000004100000410000001142613145731036016551 0ustar www-datawww-dataENV["FOG_RC"] = ENV["FOG_RC"] || File.expand_path("../.fog", __FILE__) ENV["FOG_CREDENTIAL"] = ENV["FOG_CREDENTIAL"] || "default" require "fog/google" require "securerandom" 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" 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 # create a disk to be used in tests def create_test_disk(connection, zone) zone = "us-central1-a" random_string = SecureRandom.hex disk = connection.disks.create({ :name => "fog-test-disk-#{random_string}", :size_gb => "10", :zone => zone, :source_image => "debian-8-jessie-v20161215" }) disk.wait_for { ready? } disk end def create_test_http_health_check(connection) random_string = SecureRandom.hex health_check = connection.http_health_checks.create({ :name => "fog-test-check-#{random_string}" }) health_check end def create_test_backend_service(connection) random_string = SecureRandom.hex health_check = create_test_http_health_check(connection) backend_service = connection.backend_services.create({ :name => "fog-test-backend-service-#{random_string}", :health_checks => [health_check] }) end def create_test_url_map(connection) random_string = SecureRandom.hex backend_service = create_test_backend_service(connection) url_map = connection.url_maps.create({ :name => "fog-test-url-map-#{random_string}", :default_service => backend_service.self_link }) end def create_test_server(connection, zone) random_string = SecureRandom.hex disk = create_test_disk(connection, zone) server = connection.servers.create({ :name => "fog-test-server-#{random_string}", :disks => [disk], :zone => zone, :machine_type => "n1-standard-1" }) end def create_test_target_http_proxy(connection) random_string = SecureRandom.hex url_map = create_test_url_map(connection) proxy = connection.target_http_proxies.create({ :name => "fog-test-target-http-proxy-#{random_string}", :url_map => url_map.self_link }) end def create_test_zone_view(connection, zone) random_string = SecureRandom.hex zone_view = connection.zone_views.create({ :name => "fog-test-zone-view-#{random_string}", :zone => zone }) zone_view.wait_for { ready? } zone_view end def create_test_target_pool(connection, region) random_string = SecureRandom.hex http_health_check = create_test_http_health_check(connection) instance = create_test_server(connection, "us-central1-a") target_pool = connection.target_pools.create({ :name => "fog-test-target-pool-#{random_string}", :region => region, :health_checks => [http_health_check.self_link], :instances => [instance.self_link]\ }) end def wait_operation(connection, response) operation = connection.operations.get(response["name"], response["zone"], response["region"]) operation.wait_for { ready? } 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" domain += "." if with_trailing_dot domain end fog-google-0.5.3/tests/lorem.txt0000644000004100000410000000067613145731036016631 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-google-0.5.3/tests/requests/0000755000004100000410000000000013145731036016614 5ustar www-datawww-datafog-google-0.5.3/tests/requests/storage/0000755000004100000410000000000013145731036020260 5ustar www-datawww-datafog-google-0.5.3/tests/requests/storage/object_tests.rb0000644000004100000410000000672013145731036023302 0ustar www-datawww-datarequire "securerandom" Shindo.tests("Fog::Storage[:google] | object requests", ["google"]) do random_string = SecureRandom.hex @directory = Fog::Storage[:google].directories.create(:key => "fog-test-object-#{random_string}") tests("success") do tests("#put_object('#{@directory.identity}', 'fog_object', lorem_file)").succeeds do Fog::Storage[:google].put_object(@directory.identity, "fog_object", lorem_file) end tests("#copy_object('#{@directory.identity}', 'fog_object', '#{@directory.identity}', 'fog_other_object')").succeeds do Fog::Storage[:google].copy_object(@directory.identity, "fog_object", @directory.identity, "fog_other_object") end Fog::Storage[:google].delete_object(@directory.identity, "fog_other_object") tests("#get_object('#{@directory.identity}', 'fog_object')").returns(lorem_file.read) do Fog::Storage[:google].get_object(@directory.identity, "fog_object").body end tests("#get_object('#{@directory.identity}', 'fog_object', &block)").returns(lorem_file.read) do data = "" Fog::Storage[:google].get_object(@directory.identity, "fog_object") do |chunk, _remaining_bytes, _total_bytes| data << chunk end data end tests("#head_object('#{@directory.identity}', 'fog_object')").succeeds do Fog::Storage[:google].head_object(@directory.identity, "fog_object") end tests("#delete_object('#{@directory.identity}', 'fog_object')").succeeds do Fog::Storage[:google].delete_object(@directory.identity, "fog_object") end end tests("failure") do tests("#put_object('fognonbucket', 'fog_non_object', lorem_file)").raises(Excon::Errors::NotFound) do Fog::Storage[:google].put_object("fognonbucket", "fog_non_object", lorem_file) end tests("#copy_object('fognonbucket', 'fog_object', '#{@directory.identity}', 'fog_other_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].copy_object("fognonbucket", "fog_object", @directory.identity, "fog_other_object") end tests("#copy_object('#{@directory.identity}', 'fog_non_object', '#{@directory.identity}', 'fog_other_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].copy_object(@directory.identity, "fog_non_object", @directory.identity, "fog_other_object") end tests("#copy_object('#{@directory.identity}', 'fog_object', 'fognonbucket', 'fog_other_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].copy_object(@directory.identity, "fog_object", "fognonbucket", "fog_other_object") end tests("#get_object('fognonbucket', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].get_object("fognonbucket", "fog_non_object") end tests("#get_object('#{@directory.identity}', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].get_object(@directory.identity, "fog_non_object") end tests("#head_object('fognonbucket', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].head_object("fognonbucket", "fog_non_object") end tests("#head_object('#{@directory.identity}', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].head_object(@directory.identity, "fog_non_object") end tests("#delete_object('fognonbucket', 'fog_non_object')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].delete_object("fognonbucket", "fog_non_object") end end @directory.destroy end fog-google-0.5.3/tests/requests/storage/bucket_tests.rb0000644000004100000410000000374713145731036023317 0ustar www-datawww-dataShindo.tests("Fog::Storage[:google] | bucket requests", ["google"]) do tests("success") do @bucket_format = { "CommonPrefixes" => [], "IsTruncated" => Fog::Boolean, "Marker" => NilClass, "Name" => String, "Prefix" => NilClass, "Contents" => [{ "ETag" => String, "Key" => String, "LastModified" => Time, "Owner" => { "DisplayName" => String, "ID" => String }, "Size" => Integer }] } @service_format = { "Buckets" => [{ "CreationDate" => Time, "Name" => String }], "Owner" => { "ID" => String } } tests("#put_bucket('fogbuckettests')").succeeds do Fog::Storage[:google].put_bucket("fogbuckettests") end tests("#get_service").formats(@service_format) do Fog::Storage[:google].get_service.body end file = Fog::Storage[:google].directories.get("fogbuckettests").files.create(:body => "y", :key => "x") tests("#get_bucket('fogbuckettests)").formats(@bucket_format) do Fog::Storage[:google].get_bucket("fogbuckettests").body end file.destroy tests("#delete_bucket('fogbuckettests')").succeeds do Fog::Storage[:google].delete_bucket("fogbuckettests") end end tests("failure") do tests("#delete_bucket('fognonbucket')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].delete_bucket("fognonbucket") end @bucket = Fog::Storage[:google].directories.create(:key => "fognonempty") @file = @bucket.files.create(:key => "foo", :body => "bar") tests("#delete_bucket('fognonempty')").raises(Excon::Errors::Conflict) do Fog::Storage[:google].delete_bucket("fognonempty") end @file.destroy @bucket.destroy tests("#get_bucket('fognonbucket')").raises(Excon::Errors::NotFound) do Fog::Storage[:google].get_bucket("fognonbucket") end end end fog-google-0.5.3/tests/requests/dns/0000755000004100000410000000000013145731036017400 5ustar www-datawww-datafog-google-0.5.3/tests/requests/dns/project_tests.rb0000644000004100000410000000122713145731036022617 0ustar www-datawww-dataShindo.tests("Fog::DNS[:google] | project requests", ["google"]) do @dns = Fog::DNS[:google] @project_quota_format = { "kind" => String, "managedZones" => Integer, "rrsetsPerManagedZone" => Integer, "rrsetAdditionsPerChange" => Integer, "rrsetDeletionsPerChange" => Integer, "totalRrdataSizePerChange" => Integer, "resourceRecordsPerRrset" => Integer } @get_project_format = { "kind" => String, "number" => String, "id" => String, "quota" => @project_quota_format } tests("success") do tests('#get_project').formats(@get_project_format) do @dns.get_project(@dns.project).body end end end fog-google-0.5.3/tests/requests/dns/managed_zone_tests.rb0000644000004100000410000000436113145731036023602 0ustar www-datawww-dataShindo.tests("Fog::DNS[:google] | managed_zone requests", ["google"]) do @google = Fog::DNS[:google] @managed_zone_schema = { "kind" => String, "id" => String, "creationTime" => String, "name" => String, "dnsName" => String, "description" => String, "nameServers" => [String] } @list_managed_zones_schema = { "kind" => String, "managedZones" => [@managed_zone_schema] } tests("success") do zone_name = "new-zone-test" DEFAULT_ZONE_DNS_NAME = "fog-test.your-own-domain.com." # Google requires confirmation of ownership for created domains in some # cases. If you want to run tests in non-mocked mode, set the environment # variable to a domain you own. zone_dns_name = ENV["FOG_TEST_GOOGLE_DNS_ZONE"] || DEFAULT_ZONE_DNS_NAME unless Fog.mocking? || zone_dns_name != DEFAULT_ZONE_DNS_NAME tests("Needs a verified domain, set $FOG_TEST_GOOGLE_DNS_ZONE").pending end tests("$FOG_TEST_GOOGLE_DNS_ZONE ends with dot").pending unless zone_dns_name.end_with?(".") tests("#create_managed_zone").data_matches_schema( @managed_zone_schema, :allow_extra_keys => false) do @google.create_managed_zone(zone_name, zone_dns_name, "Fog test domain").body end tests("#get_managed_zone") do response = @google.get_managed_zone(zone_name).body tests("schema").data_matches_schema(@managed_zone_schema, :allow_extra_keys => false) { response } tests("test zone present").returns(zone_name) { response["name"] } end tests("#list_managed_zones") do response = @google.list_managed_zones.body tests("schema").data_matches_schema(@list_managed_zones_schema, :allow_extra_keys => false) { response } tests("test zone present").returns(true) { response["managedZones"].one? { |zone| zone["name"] == zone_name } } end tests("#delete_managed_zone").returns(nil) do @google.delete_managed_zone(zone_name).body end end tests("failure") do tests("#delete_managed_zone").raises(Fog::Errors::NotFound) do @google.delete_managed_zone("zone-which-does-not-exist").body end tests("#get_managed_zone").raises(Fog::Errors::NotFound) do @google.get_managed_zone("zone-which-does-not-exist").body end end end fog-google-0.5.3/tests/requests/dns/record_tests.rb0000644000004100000410000000270613145731036022432 0ustar www-datawww-dataShindo.tests("Fog::DNS[:google] | record requests", ["google"]) do # Google requires confirmation of ownership for created domains in some cases. # If you want to run tests in non-mocked mode, set the environment variable to a domain you own. unless Fog.mocking? || ENV["FOG_TEST_GOOGLE_DNS_ZONE"] tests("Needs a verified domain, set $FOG_TEST_GOOGLE_DNS_ZONE").pending end @dns = Fog::DNS[:google] @get_resource_record_sets_format = { "kind" => String, "name" => String, "type" => String, "ttl" => Integer, "rrdatas" => Array } @list_resource_record_sets_format = { "kind" => String, "rrsets" => [@get_resource_record_sets_format] } tests("success") do @zone = @dns.zones.create( :name => Fog::Mock.random_letters(16), :domain => ENV["FOG_TEST_GOOGLE_DNS_ZONE"] || generate_unique_domain, :description => "Fog test domain" ) tests('#list_resource_record_sets').formats(@list_resource_record_sets_format) do @dns.list_resource_record_sets(@zone.identity).body end tests('#list_resource_record_sets (with name and type)').formats(@list_resource_record_sets_format) do @dns.list_resource_record_sets(@zone.identity, :name => @zone.domain, :type => "NS").body end @zone.destroy end tests("failure") do tests('#list_resource_record_sets').raises(Fog::Errors::NotFound) do @dns.list_resource_record_sets(generate_unique_domain).body end end end fog-google-0.5.3/tests/requests/dns/change_tests.rb0000644000004100000410000000503213145731036022374 0ustar www-datawww-dataShindo.tests("Fog::DNS[:google] | change requests", ["google"]) do # Google requires confirmation of ownership for created domains in some cases. # If you want to run tests in non-mocked mode, set the environment variable to a domain you own. unless Fog.mocking? || ENV["FOG_TEST_GOOGLE_DNS_ZONE"] tests("Needs a verified domain, set $FOG_TEST_GOOGLE_DNS_ZONE").pending end @dns = Fog::DNS[:google] @get_change_format = { "kind" => String, "id" => String, "startTime" => String, "status" => String, "additions" => Fog::Nullable::Array, "deletions" => Fog::Nullable::Array } @list_changes_format = { "kind" => String, "changes" => [@get_change_format] } @zone = @dns.zones.create( :name => Fog::Mock.random_letters(16), :domain => ENV["FOG_TEST_GOOGLE_DNS_ZONE"] || generate_unique_domain, :description => "Fog test domain" ) rrset_resource = { :name => "#{Fog::Mock.random_letters(16)}.#{ENV['FOG_TEST_GOOGLE_DNS_ZONE'] || generate_unique_domain}", :type => "A", :ttl => 3600, :rrdatas => ["192.168.1.1"] } tests("success") do tests('#create_change.additions').formats(@get_change_format) do @dns.create_change(@zone.identity, [rrset_resource], []).body end tests('#create_change.additions.deletions').formats(@get_change_format) do @dns.create_change(@zone.identity, [rrset_resource], [rrset_resource]).body end tests('#create_change.deletions').formats(@get_change_format) do @dns.create_change(@zone.identity, [], [rrset_resource]).body end tests('#list_changes').formats(@list_changes_format) do @dns.list_changes(@zone.identity).body end tests('#get_change').formats(@get_change_format) do @dns.get_change(@zone.identity, "0").body end end tests("failure") do tests('#list_changes').raises(Fog::Errors::NotFound) do @dns.list_changes(generate_unique_domain).body end tests('#get_change').raises(Fog::Errors::NotFound) do @dns.get_change(generate_unique_domain, Fog::Mock.random_letters_and_numbers(16)).body end tests('#get_change').raises(Fog::Errors::NotFound) do @dns.get_change(@zone.identity, Fog::Mock.random_letters_and_numbers(16)).body end tests('#create_change').raises(Fog::Errors::NotFound) do @dns.create_change(generate_unique_domain, [], [rrset_resource]).body end tests('#create_change').raises(Fog::Errors::NotFound) do @dns.create_change(@zone.identity, [], [rrset_resource]).body end end @zone.destroy end fog-google-0.5.3/tests/requests/sql/0000755000004100000410000000000013145731036017413 5ustar www-datawww-datafog-google-0.5.3/tests/requests/sql/ssl_cert_tests.rb0000644000004100000410000000317113145731036023002 0ustar www-datawww-dataShindo.tests("Fog::Google[:sql] | ssl_cert requests", ["google"]) do @sql = Fog::Google[:sql] @instance_id = Fog::Mock.random_letters(16) @instance = @sql.instances.create(:instance => @instance_id, :tier => "D1") @instance.wait_for { ready? } @get_ssl_cert_format = { "sha1Fingerprint" => String, "cert" => String, "certSerialNumber" => String, "commonName" => String, "createTime" => String, "expirationTime" => Fog::Nullable::String, "instance" => String, "kind" => String } @insert_ssl_cert_format = { "kind" => String, "serverCaCert" => @get_ssl_cert_format, "clientCert" => { "certInfo" => @get_ssl_cert_format, "certPrivateKey" => String } } @list_ssl_certs_format = { "kind" => String, "items" => [@get_ssl_cert_format] } @delete_ssl_cert_format = { "kind" => String, "operation" => String } tests("success") do tests('#insert_ssl_cert').formats(@insert_ssl_cert_format) do @sql.insert_ssl_cert(@instance_id, Fog::Mock.random_letters(16)).body end tests('#list_ssl_certs').formats(@list_ssl_certs_format) do @sql.list_ssl_certs(@instance_id).body end tests('#get_ssl_cert').formats(@get_ssl_cert_format) do sha1_fingerprint = @sql.ssl_certs.all(@instance_id).first.sha1_fingerprint @sql.get_ssl_cert(@instance_id, sha1_fingerprint).body end tests('#delete_ssl_cert').formats(@delete_ssl_cert_format) do sha1_fingerprint = @sql.ssl_certs.all(@instance_id).first.sha1_fingerprint @sql.delete_ssl_cert(@instance_id, sha1_fingerprint).body end end @instance.destroy end fog-google-0.5.3/tests/requests/sql/tier_tests.rb0000644000004100000410000000067413145731036022134 0ustar www-datawww-dataShindo.tests("Fog::Google[:sql] | tier requests", ["google"]) do @sql = Fog::Google[:sql] @get_tier_format = { "tier" => String, "DiskQuota" => String, "kind" => String, "RAM" => String, "region" => Array } @list_tiers_format = { "kind" => String, "items" => [@get_tier_format] } tests("success") do tests('#list_tiers').formats(@list_tiers_format) do @sql.list_tiers.body end end end fog-google-0.5.3/tests/requests/sql/operation_tests.rb0000644000004100000410000000220513145731036023161 0ustar www-datawww-dataShindo.tests("Fog::Google[:sql] | operation requests", ["google"]) do @sql = Fog::Google[:sql] @instance_id = Fog::Mock.random_letters(16) @instance = @sql.instances.create(:instance => @instance_id, :tier => "D1") @instance.wait_for { ready? } @get_operation_format = { "operation" => String, "endTime" => Fog::Nullable::String, "enqueuedTime" => String, "error" => Fog::Nullable::Array, "exportContext" => Fog::Nullable::Array, "importContext" => Fog::Nullable::Array, "instance" => String, "kind" => String, "operationType" => String, "startTime" => Fog::Nullable::String, "state" => String, "userEmailAddress" => String } @list_operations_format = { "kind" => String, "items" => [@get_operation_format] } tests("success") do tests('#list_operations').formats(@list_operations_format) do @sql.list_operations(@instance_id).body end tests('#get_operation').formats(@get_operation_format) do operation_id = @sql.operations.all(@instance_id).first.operation @sql.get_operation(@instance_id, operation_id).body end end @instance.destroy end fog-google-0.5.3/tests/requests/sql/instance_tests.rb0000644000004100000410000000714213145731036022772 0ustar www-datawww-dataShindo.tests("Fog::Google[:sql] | instance requests", ["google"]) do @sql = Fog::Google[:sql] @instance_id = Fog::Mock.random_letters(16) @insert_instance_format = { "kind" => String, "operation" => String } @get_instance_format = { "instance" => String, "currentDiskSize" => Fog::Nullable::String, "databaseVersion" => String, "etag" => String, "ipAddresses" => Fog::Nullable::String, "kind" => String, "maxDiskSize" => String, "project" => String, "region" => String, "serverCaCert" => Hash, "settings" => Hash, "state" => String } @list_instances_format = { "kind" => String, "items" => [@get_instance_format] } @clone_instance_format = { "kind" => String, "operation" => String } @export_instance_format = { "kind" => String, "operation" => String } @import_instance_format = { "kind" => String, "operation" => String } @reset_instance_ssl_config_format = { "kind" => String, "operation" => String } @restart_instance_format = { "kind" => String, "operation" => String } @set_instance_root_password_format = { "kind" => String, "operation" => String } @update_instance_format = { "kind" => String, "operation" => String } @delete_instance_format = { "kind" => String, "operation" => String } tests("success") do tests('#insert_instance').formats(@insert_instance_format) do result = @sql.insert_instance(@instance_id, "D1").body @sql.instances.get(@instance_id).wait_for { ready? } result end tests('#list_instances').formats(@list_instances_format) do @sql.list_instances.body end tests('#get_instance').formats(@get_instance_format) do @sql.get_instance(@instance_id).body end tests('#update_instance').formats(@update_instance_format) do instance = @sql.instances.get(@instance_id) @sql.update_instance(instance.instance, instance.settings_version, instance.tier, instance.attributes).body end tests('#clone_instance').formats(@clone_instance_format) do pending unless Fog.mocking? # Binary log must be activated instance_cloned_id = Fog::Mock.random_letters(16) clone_instance_format = @sql.clone_instance(@instance_id, instance_cloned_id).body @sql.delete_instance(instance_cloned_id) clone_instance_format end tests('#export_instance').formats(@export_instance_format) do pending unless Fog.mocking? # We don't have access to a Google Cloud Storage bucket @sql.export_instance(@instance_id, "gs://#{Fog::Mock.random_letters_and_numbers(16)}/mysql-export").body end tests('#import_instance').formats(@import_instance_format) do pending unless Fog.mocking? # We don't have access to a Google Cloud Storage bucket @sql.import_instance(@instance_id, "gs://#{Fog::Mock.random_letters_and_numbers(16)}/mysql-export").body end tests('#reset_instance_ssl_config').formats(@reset_instance_ssl_config_format) do @sql.reset_instance_ssl_config(@instance_id).body end tests('#set_instance_root_password').formats(@set_instance_root_password_format) do @sql.set_instance_root_password(@instance_id, Fog::Mock.random_letters_and_numbers(8)).body end tests('#restart_instance').formats(@restart_instance_format) do result = @sql.restart_instance(@instance_id).body @sql.operations.get(@instance_id, result["operation"]).wait_for { ready? } result end tests('#delete_instance').formats(@delete_instance_format) do @sql.delete_instance(@instance_id).body end end end fog-google-0.5.3/tests/requests/sql/flag_tests.rb0000644000004100000410000000105213145731036022071 0ustar www-datawww-dataShindo.tests("Fog::Google[:sql] | flag requests", ["google"]) do @sql = Fog::Google[:sql] @get_flag_format = { "name" => String, "allowedStringValues" => Fog::Nullable::Array, "appliesTo" => Array, "kind" => String, "maxValue" => Fog::Nullable::String, "minValue" => Fog::Nullable::String, "type" => String } @list_flags_format = { "kind" => String, "items" => [@get_flag_format] } tests("success") do tests('#list_flags').formats(@list_flags_format) do @sql.list_flags.body end end end fog-google-0.5.3/tests/requests/compute/0000755000004100000410000000000013145731036020270 5ustar www-datawww-datafog-google-0.5.3/tests/requests/compute/firewall_tests.rb0000644000004100000410000000374313145731036023653 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | firewall requests", ["google"]) do pending if Fog.mocking? @google = Fog::Compute[:google] @insert_firewall_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "progress" => Integer, "insertTime" => String, "startTime" => String, "operationType" => String } @get_firewall_format = { "kind" => String, "id" => String, "selfLink" => String, "creationTimestamp" => DateTime, "name" => String, "network" => String, "sourceRanges" => [], "allowed" => [] } @delete_firewall_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "progress" => Integer, "targetId" => String, "insertTime" => String, "startTime" => String, "operationType" => String } @list_firewalls_format = { "kind" => String, "id" => String, "selfLink" => String, "items" => [] } tests("success") do firewall_name = "fog-test-firewall" source_range = ["10.0.0.0/8"] allowed = [{ "IPProtocol" => "tcp", "ports" => ["1-65535"] }, { "IPProtocol" => "udp", "ports" => ["1-65535"] }, { "IPProtocol" => "icmp" }] tests("#insert_firewall").formats(@insert_firewall_format) do response = @google.insert_firewall(firewall_name, allowed, "default", :source_ranges => source_range).body wait_operation(@google, response) response end # TODO: Get better matching for firewall responses. tests("#get_firewall").succeeds do @google.get_firewall(firewall_name) end tests("#list_firewalls").succeeds do @google.list_firewalls end tests("#delete_firewall").formats(@delete_firewall_format) do @google.delete_firewall(firewall_name).body end end end fog-google-0.5.3/tests/requests/compute/disk_tests.rb0000644000004100000410000000330713145731036022774 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | disk requests", ["google"]) do @google = Fog::Compute[:google] @insert_disk_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "progress" => Integer, "zone" => String, "insertTime" => String, "startTime" => String, "operationType" => String } @get_disk_format = { "kind" => String, "id" => String, "selfLink" => String, "creationTimestamp" => String, "name" => String, "zone" => String, "status" => String, "sizeGb" => String, "sourceImageId" => String, "sourceImage" => String, "type" => String } @delete_disk_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "targetId" => String, "status" => String, "user" => String, "progress" => Integer, "insertTime" => String, "zone" => String, "startTime" => String, "operationType" => String } tests("success") do disk_name = "new-disk-test" disk_size = "2" zone_name = "us-central1-a" image_name = "debian-8-jessie-v20161215" # These will all fail if errors happen on insert tests("#insert_disk").formats(@insert_disk_format) do response = @google.insert_disk(disk_name, zone_name, image_name).body wait_operation(@google, response) response end tests("#get_disk").formats(@get_disk_format) do @google.get_disk(disk_name, zone_name).body end tests("#delete_disk").formats(@delete_disk_format) do @google.delete_disk(disk_name, zone_name).body end end end fog-google-0.5.3/tests/requests/compute/disk_type_tests.rb0000644000004100000410000000212713145731036024034 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | disk_type requests", ["google"]) do @google = Fog::Compute[:google] @get_disk_type_format = { "name" => String, "kind" => String, "id" => Fog::Nullable::String, "creationTimestamp" => String, "deprecated" => Fog::Nullable::Array, "description" => String, "selfLink" => String, "validDiskSize" => String, "zone" => String } @list_disk_types_format = { "kind" => String, "selfLink" => String, "items" => [@get_disk_type_format] } @list_aggregated_disk_types = { "kind" => String, "selfLink" => String, "items" => Hash } tests("success") do tests('#list_aggregated_disk_types').formats(@list_aggregated_disk_types) do @google.list_aggregated_disk_types.body end tests('#list_disk_types').formats(@list_disk_types_format) do @google.list_disk_types("us-central1-a").body end tests('#get_disk_type').formats(@get_disk_type_format) do disk_type = @google.disk_types.first @google.get_disk_type(disk_type.identity, disk_type.zone).body end end end fog-google-0.5.3/tests/requests/compute/backend_service_tests.rb0000644000004100000410000000416313145731036025152 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | backend services requests", ["google"]) do @google = Fog::Compute[:google] @insert_backend_service_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "progress" => Integer, "zone" => String, "insertTime" => String, "startTime" => String, "operationType" => String } @get_backend_service_format = { "kind" => String, "id" => String, "selfLink" => String, "creationTimestamp" => String, "name" => String, "backends" => Array, "healthChecks" => Array, "port" => Integer, "protocol" => String } @delete_backend_service_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "targetId" => String, "status" => String, "user" => String, "progress" => Integer, "insertTime" => String, "zone" => String, "startTime" => String, "operationType" => String } @list_backend_services_format = { "kind" => String, "selfLink" => String, "id" => String, "items" => Array } tests("success") do backend_service_name = "test-backend-service" zone_name = "us-central1-a" # These will all fail if errors happen on insert tests("#insert_backend_service").formats(@insert_backend_service_format) do health_check = create_test_http_health_check(Fog::Compute[:google]) options = { "health_check" => health_check } response = @google.insert_backend_service(backend_service_name, options).body wait_operation(@google, response) response end tests("#list_backend_services").formats(@list_backend_services_format) do @google.list_backend_services.body end tests("#get_backend_service").formats(@get_backend_service_format) do @google.get_backend_service(backend_service_name).body end tests("#delete_backend_service").formats(@delete_backend_service_format) do @google.delete_backend_service(backend_service_name).body end end end fog-google-0.5.3/tests/requests/compute/region_tests.rb0000644000004100000410000000173013145731036023323 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | region requests", ["google"]) do @google = Fog::Compute[:google] @get_region_format = { "kind" => String, "selfLink" => String, "id" => String, "creationTimestamp" => String, "name" => String, "description" => String, "status" => String, "zones" => Array, "quotas" => [{ "metric" => String, "limit" => Float, "usage" => Float }] } @list_regions_format = { "kind" => String, "selfLink" => String, "id" => String, "items" => [@get_region_format] } tests("success") do tests("#get_region").formats(@get_region_format) do region = @google.list_regions.body["items"].first["name"] @google.get_region(region).body end tests("#list_regions").formats(@list_regions_format) do @google.list_regions.body end end tests("failure") do tests("#get_region").raises(Fog::Errors::NotFound) do @google.get_region("unicorn").body end end end fog-google-0.5.3/tests/requests/compute/url_maps_tests.rb0000644000004100000410000000367013145731036023667 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | url map requests", ["google"]) do @google = Fog::Compute[:google] @insert_url_map_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "progress" => Integer, "zone" => String, "insertTime" => String, "startTime" => String, "operationType" => String } @get_url_map_format = { "kind" => String, "id" => String, "selfLink" => String, "creationTimestamp" => String, "name" => String, "hostRules" => Array, "pathMatchers" => Array, "tests" => Array, "defaultService" => String } @delete_url_map_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "targetId" => String, "status" => String, "user" => String, "progress" => Integer, "insertTime" => String, "zone" => String, "startTime" => String, "operationType" => String } @list_url_maps_format = { "kind" => String, "id" => String, "selfLink" => String, "items" => Array } tests("success") do url_map_name = "test-url-map" # These will all fail if errors happen on insert tests("#insert_url_map").formats(@insert_url_map_format) do backend_service = create_test_backend_service(Fog::Compute[:google]) options = { "defaultService" => backend_service.self_link } response = @google.insert_url_map(url_map_name, options).body wait_operation(@google, response) response end tests("#get_url_map").formats(@get_url_map_format) do @google.get_url_map(url_map_name).body end tests("#list_url_maps").formats(@list_url_maps_format) do @google.list_url_maps.body end tests("#delete_url_map").formats(@delete_url_map_format) do @google.delete_url_map(url_map_name).body end end end fog-google-0.5.3/tests/requests/compute/image_tests.rb0000644000004100000410000000361713145731036023130 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | image requests", ["google"]) do @google = Fog::Compute[:google] @insert_image_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "progress" => Integer, "insertTime" => String, "startTime" => String, "operationType" => String } @get_image_format = { "kind" => String, "id" => String, "creationTimestamp" => String, "selfLink" => String, "name" => String, "description" => String, "sourceType" => String, "rawDisk" => { "containerType" => String, "source" => String } } @delete_image_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "progress" => Integer, "insertTime" => String, "startTime" => String, "operationType" => String } @list_images_format = { "kind" => String, "id" => String, "selfLink" => String, "items" => [@get_image_format] } tests("success") do random_string = SecureRandom.hex image_name = "fog-test-image-#{random_string}" source = "https://www.google.com/images/srpr/logo4w.png" tests("#insert_image").formats(@insert_image_format) do pending if Fog.mocking? response = @google.insert_image(image_name, "rawDisk" => source).body wait_operation(@google, response) response end tests("#get_image").formats(@get_image_format) do pending if Fog.mocking? @google.get_image(image_name).body end tests("#list_images").formats(@list_images_format) do @google.list_images.body end tests("#delete_image").formats(@delete_image_format) do pending if Fog.mocking? @google.delete_image(image_name).body end end end fog-google-0.5.3/tests/requests/compute/server_tests.rb0000644000004100000410000000400313145731036023342 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | server requests", ["google"]) do @google = Fog::Compute[:google] @insert_server_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "user" => String, "startTime" => String, "insertTime" => String, "operationType" => String, "status" => String, "progress" => Integer } @get_server_format = { "kind" => String, "id" => String, "selfLink" => String, "creationTimestamp" => String, "name" => String, "image" => String, "machineType" => String, "status" => String, "zone" => String, "disks" => [], "networkInterfaces" => [] } @delete_server_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "targetId" => String, "progress" => Integer, "insertTime" => String, "startTime" => String, "operationType" => String } @list_servers_format = { "kind" => String, "id" => String, "selfLink" => String } tests("success") do server_name = "new-server-test" image_name = "centos-6-v20130813" machine_type = "n1-standard-1" zone_name = "us-central1-a" tests("#insert_server").formats(@insert_server_format) do disk = create_test_disk(Fog::Compute[:google], zone_name) @google.insert_server( server_name, zone_name, "image" => image_name, "machineType" => machine_type, "disks" => [disk] ).body end tests("#list_servers").formats(@list_servers_format) do @google.list_servers(zone_name).body end # Both of these tests require the server to be there... # tests("#get_server").formats(@get_server_format) do # @google.get_server(server_name, zone_name).body # end # tests("#delete_server").formats(@delete_server_format) do # @google.delete_server(server_name, zone_name).body # end end end fog-google-0.5.3/tests/requests/compute/http_health_checks_tests.rb0000644000004100000410000000414413145731036025666 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | HTTP health checks requests", ["google"]) do @google = Fog::Compute[:google] @insert_http_health_check_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "progress" => Integer, "zone" => String, "insertTime" => String, "startTime" => String, "operationType" => String } @get_http_health_check_format = { "kind" => String, "id" => String, "selfLink" => String, "creationTimestamp" => String, "name" => String, "host" => String, "requestPath" => String, "port" => Integer, "checkIntervalSec" => Integer, "timeoutSec" => Integer, "unhealthyThreshold" => Integer, "healthyThreshold" => Integer } @delete_http_health_check_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "targetId" => String, "status" => String, "user" => String, "progress" => Integer, "insertTime" => String, "zone" => String, "startTime" => String, "operationType" => String } @list_http_health_checks_format = { "kind" => String, "id" => String, "selfLink" => String, "items" => Array } tests("success") do http_health_check_name = "test-http-health-check" # These will all fail if errors happen on insert tests("#insert_http_health_check").formats(@insert_http_health_check_format) do response = @google.insert_http_health_check(http_health_check_name).body wait_operation(@google, response) response end tests("#get_http_health_check").formats(@get_http_health_check_format) do @google.get_http_health_check(http_health_check_name).body end tests("#list_http_health_checks").formats(@list_http_health_checks_format) do @google.list_http_health_checks.body end tests("#delete_http_health_check").formats(@delete_http_health_check_format) do @google.delete_http_health_check(http_health_check_name).body end end end fog-google-0.5.3/tests/requests/compute/forwarding_rules_tests.rb0000644000004100000410000000430313145731036025413 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | forwarding rule requests", ["google"]) do @google = Fog::Compute[:google] @insert_forwarding_rule_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "progress" => Integer, "region" => String, "insertTime" => String, "startTime" => String, "operationType" => String } @get_forwarding_rule_format = { "kind" => String, "id" => String, "selfLink" => String, "creationTimestamp" => String, "name" => String, "region" => String, "IPAddress" => String, "IPProtocol" => String, "portRange" => String, "target" => String } @delete_forwarding_rule_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "targetId" => String, "status" => String, "user" => String, "progress" => Integer, "insertTime" => String, "region" => String, "startTime" => String, "operationType" => String } @list_forwarding_rules_format = { "kind" => String, "id" => String, "items" => Array, "selfLink" => String } tests("success") do forwarding_rule_name = "test-forwarding-rule" region_name = "us-central1" # These will all fail if errors happen on insert tests("#insert_forwarding_rule").formats(@insert_forwarding_rule_format) do target = create_test_target_pool(Fog::Compute[:google], region_name) options = { "target" => target.self_link } response = @google.insert_forwarding_rule(forwarding_rule_name, region_name, options).body wait_operation(@google, response) response end tests("#get_forwarding_rule").formats(@get_forwarding_rule_format) do @google.get_forwarding_rule(forwarding_rule_name, region_name).body end tests("#list_forwarding_rules").formats(@list_forwarding_rules_format) do @google.list_forwarding_rules(region_name).body end tests("#delete_forwarding_rule").formats(@delete_forwarding_rule_format) do @google.delete_forwarding_rule(forwarding_rule_name, region_name).body end end end fog-google-0.5.3/tests/requests/compute/global_forwarding_rules_tests.rb0000644000004100000410000000441113145731036026733 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | global forwarding rule requests", ["google"]) do @google = Fog::Compute[:google] @insert_global_forwarding_rule_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "progress" => Integer, "zone" => String, "insertTime" => String, "startTime" => String, "operationType" => String } @get_global_forwarding_rule_format = { "kind" => String, "id" => String, "selfLink" => String, "creationTimestamp" => String, "name" => String, "region" => String, "IPAddress" => String, "IPProtocol" => String, "portRange" => String, "target" => String } @delete_global_forwarding_rule_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "targetId" => String, "status" => String, "user" => String, "progress" => Integer, "insertTime" => String, "zone" => String, "startTime" => String, "operationType" => String } @list_global_forwarding_rules_format = { "kind" => String, "id" => String, "items" => Array, "selfLink" => String } tests("success") do global_forwarding_rule_name = "test-global-forwarding-rule" # These will all fail if errors happen on insert tests("#insert_global_forwarding_rule").formats(@insert_global_forwarding_rule_format) do target = create_test_target_http_proxy(Fog::Compute[:google]) options = { "target" => target.self_link } response = @google.insert_global_forwarding_rule(global_forwarding_rule_name, options).body wait_operation(@google, response) response end tests("#get_global_forwarding_rule").formats(@get_global_forwarding_rule_format) do @google.get_global_forwarding_rule(global_forwarding_rule_name).body end tests("#list_global_forwarding_rules").formats(@list_global_forwarding_rules_format) do @google.list_global_forwarding_rules("global").body end tests("#delete_global_forwarding_rule").formats(@delete_global_forwarding_rule_format) do @google.delete_global_forwarding_rule(global_forwarding_rule_name).body end end end fog-google-0.5.3/tests/requests/compute/operation_tests.rb0000644000004100000410000000122513145731036024037 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | operation requests", ["google"]) do pending if Fog.mocking? @google = Fog::Compute[:google] tests("success") do # We are not testing the format here because operation formats are pretty # extensive based on what has happened to you account, ever. # https://developers.google.com/compute/docs/reference/latest/globalOperations#resource tests("#list_global_operations").succeeds do @google.list_global_operations end tests("#list_zone_operations").succeeds do zone_name = @google.list_zones.body["items"][0]["name"] @google.list_zone_operations(zone_name) end end end fog-google-0.5.3/tests/requests/compute/target_instances_tests.rb0000644000004100000410000000422613145731036025400 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | target instance requests", ["google"]) do @google = Fog::Compute[:google] @insert_target_instance_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "progress" => Integer, "zone" => String, "insertTime" => String, "startTime" => String, "operationType" => String } @get_target_instance_format = { "kind" => String, "id" => String, "selfLink" => String, "creationTimestamp" => String, "name" => String, "zone" => String, "natPolicy" => String, "instance" => String, "description" => String } @delete_target_instance_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "targetId" => String, "status" => String, "user" => String, "progress" => Integer, "insertTime" => String, "zone" => String, "startTime" => String, "operationType" => String } @list_target_instances_format = { "kind" => String, "id" => String, "selfLink" => String, "items" => Array } tests("success") do target_instance_name = "test-target_instance" @zone = "us-central1-a" # These will all fail if errors happen on insert tests("#insert_target_instance").formats(@insert_target_instance_format) do instance = create_test_server(Fog::Compute[:google], @zone) options = { "instance" => instance.self_link, "zone" => @zone } response = @google.insert_target_instance(target_instance_name, @zone, options).body wait_operation(@google, response) response end tests("#get_target_instance").formats(@get_target_instance_format) do @google.get_target_instance(target_instance_name, @zone).body end tests("#list_target_instances").formats(@list_target_instances_format) do @google.list_target_instances(@zone).body end tests("#delete_target_instance").formats(@delete_target_instance_format) do @google.delete_target_instance(target_instance_name, @zone).body end end end fog-google-0.5.3/tests/requests/compute/network_tests.rb0000644000004100000410000000324313145731036023532 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | network requests", ["google"]) do pending if Fog.mocking? @google = Fog::Compute[:google] @insert_network_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "progress" => Integer, "insertTime" => String, "startTime" => String, "operationType" => String } @get_network_format = { "kind" => String, "id" => String, "selfLink" => String, "creationTimestamp" => String, "name" => String, "IPv4Range" => String, "gatewayIPv4" => String } @delete_network_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "targetId" => String, "status" => String, "user" => String, "progress" => Integer, "insertTime" => String, "startTime" => String, "operationType" => String } @list_networks_format = { "kind" => String, "id" => String, "selfLink" => String, "items" => [@get_network_format] } tests("success") do network_name = "new-network-test" ip_range = "192.168.0.0/16" tests("#insert_network").formats(@insert_network_format) do @google.insert_network(network_name, ip_range).body end tests("#get_network").formats(@get_network_format) do @google.get_network(network_name).body end tests("#list_networks").formats(@list_networks_format) do @google.list_networks.body end tests("#delete_network").formats(@delete_network_format) do @google.delete_network(network_name).body end end end fog-google-0.5.3/tests/requests/compute/target_pools_tests.rb0000644000004100000410000000426713145731036024552 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | target pools requests", ["google"]) do @google = Fog::Compute[:google] @insert_target_pool_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "progress" => Integer, "region" => String, "insertTime" => String, "startTime" => String, "operationType" => String } @get_target_pool_format = { "kind" => String, "id" => String, "selfLink" => String, "creationTimestamp" => String, "name" => String, "region" => String, "healthChecks" => Array, "instances" => Array } @delete_target_pool_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "targetId" => String, "status" => String, "user" => String, "progress" => Integer, "insertTime" => String, "region" => String, "startTime" => String, "operationType" => String } @list_target_pools_format = { "kind" => String, "id" => String, "items" => Array, "selfLink" => String } tests("success") do target_pool_name = "test-target_pool" region_name = "us-central1" # These will all fail if errors happen on insert tests("#insert_target_pool").formats(@insert_target_pool_format) do instance = create_test_server(Fog::Compute[:google], "us-central1-a") health_check = create_test_http_health_check(Fog::Compute[:google]) options = { "instances" => [instance.self_link], "healthChecks" => [health_check.self_link] } response = @google.insert_target_pool(target_pool_name, region_name, options).body wait_operation(@google, response) response end tests("#get_target_pool").formats(@get_target_pool_format) do @google.get_target_pool(target_pool_name, region_name).body end tests("#list_target_pools").formats(@list_target_pools_format) do @google.list_target_pools(region_name).body end tests("#delete_target_pool").formats(@delete_target_pool_format) do @google.delete_target_pool(target_pool_name, region_name).body end end end fog-google-0.5.3/tests/requests/compute/zone_tests.rb0000644000004100000410000000144313145731036023014 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | zone requests", ["google"]) do @google = Fog::Compute[:google] @get_zone_format = { "kind" => String, "id" => String, "selfLink" => String, "creationTimestamp" => String, "name" => String, "description" => String, "status" => String, "region" => String, "maintenanceWindows" => Fog::Nullable::Array } @list_zones_format = { "kind" => String, "id" => String, "selfLink" => String, "items" => [@get_zone_format] } tests("success") do tests("#get_zone").formats(@get_zone_format) do zone_name = @google.list_zones.body["items"][0]["name"] @google.get_zone(zone_name).body end tests("#list_zones").formats(@list_zones_format) do @google.list_zones.body end end end fog-google-0.5.3/tests/requests/compute/target_http_proxies_test.rb0000644000004100000410000000404313145731036025753 0ustar www-datawww-dataShindo.tests("Fog::Compute[:google] | target HTTP proxy requests", ["google"]) do @google = Fog::Compute[:google] @insert_target_http_proxy_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "status" => String, "user" => String, "progress" => Integer, "zone" => String, "insertTime" => String, "startTime" => String, "operationType" => String } @get_target_http_proxy_format = { "kind" => String, "id" => String, "selfLink" => String, "creationTimestamp" => String, "name" => String, "urlMap" => String } @delete_target_http_proxy_format = { "kind" => String, "id" => String, "selfLink" => String, "name" => String, "targetLink" => String, "targetId" => String, "status" => String, "user" => String, "progress" => Integer, "insertTime" => String, "zone" => String, "startTime" => String, "operationType" => String } @list_target_http_proxies_format = { "kind" => String, "selfLink" => String, "id" => String, "items" => Array } tests("success") do target_http_proxy_name = "test-target-http-proxy" # These will all fail if errors happen on insert tests("#insert_target_http_proxy").formats(@insert_target_http_proxy_format) do url_map = create_test_url_map(Fog::Compute[:google]) options = { "urlMap" => url_map.self_link } response = @google.insert_target_http_proxy(target_http_proxy_name, options).body wait_operation(@google, response) response end tests("#get_target_http_proxy").formats(@get_target_http_proxy_format) do @google.get_target_http_proxy(target_http_proxy_name).body end tests("#list_target_http_proxies").formats(@list_target_http_proxies_format) do @google.list_target_http_proxies.body end tests("#delete_target_http_proxy").formats(@delete_target_http_proxy_format) do @google.delete_target_http_proxy(target_http_proxy_name).body end end end fog-google-0.5.3/tests/requests/monitoring/0000755000004100000410000000000013145731036021001 5ustar www-datawww-datafog-google-0.5.3/tests/requests/monitoring/timeseries_collection_tests.rb0000644000004100000410000000117113145731036027134 0ustar www-datawww-dataShindo.tests("Fog::Google[:monitoring] | timeseries_collection requests", ["google"]) do @monitoring = Fog::Google[:monitoring] @get_timeseries_format = { "timeseriesDesc" => Hash, "points" => Array } @list_timeseries_format = { "kind" => String, "youngest" => String, "oldest" => String, "timeseries" => [@get_timeseries_format] } tests("success") do tests('#list_timeseries').formats(@list_timeseries_format) do @monitoring.list_timeseries("compute.googleapis.com/instance/uptime", Time.now.strftime("%Y-%m-%dT%H:%M:%S%:z")).body end end end fog-google-0.5.3/tests/requests/monitoring/timeseries_descriptor_tests.rb0000644000004100000410000000133513145731036027161 0ustar www-datawww-dataShindo.tests("Fog::Google[:monitoring] | timeseries_descriptor requests", ["google"]) do @monitoring = Fog::Google[:monitoring] @get_timeseries_descriptor_format = { "metric" => String, "project" => String, "labels" => Hash } @list_timeseries_descriptors_format = { "kind" => String, "youngest" => String, "oldest" => String, "timeseries" => [@get_timeseries_descriptor_format] } tests("success") do tests('#list_timeseries_descriptors').formats(@list_timeseries_descriptors_format) do @monitoring.list_timeseries_descriptors("compute.googleapis.com/instance/uptime", Time.now.strftime("%Y-%m-%dT%H:%M:%S%:z")).body end end end fog-google-0.5.3/tests/requests/monitoring/metric_descriptor_tests.rb0000644000004100000410000000110313145731036026264 0ustar www-datawww-dataShindo.tests("Fog::Google[:monitoring] | metric_descriptor requests", ["google"]) do @monitoring = Fog::Google[:monitoring] @get_metric_descriptor_format = { "name" => String, "description" => String, "labels" => Array, "project" => String, "typeDescriptor" => Hash } @list_metric_descriptors_format = { "kind" => String, "metrics" => [@get_metric_descriptor_format] } tests("success") do tests('#list_metric_descriptors').formats(@list_metric_descriptors_format) do @monitoring.list_metric_descriptors.body end end end fog-google-0.5.3/tests/models/0000755000004100000410000000000013145731036016224 5ustar www-datawww-datafog-google-0.5.3/tests/models/dns/0000755000004100000410000000000013145731036017010 5ustar www-datawww-datafog-google-0.5.3/tests/models/dns/changes_tests.rb0000644000004100000410000000177013145731036022174 0ustar www-datawww-dataShindo.tests("Fog::DNS[:google] | changes model", ["google"]) do # Google requires confirmation of ownership for created domains in some cases. # If you want to run tests in non-mocked mode, set the environment variable to a domain you own. unless Fog.mocking? || ENV["FOG_TEST_GOOGLE_DNS_ZONE"] tests("Needs a verified domain, set $FOG_TEST_GOOGLE_DNS_ZONE").pending end @dns = Fog::DNS[:google] @zone = @dns.zones.create( :name => Fog::Mock.random_letters(16), :domain => ENV["FOG_TEST_GOOGLE_DNS_ZONE"] || generate_unique_domain, :description => "Fog test domain" ) tests("success") do tests('#all').succeeds do @dns.changes(:service => @dns, :zone => @zone).all end tests('#get').succeeds do @dns.changes(:service => @dns, :zone => @zone).get("0") end end tests("failure") do tests('#get').returns(nil) do @dns.changes(:service => @dns, :zone => @zone).get(Fog::Mock.random_letters_and_numbers(16)) end end @zone.destroy end fog-google-0.5.3/tests/models/dns/zones_tests.rb0000644000004100000410000000114313145731036021714 0ustar www-datawww-dataShindo.tests("Fog::DNS[:google] | zones model", ["google"]) do # Google requires confirmation of ownership for created domains in some cases. # If you want to run tests in non-mocked mode, set the environment variable to a domain you own. unless Fog.mocking? || ENV["FOG_TEST_GOOGLE_DNS_ZONE"] tests("Needs a verified domain, set $FOG_TEST_GOOGLE_DNS_ZONE").pending end params = { :name => Fog::Mock.random_letters(16), :domain => ENV["FOG_TEST_GOOGLE_DNS_ZONE"] || generate_unique_domain, :description => "Fog test domain" } collection_tests(Fog::DNS[:google].zones, params) end fog-google-0.5.3/tests/models/dns/zone_tests.rb0000644000004100000410000000147613145731036021542 0ustar www-datawww-dataShindo.tests("Fog::DNS[:google] | zone model", ["google"]) do # Google requires confirmation of ownership for created domains in some cases. # If you want to run tests in non-mocked mode, set the environment variable to a domain you own. unless Fog.mocking? || ENV["FOG_TEST_GOOGLE_DNS_ZONE"] tests("Needs a verified domain, set $FOG_TEST_GOOGLE_DNS_ZONE").pending end params = { :name => Fog::Mock.random_letters(16), :domain => ENV["FOG_TEST_GOOGLE_DNS_ZONE"] || generate_unique_domain, :description => "Fog test domain" } model_tests(Fog::DNS[:google].zones, params) tests("success") do @zone = Fog::DNS[:google].zones.create(params) tests('#changes').succeeds do @zone.changes end tests('#records').succeeds do @zone.records end @zone.destroy end end fog-google-0.5.3/tests/models/dns/records_tests.rb0000644000004100000410000000176013145731036022224 0ustar www-datawww-dataShindo.tests("Fog::DNS[:google] | records model", ["google"]) do # Google requires confirmation of ownership for created domains in some cases. # If you want to run tests in non-mocked mode, set the environment variable to a domain you own. unless Fog.mocking? || ENV["FOG_TEST_GOOGLE_DNS_ZONE"] tests("Needs a verified domain, set $FOG_TEST_GOOGLE_DNS_ZONE").pending end @dns = Fog::DNS[:google] @zone = @dns.zones.create( :name => Fog::Mock.random_letters(16), :domain => ENV["FOG_TEST_GOOGLE_DNS_ZONE"] || generate_unique_domain, :description => "Fog test domain" ) tests("success") do tests('#all').succeeds do @dns.records(:service => @dns, :zone => @zone).all end tests('#get').succeeds do @dns.records(:service => @dns, :zone => @zone).get(@zone.domain, "NS") end end tests("failure") do tests('#get').returns(nil) do @dns.records(:service => @dns, :zone => @zone).get(@zone.domain, "A") end end @zone.destroy end fog-google-0.5.3/tests/models/dns/record_tests.rb0000644000004100000410000000217013145731036022035 0ustar www-datawww-dataShindo.tests("Fog::DNS[:google] | record model", ["google"]) do # Google requires confirmation of ownership for created domains in some cases. # If you want to run tests in non-mocked mode, set the environment variable to a domain you own. unless Fog.mocking? || ENV["FOG_TEST_GOOGLE_DNS_ZONE"] tests("Needs a verified domain, set $FOG_TEST_GOOGLE_DNS_ZONE").pending end @dns = Fog::DNS[:google] params = { :name => "#{Fog::Mock.random_letters(16)}.#{ENV['FOG_TEST_GOOGLE_DNS_ZONE'] || generate_unique_domain}", :type => "A", :ttl => 3600, :rrdatas => ["192.168.1.1"] } tests("success") do @zone = @dns.zones.create( :name => Fog::Mock.random_letters(8), :domain => ENV["FOG_TEST_GOOGLE_DNS_ZONE"] || generate_unique_domain, :description => "Fog test domain" ) tests('#save').succeeds do @record = @zone.records.create(params) end tests('#modify').succeeds do @record.modify(:ttl => 2600) end tests('#reload').succeeds do @record.reload end tests('#destroy').succeeds do @record.destroy end @zone.destroy end end fog-google-0.5.3/tests/models/dns/projects_tests.rb0000644000004100000410000000034113145731036022406 0ustar www-datawww-dataShindo.tests("Fog::DNS[:google] | projects model", ["google"]) do @projects = Fog::DNS[:google].projects tests("success") do tests('#get').succeeds do @projects.get(Fog::DNS[:google].project) end end end fog-google-0.5.3/tests/models/dns/change_tests.rb0000644000004100000410000000157313145731036022012 0ustar www-datawww-dataShindo.tests("Fog::DNS[:google] | change model", ["google"]) do # Google requires confirmation of ownership for created domains in some cases. # If you want to run tests in non-mocked mode, set the environment variable to a domain you own. unless Fog.mocking? || ENV["FOG_TEST_GOOGLE_DNS_ZONE"] tests("Needs a verified domain, set $FOG_TEST_GOOGLE_DNS_ZONE").pending end @dns = Fog::DNS[:google] @zone = @dns.zones.create( :name => Fog::Mock.random_letters(16), :domain => ENV["FOG_TEST_GOOGLE_DNS_ZONE"] || generate_unique_domain, :description => "Fog test domain" ) tests("success") do tests('#pending?').succeeds do @dns.changes(:service => @dns, :zone => @zone).get("0").pending? == false end tests('#ready?').succeeds do @dns.changes(:service => @dns, :zone => @zone).get("0").ready? == true end end @zone.destroy end fog-google-0.5.3/tests/models/sql/0000755000004100000410000000000013145731036017023 5ustar www-datawww-datafog-google-0.5.3/tests/models/sql/ssl_cert_tests.rb0000644000004100000410000000111613145731036022407 0ustar www-datawww-dataShindo.tests("Fog::Google[:sql] | ssl_cert model", ["google"]) do @instance = Fog::Google[:sql].instances.create(:instance => Fog::Mock.random_letters(16), :tier => "D1") @instance.wait_for { ready? } @ssl_certs = Fog::Google[:sql].ssl_certs tests("success") do tests('#create').succeeds do @ssl_cert = @ssl_certs.create(:instance => @instance.instance, :common_name => Fog::Mock.random_letters(16)) end tests('#reload').succeeds do @ssl_cert.reload end tests('#destroy').succeeds do @ssl_cert.destroy end end @instance.destroy end fog-google-0.5.3/tests/models/sql/instances_tests.rb0000644000004100000410000000122013145731036022554 0ustar www-datawww-dataShindo.tests("Fog::Google[:sql] | instances model", ["google"]) do @instance = Fog::Google[:sql].instances.create(:instance => Fog::Mock.random_letters(16), :tier => "D1") @instance.wait_for { ready? } @instances = Fog::Google[:sql].instances tests("success") do tests('#all').succeeds do @instances.all end tests('#get').succeeds do @instances.get(@instance.instance) end end @instance.destroy(:async => false) tests("failure") do tests('#all').returns([]) do @instances.all end tests('#get').returns(nil) do @instances.get(Fog::Mock.random_letters_and_numbers(16)) end end end fog-google-0.5.3/tests/models/sql/operation_tests.rb0000644000004100000410000000110413145731036022566 0ustar www-datawww-dataShindo.tests("Fog::Google[:sql] | operation model", ["google"]) do @instance = Fog::Google[:sql].instances.create(:instance => Fog::Mock.random_letters(16), :tier => "D1") @instance.wait_for { ready? } @operations = Fog::Google[:sql].operations @operation = @operations.all(@instance.instance).first tests("success") do tests('#pending?').succeeds do @operation.pending? == false end tests('#ready?').succeeds do @operation.ready? == true end tests('#reload').succeeds do @operation.reload end end @instance.destroy end fog-google-0.5.3/tests/models/sql/operations_tests.rb0000644000004100000410000000221613145731036022756 0ustar www-datawww-dataShindo.tests("Fog::Google[:sql] | operations model", ["google"]) do @instance = Fog::Google[:sql].instances.create(:instance => Fog::Mock.random_letters(16), :tier => "D1") @instance.wait_for { ready? } @operations = Fog::Google[:sql].operations tests("success") do tests('#all').succeeds do @operations.all(@instance.instance) end tests('#get').succeeds do @operations.get(@instance.instance, @operations.all(@instance.instance).first.operation) end end tests("failure") do tests('#all').returns([]) do @operations.all(Fog::Mock.random_letters_and_numbers(16)) end tests('#get').returns(nil) do pending unless Fog.mocking? # Real test fails on google-api-client (mismatch between catalog and real response) @operations.get(@instance.instance, Fog::Mock.random_letters_and_numbers(16)) end tests('#get').returns(nil) do pending unless Fog.mocking? # Real test fails on google-api-client (mismatch between catalog and real response) @operations.get(Fog::Mock.random_letters_and_numbers(16), Fog::Mock.random_letters_and_numbers(16)) end end @instance.destroy end fog-google-0.5.3/tests/models/sql/tiers_tests.rb0000644000004100000410000000027213145731036021721 0ustar www-datawww-dataShindo.tests("Fog::Google[:sql] | tiers model", ["google"]) do @tiers = Fog::Google[:sql].tiers tests("success") do tests('#all').succeeds do @tiers.all end end end fog-google-0.5.3/tests/models/sql/flags_tests.rb0000644000004100000410000000027213145731036021667 0ustar www-datawww-dataShindo.tests("Fog::Google[:sql] | flags model", ["google"]) do @flags = Fog::Google[:sql].tiers tests("success") do tests('#all').succeeds do @flags.all end end end fog-google-0.5.3/tests/models/sql/ssl_certs_tests.rb0000644000004100000410000000210613145731036022572 0ustar www-datawww-dataShindo.tests("Fog::Google[:sql] | ssl_certs model", ["google"]) do @instance = Fog::Google[:sql].instances.create(:instance => Fog::Mock.random_letters(16), :tier => "D1") @instance.wait_for { ready? } @ssl_cert = Fog::Google[:sql].ssl_certs.create(:instance => @instance.instance, :common_name => Fog::Mock.random_letters(16)) @ssl_certs = Fog::Google[:sql].ssl_certs tests("success") do tests('#all').succeeds do @ssl_certs.all(@instance.instance) end tests('#get').succeeds do @ssl_certs.get(@instance.instance, @ssl_cert.sha1_fingerprint) end end tests("failure") do tests('#all').returns([]) do @ssl_certs.all(Fog::Mock.random_letters_and_numbers(16)) end tests('#get').returns(nil) do @ssl_certs.get(@instance.instance, Fog::Mock.random_letters_and_numbers(16)) end tests('#get').returns(nil) do @ssl_certs.get(Fog::Mock.random_letters_and_numbers(16), Fog::Mock.random_letters_and_numbers(16)) end end @ssl_cert.destroy @instance.destroy end fog-google-0.5.3/tests/models/sql/instance_tests.rb0000644000004100000410000000321213145731036022374 0ustar www-datawww-dataShindo.tests("Fog::Google[:sql] | instance model", ["google"]) do @instances = Fog::Google[:sql].instances tests("success") do tests('#create').succeeds do @instance = @instances.create(:instance => Fog::Mock.random_letters(16), :tier => "D1") @instance.wait_for { ready? } end tests('#update').succeeds do @instance.activation_policy = "ALWAYS" @instance.update @instance.wait_for { ready? } end tests('#clone').succeeds do pending unless Fog.mocking? # Binary log must be activated instance_cloned_id = Fog::Mock.random_letters(16) @instance.clone(instance_cloned_id, :async => false) @instances.get(instance_cloned_id).destroy end tests('#export').succeeds do pending unless Fog.mocking? # We don't have access to a Google Cloud Storage bucket @instance.export("gs://#{Fog::Mock.random_letters_and_numbers(16)}/mysql-export", :async => false) end tests('#import').succeeds do pending unless Fog.mocking? # We don't have access to a Google Cloud Storage bucket @instance.import("gs://#{Fog::Mock.random_letters_and_numbers(16)}/mysql-export", :async => false) end tests('#ready?').succeeds do @instance.ready? == true end tests('#reset_ssl_config').succeeds do @instance.reset_ssl_config(:async => false) end tests('#restart').succeeds do @instance.restart(:async => false) end tests('#set_root_password').succeeds do @instance.set_root_password(Fog::Mock.random_letters_and_numbers(8), :async => false) end tests('#destroy').succeeds do @instance.destroy end end end fog-google-0.5.3/tests/models/pubsub/0000755000004100000410000000000013145731036017524 5ustar www-datawww-datafog-google-0.5.3/tests/models/pubsub/received_message_tests.rb0000644000004100000410000000115213145731036024564 0ustar www-datawww-dataShindo.tests("Fog::Google[:pubsub] | received_message model", ["google"]) do @connection = Fog::Google[:pubsub] @topic = @connection.topics.create(:name => "projects/#{@connection.project}/topics/#{Fog::Mock.random_letters(16)}") @subscription = @connection.subscriptions.create( :name => "projects/#{@connection.project}/subscriptions/#{Fog::Mock.random_letters(16)}", :topic => @topic.name ) tests("success") do tests('#acknowledge').returns(nil) do @topic.publish(["foo"]) @subscription.pull[0].acknowledge end end # teardown @topic.destroy @subscription.destroy end fog-google-0.5.3/tests/models/pubsub/topics_tests.rb0000644000004100000410000000114413145731036022574 0ustar www-datawww-dataShindo.tests("Fog::Google[:pubsub] | topics model", ["google"]) do @connection = Fog::Google[:pubsub] @topics = @connection.topics @topic = @topics.create(:name => "projects/#{@connection.project}/topics/#{Fog::Mock.random_letters(16)}") tests("success") do tests('#all').succeeds do @topics.all end tests('#get').succeeds do @topics.get(@topic.name) end end @topic.destroy tests("failure") do tests('#all').returns([]) do @topics.all end tests('#get').returns(nil) do @topics.get(Fog::Mock.random_letters_and_numbers(16)) end end end fog-google-0.5.3/tests/models/pubsub/topic_tests.rb0000644000004100000410000000071213145731036022411 0ustar www-datawww-dataShindo.tests("Fog::Google[:pubsub] | topic model", ["google"]) do @connection = Fog::Google[:pubsub] @topics = @connection.topics tests("success") do tests('#create').succeeds do @topic = @topics.create(:name => "projects/#{@connection.project}/topics/#{Fog::Mock.random_letters(16)}") end tests('#publish').succeeds do @topic.publish(["foo"]) end tests('#destroy').succeeds do @topic.destroy end end end fog-google-0.5.3/tests/models/pubsub/subscription_tests.rb0000644000004100000410000000137613145731036024026 0ustar www-datawww-dataShindo.tests("Fog::Google[:pubsub] | subscription model", ["google"]) do @connection = Fog::Google[:pubsub] @topic = @connection.topics.create(:name => "projects/#{@connection.project}/topics/#{Fog::Mock.random_letters(16)}") @subscriptions = @connection.subscriptions tests("success") do tests('#create').succeeds do @subscription = @subscriptions.create( :name => "projects/#{@connection.project}/subscriptions/#{Fog::Mock.random_letters(16)}", :topic => @topic.name ) end tests('#pull').returns("foo") do @topic.publish(["foo"]) @message = @subscription.pull[0] @message.message["data"] end tests('#destroy').succeeds do @subscription.destroy end end @topic.destroy end fog-google-0.5.3/tests/models/pubsub/subscriptions_tests.rb0000644000004100000410000000154513145731036024207 0ustar www-datawww-dataShindo.tests("Fog::Google[:pubsub] | subscriptions model", ["google"]) do @connection = Fog::Google[:pubsub] @topic = @connection.topics.create(:name => "projects/#{@connection.project}/topics/#{Fog::Mock.random_letters(16)}") @subscriptions = @connection.subscriptions @subscription = @subscriptions.create( :name => "projects/#{@connection.project}/subscriptions/#{Fog::Mock.random_letters(16)}", :topic => @topic.name ) tests("success") do tests('#all').succeeds do @subscriptions.all end tests('#get').succeeds do @subscriptions.get(@subscription.name) end end @subscription.destroy tests("failure") do tests('#all').returns([]) do @subscriptions.all end tests('#get').returns(nil) do @subscriptions.get(Fog::Mock.random_letters_and_numbers(16)) end end @topic.destroy end fog-google-0.5.3/tests/models/monitoring/0000755000004100000410000000000013145731036020411 5ustar www-datawww-datafog-google-0.5.3/tests/models/monitoring/timeseries_collection_tests.rb0000644000004100000410000000053513145731036026547 0ustar www-datawww-dataShindo.tests("Fog::Google[:monitoring] | timeseries_collection model", ["google"]) do @timeseries_collection = Fog::Google[:monitoring].timeseries_collection tests("success") do tests('#all').succeeds do @timeseries_collection.all("compute.googleapis.com/instance/uptime", Time.now.strftime("%Y-%m-%dT%H:%M:%S%:z")) end end end fog-google-0.5.3/tests/models/monitoring/metric_descriptors_tests.rb0000644000004100000410000000037413145731036026070 0ustar www-datawww-dataShindo.tests("Fog::Google[:monitoring] | metric_descriptors model", ["google"]) do @metric_descriptors = Fog::Google[:monitoring].metric_descriptors tests("success") do tests('#all').succeeds do @metric_descriptors.all end end end fog-google-0.5.3/tests/models/monitoring/timeseries_descriptors_tests.rb0000644000004100000410000000060313145731036026751 0ustar www-datawww-dataShindo.tests("Fog::Google[:monitoring] | timeseries_descriptors model", ["google"]) do @timeseries_descriptors = Fog::Google[:monitoring].timeseries_descriptors tests("success") do tests('#all').succeeds do @timeseries_descriptors.all("compute.googleapis.com/instance/uptime", Time.now.strftime("%Y-%m-%dT%H:%M:%S%:z")) end end end fog-google-0.5.3/tests/helpers/0000755000004100000410000000000013145731036016403 5ustar www-datawww-datafog-google-0.5.3/tests/helpers/responds_to_helper.rb0000644000004100000410000000037413145731036022632 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-google-0.5.3/tests/helpers/formats_helper.rb0000644000004100000410000000710213145731036021742 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-google-0.5.3/tests/helpers/succeeds_helper.rb0000644000004100000410000000020613145731036022063 0ustar www-datawww-datamodule Shindo class Tests def succeeds test("succeeds") do !!instance_eval(&Proc.new) end end end end fog-google-0.5.3/tests/helpers/collection_helper.rb0000644000004100000410000000510513145731036022423 0ustar www-datawww-data# TODO: REMOVE this testing functionality is now covered in `spec/helpers/model_helper.rb` def 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 @identity = @instance.identity if !Fog.mocking? || mocks_implemented 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" && JRUBY_VERSION =~ /1\.7\.[5-8]/ methods.delete("all?") end methods.each do |enum_method| next unless collection.respond_to?(enum_method) tests("##{enum_method}").succeeds do block_called = false collection.send(enum_method) { |_| block_called = true } block_called end end %w( max_by min_by).each do |enum_method| next unless collection.respond_to?(enum_method) tests("##{enum_method}").succeeds do block_called = false collection.send(enum_method) do |_| block_called = true 0 end block_called end end end yield(@instance) if block_given? @instance.destroy if !Fog.mocking? || mocks_implemented 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-google-0.5.3/tests/helpers/compute/0000755000004100000410000000000013145731036020057 5ustar www-datawww-datafog-google-0.5.3/tests/helpers/compute/servers_helper.rb0000644000004100000410000000040613145731036023434 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-google-0.5.3/tests/helpers/compute/server_helper.rb0000644000004100000410000000122613145731036023252 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 @instance.wait_for { ready? } if !Fog.mocking? || mocks_implemented end end fog-google-0.5.3/tests/helpers/compute/flavors_helper.rb0000644000004100000410000000146013145731036023420 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-google-0.5.3/tests/helpers/model_helper.rb0000644000004100000410000000153513145731036021373 0ustar www-datawww-data# TODO: REMOVE this testing functionality is now covered in `spec/helpers/model_helper.rb` def 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 yield(@instance) if block_given? 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(65_536).to_s(16).rjust(4, "0") [base_name, suffix].join("-") end fog-google-0.5.3/tests/helpers/formats_helper_tests.rb0000644000004100000410000000705513145731036023173 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-google-0.5.3/tests/helpers/mock_helper.rb0000644000004100000410000000111613145731036021217 0ustar www-datawww-data# Use so you can run in mock mode from the command line # # FOG_MOCK=true fog Fog.mock! if ENV["FOG_MOCK"] == "true" # if in mocked mode, fill in some fake credentials for us if Fog.mock? Fog.credentials = { :google_storage_access_key_id => "google_storage_access_key_id", :google_storage_secret_access_key => "google_storage_secret_access_key", :google_project => "google_project_name", :google_client_email => "fake@developer.gserviceaccount.com", :google_key_location => "~/fake.p12" }.merge(Fog.credentials) end fog-google-0.5.3/tests/helpers/schema_validator_tests.rb0000644000004100000410000000726513145731036023471 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-google-0.5.3/fog-google.gemspec0000644000004100000410000000321513145731036017172 0ustar www-datawww-data# coding: utf-8 lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "fog/google/version" Gem::Specification.new do |spec| spec.name = "fog-google" spec.version = Fog::Google::VERSION spec.authors = ["Nat Welch", "Daniel Broudy", "Isaac Hollander McCreery", "Dean Putney"] spec.email = ["nat@natwelch.com", "broudy@google.com", "ihmccreery@google.com", "dean@glowforge.com"] spec.summary = "Module for the 'fog' gem to support Google." spec.description = 'This library can be used as a module for `fog` or as standalone provider to use the Google in applications.' spec.homepage = "https://github.com/fog/fog-google" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] # As of 0.1.1 spec.required_ruby_version = "~> 2.0" spec.add_dependency "fog-core" spec.add_dependency "fog-json" spec.add_dependency "fog-xml" # TODO: Upgrade to 0.9, which is not compatible. spec.add_development_dependency "google-api-client", "~> 0.8.7" spec.add_development_dependency "rake" spec.add_development_dependency "shindo" spec.add_development_dependency "minitest" spec.add_development_dependency "pry" spec.add_development_dependency "vcr" spec.add_development_dependency "webmock" spec.add_development_dependency "coveralls" spec.add_development_dependency "rubocop" spec.add_development_dependency "mime-types" end fog-google-0.5.3/.editorconfig0000644000004100000410000000031013145731036016246 0ustar www-datawww-data# For more info on EditorConfig, see: http://EditorConfig.org root = true [*.gemspec,*.rb,Gemfile,Rakefile] indent_style = space indent_size = 2 [*.yml,*.yaml] indent_style = space indent_size = 2 fog-google-0.5.3/.fog.example0000644000004100000410000000227413145731036016012 0ustar www-datawww-data################################################################## # This is configuration snippet to configure Google Cloud Platform # for fog library. # # 1. Copy this file into your home dir: "~/.fog": # # $ cat .fog.example >> ~/.fog # # 2. Follow instructions to generate a private key: # https://cloud.google.com/storage/docs/authentication#generating-a-private-key # # 3. Edit the new file accordingly. # ################################################################## # START GOOGLE CONFIG my_google_credentials: google_project: my-project-id google_client_email: xxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com google_json_key_location: /path/to/my-project-xxxxxxxxxxxx.json # You can also provide service account credentials with `google_json_key_string` or # with `google_key_location` and `google_key_string` for P12 private keys. # If so, uncomment the two following lines. # HMAC credentials follow a similar format: #google_storage_access_key_id: GOOGXXXXXXXXXXXXXXXX #google_storage_secret_access_key: XXXX+XXX/XXXXXXXX+XXXXXXXXXXXXXXXXXXXXX # /END GOOGLE CONFIG #################################################################fog-google-0.5.3/.hound.yml0000644000004100000410000000004213145731036015511 0ustar www-datawww-dataruby: config_file: .rubocop.yml fog-google-0.5.3/CONTRIBUTORS.md0000644000004100000410000000320713145731036016060 0ustar www-datawww-data* Alexander Lomov * Alexander Kolesen * althras * Andrew Leonard * Antonio <0x414f@gmail.com> * Ariel Zavala * ashmrtnz * Akshay Moghe * Benson Kalahar * Bob Lail and Luke Booth * Brett Porter * Brian D. Burns * Carlos Sanchez * Chris Gianelloni * Dan Prince * Daniel Broudy * Dean Putney * Doug Henderson * Eric Johnson * Ferran Rodenas * Frederick Cheung * Jacob Mattingley * James Herdman * jordangbull * Juris Galang * kbockmanrs * Lance Ivy * leonidlm * Marcin Owsiany * Matt Darby * Michael Elfassy * Nat Welch * neillturner * Paul Thornthwaite * Paulo Henrique Lopes Ribeiro * Romain Haenni * Romain Vrignaud * snyquist2 * Stephen von Takach * Timur Alperovich * unknown * Wesley Beary * Google Inc. fog-google-0.5.3/LICENSE.md0000644000004100000410000000217613145731036015211 0ustar www-datawww-datahe MIT License (MIT) Copyright (c) 2014-2015 [CONTRIBUTORS.md](https://github.com/fog/fog-google/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-google-0.5.3/.travis.yml0000644000004100000410000000043213145731036015707 0ustar www-datawww-datalanguage: ruby cache: bundler sudo: false dist: trusty matrix: fast_finish: true include: - rvm: 2.1 - rvm: 2.2 - rvm: 2.3 - rvm: 2.4.0 - rvm: 2.4.1 - rvm: jruby-head allow_failures: - rvm: jruby-head - rvm: 2.4.1 notifications: email: false fog-google-0.5.3/lib/0000755000004100000410000000000013145731036014345 5ustar www-datawww-datafog-google-0.5.3/lib/fog/0000755000004100000410000000000013145731036015120 5ustar www-datawww-datafog-google-0.5.3/lib/fog/bin/0000755000004100000410000000000013145731036015670 5ustar www-datawww-datafog-google-0.5.3/lib/fog/bin/google.rb0000644000004100000410000000561613145731036017501 0ustar www-datawww-datamodule Google # deviates from other bin stuff to accomodate gem class << self def class_for(key) case key when :compute Fog::Compute::Google when :dns Fog::DNS::Google when :monitoring Fog::Google::Monitoring when :storage Fog::Storage::Google when :storage_json Fog::Storage::Google when :sql Fog::Google::SQL 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("Google[:compute] is not recommended, use Compute[:google] for portability") Fog::Compute.new(:provider => "Google") when :dns Fog::Logger.warning("Google[:dns] is not recommended, use DNS[:google] for portability") Fog::DNS.new(:provider => "Google") when :monitoring Fog::Google::Monitoring.new when :sql Fog::Google::SQL.new when :storage Fog::Logger.warning("Google[:storage] is not recommended, use Storage[:google] for portability") Fog::Storage.new(:provider => "Google") else raise ArgumentError, "Unrecognized service: #{key.inspect}" end end @@connections[service] end def account @@connections[:compute].account end def services Fog::Google.services end # based off of virtual_box.rb def available? # Make sure the gem we use is enabled. availability = if Gem::Specification.respond_to?(:find_all_by_name) !Gem::Specification.find_all_by_name("google-api-client").empty? # newest rubygems else !Gem.source_index.find_name("google-api-client").empty? # legacy end # Then make sure we have all of the requirements for service in services begin service = 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 class_for(service).collections unless self.respond_to?(collection) class_eval <<-EOS, __FILE__, __LINE__ def self.#{collection} self[:#{service}].#{collection} end EOS end end end end availability end end end fog-google-0.5.3/lib/fog/storage/0000755000004100000410000000000013145731036016564 5ustar www-datawww-datafog-google-0.5.3/lib/fog/storage/google_json.rb0000644000004100000410000000343413145731036021422 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON < Fog::Service autoload :Mock, File.expand_path("../google_json/mock", __FILE__) autoload :Real, File.expand_path("../google_json/real", __FILE__) autoload :Utils, File.expand_path("../google_json/utils", __FILE__) requires :google_project recognizes( :app_name, :app_version, :google_client, :google_client_email, :google_client_options, :google_key_location, :google_key_string, :google_json_key_location, :google_json_key_string ) # https://cloud.google.com/storage/docs/json_api/v1/ GOOGLE_STORAGE_JSON_API_VERSION = "v1" GOOGLE_STORAGE_JSON_BASE_URL = "https://www.googleapis.com/storage/" # TODO: Come up with a way to only request a subset of permissions. # https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing GOOGLE_STORAGE_JSON_API_SCOPE_URLS = %w(https://www.googleapis.com/auth/devstorage.full_control) ## # Models model_path "fog/storage/google_json/models" collection :directories model :directory collection :files model :file ## # Requests request_path "fog/storage/google_json/requests" request :copy_object request :delete_bucket request :delete_object request :get_bucket request :get_bucket_acl request :get_object request :get_object_acl request :get_object_http_url request :get_object_https_url request :get_object_url request :head_object request :list_buckets request :list_objects request :put_bucket request :put_bucket_acl request :put_object request :put_object_acl request :put_object_url end end end fog-google-0.5.3/lib/fog/storage/google.rb0000644000004100000410000000076513145731036020375 0ustar www-datawww-datamodule Fog module Storage class Google < Fog::Service def self.new(options = {}) begin fog_creds = Fog.credentials rescue fog_creds = nil end if options.keys.include?(:google_storage_access_key_id) || (!fog_creds.nil? && fog_creds.keys.include?(:google_storage_access_key_id)) Fog::Storage::GoogleXML.new(options) else Fog::Storage::GoogleJSON.new(options) end end end end end fog-google-0.5.3/lib/fog/storage/google_xml.rb0000644000004100000410000000215713145731036021252 0ustar www-datawww-datamodule Fog module Storage class GoogleXML < Fog::Service autoload :Mock, File.expand_path("../google_xml/mock", __FILE__) autoload :Real, File.expand_path("../google_xml/real", __FILE__) autoload :Utils, File.expand_path("../google_xml/utils", __FILE__) requires :google_storage_access_key_id, :google_storage_secret_access_key recognizes :host, :port, :scheme, :persistent, :path_style model_path "fog/storage/google_xml/models" collection :directories model :directory collection :files model :file request_path "fog/storage/google_xml/requests" request :copy_object request :delete_bucket request :delete_object request :get_bucket request :get_bucket_acl request :get_object request :get_object_acl request :get_object_http_url request :get_object_https_url request :get_object_url request :get_service request :head_object request :put_bucket request :put_bucket_acl request :put_object request :put_object_acl request :put_object_url end end end fog-google-0.5.3/lib/fog/storage/google_xml/0000755000004100000410000000000013145731036020720 5ustar www-datawww-datafog-google-0.5.3/lib/fog/storage/google_xml/utils.rb0000644000004100000410000000574713145731036022422 0ustar www-datawww-datamodule Fog module Storage class GoogleXML module Utils def http_url(params, expires) "http://" << host_path_query(params, expires) end def https_url(params, expires) "https://" << host_path_query(params, expires) end def url(params, expires) Fog::Logger.deprecation("Fog::Storage::Google => #url is deprecated, use #https_url instead [light_black](#{caller.first})[/]") https_url(params, expires) end private def host_path_query(params, expires) params[:headers]["Date"] = expires.to_i params[:path] = CGI.escape(params[:path]).gsub("%2F", "/") query = [params[:query]].compact query << "GoogleAccessId=#{@google_storage_access_key_id}" query << "Signature=#{CGI.escape(signature(params))}" query << "Expires=#{params[:headers]['Date']}" "#{params[:host]}/#{params[:path]}?#{query.join('&')}" end def request_params(params) subdomain = params[:host].split(".#{@host}").first if @path_style || subdomain !~ /^(?!goog)(?:[a-z]|\d(?!\d{0,2}(?:\.\d{1,3}){3}$))(?:[a-z0-9]|\.(?![\.\-])|\-(?![\.])){1,61}[a-z0-9]$/ if subdomain =~ /_/ # https://github.com/fog/fog/pull/1258#issuecomment-10248620. Fog::Logger.warning("fog: the specified google storage bucket name (#{subdomain}) is not DNS compliant (only characters a through z, digits 0 through 9, and the hyphen).") else # - Bucket names must contain only lowercase letters, numbers, dashes (-), underscores (_), and dots (.). Names containing dots require verification. # - Bucket names must start and end with a number or letter. # - Bucket names must contain 3 to 63 characters. Names containing dots can contain up to 222 characters, but each dot-separated component can be no longer than 63 characters. # - Bucket names cannot be represented as an IP address in dotted-decimal notation (for example, 192.168.5.4). # - Bucket names cannot begin with the "goog" prefix. # - Also, for DNS compliance, you should not have a period adjacent to another period or dash. For example, ".." or "-." or ".-" are not acceptable. Fog::Logger.warning("fog: the specified google storage bucket name (#{subdomain}) is not a valid dns name. See: https://developers.google.com/storage/docs/bucketnaming") unless @path_style end params[:host] = params[:host].split("#{subdomain}.")[-1] params[:path] = if params[:path] "#{subdomain}/#{params[:path]}" else subdomain.to_s end subdomain = nil end params[:subdomain] = subdomain if subdomain && subdomain != @host params[:scheme] ||= @scheme params[:port] ||= @port params end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/0000755000004100000410000000000013145731036022573 5ustar www-datawww-datafog-google-0.5.3/lib/fog/storage/google_xml/requests/get_object_url.rb0000644000004100000410000000220513145731036026106 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real # Get an expiring object url from Google Storage # # ==== Parameters # * bucket_name<~String> - Name of bucket containing object # * object_name<~String> - Name of object to get expiring url for # * expires<~Time> - An expiry time for this url # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object def get_object_url(bucket_name, object_name, expires) Fog::Logger.deprecation("Fog::Storage::Google => ##{get_object_url} is deprecated, use ##{get_object_https_url} instead[/] [light_black](#{caller.first})") get_object_https_url(bucket_name, object_name, expires) end end class Mock # :nodoc:all def get_object_url(bucket_name, object_name, expires) Fog::Logger.deprecation("Fog::Storage::Google => ##{get_object_url} is deprecated, use ##{get_object_https_url} instead[/] [light_black](#{caller.first})") get_object_https_url(bucket_name, object_name, expires) end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/put_object.rb0000644000004100000410000000740713145731036025266 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real # Create an object in an Google Storage bucket # # ==== Parameters # * bucket_name<~String> - Name of bucket to create object in # * object_name<~String> - Name of object to create # * data<~File> - File or String to create object from # * options<~Hash>: # * 'Cache-Control'<~String> - Caching behaviour # * 'Content-Disposition'<~String> - Presentational information for the object # * 'Content-Encoding'<~String> - Encoding of object data # * 'Content-Length'<~String> - Size of object in bytes (defaults to object.read.length) # * 'Content-MD5'<~String> - Base64 encoded 128-bit MD5 digest of message (defaults to Base64 encoded MD5 of object.read) # * 'Content-Type'<~String> - Standard MIME type describing contents (defaults to MIME::Types.of.first) # * 'x-goog-acl'<~String> - Permissions, must be in ['private', 'public-read', 'public-read-write', 'authenticated-read'] # * "x-goog-meta-#{name}" - Headers to be returned with object, note total size of request without body must be less than 8 KB. # # ==== Returns # * response<~Excon::Response>: # * headers<~Hash>: # * 'ETag'<~String> - etag of new object def put_object(bucket_name, object_name, data, options = {}) data = Fog::Storage.parse_data(data) headers = data[:headers].merge!(options) request(:body => data[:body], :expects => 200, :headers => headers, :host => "#{bucket_name}.#{@host}", :idempotent => true, :method => "PUT", :path => Fog::Google.escape(object_name)) end end class Mock def put_object(bucket_name, object_name, data, options = {}) acl = options["x-goog-acl"] || "private" if !["private", "public-read", "public-read-write", "authenticated-read"].include?(acl) raise Excon::Errors::BadRequest.new("invalid x-goog-acl") else self.data[:acls][:object][bucket_name] ||= {} self.data[:acls][:object][bucket_name][object_name] = self.class.acls(acl) end data = Fog::Storage.parse_data(data) data[:body] = data[:body].read unless data[:body].is_a?(String) response = Excon::Response.new if (bucket = self.data[:buckets][bucket_name]) response.status = 200 object = { :body => data[:body], "Content-Type" => options["Content-Type"] || data[:headers]["Content-Type"], "ETag" => Fog::Google::Mock.etag, "Key" => object_name, "Last-Modified" => Fog::Time.now.to_date_header, "Content-Length" => options["Content-Length"] || data[:headers]["Content-Length"] } for key, value in options case key when "Cache-Control", "Content-Disposition", "Content-Encoding", "Content-MD5", "Expires", /^x-goog-meta-/ object[key] = value end end bucket[:objects][object_name] = object response.headers = { "Content-Length" => object["Content-Length"], "Content-Type" => object["Content-Type"], "ETag" => object["ETag"], "Last-Modified" => object["Last-Modified"] } else response.status = 404 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/head_object.rb0000644000004100000410000000511313145731036025347 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real # Get headers for an object from Google Storage # # ==== Parameters # * bucket_name<~String> - Name of bucket to read from # * object_name<~String> - Name of object to read # * options<~Hash>: # * 'If-Match'<~String> - Returns object only if its etag matches this value, otherwise returns 412 (Precondition Failed). # * 'If-Modified-Since'<~Time> - Returns object only if it has been modified since this time, otherwise returns 304 (Not Modified). # * 'If-None-Match'<~String> - Returns object only if its etag differs from this value, otherwise returns 304 (Not Modified) # * 'If-Unmodified-Since'<~Time> - Returns object only if it has not been modified since this time, otherwise returns 412 (Precodition Failed). # * 'Range'<~String> - Range of object to download # * 'versionId'<~String> - specify a particular version to retrieve # # ==== Returns # * response<~Excon::Response>: # * body<~String> - Contents of object # * headers<~Hash>: # * 'Content-Length'<~String> - Size of object contents # * 'Content-Type'<~String> - MIME type of object # * 'ETag'<~String> - Etag of object # * 'Last-Modified'<~String> - Last modified timestamp for object def head_object(bucket_name, object_name, options = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name if version_id = options.delete("versionId") query = { "versionId" => version_id } end headers = {} headers["If-Modified-Since"] = Fog::Time.at(options["If-Modified-Since"].to_i).to_date_header if options["If-Modified-Since"] headers["If-Unmodified-Since"] = Fog::Time.at(options["If-Unmodified-Since"].to_i).to_date_header if options["If-Modified-Since"] headers.merge!(options) request(:expects => [200, 206], :headers => headers, :host => "#{bucket_name}.#{@host}", :method => "HEAD", :path => Fog::Google.escape(object_name), :query => query) end end class Mock def head_object(bucket_name, object_name, options = {}) response = get_object(bucket_name, object_name, options) response.body = nil response end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/get_object_acl.rb0000644000004100000410000000466213145731036026054 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real # Get access control list for an Google Storage object # # ==== Parameters # * bucket_name<~String> - name of bucket containing object # * object_name<~String> - name of object to get access control list for # * options<~Hash>: # * 'versionId'<~String> - specify a particular version to retrieve # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'AccessControlPolicy'<~Hash> # * 'Owner'<~Hash>: # * 'DisplayName'<~String> - Display name of object owner # * 'ID'<~String> - Id of object owner # * 'AccessControlList'<~Array>: # * 'Grant'<~Hash>: # * 'Grantee'<~Hash>: # * 'DisplayName'<~String> - Display name of grantee # * 'ID'<~String> - Id of grantee # or # * 'URI'<~String> - URI of group to grant access for # * 'Permission'<~String> - Permission, in [FULL_CONTROL, WRITE, WRITE_ACP, READ, READ_ACP] # def get_object_acl(bucket_name, object_name, options = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name query = { "acl" => nil } if version_id = options.delete("versionId") query["versionId"] = version_id end request(:expects => 200, :headers => {}, :host => "#{bucket_name}.#{@host}", :idempotent => true, :method => "GET", :parser => Fog::Parsers::Storage::Google::AccessControlList.new, :path => Fog::Google.escape(object_name), :query => query) end end class Mock def get_object_acl(bucket_name, object_name) response = Excon::Response.new if acl = data[:acls][:object][bucket_name] && data[:acls][:object][bucket_name][object_name] response.status = 200 response.body = acl else response.status = 404 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/get_service.rb0000644000004100000410000000251013145731036025415 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real # List information about Google Storage buckets for authorized user # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Buckets'<~Hash>: # * 'Name'<~String> - Name of bucket # * 'CreationTime'<~Time> - Timestamp of bucket creation # * 'Owner'<~Hash>: # * 'DisplayName'<~String> - Display name of bucket owner # * 'ID'<~String> - Id of bucket owner def get_service request(:expects => 200, :headers => {}, :host => @host, :idempotent => true, :method => "GET", :parser => Fog::Parsers::Storage::Google::GetService.new) end end class Mock def get_service response = Excon::Response.new response.headers["Status"] = 200 buckets = data[:buckets].values.map do |bucket| bucket.reject do |key, _value| !%w(CreationDate Name).include?(key) end end response.body = { "Buckets" => buckets, "Owner" => { "ID" => "some_id" } } response end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/get_bucket_acl.rb0000644000004100000410000000362013145731036026054 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real # Get access control list for an Google Storage bucket # # ==== Parameters # * bucket_name<~String> - name of bucket to get access control list for # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'AccessControlPolicy'<~Hash> # * 'Owner'<~Hash>: # * 'DisplayName'<~String> - Display name of object owner # * 'ID'<~String> - Id of object owner # * 'AccessControlList'<~Array>: # * 'Grant'<~Hash>: # * 'Grantee'<~Hash>: # * 'DisplayName'<~String> - Display name of grantee # * 'ID'<~String> - Id of grantee # or # * 'URI'<~String> - URI of group to grant access for # * 'Permission'<~String> - Permission, in [FULL_CONTROL, WRITE, WRITE_ACP, READ, READ_ACP] # def get_bucket_acl(bucket_name) raise ArgumentError.new("bucket_name is required") unless bucket_name request(:expects => 200, :headers => {}, :host => "#{bucket_name}.#{@host}", :idempotent => true, :method => "GET", :parser => Fog::Parsers::Storage::Google::AccessControlList.new, :query => { "acl" => nil }) end end class Mock def get_bucket_acl(bucket_name) response = Excon::Response.new if acl = data[:acls][:bucket][bucket_name] response.status = 200 response.body = acl else response.status = 404 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/put_object_url.rb0000644000004100000410000000302513145731036026140 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real # Get an expiring object url from Google Storage for putting an object # # ==== Parameters # * bucket_name<~String> - Name of bucket containing object # * object_name<~String> - Name of object to get expiring url for # * expires<~Time> - An expiry time for this url # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object # def put_object_url(bucket_name, object_name, expires, headers = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name https_url({ :headers => headers, :host => @host, :method => "PUT", :path => "#{bucket_name}/#{object_name}" }, expires) end end class Mock def put_object_url(bucket_name, object_name, expires, headers = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name https_url({ :headers => headers, :host => @host, :method => "PUT", :path => "#{bucket_name}/#{object_name}" }, expires) end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/get_object_http_url.rb0000644000004100000410000000214313145731036027146 0ustar www-datawww-datamodule Fog module Storage class GoogleXML module GetObjectHttpUrl def get_object_http_url(bucket_name, object_name, expires) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name http_url({ :headers => {}, :host => @host, :method => "GET", :path => "#{bucket_name}/#{object_name}" }, expires) end end class Real # Get an expiring object http url from GCS # # ==== Parameters # * bucket_name<~String> - Name of bucket containing object # * object_name<~String> - Name of object to get expiring url for # * expires<~Time> - An expiry time for this url # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object include GetObjectHttpUrl end class Mock # :nodoc:all include GetObjectHttpUrl end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/delete_bucket.rb0000644000004100000410000000222413145731036025717 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real # Delete an Google Storage bucket # # ==== Parameters # * bucket_name<~String> - name of bucket to delete # # ==== Returns # * response<~Excon::Response>: # * status<~Integer> - 204 def delete_bucket(bucket_name) request(:expects => 204, :headers => {}, :host => "#{bucket_name}.#{@host}", :method => "DELETE") end end class Mock def delete_bucket(bucket_name) response = Excon::Response.new if data[:buckets][bucket_name].nil? response.status = 404 raise(Excon::Errors.status_error({ :expects => 204 }, response)) elsif data[:buckets][bucket_name] && !data[:buckets][bucket_name][:objects].empty? response.status = 409 raise(Excon::Errors.status_error({ :expects => 204 }, response)) else data[:buckets].delete(bucket_name) response.status = 204 end response end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/copy_object.rb0000644000004100000410000000554613145731036025432 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real # Copy an object from one Google Storage bucket to another # # ==== Parameters # * source_bucket_name<~String> - Name of source bucket # * source_object_name<~String> - Name of source object # * target_bucket_name<~String> - Name of bucket to create copy in # * target_object_name<~String> - Name for new copy of object # * options<~Hash>: # * 'x-goog-metadata-directive'<~String> - Specifies whether to copy metadata from source or replace with data in request. Must be in ['COPY', 'REPLACE'] # * 'x-goog-copy_source-if-match'<~String> - Copies object if its etag matches this value # * 'x-goog-copy_source-if-modified_since'<~Time> - Copies object it it has been modified since this time # * 'x-goog-copy_source-if-none-match'<~String> - Copies object if its etag does not match this value # * 'x-goog-copy_source-if-unmodified-since'<~Time> - Copies object it it has not been modified since this time # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ETag'<~String> - etag of new object # * 'LastModified'<~Time> - date object was last modified # def copy_object(source_bucket_name, source_object_name, target_bucket_name, target_object_name, options = {}) headers = { "x-goog-copy-source" => "/#{source_bucket_name}/#{source_object_name}" }.merge(options) request(:expects => 200, :headers => headers, :host => "#{target_bucket_name}.#{@host}", :method => "PUT", :parser => Fog::Parsers::Storage::Google::CopyObject.new, :path => Fog::Google.escape(target_object_name)) end end class Mock def copy_object(source_bucket_name, source_object_name, target_bucket_name, target_object_name, _options = {}) response = Excon::Response.new source_bucket = data[:buckets][source_bucket_name] source_object = source_bucket && source_bucket[:objects][source_object_name] target_bucket = data[:buckets][target_bucket_name] if source_object && target_bucket response.status = 200 target_object = source_object.dup target_object.merge!("Name" => target_object_name) target_bucket[:objects][target_object_name] = target_object response.body = { "ETag" => target_object["ETag"], "LastModified" => Time.parse(target_object["Last-Modified"]) } else response.status = 404 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/delete_object.rb0000644000004100000410000000257213145731036025716 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real # Delete an object from Google Storage # # ==== Parameters # * bucket_name<~String> - Name of bucket containing object to delete # * object_name<~String> - Name of object to delete # # ==== Returns # * response<~Excon::Response>: # * status<~Integer> - 204 def delete_object(bucket_name, object_name) request(:expects => 204, :headers => {}, :host => "#{bucket_name}.#{@host}", :idempotent => true, :method => "DELETE", :path => Fog::Google.escape(object_name)) end end class Mock def delete_object(bucket_name, object_name) response = Excon::Response.new if bucket = data[:buckets][bucket_name] if object = bucket[:objects][object_name] response.status = 204 bucket[:objects].delete(object_name) else response.status = 404 raise(Excon::Errors.status_error({ :expects => 204 }, response)) end else response.status = 404 raise(Excon::Errors.status_error({ :expects => 204 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/get_object_https_url.rb0000644000004100000410000000217113145731036027332 0ustar www-datawww-datamodule Fog module Storage class GoogleXML module GetObjectHttpsUrl def get_object_https_url(bucket_name, object_name, expires) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name https_url({ :headers => {}, :host => @host, :method => "GET", :path => "#{bucket_name}/#{object_name}" }, expires) end end class Real # Get an expiring object https url from Google Storage # # ==== Parameters # * bucket_name<~String> - Name of bucket containing object # * object_name<~String> - Name of object to get expiring url for # * expires<~Time> - An expiry time for this url # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object include GetObjectHttpsUrl end class Mock # :nodoc:all include GetObjectHttpsUrl end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/put_bucket_acl.rb0000644000004100000410000000272013145731036026105 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Mock def put_bucket_acl(_bucket_name, _acl) Fog::Mock.not_implemented end end class Real # Change access control list for an Google Storage bucket def put_bucket_acl(bucket_name, acl) data = <<-DATA #{tag('ID', acl['Owner']['ID'])} #{entries_list(acl['AccessControlList'])} DATA request(:body => data, :expects => 200, :headers => {}, :host => "#{bucket_name}.#{@host}", :method => "PUT", :query => { "acl" => nil }) end private def tag(name, value) "<#{name}>#{value}" end def scope_tag(scope) if %w(AllUsers AllAuthenticatedUsers).include?(scope["type"]) "" else "" + scope.to_a.select { |pair| pair[0] != "type" }.map { |pair| tag(pair[0], pair[1]) }.join("\n") + "" end end def entries_list(access_control_list) access_control_list.map do |entry| tag("Entry", scope_tag(entry["Scope"]) + tag("Permission", entry["Permission"])) end.join("\n") end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/get_bucket.rb0000644000004100000410000001056513145731036025243 0ustar www-datawww-datarequire "pp" module Fog module Storage class GoogleXML class Real # List information about objects in an Google Storage bucket # # ==== Parameters # * bucket_name<~String> - name of bucket to list object keys from # * options<~Hash> - config arguments for list. Defaults to {}. # * 'delimiter'<~String> - causes keys with the same string between the prefix # value and the first occurence of delimiter to be rolled up # * 'marker'<~String> - limits object keys to only those that appear # lexicographically after its value. # * 'max-keys'<~Integer> - limits number of object keys returned # * 'prefix'<~String> - limits object keys to those beginning with its value. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'Delimeter'<~String> - Delimiter specified for query # * 'IsTruncated'<~Boolean> - Whether or not the listing is truncated # * 'Marker'<~String> - Marker specified for query # * 'MaxKeys'<~Integer> - Maximum number of keys specified for query # * 'Name'<~String> - Name of the bucket # * 'Prefix'<~String> - Prefix specified for query # * 'CommonPrefixes'<~Array> - Array of strings for common prefixes # * 'Contents'<~Array>: # * 'ETag'<~String>: Etag of object # * 'Key'<~String>: Name of object # * 'LastModified'<~String>: Timestamp of last modification of object # * 'Owner'<~Hash>: # * 'DisplayName'<~String> - Display name of object owner # * 'ID'<~String> - Id of object owner # * 'Size'<~Integer> - Size of object # def get_bucket(bucket_name, options = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name request(:expects => 200, :headers => {}, :host => "#{bucket_name}.#{@host}", :idempotent => true, :method => "GET", :parser => Fog::Parsers::Storage::Google::GetBucket.new, :query => options) end end class Mock def get_bucket(bucket_name, options = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name response = Excon::Response.new name = /(\w+\.?)*/.match(bucket_name) if bucket_name == name.to_s if bucket = data[:buckets][bucket_name] contents = bucket[:objects].values.sort { |x, y| x["Key"] <=> y["Key"] }.reject do |object| (options["prefix"] && object["Key"][0...options["prefix"].length] != options["prefix"]) || (options["marker"] && object["Key"] <= options["marker"]) end.map do |object| data = object.reject { |key, _value| !%w(ETag Key).include?(key) } data.merge!("LastModified" => Time.parse(object["Last-Modified"]), "Owner" => bucket["Owner"], "Size" => object["Content-Length"].to_i) data end max_keys = options["max-keys"] || 1000 size = [max_keys, 1000].min truncated_contents = contents[0...size] response.status = 200 response.body = { "CommonPrefixes" => [], "Contents" => truncated_contents, "IsTruncated" => truncated_contents.size != contents.size, "Marker" => options["marker"], "Name" => bucket["Name"], "Prefix" => options["prefix"] } if options["max-keys"] && options["max-keys"] < response.body["Contents"].length response.body["IsTruncated"] = true response.body["Contents"] = response.body["Contents"][0...options["max-keys"]] end else response.status = 404 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end else response.status = 400 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/get_object.rb0000644000004100000410000001075013145731036025230 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real # Get an object from Google Storage # # ==== Parameters # * bucket_name<~String> - Name of bucket to read from # * object_name<~String> - Name of object to read # * options<~Hash>: # * 'If-Match'<~String> - Returns object only if its etag matches this value, otherwise returns 412 (Precondition Failed). # * 'If-Modified-Since'<~Time> - Returns object only if it has been modified since this time, otherwise returns 304 (Not Modified). # * 'If-None-Match'<~String> - Returns object only if its etag differs from this value, otherwise returns 304 (Not Modified) # * 'If-Unmodified-Since'<~Time> - Returns object only if it has not been modified since this time, otherwise returns 412 (Precodition Failed). # * 'Range'<~String> - Range of object to download # * 'versionId'<~String> - specify a particular version to retrieve # # ==== Returns # * response<~Excon::Response>: # * body<~String> - Contents of object # * headers<~Hash>: # * 'Content-Length'<~String> - Size of object contents # * 'Content-Type'<~String> - MIME type of object # * 'ETag'<~String> - Etag of object # * 'Last-Modified'<~String> - Last modified timestamp for object # def get_object(bucket_name, object_name, options = {}, &_block) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name params = { :headers => {} } if version_id = options.delete("versionId") params[:query] = { "versionId" => version_id } end params[:headers].merge!(options) if options["If-Modified-Since"] params[:headers]["If-Modified-Since"] = Fog::Time.at(options["If-Modified-Since"].to_i).to_date_header end if options["If-Modified-Since"] params[:headers]["If-Unmodified-Since"] = Fog::Time.at(options["If-Unmodified-Since"].to_i).to_date_header end params[:response_block] = Proc.new if block_given? request(params.merge!(:expects => [200, 206], :host => "#{bucket_name}.#{@host}", :idempotent => true, :method => "GET", :path => Fog::Google.escape(object_name))) end end class Mock def get_object(bucket_name, object_name, options = {}, &block) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name response = Excon::Response.new if (bucket = data[:buckets][bucket_name]) && (object = bucket[:objects][object_name]) if options["If-Match"] && options["If-Match"] != object["ETag"] response.status = 412 elsif options["If-Modified-Since"] && options["If-Modified-Since"] >= Time.parse(object["Last-Modified"]) response.status = 304 elsif options["If-None-Match"] && options["If-None-Match"] == object["ETag"] response.status = 304 elsif options["If-Unmodified-Since"] && options["If-Unmodified-Since"] < Time.parse(object["Last-Modified"]) response.status = 412 else response.status = 200 for key, value in object case key when "Cache-Control", "Content-Disposition", "Content-Encoding", "Content-Length", "Content-MD5", "Content-Type", "ETag", "Expires", "Last-Modified", /^x-goog-meta-/ response.headers[key] = value end end unless block_given? response.body = object[:body] else data = StringIO.new(object[:body]) remaining = data.length while remaining > 0 chunk = data.read([remaining, Excon::CHUNK_SIZE].min) block.call(chunk) remaining -= Excon::CHUNK_SIZE end end end else response.status = 404 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/put_bucket.rb0000644000004100000410000000515413145731036025272 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real # Create an Google Storage bucket # # ==== Parameters # * bucket_name<~String> - name of bucket to create # * options<~Hash> - config arguments for bucket. Defaults to {}. # * 'LocationConstraint'<~Symbol> - sets the location for the bucket # * 'x-goog-acl'<~String> - The predefined access control list (ACL) that you want to apply to the bucket. # # ==== Returns # * response<~Excon::Response>: # * status<~Integer> - 200 def put_bucket(bucket_name, options = {}) location_constraint = options.delete("LocationConstraint") storage_class = options.delete("StorageClass") if location_constraint || storage_class data = "" data += "#{location_constraint}" if location_constraint data += "#{storage_class}" if storage_class data += "" else data = nil end request(:expects => 200, :body => data, :headers => options, :idempotent => true, :host => "#{bucket_name}.#{@host}", :method => "PUT") end end class Mock def put_bucket(bucket_name, options = {}) acl = options["x-goog-acl"] || "private" if !["private", "public-read", "public-read-write", "authenticated-read"].include?(acl) raise Excon::Errors::BadRequest.new("invalid x-goog-acl") else data[:acls][:bucket][bucket_name] = self.class.acls(options[acl]) end response = Excon::Response.new response.status = 200 bucket = { :objects => {}, "Name" => bucket_name, "CreationDate" => Time.now, "Owner" => { "DisplayName" => "owner", "ID" => "some_id" }, "Payer" => "BucketOwner" } if options["LocationConstraint"] bucket["LocationConstraint"] = options["LocationConstraint"] else bucket["LocationConstraint"] = "" end if data[:buckets][bucket_name].nil? data[:buckets][bucket_name] = bucket else response.status = 409 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/requests/put_object_acl.rb0000644000004100000410000000264313145731036026102 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real # TODO: move this methods to helper to use them with put_bucket_acl request def tag(name, value) "<#{name}>#{value}" end def scope_tag(scope) if %w(AllUsers AllAuthenticatedUsers).include?(scope["type"]) "" else "" + scope.to_a.select { |pair| pair[0] != "type" }.map { |pair| tag(pair[0], pair[1]) }.join("\n") + "" end end def entries_list(access_control_list) access_control_list.map do |entry| tag("Entry", scope_tag(entry["Scope"]) + tag("Permission", entry["Permission"])) end.join("\n") end def put_object_acl(bucket_name, object_name, acl) data = <<-DATA #{tag('ID', acl['Owner']['ID'])} #{entries_list(acl['AccessControlList'])} DATA request(:body => data, :expects => 200, :headers => {}, :host => "#{bucket_name}.#{@host}", :method => "PUT", :query => { "acl" => nil }, :path => Fog::Google.escape(object_name)) end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/mock.rb0000644000004100000410000000615213145731036022202 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Mock include Utils def self.acls(type) case type when "private" { "AccessControlList" => [ { "Permission" => "FULL_CONTROL", "Scope" => { "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0", "type" => "UserById" } } ], "Owner" => { "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0" } } when "public-read" { "AccessControlList" => [ { "Permission" => "FULL_CONTROL", "Scope" => { "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0", "type" => "UserById" } }, { "Permission" => "READ", "Scope" => { "type" => "AllUsers" } } ], "Owner" => { "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0" } } when "public-read-write" { "AccessControlList" => [ { "Permission" => "FULL_CONTROL", "Scope" => { "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0", "type" => "UserById" } }, { "Permission" => "READ", "Scope" => { "type" => "AllUsers" } }, { "Permission" => "WRITE", "Scope" => { "type" => "AllUsers" } } ], "Owner" => { "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0" } } when "authenticated-read" { "AccessControlList" => [ { "Permission" => "FULL_CONTROL", "Scope" => { "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0", "type" => "UserById" } }, { "Permission" => "READ", "Scope" => { "type" => "AllAuthenticatedUsers" } } ], "Owner" => { "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0" } } end end def self.data @data ||= Hash.new do |hash, key| hash[key] = { :acls => { :bucket => {}, :object => {} }, :buckets => {} } end end def self.reset @data = nil end def initialize(options = {}) @google_storage_access_key_id = options[:google_storage_access_key_id] end def data self.class.data[@google_storage_access_key_id] end def reset_data self.class.data.delete(@google_storage_access_key_id) end def signature(_params) "foo" end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/real.rb0000644000004100000410000000723713145731036022201 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real include Utils # Initialize connection to Google Storage # # ==== Notes # options parameter must include values for :google_storage_access_key_id and # :google_storage_secret_access_key in order to create a connection # # ==== Examples # google_storage = Storage.new( # :google_storage_access_key_id => your_google_storage_access_key_id, # :google_storage_secret_access_key => your_google_storage_secret_access_key # ) # # ==== Parameters # * options<~Hash> - config arguments for connection. Defaults to {}. # # ==== Returns # * Storage object with connection to google. def initialize(options = {}) @google_storage_access_key_id = options[:google_storage_access_key_id] @google_storage_secret_access_key = options[:google_storage_secret_access_key] @connection_options = options[:connection_options] || {} @hmac = Fog::HMAC.new("sha1", @google_storage_secret_access_key) @host = options[:host] || "storage.googleapis.com" @persistent = options.fetch(:persistent, true) @port = options[:port] || 443 @scheme = options[:scheme] || "https" @path_style = options[:path_style] || false end def reload @connection.reset if @connection end def signature(params) string_to_sign = <<-DATA #{params[:method]} #{params[:headers]['Content-MD5']} #{params[:headers]['Content-Type']} #{params[:headers]['Date']} DATA google_headers = {} canonical_google_headers = "" params[:headers].each do |key, value| google_headers[key] = value if key[0..6] == "x-goog-" end google_headers = google_headers.sort { |x, y| x[0] <=> y[0] } google_headers.each do |key, value| canonical_google_headers << "#{key}:#{value}\n" end string_to_sign << canonical_google_headers.to_s canonical_resource = "/" if subdomain = params.delete(:subdomain) canonical_resource << "#{CGI.escape(subdomain).downcase}/" end canonical_resource << params[:path].to_s canonical_resource << "?" (params[:query] || {}).keys.each do |key| if %w(acl cors location logging requestPayment versions versioning).include?(key) canonical_resource << "#{key}&" end end canonical_resource.chop! string_to_sign << canonical_resource.to_s signed_string = @hmac.sign(string_to_sign) Base64.encode64(signed_string).chomp! end def connection(scheme, host, port) uri = "#{scheme}://#{host}:#{port}" if @persistent unless uri == @connection_uri @connection_uri = uri reload @connection = nil end else @connection = nil end @connection ||= Fog::XML::Connection.new(uri, @persistent, @connection_options) end private def request(params, &block) params = request_params(params) scheme = params.delete(:scheme) host = params.delete(:host) port = params.delete(:port) params[:headers]["Date"] = Fog::Time.now.to_date_header params[:headers]["Authorization"] = "GOOG1 #{@google_storage_access_key_id}:#{signature(params)}" connection(scheme, host, port).request(params, &block) end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/models/0000755000004100000410000000000013145731036022203 5ustar www-datawww-datafog-google-0.5.3/lib/fog/storage/google_xml/models/directory.rb0000644000004100000410000000356013145731036024540 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Directory < Fog::Model identity :key, :aliases => %w(Name name) attribute :creation_date, :aliases => "CreationDate" def acl=(new_acl) valid_acls = ["private", "public-read", "public-read-write", "authenticated-read"] unless valid_acls.include?(new_acl) raise ArgumentError.new("acl must be one of [#{valid_acls.join(', ')}]") end @acl = new_acl end def destroy requires :key service.delete_bucket(key) true rescue Excon::Errors::NotFound false end def files @files ||= begin Fog::Storage::GoogleXML::Files.new( :directory => self, :service => service ) end end def public=(new_public) if new_public @acl = "public-read" else @acl = "private" end new_public end def public_url requires :key if service.get_bucket_acl(key).body["AccessControlList"].detect { |entry| entry["Scope"]["type"] == "AllUsers" && entry["Permission"] == "READ" } if key.to_s =~ /^(?:[a-z]|\d(?!\d{0,2}(?:\.\d{1,3}){3}$))(?:[a-z0-9]|\.(?![\.\-])|\-(?![\.])){1,61}[a-z0-9]$/ "https://#{key}.storage.googleapis.com" else "https://storage.googleapis.com/#{key}" end end end def save requires :key options = {} options["x-goog-acl"] = @acl if @acl options["LocationConstraint"] = @location if @location options["StorageClass"] = attributes[:storage_class] if attributes[:storage_class] service.put_bucket(key, options) true end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/models/files.rb0000644000004100000410000000543713145731036023643 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Files < Fog::Collection extend Fog::Deprecation deprecate :get_url, :get_https_url attribute :common_prefixes, :aliases => "CommonPrefixes" attribute :delimiter, :aliases => "Delimiter" attribute :directory attribute :is_truncated, :aliases => "IsTruncated" attribute :marker, :aliases => "Marker" attribute :max_keys, :aliases => ["MaxKeys", "max-keys"] attribute :prefix, :aliases => "Prefix" model Fog::Storage::GoogleXML::File def all(options = {}) requires :directory options = { "delimiter" => delimiter, "marker" => marker, "max-keys" => max_keys, "prefix" => prefix }.merge!(options) options = options.reject { |_key, value| value.nil? || value.to_s.empty? } merge_attributes(options) parent = directory.collection.get( directory.key, options ) if parent merge_attributes(parent.files.attributes) load(parent.files.map(&:attributes)) end end alias_method :each_file_this_page, :each def each if !block_given? self else subset = dup.all subset.each_file_this_page { |f| yield f } while subset.is_truncated subset = subset.all(:marker => subset.last.key) subset.each_file_this_page { |f| yield f } end self end end def get(key, options = {}, &block) requires :directory data = service.get_object(directory.key, key, options, &block) file_data = {} data.headers.each do |k, v| file_data[k] = v end file_data.merge!(:body => data.body, :key => key) new(file_data) rescue Excon::Errors::NotFound nil end def get_http_url(key, expires) requires :directory service.get_object_http_url(directory.key, key, expires) end def get_https_url(key, expires) requires :directory service.get_object_https_url(directory.key, key, expires) end def head(key, options = {}) requires :directory data = service.head_object(directory.key, key, options) file_data = data.headers.merge(:key => key) new(file_data) rescue Excon::Errors::NotFound nil end def new(attributes = {}) requires :directory super({ :directory => directory }.merge(attributes)) end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/models/directories.rb0000644000004100000410000000210313145731036025040 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Directories < Fog::Collection model Fog::Storage::GoogleXML::Directory def all data = service.get_service.body["Buckets"] load(data) end def get(key, options = {}) remap_attributes(options, :delimiter => "delimiter", :marker => "marker", :max_keys => "max-keys", :prefix => "prefix") data = service.get_bucket(key, options).body directory = new(:key => data["Name"]) options = {} for k, v in data if %w(CommonPrefixes Delimiter IsTruncated Marker MaxKeys Prefix).include?(k) options[k] = v end end directory.files.merge_attributes(options) directory.files.load(data["Contents"]) directory rescue Excon::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/storage/google_xml/models/file.rb0000644000004100000410000001146113145731036023452 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class File < Fog::Model identity :key, :aliases => "Key" attribute :cache_control, :aliases => "Cache-Control" attribute :content_disposition, :aliases => "Content-Disposition" attribute :content_encoding, :aliases => "Content-Encoding" attribute :content_length, :aliases => ["Content-Length", "Size"], :type => :integer attribute :content_md5, :aliases => "Content-MD5" attribute :content_type, :aliases => "Content-Type" attribute :etag, :aliases => %w(Etag ETag) attribute :expires, :aliases => "Expires" attribute :last_modified, :aliases => ["Last-Modified", "LastModified"] attribute :metadata attribute :owner, :aliases => "Owner" attribute :storage_class, :aliases => ["x-goog-storage-class", "StorageClass"] # https://cloud.google.com/storage/docs/access-control#predefined-acl VALID_ACLS = [ "authenticated-read", "bucket-owner-full-control", "bucket-owner-read", "private", "project-private", "public-read", "public-read-write" ].freeze def acl=(new_acl) unless VALID_ACLS.include?(new_acl) raise ArgumentError.new("acl must be one of [#{VALID_ACLS.join(', ')}]") end @acl = new_acl end def body attributes[:body] ||= last_modified && (file = collection.get(identity)) ? file.body : "" end def body=(new_body) attributes[:body] = new_body end attr_reader :directory def copy(target_directory_key, target_file_key, options = {}) requires :directory, :key service.copy_object(directory.key, key, target_directory_key, target_file_key, options) target_directory = service.directories.new(:key => target_directory_key) target_directory.files.get(target_file_key) end def destroy requires :directory, :key service.delete_object(directory.key, key) true rescue Excon::Errors::NotFound false end remove_method :metadata def metadata attributes.reject { |key, _value| !(key.to_s =~ /^x-goog-meta-/) } end remove_method :metadata= def metadata=(new_metadata) merge_attributes(new_metadata) end remove_method :owner= def owner=(new_owner) if new_owner attributes[:owner] = { :display_name => new_owner["DisplayName"], :id => new_owner["ID"] } end end def public=(new_public) if new_public @acl = "public-read" else @acl = "project-private" end new_public end def public_url requires :directory, :key acl = service.get_object_acl(directory.key, key).body["AccessControlList"] access_granted = acl.detect do |entry| entry["Scope"]["type"] == "AllUsers" && entry["Permission"] == "READ" end if access_granted if directory.key.to_s =~ /^(?:[a-z]|\d(?!\d{0,2}(?:\.\d{1,3}){3}$))(?:[a-z0-9]|\.(?![\.\-])|\-(?![\.])){1,61}[a-z0-9]$/ "https://#{directory.key}.storage.googleapis.com/#{key}" else "https://storage.googleapis.com/#{directory.key}/#{key}" end end end def save(options = {}) requires :body, :directory, :key if options != {} Fog::Logger.deprecation("options param is deprecated, use acl= instead [light_black](#{caller.first})[/]") end options["x-goog-acl"] ||= @acl if @acl options["Cache-Control"] = cache_control if cache_control options["Content-Disposition"] = content_disposition if content_disposition options["Content-Encoding"] = content_encoding if content_encoding options["Content-MD5"] = content_md5 if content_md5 options["Content-Type"] = content_type if content_type options["Expires"] = expires if expires options.merge!(metadata) data = service.put_object(directory.key, key, body, options) merge_attributes(data.headers.reject { |key, _value| ["Content-Length", "Content-Type"].include?(key) }) self.content_length = Fog::Storage.get_body_size(body) self.content_type ||= Fog::Storage.get_content_type(body) true end def url(expires) requires :key collection.get_http_url(key, expires) end private attr_writer :directory end end end end fog-google-0.5.3/lib/fog/storage/google_json/0000755000004100000410000000000013145731036021071 5ustar www-datawww-datafog-google-0.5.3/lib/fog/storage/google_json/utils.rb0000644000004100000410000000177713145731036022572 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON module Utils def http_url(params, expires) "http://" << host_path_query(params, expires) end def https_url(params, expires) "https://" << host_path_query(params, expires) end def url(params, expires) Fog::Logger.deprecation("Fog::Storage::Google => #url is deprecated, use #https_url instead [light_black](#{caller.first})[/]") https_url(params, expires) end private def host_path_query(params, expires) params[:headers]["Date"] = expires.to_i params[:path] = CGI.escape(params[:path]).gsub("%2F", "/") query = [params[:query]].compact query << "GoogleAccessId=#{@client.authorization.issuer}" query << "Signature=#{CGI.escape(signature(params))}" query << "Expires=#{params[:headers]['Date']}" "#{params[:host]}/#{params[:path]}?#{query.join('&')}" end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/0000755000004100000410000000000013145731036022744 5ustar www-datawww-datafog-google-0.5.3/lib/fog/storage/google_json/requests/list_objects.rb0000644000004100000410000000326513145731036025763 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Lists objects in a bucket matching some criteria. # # @param bucket [String] name of bucket to list # @param options [Hash] optional hash of options # @option options [String] :delimiter Delimiter to collapse objects # under to emulate a directory-like mode # @option options [Integer] :max_results Maximum number of results to # retrieve # @option options [String] :page_token Token to select a particular page # of results # @option options [String] :prefix String that an object must begin with # in order to be returned # @option options ["full", "noAcl"] :projection Set of properties to # return (defaults to "noAcl") # @option options [Boolean] :versions If true, lists all versions of an # object as distinct results (defaults to False) def list_objects(bucket, options = {}) api_method = @storage_json.objects.list parameters = { "bucket" => bucket } # Optional parameters { :delimiter => "delimiter", :max_results => "maxResults", :page_token => "pageToken", :prefix => "prefix", :projection => "projection", :versions => "versions" }.each do |k, v| parameters[v] = options[k] unless options[k].nil? end request(api_method, parameters) end end class Mock def list_objects(_bucket, _options = {}) Fog::Mock.not_implemented end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/get_object_url.rb0000644000004100000410000000152513145731036026263 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Get an expiring object url from GCS # Deprecated, redirects to get_object_https_url.rb def get_object_url(bucket_name, object_name, expires) Fog::Logger.deprecation("Fog::Storage::Google => ##{get_object_url} is deprecated, use ##{get_object_https_url} instead[/] [light_black](#{caller.first})") get_object_https_url(bucket_name, object_name, expires) end end class Mock # :nodoc:all def get_object_url(bucket_name, object_name, expires) Fog::Logger.deprecation("Fog::Storage::Google => ##{get_object_url} is deprecated, use ##{get_object_https_url} instead[/] [light_black](#{caller.first})") get_object_https_url(bucket_name, object_name, expires) end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/put_object.rb0000644000004100000410000001144513145731036025434 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Create an object in an Google Storage bucket # https://cloud.google.com/storage/docs/json_api/v1/objects/insert # # ==== Parameters # * bucket_name<~String> - Name of bucket to create object in # * object_name<~String> - Name of object to create # * data<~File> - File or String to create object from # * options<~Hash>: # * 'Cache-Control'<~String> - Caching behaviour # * 'Content-Disposition'<~String> - Presentational information for the object # * 'Content-Encoding'<~String> - Encoding of object data # * 'Content-Length'<~String> - Size of object in bytes (defaults to object.read.length) # * 'Content-MD5'<~String> - Base64 encoded 128-bit MD5 digest of message (defaults to Base64 encoded MD5 of object.read) # * 'Content-Type'<~String> - Standard MIME type describing contents (defaults to MIME::Types.of.first) # * 'x-goog-acl'<~String> - Permissions, must be in ['private', 'public-read', 'public-read-write', 'authenticated-read'] # * "x-goog-meta-#{name}" - Headers to be returned with object, note total size of request without body must be less than 8 KB. # # ==== Returns # * response<~Excon::Response>: # * headers<~Hash>: # * 'ETag'<~String> - etag of new object def put_object(bucket_name, object_name, data, options = {}) if options["contentType"] mime_type = options["contentType"] if data.is_a? String data = StringIO.new(data) end elsif data.is_a? String data = StringIO.new(data) mime_type = "text/plain" elsif data.is_a? ::File mime_type = Fog::Storage.parse_data(data)[:headers]["Content-Type"] end media = ::Google::APIClient::UploadIO.new(data, mime_type, object_name) api_method = @storage_json.objects.insert parameters = { "uploadType" => "multipart", "bucket" => bucket_name, "name" => object_name } body_object = { :contentType => mime_type, :contentEncoding => options["contentEncoding"] } body_object.merge! options acl = [] case options["predefinedAcl"] when "publicRead" acl.push({ "entity" => "allUsers", "role" => "READER" }) when "publicReadWrite" acl.push({ "entity" => "allUsers", "role" => "OWNER" }) when "authenticatedRead" acl.push({ "entity" => "allAuthenticatedUsers", "role" => "READER" }) end unless acl.empty? body_object[:acl] = acl end request(api_method, parameters, body_object = body_object, media = media) end end class Mock def put_object(bucket_name, object_name, data, options = {}) acl = options["x-goog-acl"] || "private" if !%w(private publicRead publicReadWrite authenticatedRead).include?(acl) raise Excon::Errors::BadRequest.new("invalid x-goog-acl") else self.data[:acls][:object][bucket_name] ||= {} self.data[:acls][:object][bucket_name][object_name] = self.class.acls(acl) end data = Fog::Storage.parse_data(data) data[:body] = data[:body].read unless data[:body].is_a?(String) response = Excon::Response.new if (bucket = self.data[:buckets][bucket_name]) response.status = 200 object = { :body => data[:body], "Content-Type" => options["Content-Type"] || data[:headers]["Content-Type"], "ETag" => Fog::Google::Mock.etag, "Key" => object_name, "Last-Modified" => Fog::Time.now.to_date_header, "Content-Length" => options["Content-Length"] || data[:headers]["Content-Length"] } for key, value in options case key when "Cache-Control", "Content-Disposition", "Content-Encoding", "Content-MD5", "Expires", /^x-goog-meta-/ object[key] = value end end bucket[:objects][object_name] = object response.headers = { "Content-Length" => object["Content-Length"], "Content-Type" => object["Content-Type"], "ETag" => object["ETag"], "Last-Modified" => object["Last-Modified"] } else response.status = 404 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/head_object.rb0000644000004100000410000000440413145731036025522 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Get headers for an object from Google Storage # https://cloud.google.com/storage/docs/json_api/v1/objects/get # # ==== Parameters # * bucket_name<~String> - Name of bucket to read from # * object_name<~String> - Name of object to read # * options<~Hash>: # * 'If-Match'<~String> - Returns object only if its etag matches this value, otherwise returns 412 (Precondition Failed). # * 'If-Modified-Since'<~Time> - Returns object only if it has been modified since this time, otherwise returns 304 (Not Modified). # * 'If-None-Match'<~String> - Returns object only if its etag differs from this value, otherwise returns 304 (Not Modified) # * 'If-Unmodified-Since'<~Time> - Returns object only if it has not been modified since this time, otherwise returns 412 (Precodition Failed). # * 'Range'<~String> - Range of object to download # * 'versionId'<~String> - specify a particular version to retrieve # # ==== Returns # * response<~Excon::Response>: # * body<~String> - Contents of object # * headers<~Hash>: # * 'Content-Length'<~String> - Size of object contents # * 'Content-Type'<~String> - MIME type of object # * 'ETag'<~String> - Etag of object # * 'Last-Modified'<~String> - Last modified timestamp for object def head_object(bucket_name, object_name, _options = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name api_method = @storage_json.objects.get parameters = { "bucket" => bucket_name, "object" => object_name, "projection" => "full" } object = request(api_method, parameters) object.headers = object.body object.body = nil object end end class Mock def head_object(bucket_name, object_name, options = {}) response = get_object(bucket_name, object_name, options) response.body = nil response end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/get_object_acl.rb0000644000004100000410000000427213145731036026222 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Get access control list for an Google Storage object # https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/get # # ==== Parameters # * bucket_name<~String> - name of bucket containing object # * object_name<~String> - name of object to get access control list for # * options<~Hash>: # * 'versionId'<~String> - specify a particular version to retrieve # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'AccessControlPolicy'<~Hash> # * 'Owner'<~Hash>: # * 'DisplayName'<~String> - Display name of object owner # * 'ID'<~String> - Id of object owner # * 'AccessControlList'<~Array>: # * 'Grant'<~Hash>: # * 'Grantee'<~Hash>: # * 'DisplayName'<~String> - Display name of grantee # * 'ID'<~String> - Id of grantee # or # * 'URI'<~String> - URI of group to grant access for # * 'Permission'<~String> - Permission, in [FULL_CONTROL, WRITE, WRITE_ACP, READ, READ_ACP] # def get_object_acl(bucket_name, object_name, _options = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name api_method = @storage_json.object_access_controls.list parameters = { "bucket" => bucket_name, "object" => object_name } request(api_method, parameters) end end class Mock def get_object_acl(bucket_name, object_name) response = Excon::Response.new if acl = data[:acls][:object][bucket_name] && data[:acls][:object][bucket_name][object_name] response.status = 200 response.body = acl else response.status = 404 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/get_bucket_acl.rb0000644000004100000410000000347513145731036026235 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Get access control list for an Google Storage bucket # https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/list # # ==== Parameters # * bucket_name<~String> - name of bucket to get access control list for # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'AccessControlPolicy'<~Hash> # * 'Owner'<~Hash>: # * 'DisplayName'<~String> - Display name of object owner # * 'ID'<~String> - Id of object owner # * 'AccessControlList'<~Array>: # * 'Grant'<~Hash>: # * 'Grantee'<~Hash>: # * 'DisplayName'<~String> - Display name of grantee # * 'ID'<~String> - Id of grantee # or # * 'URI'<~String> - URI of group to grant access for # * 'Permission'<~String> - Permission, in [FULL_CONTROL, WRITE, WRITE_ACP, READ, READ_ACP] # def get_bucket_acl(bucket_name) raise ArgumentError.new("bucket_name is required") unless bucket_name api_method = @storage_json.bucket_access_controls.list parameters = { "bucket" => bucket_name } request(api_method, parameters) end end class Mock def get_bucket_acl(bucket_name) response = Excon::Response.new if acl = data[:acls][:bucket][bucket_name] response.status = 200 response.body = acl else response.status = 404 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/put_object_url.rb0000644000004100000410000000351513145731036026315 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Get an expiring object url from Google Storage for putting an object # # ==== Parameters # * bucket_name<~String> - Name of bucket containing object # * object_name<~String> - Name of object to get expiring url for # * expires<~Time> - An expiry time for this url # * If you want a file to be public you should to add { 'x-goog-acl' => 'public-read' } to headers # And then call for example: curl -H "x-goog-acl:public-read" "signed url" # # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object # # ==== See Also # https://cloud.google.com/storage/docs/access-control#Signed-URLs # def put_object_url(bucket_name, object_name, expires, headers = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name https_url({ :headers => headers, :host => @host, :method => "PUT", :path => "#{bucket_name}/#{object_name}" }, expires) end end class Mock def put_object_url(bucket_name, object_name, expires, headers = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name https_url({ :headers => headers, :host => @host, :method => "PUT", :path => "#{bucket_name}/#{object_name}" }, expires) end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/get_object_http_url.rb0000644000004100000410000000232113145731036027315 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON module GetObjectHttpUrl def get_object_http_url(bucket_name, object_name, expires) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name http_url({ :headers => {}, :host => @host, :method => "GET", :path => "#{bucket_name}/#{object_name}" }, expires) end end class Real # Get an expiring object http url from GCS # # ==== Parameters # * bucket_name<~String> - Name of bucket containing object # * object_name<~String> - Name of object to get expiring url for # * expires<~Time> - An expiry time for this url # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object # # ==== See Also # https://cloud.google.com/storage/docs/access-control#Signed-URLs include GetObjectHttpUrl end class Mock # :nodoc:all include GetObjectHttpUrl end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/delete_bucket.rb0000644000004100000410000000233613145731036026074 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Delete an Google Storage bucket # https://cloud.google.com/storage/docs/json_api/v1/buckets/delete # # ==== Parameters # * bucket_name<~String> - name of bucket to delete # # ==== Returns # * response<~Excon::Response>: # * status<~Integer> - 204 def delete_bucket(bucket_name) api_method = @storage_json.buckets.delete parameters = { "bucket" => bucket_name } request(api_method, parameters) end end class Mock def delete_bucket(bucket_name) response = Excon::Response.new if data[:buckets][bucket_name].nil? response.status = 404 raise(Excon::Errors.status_error({ :expects => 204 }, response)) elsif data[:buckets][bucket_name] && !data[:buckets][bucket_name][:objects].empty? response.status = 409 raise(Excon::Errors.status_error({ :expects => 204 }, response)) else data[:buckets].delete(bucket_name) response.status = 204 end response end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/copy_object.rb0000644000004100000410000000556113145731036025600 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Copy an object from one Google Storage bucket to another # https://cloud.google.com/storage/docs/json_api/v1/objects/copy # # ==== Parameters # * source_bucket_name<~String> - Name of source bucket # * source_object_name<~String> - Name of source object # * target_bucket_name<~String> - Name of bucket to create copy in # * target_object_name<~String> - Name for new copy of object # * options<~Hash>: # * 'x-goog-metadata-directive'<~String> - Specifies whether to copy metadata from source or replace with data in request. Must be in ['COPY', 'REPLACE'] # * 'x-goog-copy_source-if-match'<~String> - Copies object if its etag matches this value # * 'x-goog-copy_source-if-modified_since'<~Time> - Copies object it it has been modified since this time # * 'x-goog-copy_source-if-none-match'<~String> - Copies object if its etag does not match this value # * 'x-goog-copy_source-if-unmodified-since'<~Time> - Copies object it it has not been modified since this time # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'ETag'<~String> - etag of new object # * 'LastModified'<~Time> - date object was last modified # def copy_object(source_bucket_name, source_object_name, target_bucket_name, target_object_name, options = {}) api_method = @storage_json.objects.copy parameters = { "sourceBucket" => source_bucket_name, "sourceObject" => source_object_name, "destinationBucket" => target_bucket_name, "destinationObject" => target_object_name } parameters.merge! options request(api_method, parameters) end end class Mock def copy_object(source_bucket_name, source_object_name, target_bucket_name, target_object_name, _options = {}) response = Excon::Response.new source_bucket = data[:buckets][source_bucket_name] source_object = source_bucket && source_bucket[:objects][source_object_name] target_bucket = data[:buckets][target_bucket_name] if source_object && target_bucket response.status = 200 target_object = source_object.dup target_object.merge!("Name" => target_object_name) target_bucket[:objects][target_object_name] = target_object response.body = { "ETag" => target_object["ETag"], "LastModified" => Time.parse(target_object["Last-Modified"]) } else response.status = 404 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/delete_object.rb0000644000004100000410000000257013145731036026065 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Delete an object from Google Storage # https://cloud.google.com/storage/docs/json_api/v1/objects/delete # # ==== Parameters # * bucket_name<~String> - Name of bucket containing object to delete # * object_name<~String> - Name of object to delete # # ==== Returns # * response<~Excon::Response>: # * status<~Integer> - 204 def delete_object(bucket_name, object_name) api_method = @storage_json.objects.delete parameters = { "bucket" => bucket_name, "object" => object_name } request(api_method, parameters) end end class Mock def delete_object(bucket_name, object_name) response = Excon::Response.new if bucket = data[:buckets][bucket_name] if object = bucket[:objects][object_name] response.status = 204 bucket[:objects].delete(object_name) else response.status = 404 raise(Excon::Errors.status_error({ :expects => 204 }, response)) end else response.status = 404 raise(Excon::Errors.status_error({ :expects => 204 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/get_object_https_url.rb0000644000004100000410000000235013145731036027502 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON module GetObjectHttpsUrl def get_object_https_url(bucket_name, object_name, expires) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name https_url({ :headers => {}, :host => @host, :method => "GET", :path => "#{bucket_name}/#{object_name}" }, expires) end end class Real # Get an expiring object https url from Google Storage # # ==== Parameters # * bucket_name<~String> - Name of bucket containing object # * object_name<~String> - Name of object to get expiring url for # * expires<~Time> - An expiry time for this url # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object # # ==== See Also # https://cloud.google.com/storage/docs/access-control#Signed-URLs include GetObjectHttpsUrl end class Mock # :nodoc:all include GetObjectHttpsUrl end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/put_bucket_acl.rb0000644000004100000410000000200513145731036026252 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Mock def put_bucket_acl(_bucket_name, _acl) Fog::Mock.not_implemented end end class Real # Change access control list for an Google Storage bucket # https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/insert # # ==== Parameters # * bucket_name<~String> - name of bucket to create # * acl<~Hash> - ACL hash to add to bucket, see GCS documentation above # * entity # * role def put_bucket_acl(bucket_name, acl) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("acl is required") unless acl api_method = @storage_json.bucket_access_controls.insert parameters = { "bucket" => bucket_name } body_object = acl request(api_method, parameters, body_object = body_object) end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/get_bucket.rb0000644000004100000410000000665313145731036025417 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # List information about objects in an Google Storage bucket # # ==== Parameters # * bucket_name<~String> - name of bucket to list object keys from # * options<~Hash> - config arguments for list. Defaults to {}. # * 'ifMetagenerationMatch'<~Long> - Makes the return of the bucket metadata # conditional on whether the bucket's current metageneration matches the # given value. # * 'ifMetagenerationNotMatch'<~Long> - Makes the return of the bucket # metadata conditional on whether the bucket's current metageneration does # not match the given value. # * 'projection'<~String> - Set of properties to return. Defaults to 'noAcl', # also accepts 'full'. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # See Google documentation on Bucket resource: # https://cloud.google.com/storage/docs/json_api/v1/buckets#resource # def get_bucket(bucket_name, options = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name api_method = @storage_json.buckets.get parameters = { "bucket" => bucket_name } parameters.merge! options request(api_method, parameters) end end class Mock def get_bucket(bucket_name, options = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name response = Excon::Response.new name = /(\w+\.?)*/.match(bucket_name) if bucket_name == name.to_s if bucket = data[:buckets][bucket_name] contents = bucket[:objects].values.sort { |x, y| x["Key"] <=> y["Key"] }.reject do |object| (options["prefix"] && object["Key"][0...options["prefix"].length] != options["prefix"]) || (options["marker"] && object["Key"] <= options["marker"]) end.map do |object| data = object.reject { |key, _value| !%w(ETag Key).include?(key) } data.merge!("LastModified" => Time.parse(object["Last-Modified"]), "Owner" => bucket["Owner"], "Size" => object["Content-Length"].to_i) data end max_keys = options["max-keys"] || 1000 size = [max_keys, 1000].min truncated_contents = contents[0...size] response.status = 200 response.body = { "CommonPrefixes" => [], "Contents" => truncated_contents, "Marker" => options["marker"], "Name" => bucket["Name"], "Prefix" => options["prefix"] } if options["max-keys"] && options["max-keys"] < response.body["Contents"].length response.body["Contents"] = response.body["Contents"][0...options["max-keys"]] end else response.status = 404 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end else response.status = 400 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/get_object.rb0000644000004100000410000001040713145731036025400 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Get an object from Google Storage # https://cloud.google.com/storage/docs/json_api/v1/objects/get # # ==== Parameters # * bucket_name<~String> - Name of bucket to read from # * object_name<~String> - Name of object to read # * options<~Hash>: # * 'If-Match'<~String> - Returns object only if its etag matches this value, otherwise returns 412 (Precondition Failed). # * 'If-Modified-Since'<~Time> - Returns object only if it has been modified since this time, otherwise returns 304 (Not Modified). # * 'If-None-Match'<~String> - Returns object only if its etag differs from this value, otherwise returns 304 (Not Modified) # * 'If-Unmodified-Since'<~Time> - Returns object only if it has not been modified since this time, otherwise returns 412 (Precodition Failed). # * 'Range'<~String> - Range of object to download # * 'versionId'<~String> - specify a particular version to retrieve # # ==== Returns # * response<~Excon::Response>: # * body<~String> - Contents of object # * headers<~Hash>: # * 'Content-Length'<~String> - Size of object contents # * 'Content-Type'<~String> - MIME type of object # * 'ETag'<~String> - Etag of object # * 'Last-Modified'<~String> - Last modified timestamp for object # def get_object(bucket_name, object_name, _options = {}, &_block) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name api_method = @storage_json.objects.get parameters = { "bucket" => bucket_name, "object" => object_name, "projection" => "full" } object = request(api_method, parameters) # Get the body of the object (can't use request for this) parameters["alt"] = "media" client_parms = { :api_method => api_method, :parameters => parameters } result = @client.execute(client_parms) object.headers = object.body object.body = result.body.nil? || result.body.empty? ? nil : result.body object end end class Mock def get_object(bucket_name, object_name, options = {}, &block) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name response = Excon::Response.new if (bucket = data[:buckets][bucket_name]) && (object = bucket[:objects][object_name]) if options["If-Match"] && options["If-Match"] != object["ETag"] response.status = 412 elsif options["If-Modified-Since"] && options["If-Modified-Since"] >= Time.parse(object["Last-Modified"]) response.status = 304 elsif options["If-None-Match"] && options["If-None-Match"] == object["ETag"] response.status = 304 elsif options["If-Unmodified-Since"] && options["If-Unmodified-Since"] < Time.parse(object["Last-Modified"]) response.status = 412 else response.status = 200 for key, value in object case key when "Cache-Control", "Content-Disposition", "Content-Encoding", "Content-Length", "Content-MD5", "Content-Type", "ETag", "Expires", "Last-Modified", /^x-goog-meta-/ response.headers[key] = value end end unless block_given? response.body = object[:body] else data = StringIO.new(object[:body]) remaining = data.length while remaining > 0 chunk = data.read([remaining, Excon::CHUNK_SIZE].min) block.call(chunk) remaining -= Excon::CHUNK_SIZE end end end else response.status = 404 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/put_bucket.rb0000644000004100000410000000535213145731036025443 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Create a Google Storage bucket # # ==== Parameters # * bucket_name<~String> - name of bucket to create # * options<~Hash> - config arguments for bucket. Defaults to {}. # * 'LocationConstraint'<~Symbol> - sets the location for the bucket # * 'predefinedAcl'<~String> - Apply a predefined set of access controls to this bucket. # * 'predefinedDefaultObjectAcl'<~String> - Apply a predefined set of default object access controls to this bucket. # * body_options<~Hash> - body arguments for bucket creation. # See https://cloud.google.com/storage/docs/json_api/v1/buckets/insert#request-body # # ==== Returns # * response<~Excon::Response>: # * status<~Integer> - 200 # # ==== See also # https://cloud.google.com/storage/docs/json_api/v1/buckets/insert def put_bucket(bucket_name, options = {}, body_options = {}) location = options["LocationConstraint"] if options["LocationConstraint"] api_method = @storage_json.buckets.insert parameters = { "project" => @project, "projection" => "full" } parameters.merge! options body_object = { "name" => bucket_name, "location" => location } body_object.merge! body_options request(api_method, parameters, body_object = body_object) end end class Mock def put_bucket(bucket_name, options = {}, _body_options = {}) acl = options["x-goog-acl"] || "private" if !%w(private publicRead publicReadWrite authenticatedRead).include?(acl) raise Excon::Errors::BadRequest.new("invalid x-goog-acl") else data[:acls][:bucket][bucket_name] = self.class.acls(options[acl]) end response = Excon::Response.new response.status = 200 bucket = { :objects => {}, "Name" => bucket_name, "CreationDate" => Time.now, "Owner" => { "DisplayName" => "owner", "ID" => "some_id" }, "Payer" => "BucketOwner" } if options["LocationConstraint"] bucket["LocationConstraint"] = options["LocationConstraint"] else bucket["LocationConstraint"] = "" end if data[:buckets][bucket_name].nil? data[:buckets][bucket_name] = bucket else response.status = 409 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/list_buckets.rb0000644000004100000410000000157313145731036025772 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Retrieves a list of buckets for a given project. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash> - Hash of bucket items # * 'kind'<~String> - The kind of item this is (storage#buckets) # * 'items'<~Array> - The array of items. # # ==== See Also # https://cloud.google.com/storage/docs/json_api/v1/buckets/list # TODO: check if very large lists require working with nextPageToken def list_buckets api_method = @storage_json.buckets.list parameters = { "project" => @project } request(api_method, parameters) end end class Mock def list_buckets Fog::Mock.not_implemented end end end end end fog-google-0.5.3/lib/fog/storage/google_json/requests/put_object_acl.rb0000644000004100000410000000211713145731036026247 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Change access control list for an Google Storage object # https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert # # ==== Parameters # * bucket_name<~String> - name of bucket object is in # * object_name<~String> - name of object to add ACL to # * acl<~Hash> - ACL hash to add to bucket, see GCS documentation above # * entity # * role def put_object_acl(bucket_name, object_name, acl) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name raise ArgumentError.new("acl is required") unless acl api_method = @storage_json.object_access_controls.insert parameters = { "bucket" => bucket_name, "object" => object_name } body_object = acl request(api_method, parameters, body_object = body_object) end end end end end fog-google-0.5.3/lib/fog/storage/google_json/mock.rb0000644000004100000410000000057313145731036022354 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Mock include Utils include Fog::Google::Shared def initialize(options = {}) shared_initialize(options[:google_project], GOOGLE_STORAGE_JSON_API_VERSION, GOOGLE_STORAGE_JSON_BASE_URL) end def signature(_params) "foo" end end end end end fog-google-0.5.3/lib/fog/storage/google_json/real.rb0000644000004100000410000000407313145731036022345 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real include Utils include Fog::Google::Shared attr_accessor :client attr_reader :storage_json def initialize(options = {}) shared_initialize(options[:google_project], GOOGLE_STORAGE_JSON_API_VERSION, GOOGLE_STORAGE_JSON_BASE_URL) options[:google_api_scope_url] = GOOGLE_STORAGE_JSON_API_SCOPE_URLS.join(" ") @host = options[:host] || "storage.googleapis.com" @client = initialize_google_client(options) @storage_json = @client.discovered_api("storage", api_version) end def signature(params) string_to_sign = <<-DATA #{params[:method]} #{params[:headers]['Content-MD5']} #{params[:headers]['Content-Type']} #{params[:headers]['Date']} DATA google_headers = {} canonical_google_headers = "" params[:headers].each do |key, value| google_headers[key] = value if key[0..6] == "x-goog-" end google_headers = google_headers.sort { |x, y| x[0] <=> y[0] } google_headers.each do |key, value| canonical_google_headers << "#{key}:#{value}\n" end string_to_sign << canonical_google_headers.to_s canonical_resource = "/" if subdomain = params.delete(:subdomain) canonical_resource << "#{CGI.escape(subdomain).downcase}/" end canonical_resource << params[:path].to_s canonical_resource << "?" for key in (params[:query] || {}).keys if %w(acl cors location logging requestPayment versions versioning).include?(key) canonical_resource << "#{key}&" end end canonical_resource.chop! string_to_sign << canonical_resource.to_s key = OpenSSL::PKey::RSA.new(@client.authorization.signing_key) digest = OpenSSL::Digest::SHA256.new signed_string = key.sign(digest, string_to_sign) Base64.encode64(signed_string).chomp! end end end end end fog-google-0.5.3/lib/fog/storage/google_json/models/0000755000004100000410000000000013145731036022354 5ustar www-datawww-datafog-google-0.5.3/lib/fog/storage/google_json/models/directory.rb0000644000004100000410000000346313145731036024713 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Directory < Fog::Model identity :key, :aliases => %w(Name name) def acl=(new_acl) valid_acls = %w(private projectPrivate publicRead publicReadWrite authenticatedRead) unless valid_acls.include?(new_acl) raise ArgumentError.new("acl must be one of [#{valid_acls.join(', ')}]") end @acl = new_acl end def destroy requires :key service.delete_bucket(key) true rescue Fog::Errors::NotFound false end def files @files ||= begin Fog::Storage::GoogleJSON::Files.new( :directory => self, :service => service ) end end def public=(new_public) if new_public @acl = "publicRead" else @acl = "private" end new_public end def public_url requires :key acl = service.get_bucket_acl(key).body if acl["items"].detect { |entry| entry["entity"] == "allUsers" && entry["role"] == "READER" } if key.to_s =~ /^(?:[a-z]|\d(?!\d{0,2}(?:\.\d{1,3}){3}$))(?:[a-z0-9]|\.(?![\.\-])|\-(?![\.])){1,61}[a-z0-9]$/ "https://#{key}.storage.googleapis.com" else "https://storage.googleapis.com/#{key}" end end end def save requires :key options = {} options["predefinedAcl"] = @acl if @acl options["LocationConstraint"] = @location if @location options["StorageClass"] = attributes[:storage_class] if attributes[:storage_class] service.put_bucket(key, options) true end end end end end fog-google-0.5.3/lib/fog/storage/google_json/models/files.rb0000644000004100000410000000370713145731036024012 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Files < Fog::Collection extend Fog::Deprecation deprecate :get_url, :get_https_url attribute :common_prefixes, :aliases => "CommonPrefixes" attribute :delimiter, :aliases => "Delimiter" attribute :directory attribute :page_token, :aliases => %w(pageToken page_token) attribute :max_results, :aliases => ["MaxKeys", "max-keys"] attribute :prefix, :aliases => "Prefix" model Fog::Storage::GoogleJSON::File def all(options = {}) requires :directory load(service.list_objects(directory.key, options)[:body]["items"]) end alias_method :each_file_this_page, :each def each if !block_given? self else subset = dup.all subset.each_file_this_page { |f| yield f } self end end def get(key, options = {}, &block) requires :directory data = service.get_object(directory.key, key, options, &block) file_data = {} data.headers.each do |k, v| file_data[k] = v end file_data.merge!(:body => data.body, :key => key) new(file_data) rescue Fog::Errors::NotFound nil end def get_https_url(key, expires) requires :directory service.get_object_https_url(directory.key, key, expires) end def head(key, options = {}) requires :directory data = service.head_object(directory.key, key, options) file_data = data.headers.merge(:key => key) new(file_data) rescue Fog::Errors::NotFound nil end def new(attributes = {}) requires :directory super({ :directory => directory }.merge(attributes)) end end end end end fog-google-0.5.3/lib/fog/storage/google_json/models/directories.rb0000644000004100000410000000137413145731036025222 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Directories < Fog::Collection model Fog::Storage::GoogleJSON::Directory def all data = service.list_buckets.body["items"] || [] load(data) end def get(key, options = {}) remap_attributes(options, :delimiter => "delimiter", :marker => "marker", :max_keys => "max-keys", :prefix => "prefix") data = service.get_bucket(key, options).body new(:key => data["name"]) rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/storage/google_json/models/file.rb0000644000004100000410000001270113145731036023621 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class File < Fog::Model identity :key, :aliases => %w{Key name} attribute :acl attribute :predefined_acl attribute :cache_control, :aliases => "cacheControl" attribute :content_disposition, :aliases => "contentDisposition" attribute :content_encoding, :aliases => "contentEncoding" attribute :content_length, :aliases => "size", :type => :integer attribute :content_md5, :aliases => "md5Hash" attribute :content_type, :aliases => "contentType" attribute :crc32c attribute :etag, :aliases => "etag" attribute :time_created, :aliases => "timeCreated" attribute :last_modified, :aliases => "updated" attribute :generation attribute :metageneration attribute :metadata attribute :self_link, :aliases => "selfLink" attribute :media_link, :aliases => "mediaLink" attribute :owner attribute :storage_class, :aliases => "storageClass" @valid_predefined_acls = %w(private projectPrivate bucketOwnerFullControl bucketOwnerRead authenticatedRead publicRead) def predefined_acl=(new_acl) unless @valid_predefined_acls.include?(new_acl) raise ArgumentError.new("acl must be one of [#{@valid_predefined_acls.join(', ')}]") end @predefined_acl = new_acl end # TODO: Implement object ACLs # def acl=(new_acl) # valid_acls = ["private", "projectPrivate", "bucketOwnerFullControl", "bucketOwnerRead", "authenticatedRead", "publicRead"] # unless valid_acls.include?(new_acl) # raise ArgumentError.new("acl must be one of [#{valid_acls.join(', ')}]") # end # @acl = new_acl # end def body attributes[:body] ||= last_modified && (file = collection.get(identity)) ? file.body : "" end def body=(new_body) attributes[:body] = new_body end attr_reader :directory def copy(target_directory_key, target_file_key, options = {}) requires :directory, :key service.copy_object(directory.key, key, target_directory_key, target_file_key, options) target_directory = service.directories.new(:key => target_directory_key) target_directory.files.get(target_file_key) end def destroy requires :directory, :key service.delete_object(directory.key, key) true rescue Fog::Errors::NotFound false end remove_method :metadata= def metadata=(new_metadata) if attributes[:metadata].nil? attributes[:metadata] = {} end attributes[:metadata].merge!(new_metadata) end # TODO: Not functional remove_method :owner= def owner=(new_owner) if new_owner attributes[:owner] = { :entity => new_owner["entity"], :entityId => new_owner["entityId"] } end end def public=(new_public) if new_public @predefined_acl = "publicRead" else @predefined_acl = "private" end new_public end def public_url requires :directory, :key acl = service.get_object_acl(directory.key, key).body access_granted = acl["items"].detect { |entry| entry["entity"] == "allUsers" && entry["role"] == "READER" } if access_granted if directory.key.to_s =~ /^(?:[a-z]|\d(?!\d{0,2}(?:\.\d{1,3}){3}$))(?:[a-z0-9]|\.(?![\.\-])|\-(?![\.])){1,61}[a-z0-9]$/ "https://#{directory.key}.storage.googleapis.com/#{key}" else "https://storage.googleapis.com/#{directory.key}/#{key}" end end end def save(options = {}) requires :body, :directory, :key if options != {} Fog::Logger.deprecation("options param is deprecated, use acl= instead [light_black](#{caller.first})[/]") end options["contentType"] = content_type if content_type options["predefinedAcl"] ||= @predefined_acl if @predefined_acl # predefinedAcl may need to be in parameters options["acl"] ||= @acl if @acl # Not sure if you can provide both acl and predefinedAcl options["cacheControl"] = cache_control if cache_control options["contentDisposition"] = content_disposition if content_disposition options["contentEncoding"] = content_encoding if content_encoding # TODO: Should these hashes be recomputed on changes to file contents? # options["md5Hash"] = content_md5 if content_md5 # options["crc32c"] = crc32c if crc32c options["metadata"] = metadata data = service.put_object(directory.key, key, body, options) merge_attributes(data.headers.reject { |key, _value| %w(contentLength contentType).include?(key) }) self.content_length = Fog::Storage.get_body_size(body) self.content_type ||= Fog::Storage.get_content_type(body) true end # params[:expires] : Eg: Time.now to integer value. def url(expires) requires :key collection.get_https_url(key, expires) end private attr_writer :directory end end end end fog-google-0.5.3/lib/fog/google.rb0000644000004100000410000000332613145731036016725 0ustar www-datawww-datarequire "fog/core" require "fog/json" require "fog/xml" require "fog/google/version" module Fog module Compute autoload :Google, File.expand_path("../compute/google", __FILE__) end module DNS autoload :Google, File.expand_path("../dns/google", __FILE__) end module Google autoload :Mock, File.expand_path("../google/mock", __FILE__) autoload :Monitoring, File.expand_path("../google/monitoring", __FILE__) autoload :Pubsub, File.expand_path("../google/pubsub", __FILE__) autoload :Shared, File.expand_path("../google/shared", __FILE__) autoload :SQL, File.expand_path("../google/sql", __FILE__) extend Fog::Provider service(:compute, "Compute") service(:dns, "DNS") service(:monitoring, "Monitoring") service(:pubsub, "Pubsub") service(:storage, "Storage") service(:sql, "SQL") # CGI.escape, but without special treatment on spaces def self.escape(str, extra_exclude_chars = "") # '-' is a special character inside a regex class so it must be first or last. # Add extra excludes before the final '-' so it always remains trailing, otherwise # an unwanted range is created by mistake. str.gsub(/([^a-zA-Z0-9_.#{extra_exclude_chars}-]+)/) do "%" + Regexp.last_match(1).unpack("H2" * Regexp.last_match(1).bytesize).join("%").upcase end end end module Parsers module Storage autoload :Google, File.expand_path("../parsers/storage/google", __FILE__) end end module Storage autoload :Google, File.expand_path("../storage/google", __FILE__) autoload :GoogleJSON, File.expand_path("../storage/google_json", __FILE__) autoload :GoogleXML, File.expand_path("../storage/google_xml", __FILE__) end end fog-google-0.5.3/lib/fog/dns/0000755000004100000410000000000013145731036015704 5ustar www-datawww-datafog-google-0.5.3/lib/fog/dns/google.rb0000644000004100000410000000266013145731036017511 0ustar www-datawww-datamodule Fog module DNS class Google < Fog::Service autoload :Mock, File.expand_path("../google/mock", __FILE__) autoload :Real, File.expand_path("../google/real", __FILE__) requires :google_project recognizes( :app_name, :app_version, :google_client, :google_client_email, :google_client_options, :google_key_location, :google_key_string, :google_json_key_location, :google_json_key_string ) GOOGLE_DNS_API_VERSION = "v1" GOOGLE_DNS_BASE_URL = "https://www.googleapis.com/dns/" GOOGLE_DNS_API_SCOPE_URLS = %w(https://www.googleapis.com/auth/ndev.clouddns.readwrite) ## # MODELS model_path "fog/dns/google/models" # Zone model :zone collection :zones # Record model :record collection :records # Change model :change collection :changes # Project model :project collection :projects ## # REQUESTS request_path "fog/dns/google/requests" # Zone request :create_managed_zone request :delete_managed_zone request :get_managed_zone request :list_managed_zones # Record request :list_resource_record_sets # Change request :create_change request :get_change request :list_changes # Project request :get_project end end end fog-google-0.5.3/lib/fog/dns/google/0000755000004100000410000000000013145731036017160 5ustar www-datawww-datafog-google-0.5.3/lib/fog/dns/google/requests/0000755000004100000410000000000013145731036021033 5ustar www-datawww-datafog-google-0.5.3/lib/fog/dns/google/requests/list_resource_record_sets.rb0000644000004100000410000000307213145731036026640 0ustar www-datawww-datamodule Fog module DNS class Google ## # Enumerates Resource Record Sets that have been created but not yet deleted. # # @see https://developers.google.com/cloud-dns/api/v1/resourceRecordSets/list class Real def list_resource_record_sets(zone_name_or_id, options = {}) api_method = @dns.resource_record_sets.list parameters = { "project" => @project, "managedZone" => zone_name_or_id } [:name, :type].reject { |o| options[o].nil? }.each do |key| parameters[key] = options[key] end request(api_method, parameters) end end class Mock def list_resource_record_sets(zone_name_or_id, options = {}) if data[:managed_zones].key?(zone_name_or_id) zone = data[:managed_zones][zone_name_or_id] else zone = data[:managed_zones].values.detect { |z| z["name"] = zone_name_or_id } end unless zone raise Fog::Errors::NotFound, "The 'parameters.managedZone' resource named '#{zone_name_or_id}' does not exist." end rrsets = data[:resource_record_sets][zone["id"]] if options.key?(:name) && options.key?(:type) rrsets.delete_if { |rrset| rrset["name"] != options[:name] || rrset["type"] != options[:type] } end body = { "kind" => 'dns#resourceRecordSetsListResponse', "rrsets" => rrsets } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/dns/google/requests/create_managed_zone.rb0000644000004100000410000000464213145731036025340 0ustar www-datawww-datarequire "date" module Fog module DNS class Google ## # Creates a new Managed Zone. # # @see https://developers.google.com/cloud-dns/api/v1/managedZones/create class Real def create_managed_zone(name, dns_name, description) api_method = @dns.managed_zones.create parameters = { "project" => @project } body_object = { "name" => name, "dnsName" => dns_name, "description" => description } request(api_method, parameters, body_object) end end class Mock def create_managed_zone(name, dns_name, description) id = Fog::Mock.random_numbers(19).to_s data = { "kind" => 'dns#managedZone', "id" => id, "creationTime" => DateTime.now.strftime("%FT%T.%LZ"), "name" => name, "dnsName" => dns_name, "description" => description, "nameServers" => [ "ns-cloud-e1.googledomains.com.", "ns-cloud-e2.googledomains.com.", "ns-cloud-e3.googledomains.com.", "ns-cloud-e4.googledomains.com." ] } self.data[:managed_zones][id] = data self.data[:resource_record_sets][id] = [ { "kind" => 'dns#resourceRecordSet', "name" => dns_name, "type" => "NS", "ttl" => 21_600, "rrdatas" => [ "ns-cloud-c1.googledomains.com.", "ns-cloud-c2.googledomains.com.", "ns-cloud-c3.googledomains.com.", "ns-cloud-c4.googledomains.com." ] }, { "kind" => 'dns#resourceRecordSet', "name" => dns_name, "type" => "SOA", "ttl" => 21_600, "rrdatas" => [ "ns-cloud-c1.googledomains.com. dns-admin.google.com. 0 21600 3600 1209600 300" ] } ] self.data[:changes][id] = [ { "kind" => 'dns#change', "id" => "0", "startTime" => DateTime.now.strftime("%FT%T.%LZ"), "status" => "done", "additions" => self.data[:resource_record_sets][id] } ] build_excon_response(data) end end end end end fog-google-0.5.3/lib/fog/dns/google/requests/list_managed_zones.rb0000644000004100000410000000131313145731036025223 0ustar www-datawww-datamodule Fog module DNS class Google ## # Enumerates Managed Zones that have been created but not yet deleted. # # @see hhttps://developers.google.com/cloud-dns/api/v1/managedZones/list class Real def list_managed_zones api_method = @dns.managed_zones.list parameters = { "project" => @project } request(api_method, parameters) end end class Mock def list_managed_zones body = { "kind" => 'dns#managedZonesListResponse', "managedZones" => data[:managed_zones].values } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/dns/google/requests/get_managed_zone.rb0000644000004100000410000000175613145731036024657 0ustar www-datawww-datamodule Fog module DNS class Google ## # Fetches the representation of an existing Managed Zone. # # @see https://developers.google.com/cloud-dns/api/v1/managedZones/get class Real def get_managed_zone(name_or_id) api_method = @dns.managed_zones.get parameters = { "project" => @project, "managedZone" => name_or_id } request(api_method, parameters) end end class Mock def get_managed_zone(name_or_id) if data[:managed_zones].key?(name_or_id) data = self.data[:managed_zones][name_or_id] else data = self.data[:managed_zones].values.detect { |zone| zone["name"] = name_or_id } end unless data raise Fog::Errors::NotFound, "The 'parameters.managedZone' resource named '#{name_or_id}' does not exist." end build_excon_response(data) end end end end end fog-google-0.5.3/lib/fog/dns/google/requests/delete_managed_zone.rb0000644000004100000410000000175713145731036025343 0ustar www-datawww-datamodule Fog module DNS class Google ## # Deletes a previously created Managed Zone. # # @see https://developers.google.com/cloud-dns/api/v1/managedZones/delete class Real def delete_managed_zone(name_or_id) api_method = @dns.managed_zones.delete parameters = { "project" => @project, "managedZone" => name_or_id } request(api_method, parameters) end end class Mock def delete_managed_zone(name_or_id) if data[:managed_zones].key?(name_or_id) data[:managed_zones].delete(name_or_id) elsif zone = data[:managed_zones].values.detect { |z| z["name"] = name_or_id } data[:managed_zones].delete(zone["id"]) else raise Fog::Errors::NotFound, "The 'parameters.managedZone' resource named '#{name_or_id}' does not exist." end build_excon_response(nil) end end end end end fog-google-0.5.3/lib/fog/dns/google/requests/get_project.rb0000644000004100000410000000222313145731036023664 0ustar www-datawww-datamodule Fog module DNS class Google ## # Fetches the representation of an existing Project. Use this method to look up the limits on the number of # resources that are associated with your project. # # @see https://developers.google.com/cloud-dns/api/v1/projects/get class Real def get_project(identity) api_method = @dns.projects.get parameters = { :project => identity } request(api_method, parameters) end end class Mock def get_project(identity) body = { "kind" => 'dns#project', "number" => Fog::Mock.random_numbers(12).to_s, "id" => identity, "quota" => { "kind" => 'dns#quota', "managedZones" => 100, "rrsetsPerManagedZone" => 10_000, "rrsetAdditionsPerChange" => 100, "rrsetDeletionsPerChange" => 100, "totalRrdataSizePerChange" => 10_000, "resourceRecordsPerRrset" => 20 } } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/dns/google/requests/list_changes.rb0000644000004100000410000000213513145731036024024 0ustar www-datawww-datamodule Fog module DNS class Google ## # Enumerates the list of Changes. # # @see https://developers.google.com/cloud-dns/api/v1/changes/list class Real def list_changes(zone_name_or_id) api_method = @dns.changes.list parameters = { "project" => @project, "managedZone" => zone_name_or_id } request(api_method, parameters) end end class Mock def list_changes(zone_name_or_id) if data[:managed_zones].key?(zone_name_or_id) zone = data[:managed_zones][zone_name_or_id] else zone = data[:managed_zones].values.detect { |z| z["name"] == zone_name_or_id } end unless zone raise Fog::Errors::NotFound, "The 'parameters.managedZone' resource named '#{zone_name_or_id}' does not exist." end body = { "kind" => 'dns#changesListResponse', "changes" => data[:changes][zone["id"]] } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/dns/google/requests/get_change.rb0000644000004100000410000000237013145731036023446 0ustar www-datawww-datamodule Fog module DNS class Google ## # Fetches the representation of an existing Change. # # @see https://developers.google.com/cloud-dns/api/v1/changes/get class Real def get_change(zone_name_or_id, identity) api_method = @dns.changes.get parameters = { "project" => @project, "managedZone" => zone_name_or_id, "changeId" => identity } request(api_method, parameters) end end class Mock def get_change(zone_name_or_id, identity) if data[:managed_zones].key?(zone_name_or_id) zone = data[:managed_zones][zone_name_or_id] else zone = data[:managed_zones].values.detect { |z| z["name"] = zone_name_or_id } end unless zone raise Fog::Errors::NotFound, "The 'parameters.managedZone' resource named '#{zone_name_or_id}' does not exist." end unless data = self.data[:changes][zone["id"]].detect { |c| c["id"] == identity } raise Fog::Errors::NotFound, "The 'parameters.changeId' resource named '#{identity}' does not exist." end build_excon_response(data) end end end end end fog-google-0.5.3/lib/fog/dns/google/requests/create_change.rb0000644000004100000410000000377513145731036024144 0ustar www-datawww-datamodule Fog module DNS class Google ## # Atomically updates a ResourceRecordSet collection. # # @see https://cloud.google.com/dns/api/v1/changes/create class Real def create_change(zone_name_or_id, additions = [], deletions = []) api_method = @dns.changes.create parameters = { "project" => @project, "managedZone" => zone_name_or_id } body = { "additions" => additions, "deletions" => deletions } request(api_method, parameters, body) end end class Mock def create_change(zone_name_or_id, additions = [], deletions = []) if data[:managed_zones].key?(zone_name_or_id) zone = data[:managed_zones][zone_name_or_id] else zone = data[:managed_zones].values.detect { |z| z["name"] = zone_name_or_id } end unless zone raise Fog::Errors::NotFound, "The 'parameters.managedZone' resource named '#{zone_name_or_id}' does not exist." end deletions.each do |del| rrset = data[:resource_record_sets][zone["id"]].reject! { |r| r["name"] == del["name"] && r["type"] == del["type"] } unless rrset raise Fog::Errors::NotFound, "The 'entity.change.deletions[0]' resource named '#{del['name']} ('#{del['type']})' does not exist." end end additions.each do |add| data[:resource_record_sets][zone["id"]] << add end id = data[:changes][zone["id"]].max_by { |c| c["id"] }["id"] data = { "kind" => 'dns#change', "id" => (id.to_i + 1).to_s, "startTime" => DateTime.now.strftime("%FT%T.%LZ"), "status" => "done", "additions" => additions, "deletions" => deletions } self.data[:changes][zone["id"]] << data build_excon_response(data) end end end end end fog-google-0.5.3/lib/fog/dns/google/mock.rb0000644000004100000410000000130213145731036020432 0ustar www-datawww-datamodule Fog module DNS class Google class Mock include Fog::Google::Shared def initialize(options) shared_initialize(options[:google_project], GOOGLE_DNS_API_VERSION, GOOGLE_DNS_BASE_URL) end def self.data(_api_version) @data ||= {} end def self.reset @data = nil end def data(project = @project) self.class.data(api_version)[project] ||= { :managed_zones => {}, :resource_record_sets => {}, :changes => {} } end def reset_data self.class.data(api_version).delete(@project) end end end end end fog-google-0.5.3/lib/fog/dns/google/real.rb0000644000004100000410000000100313145731036020422 0ustar www-datawww-datamodule Fog module DNS class Google class Real include Fog::Google::Shared attr_accessor :client attr_reader :dns def initialize(options) shared_initialize(options[:google_project], GOOGLE_DNS_API_VERSION, GOOGLE_DNS_BASE_URL) options[:google_api_scope_url] = GOOGLE_DNS_API_SCOPE_URLS.join(" ") @client = initialize_google_client(options) @dns = @client.discovered_api("dns", api_version) end end end end end fog-google-0.5.3/lib/fog/dns/google/models/0000755000004100000410000000000013145731036020443 5ustar www-datawww-datafog-google-0.5.3/lib/fog/dns/google/models/project.rb0000644000004100000410000000476413145731036022451 0ustar www-datawww-datamodule Fog module DNS class Google ## # Represents a Project resource # # @see https://developers.google.com/cloud-dns/api/v1/projects class Project < Fog::Model identity :id attribute :kind attribute :number attribute :quota # These attributes are not available in the representation of a 'Project' returned by the Google DNS API attribute :managed_zones attribute :rrsets_per_managed_zone attribute :resource_records_per_rrset attribute :rrset_additions_per_change attribute :rrset_deletions_per_change attribute :total_rrdatasize_per_change ## # Returns the maximum allowed number of managed zones in the project # # @return [Integer] Maximum allowed number of managed zones in the project def managed_zones quota["managedZones"] end ## # Returns the maximum allowed number of ResourceRecordSets per zone in the project # # @return [Integer] The maximum allowed number of ResourceRecordSets per zone in the project def rrsets_per_managed_zone quota["rrsetsPerManagedZone"] end ## # Returns the maximum allowed number of resource records per ResourceRecordSet # # @return [Integer] The maximum allowed number of resource records per ResourceRecordSet def resource_records_per_rrset quota["resourceRecordsPerRrset"] end ## # Returns the maximum allowed number of ResourceRecordSets to add per Changes.create request # # @return [Integer] The maximum allowed number of ResourceRecordSets to add per Changes.create request def rrset_additions_per_change quota["rrsetAdditionsPerChange"] end ## # Returns the maximum allowed number of ResourceRecordSets to delete per Changes.create request # # @return [Integer] The maximum allowed number of ResourceRecordSets to delete per Changes.create request def rrset_deletions_per_change quota["rrsetDeletionsPerChange"] end ## # Returns the maximum allowed size in bytes for the rrdata field in one Changes.create request # # @return [Integer] The maximum allowed size in bytes for the rrdata field in one Changes.create request def total_rrdatasize_per_change quota["totalRrdataSizePerChange"] end end end end end fog-google-0.5.3/lib/fog/dns/google/models/zones.rb0000644000004100000410000000152313145731036022127 0ustar www-datawww-datamodule Fog module DNS class Google class Zones < Fog::Collection model Fog::DNS::Google::Zone ## # Enumerates Managed Zones that have been created but not yet deleted # # @return [Array] List of Managed Zone resources def all data = service.list_managed_zones.body["managedZones"] || [] load(data) end ## # Fetches the representation of an existing Managed Zone # # @param [String] name_or_id Managed Zone name or identity # @return [Fog::DNS::Google::Zone] Managed Zone resource def get(name_or_id) if zone = service.get_managed_zone(name_or_id).body new(zone) end rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/dns/google/models/change.rb0000644000004100000410000000162313145731036022217 0ustar www-datawww-datamodule Fog module DNS class Google ## # Represents a Change resource # # @see https://developers.google.com/cloud-dns/api/v1/changes class Change < Fog::Model identity :id attribute :kind attribute :start_time, :aliases => "startTime" attribute :status attribute :additions attribute :deletions DONE_STATE = "done" PENDING_STATE = "pending" ## # Checks if the change operation is pending # # @return [Boolean] True if the change operation is pending; False otherwise def pending? status == PENDING_STATE end ## # Checks if the change operation is done # # @return [Boolean] True if the change operation is done; False otherwise def ready? status == DONE_STATE end end end end end fog-google-0.5.3/lib/fog/dns/google/models/changes.rb0000644000004100000410000000223613145731036022403 0ustar www-datawww-datamodule Fog module DNS class Google class Changes < Fog::Collection model Fog::DNS::Google::Change attribute :zone ## # Enumerates the list of Changes # # @return [Array] List of Changes resources def all requires :zone data = service.list_changes(zone.identity).body["changes"] || [] load(data) rescue Fog::Errors::NotFound [] end ## # Fetches the representation of an existing Change # # @param [String] identity Change identity # @return [Fog::DNS::Google::Change] Change resource def get(identity) requires :zone if change = service.get_change(zone.identity, identity).body new(change) end rescue Fog::Errors::NotFound nil end ## # Creates a new instance of a Change # # @return [Fog::DNS::Google::Change] Change resource def new(attributes = {}) requires :zone super({ :zone => zone }.merge!(attributes)) end end end end end fog-google-0.5.3/lib/fog/dns/google/models/projects.rb0000644000004100000410000000102313145731036022615 0ustar www-datawww-datamodule Fog module DNS class Google class Projects < Fog::Collection model Fog::DNS::Google::Project ## # Fetches the representation of an existing Project # # @param [String] identity Project identity # @return [Fog::DNS::Google::Project] Project resource def get(identity) if project = service.get_project(identity).body new(project) end rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/dns/google/models/record.rb0000644000004100000410000000630313145731036022250 0ustar www-datawww-datamodule Fog module DNS class Google ## # Resource Record Sets resource # # @see https://cloud.google.com/dns/api/v1/resourceRecordSets class Record < Fog::Model identity :name attribute :kind attribute :type attribute :ttl attribute :rrdatas ## # Deletes a previously created Resource Record Sets resource # # @param [Boolean] async If the operation must be asyncronous (true by default) # @return [Boolean] If the Resource Record Set has been deleted def destroy(async = true) requires :name, :type, :ttl, :rrdatas data = service.create_change(zone.id, [], [resource_record_set_format]) change = Fog::DNS::Google::Changes.new(:service => service, :zone => zone).get(data.body["id"]) change.wait_for { ready? } unless async true end ## # Modifies a previously created Resource Record Sets resource # # @param [Hash] new_attributes Resource Record Set new attributes # @return [Fog::DNS::Google::Record] Resource Record Sets resource def modify(new_attributes) requires :name, :type, :ttl, :rrdatas deletions = resource_record_set_format merge_attributes(new_attributes) data = service.create_change(zone.id, [resource_record_set_format], [deletions]) change = Fog::DNS::Google::Changes.new(:service => service, :zone => zone).get(data.body["id"]) async = new_attributes.key?(:async) ? new_attributes[:async] : true change.wait_for { ready? } unless async self end ## # Reloads a Resource Record Sets resource # # @return [Fog::DNS::Google::Record] Resource Record Sets resource def reload requires :name, :type data = collection.get(name, type) merge_attributes(data.attributes) self end ## # Creates a new Resource Record Sets resource # # @return [Fog::DNS::Google::Record] Resource Record Sets resource def save requires :name, :type, :ttl, :rrdatas data = service.create_change(zone.id, [resource_record_set_format], []) change = Fog::DNS::Google::Changes.new(:service => service, :zone => zone).get(data.body["id"]) change.wait_for { !pending? } self end ## # Returns the Managed Zone of the Resource Record Sets resource # # @return [Fog::DNS::Google::Zone] Managed Zone of the Resource Record Sets resource attr_reader :zone private ## # Assigns the Managed Zone of the Resource Record Sets resource # # @param [Fog::DNS::Google::Zone] new_zone Managed Zone of the Resource Record Sets resource attr_writer :zone ## # Resource Record Sets resource representation # def resource_record_set_format { "kind" => 'dns#resourceRecordSet', "name" => name, "type" => type, "ttl" => ttl, "rrdatas" => rrdatas } end end end end end fog-google-0.5.3/lib/fog/dns/google/models/zone.rb0000644000004100000410000000372313145731036021750 0ustar www-datawww-datamodule Fog module DNS class Google ## # Managed Zone resource # # @see https://developers.google.com/cloud-dns/api/v1/managedZones class Zone < Fog::Model identity :id attribute :creation_time, :aliases => "creationTime" attribute :description attribute :domain, :aliases => "dnsName" attribute :kind attribute :name attribute :nameservers, :aliases => "nameServers" ## # Enumerates the list of Changes for the Managed Zone # # @return Array] List of Changes for the Managed Zone def changes @changes = begin Fog::DNS::Google::Changes.new( :service => service, :zone => self ) end end ## # Deletes a previously created Managed Zone # # @return [Boolean] If the Managed Zone has been deleted def destroy requires :identity service.delete_managed_zone(identity) true end ## # Enumerates the list of Resource Record Sets for the Managed Zone # # @return Array] List of Resource Record Sets for the Managed Zone def records @records = begin Fog::DNS::Google::Records.new( :service => service, :zone => self ) end end ## # Creates a new Managed Zone # # @return [Fog::DNS::Google::Zone] Managed Zone # @raise [Fog::Errors::Error] If Managed Zone already exists def save requires :name, :domain, :description raise Fog::Errors::Error.new("Resaving an existing object may create a duplicate") if persisted? data = service.create_managed_zone(name, domain, description) merge_attributes(data.body) self end end end end end fog-google-0.5.3/lib/fog/dns/google/models/records.rb0000644000004100000410000000262313145731036022434 0ustar www-datawww-datamodule Fog module DNS class Google class Records < Fog::Collection model Fog::DNS::Google::Record attribute :zone ## # Enumerates Resource Record Sets that have been created but not yet deleted # # @return [Array] List of Resource Record Sets resources def all requires :zone data = service.list_resource_record_sets(zone.identity).body["rrsets"] || [] load(data) rescue Fog::Errors::NotFound [] end ## # Fetches the representation of an existing Resource Record Set # # @param [String] name Resource Record Set name # @param [String] type Resource Record Set type # @return [Fog::DNS::Google::Record] Resource Record Set resource def get(name, type) requires :zone records = service.list_resource_record_sets(zone.identity, :name => name, :type => type).body["rrsets"] || [] records.any? ? new(records.first) : nil rescue Fog::Errors::NotFound nil end ## # Creates a new instance of a Resource Record Set # # @return [Fog::DNS::Google::Record] Resource Record Set resource def new(attributes = {}) requires :zone super({ :zone => zone }.merge!(attributes)) end end end end end fog-google-0.5.3/lib/fog/parsers/0000755000004100000410000000000013145731036016577 5ustar www-datawww-datafog-google-0.5.3/lib/fog/parsers/storage/0000755000004100000410000000000013145731036020243 5ustar www-datawww-datafog-google-0.5.3/lib/fog/parsers/storage/google.rb0000644000004100000410000000134213145731036022044 0ustar www-datawww-datamodule Fog module Parsers module Storage module Google autoload :AccessControlList, File.expand_path("../google/access_control_list", __FILE__) autoload :CopyObject, File.expand_path("../google/copy_object", __FILE__) autoload :GetBucket, File.expand_path("../google/get_bucket", __FILE__) autoload :GetBucketLogging, File.expand_path("../google/get_bucket_logging", __FILE__) autoload :GetBucketObjectVersions, File.expand_path("../google/get_bucket_object_versions", __FILE__) autoload :GetRequestPayment, File.expand_path("../google/get_request_payment", __FILE__) autoload :GetService, File.expand_path("../google/get_service", __FILE__) end end end end fog-google-0.5.3/lib/fog/parsers/storage/google/0000755000004100000410000000000013145731036021517 5ustar www-datawww-datafog-google-0.5.3/lib/fog/parsers/storage/google/get_service.rb0000644000004100000410000000126113145731036024343 0ustar www-datawww-datamodule Fog module Parsers module Storage module Google class GetService < Fog::Parsers::Base def reset @bucket = {} @response = { "Owner" => {}, "Buckets" => [] } end def end_element(name) case name when "Bucket" @response["Buckets"] << @bucket @bucket = {} when "CreationDate" @bucket["CreationDate"] = Time.parse(value) when "DisplayName", "ID" @response["Owner"][name] = value when "Name" @bucket[name] = value end end end end end end end fog-google-0.5.3/lib/fog/parsers/storage/google/copy_object.rb0000644000004100000410000000061113145731036024342 0ustar www-datawww-datamodule Fog module Parsers module Storage module Google class CopyObject < Fog::Parsers::Base def end_element(name) case name when "ETag" @response[name] = value.delete('"') when "LastModified" @response[name] = Time.parse(value) end end end end end end end fog-google-0.5.3/lib/fog/parsers/storage/google/get_bucket_versioning.rb0000644000004100000410000000066013145731036026425 0ustar www-datawww-datamodule Fog module Parsers module Storage module Google class GetBucketVersioning < Fog::Parsers::Base def reset @response = { "VersioningConfiguration" => {} } end def end_element(name) case name when "Status" @response["VersioningConfiguration"][name] = value end end end end end end end fog-google-0.5.3/lib/fog/parsers/storage/google/get_bucket_object_versions.rb0000644000004100000410000000502613145731036027441 0ustar www-datawww-datamodule Fog module Parsers module Storage module Google class GetBucketObjectVersions < Fog::Parsers::Base def reset @delete_marker = { "Owner" => {} } @version = { "Owner" => {} } @in_delete_marke = false @in_version = false @response = { "Versions" => [] } end def start_element(name, attrs = []) super case name when "DeleteMarker" @in_delete_marker = true when "Version" @in_version = true end end def end_element(name) case name when "DeleteMarker" @response["Versions"] << { "DeleteMarker" => @delete_marker } @delete_marker = { "Owner" => {} } @in_delete_marker = false when "Version" @response["Versions"] << { "Version" => @version } @version = { "Owner" => {} } @in_version = false when "DisplayName", "ID" if @in_delete_marker @delete_marker elsif @in_version @version end["Owner"][name] = value when "ETag" @version[name] = value.delete('"') when "IsLatest" if @in_delete_marker @delete_marker elsif @in_version @version end["IsLatest"] = if value == "true" true else false end when "IsTruncated" if value == "true" @response["IsTruncated"] = true else @response["IsTruncated"] = false end when "LastModified" if @in_delete_marker @delete_marker elsif @in_version @version end["LastModified"] = Time.parse(value) when "KeyMarker", "Name", "Prefix", "VersionIdMarker" @response[name] = value when "MaxKeys" @response["MaxKeys"] = value.to_i when "Size" @version["Size"] = value.to_i when "Key", "Name", "StorageClass", "VersionId" if @in_delete_marker @delete_marker elsif @in_version @version end[name] = value end end end end end end end fog-google-0.5.3/lib/fog/parsers/storage/google/get_request_payment.rb0000644000004100000410000000046313145731036026133 0ustar www-datawww-datamodule Fog module Parsers module Storage module Google class GetRequestPayment < Fog::Parsers::Base def end_element(name) case name when "Payer" @response[name] = value end end end end end end end fog-google-0.5.3/lib/fog/parsers/storage/google/access_control_list.rb0000644000004100000410000000221413145731036026077 0ustar www-datawww-datamodule Fog module Parsers module Storage module Google class AccessControlList < Fog::Parsers::Base def reset @in_entries = false @entry = { "Scope" => {} } @response = { "Owner" => {}, "AccessControlList" => [] } end def start_element(name, attrs = []) super case name when "Entries" @in_entries = true when "Scope" struct = attrs.first @entry["Scope"][struct.localname] = struct.value end end def end_element(name) case name when "Entries" @in_entries = false when "Entry" @response["AccessControlList"] << @entry @entry = { "Scope" => {} } when "DisplayName", "ID" if @in_entries @entry["Scope"][name] = value else @response["Owner"][name] = value end when "Permission" @entry[name] = value end end end end end end end fog-google-0.5.3/lib/fog/parsers/storage/google/get_bucket.rb0000644000004100000410000000324613145731036024165 0ustar www-datawww-datamodule Fog module Parsers module Storage module Google class GetBucket < Fog::Parsers::Base def reset @object = { "Owner" => {} } @response = { "Contents" => [], "CommonPrefixes" => [] } end def start_element(name, attrs = []) super case name when "CommonPrefixes" @in_common_prefixes = true end end def end_element(name) case name when "CommonPrefixes" @in_common_prefixes = false when "Contents" @response["Contents"] << @object @object = { "Owner" => {} } when "DisplayName", "ID" @object["Owner"][name] = value when "ETag" @object[name] = value.delete('"') when "IsTruncated" if value == "true" @response["IsTruncated"] = true else @response["IsTruncated"] = false end when "LastModified" @object["LastModified"] = Time.parse(value) when "Marker", "Name" @response[name] = value when "MaxKeys" @response["MaxKeys"] = value.to_i when "Prefix" if @in_common_prefixes @response["CommonPrefixes"] << value else @response[name] = value end when "Size" @object["Size"] = value.to_i when "Delimiter", "Key", "StorageClass" @object[name] = value end end end end end end end fog-google-0.5.3/lib/fog/parsers/storage/google/get_bucket_logging.rb0000644000004100000410000000213413145731036025666 0ustar www-datawww-datamodule Fog module Parsers module Storage module Google class AccessControlList < Fog::Parsers::Base def reset @grant = { "Grantee" => {} } @response = { "BucketLoggingStatus" => {} } end def end_element(name) case name when "DisplayName", "ID" if @in_access_control_list @grant["Grantee"][name] = value else @response["Owner"][name] = value end when "Grant" @response["BucketLoggingStatus"]["LoggingEnabled"]["TargetGrants"] << @grant @grant = { "Grantee" => {} } when "LoggingEnabled" @response["BucketLoggingStatus"]["LoggingEnabled"] = { "TargetGrants" => [] } when "Permission" @grant[name] = value when "TargetBucket", "TargetPrefix" @response["BucketLoggingStatus"][name] = value when "URI" @grant["Grantee"][name] = value end end end end end end end fog-google-0.5.3/lib/fog/google/0000755000004100000410000000000013145731036016374 5ustar www-datawww-datafog-google-0.5.3/lib/fog/google/sql.rb0000644000004100000410000000412713145731036017524 0ustar www-datawww-datamodule Fog module Google class SQL < Fog::Service autoload :Mock, File.expand_path("../sql/mock", __FILE__) autoload :Real, File.expand_path("../sql/real", __FILE__) requires :google_project recognizes( :app_name, :app_version, :google_client, :google_client_email, :google_client_options, :google_key_location, :google_key_string, :google_json_key_location, :google_json_key_string ) GOOGLE_SQL_API_VERSION = "v1beta3" GOOGLE_SQL_BASE_URL = "https://www.googleapis.com/sql/" GOOGLE_SQL_API_SCOPE_URLS = %w(https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/cloud-platform) ## # MODELS model_path "fog/google/models/sql" # Backup Run model :backup_run collection :backup_runs # Flag model :flag collection :flags # Instance model :instance collection :instances # Operation model :operation collection :operations # SSL Certificate model :ssl_cert collection :ssl_certs # Tier model :tier collection :tiers ## # REQUESTS request_path "fog/google/requests/sql" # Backup Run request :get_backup_run request :list_backup_runs # Flag request :list_flags # Instance request :clone_instance request :delete_instance request :export_instance request :get_instance request :import_instance request :insert_instance request :list_instances request :reset_instance_ssl_config request :restart_instance request :restore_instance_backup request :set_instance_root_password request :update_instance # Operation request :get_operation request :list_operations # SSL Certificate request :delete_ssl_cert request :get_ssl_cert request :insert_ssl_cert request :list_ssl_certs # Tier request :list_tiers end end end fog-google-0.5.3/lib/fog/google/requests/0000755000004100000410000000000013145731036020247 5ustar www-datawww-datafog-google-0.5.3/lib/fog/google/requests/sql/0000755000004100000410000000000013145731036021046 5ustar www-datawww-datafog-google-0.5.3/lib/fog/google/requests/sql/clone_instance.rb0000644000004100000410000000604113145731036024360 0ustar www-datawww-datamodule Fog module Google class SQL ## # Creates a Cloud SQL instance as a clone of the source instance # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/instances/clone class Real def clone_instance(instance_id, destination_name, options = {}) # The @sql.instances.clone method is overrided by the standard Ruby clone method # so we cannot call it because it will just clone the @sql.instances instance. # Instead we need to find the proper method trough the discovered_methods. api_method = @sql.instances.discovered_methods.detect { |x| x.id == "sql.instances.clone" } parameters = { "project" => @project } body = { "cloneContext" => { "kind" => 'sql#cloneContext', "sourceInstanceName" => instance_id, "destinationInstanceName" => destination_name } } if options[:log_position] body["cloneContext"]["binLogCoordinates"] = { "kind" => 'sql#binLogCoordinates', "binLogFileName" => options[:log_filename], "binLogPosition" => options[:log_position] } end request(api_method, parameters, body) end end class Mock def clone_instance(instance_id, destination_name, _options = {}) data[:instances][destination_name] = data[:instances][instance_id] data[:instances][destination_name]["instance"] = destination_name data[:ssl_certs][destination_name] = {} data[:backup_runs][destination_name] = {} operation = random_operation data[:operations][destination_name] ||= {} data[:operations][destination_name][operation] = { "kind" => 'sql#instanceOperation', "instance" => destination_name, "operation" => operation, "operationType" => "CREATE", "state" => Fog::Google::SQL::Operation::DONE_STATE, "userEmailAddress" => "google_client_email@developer.gserviceaccount.com", "enqueuedTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "endTime" => Time.now.iso8601 } operation = random_operation data[:operations][instance_id] ||= {} data[:operations][instance_id][operation] = { "kind" => 'sql#instanceOperation', "instance" => instance_id, "operation" => operation, "operationType" => "CLONE", "state" => Fog::Google::SQL::Operation::DONE_STATE, "userEmailAddress" => "google_client_email@developer.gserviceaccount.com", "enqueuedTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "endTime" => Time.now.iso8601 } body = { "kind" => 'sql#instancesClone', "operation" => operation } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/set_instance_root_password.rb0000644000004100000410000000306513145731036027043 0ustar www-datawww-datamodule Fog module Google class SQL ## # Sets the password for the root user # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/instances/setRootPassword class Real def set_instance_root_password(instance_id, password) api_method = @sql.instances.set_root_password parameters = { "project" => @project, "instance" => instance_id } body = { "setRootPasswordContext" => { "kind" => 'sql#setRootUserContext', "password" => password } } request(api_method, parameters, body) end end class Mock def set_instance_root_password(instance_id, _password) operation = random_operation data[:operations][instance_id] ||= {} data[:operations][instance_id][operation] = { "kind" => 'sql#instanceOperation', "instance" => instance_id, "operation" => operation, "operationType" => "INJECT_USER", "state" => Fog::Google::SQL::Operation::DONE_STATE, "userEmailAddress" => "google_client_email@developer.gserviceaccount.com", "enqueuedTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "endTime" => Time.now.iso8601 } body = { "kind" => 'sql#instancesSetRootPassword', "operation" => operation } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/get_operation.rb0000644000004100000410000000367413145731036024244 0ustar www-datawww-datamodule Fog module Google class SQL ## # Retrieves an instance operation that has been performed on an instance # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/operations/get class Real def get_operation(instance_id, operation_id) api_method = @sql.operations.get parameters = { "project" => @project, "instance" => instance_id, "operation" => operation_id } request(api_method, parameters) end end class Mock def get_operation(instance_id, operation_id) if data[:operations].key?(instance_id) if data[:operations][instance_id].key?(operation_id) body = data[:operations][instance_id][operation_id] status = 200 else body = { "error" => { "errors" => [ { "domain" => "global", "reason" => "operationDoesNotExist", "message" => "The Cloud SQL instance operation does not exist." } ], "code" => 404, "message" => "The Cloud SQL instance operation does not exist." } } status = 404 end else body = { "error" => { "errors" => [ { "domain" => "global", "reason" => "notAuthorized", "message" => "The client is not authorized to make this request." } ], "code" => 403, "message" => "The client is not authorized to make this request." } } status = 403 end build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/restore_instance_backup.rb0000644000004100000410000000144013145731036026266 0ustar www-datawww-datamodule Fog module Google class SQL ## # Restores a backup of a Cloud SQL instance # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/instances/restoreBackup class Real def restore_instance_backup(identity, backup_configuration, due_time) api_method = @sql.instances.reset_ssl_config parameters = { "project" => @project, "instance" => identity, "backupConfiguration" => backup_configuration, "dueTime" => due_time } request(api_method, parameters) end end class Mock def restore_instance_backup(_identity, _backup_configuration, _due_time) Fog::Mock.not_implemented end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/list_tiers.rb0000644000004100000410000000503513145731036023557 0ustar www-datawww-datamodule Fog module Google class SQL ## # Lists all available service tiers for Google Cloud SQL # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/tiers/list class Real def list_tiers api_method = @sql.tiers.list parameters = { "project" => @project } request(api_method, parameters) end end class Mock def list_tiers body = { "kind" => 'sql#tiersList', "items" => [ { "kind" => 'sql#tier', "tier" => "D0", "RAM" => "134217728", "DiskQuota" => "268435456000", "region" => ["us-central", "europe-west1", "asia-east1"] }, { "kind" => 'sql#tier', "tier" => "D1", "RAM" => "536870912", "DiskQuota" => "268435456000", "region" => ["us-central", "europe-west1", "asia-east1"] }, { "kind" => 'sql#tier', "tier" => "D2", "RAM" => "1073741824", "DiskQuota" => "268435456000", "region" => ["us-central", "europe-west1", "asia-east1"] }, { "kind" => 'sql#tier', "tier" => "D4", "RAM" => "2147483648", "DiskQuota" => "268435456000", "region" => ["us-central", "europe-west1", "asia-east1"] }, { "kind" => 'sql#tier', "tier" => "D8", "RAM" => "4294967296", "DiskQuota" => "268435456000", "region" => ["us-central", "europe-west1", "asia-east1"] }, { "kind" => 'sql#tier', "tier" => "D16", "RAM" => "8589934592", "DiskQuota" => "268435456000", "region" => ["us-central", "europe-west1", "asia-east1"] }, { "kind" => 'sql#tier', "tier" => "D32", "RAM" => "17179869184", "DiskQuota" => "268435456000", "region" => ["us-central"] } ] } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/delete_ssl_cert.rb0000644000004100000410000000416613145731036024542 0ustar www-datawww-datamodule Fog module Google class SQL ## # Deletes a SSL certificate. The change will not take effect until the instance is restarted. # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/sslCerts/delete class Real def delete_ssl_cert(instance_id, sha1_fingerprint) api_method = @sql.ssl_certs.delete parameters = { "project" => @project, "instance" => instance_id, "sha1Fingerprint" => sha1_fingerprint } request(api_method, parameters) end end class Mock def delete_ssl_cert(instance_id, sha1_fingerprint) if data[:ssl_certs].key?(instance_id) data[:ssl_certs][instance_id].delete(sha1_fingerprint) operation = random_operation data[:operations][instance_id] ||= {} data[:operations][instance_id][operation] = { "kind" => 'sql#instanceOperation', "instance" => instance_id, "operation" => operation, "operationType" => "UPDATE", "state" => Fog::Google::SQL::Operation::DONE_STATE, "userEmailAddress" => "google_client_email@developer.gserviceaccount.com", "enqueuedTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "endTime" => Time.now.iso8601 } body = { "kind" => 'sql#sslCertsDelete', "operation" => operation } status = 200 else body = { "error" => { "errors" => [ { "domain" => "global", "reason" => "notAuthorized", "message" => "The client is not authorized to make this request." } ], "code" => 403, "message" => "The client is not authorized to make this request." } } status = 403 end build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/get_ssl_cert.rb0000644000004100000410000000367413145731036024062 0ustar www-datawww-datamodule Fog module Google class SQL ## # Retrieves a particular SSL certificate (does not include the private key) # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/sslCerts/get class Real def get_ssl_cert(instance_id, sha1_fingerprint) api_method = @sql.ssl_certs.get parameters = { "project" => @project, "instance" => instance_id, "sha1Fingerprint" => sha1_fingerprint } request(api_method, parameters) end end class Mock def get_ssl_cert(instance_id, sha1_fingerprint) if data[:ssl_certs].key?(instance_id) if data[:ssl_certs][instance_id].key?(sha1_fingerprint) body = data[:ssl_certs][instance_id][sha1_fingerprint] status = 200 else body = { "error" => { "errors" => [ { "domain" => "global", "reason" => "sslCertificateDoesNotExist", "message" => "The SSL certificate does not exist." } ], "code" => 404, "message" => "The SSL certificate does not exist." } } status = 404 end else body = { "error" => { "errors" => [ { "domain" => "global", "reason" => "notAuthorized", "message" => "The client is not authorized to make this request." } ], "code" => 403, "message" => "The client is not authorized to make this request." } } status = 403 end build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/update_instance.rb0000644000004100000410000001272413145731036024547 0ustar www-datawww-datamodule Fog module Google class SQL ## # Updates settings of a Cloud SQL instance # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/instances/update class Real def update_instance(instance_id, settings_version, tier, options = {}) api_method = @sql.instances.update parameters = { "project" => @project, "instance" => instance_id } body = { "project" => @project, "instance" => instance_id, "settings" => { "settingsVersion" => settings_version, "tier" => tier } } if options[:activation_policy] body["settings"]["activationPolicy"] = options[:activation_policy] end if options[:autorized_gae_applications] body["settings"]["authorizedGaeApplications"] = Array(options[:autorized_gae_applications]) end if options[:backup_configuration] body["settings"]["backupConfiguration"] = options[:backup_configuration] end if options[:ip_configuration_authorized_networks] body["settings"]["ipConfiguration"] ||= {} body["settings"]["ipConfiguration"]["authorizedNetworks"] = Array(options[:ip_configuration_authorized_networks]) end if options[:ip_configuration_enabled] body["settings"]["ipConfiguration"] ||= {} body["settings"]["ipConfiguration"]["enabled"] = options[:ip_configuration_enabled] end if options[:ip_configuration_require_ssl] body["settings"]["ipConfiguration"] ||= {} body["settings"]["ipConfiguration"]["requireSsl"] = options[:ip_configuration_require_ssl] end if options[:location_preference_zone_follow_gae_application] body["settings"]["locationPreference"] ||= {} body["settings"]["locationPreference"]["followGaeApplication"] = options[:location_preference_zone_follow_gae_application] end if options[:location_preference_zone] body["settings"]["locationPreference"] ||= {} body["settings"]["locationPreference"]["zone"] = options[:location_preference_zone] end if options[:pricing_plan] body["settings"]["pricingPlan"] = options[:pricing_plan] end if options[:replication_type] body["settings"]["replicationType"] = options[:replication_type] end request(api_method, parameters, body) end end class Mock def update_instance(instance_id, _settings_version, tier, options = {}) data = self.data[:instances][instance_id] data["tier"] = tier if options[:activation_policy] data["settings"]["activationPolicy"] = options[:activation_policy] end if options[:autorized_gae_applications] data["settings"]["authorizedGaeApplications"] = Array(options[:autorized_gae_applications]) end if options[:backup_configuration] data["settings"]["backupConfiguration"] = options[:backup_configuration] end if options[:ip_configuration_authorized_networks] data["settings"]["ipConfiguration"] ||= {} data["settings"]["ipConfiguration"]["authorizedNetworks"] = Array(options[:ip_configuration_authorized_networks]) end if options[:ip_configuration_enabled] data["settings"]["ipConfiguration"] ||= {} data["settings"]["ipConfiguration"]["enabled"] = options[:ip_configuration_enabled] end if options[:ip_configuration_require_ssl] data["settings"]["ipConfiguration"] ||= {} data["settings"]["ipConfiguration"]["requireSsl"] = options[:ip_configuration_require_ssl] end if options[:location_preference_zone_follow_gae_application] data["settings"]["locationPreference"] ||= {} data["settings"]["locationPreference"]["followGaeApplication"] = options[:location_preference_zone_follow_gae_application] end if options[:location_preference_zone] data["settings"]["locationPreference"] ||= {} data["settings"]["locationPreference"]["zone"] = options[:location_preference_zone] end if options[:pricing_plan] data["settings"]["pricingPlan"] = options[:pricing_plan] end if options[:replication_type] data["settings"]["replicationType"] = options[:replication_type] end self.data[:instances][instance_id] = data operation = random_operation self.data[:operations][instance_id] ||= {} self.data[:operations][instance_id][operation] = { "kind" => 'sql#instanceOperation', "instance" => instance_id, "operation" => operation, "operationType" => "UPDATE", "state" => Fog::Google::SQL::Operation::DONE_STATE, "userEmailAddress" => "google_client_email@developer.gserviceaccount.com", "enqueuedTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "endTime" => Time.now.iso8601 } body = { "kind" => 'sql#instancesUpdate', "operation" => operation } status = 200 build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/reset_instance_ssl_config.rb0000644000004100000410000000312413145731036026607 0ustar www-datawww-datamodule Fog module Google class SQL ## # Deletes all client certificates and generates a new server SSL certificate for the instance. # The changes will not take effect until the instance is restarted. Existing instances without # a server certificate will need to call this once to set a server certificate # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/instances/resetSslConfig class Real def reset_instance_ssl_config(instance_id) api_method = @sql.instances.reset_ssl_config parameters = { "project" => @project, "instance" => instance_id } request(api_method, parameters) end end class Mock def reset_instance_ssl_config(instance_id) operation = random_operation data[:operations][instance_id] ||= {} data[:operations][instance_id][operation] = { "kind" => 'sql#instanceOperation', "instance" => instance_id, "operation" => operation, "operationType" => "UPDATE", "state" => Fog::Google::SQL::Operation::DONE_STATE, "userEmailAddress" => "google_client_email@developer.gserviceaccount.com", "enqueuedTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "endTime" => Time.now.iso8601 } body = { "kind" => 'sql#instancesResetSslConfig', "operation" => operation } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/restart_instance.rb0000644000004100000410000000246313145731036024750 0ustar www-datawww-datamodule Fog module Google class SQL ## # Restarts a Cloud SQL instance # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/instances/restart class Real def restart_instance(instance_id) api_method = @sql.instances.restart parameters = { "project" => @project, "instance" => instance_id } request(api_method, parameters) end end class Mock def restart_instance(instance_id) operation = random_operation data[:operations][instance_id] ||= {} data[:operations][instance_id][operation] = { "kind" => 'sql#instanceOperation', "instance" => instance_id, "operation" => operation, "operationType" => "RESTART", "state" => Fog::Google::SQL::Operation::DONE_STATE, "userEmailAddress" => "google_client_email@developer.gserviceaccount.com", "enqueuedTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "endTime" => Time.now.iso8601 } body = { "kind" => 'sql#instancesRestart', "operation" => operation } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/delete_instance.rb0000644000004100000410000000373313145731036024527 0ustar www-datawww-datamodule Fog module Google class SQL ## # Deletes a Cloud SQL instance # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/instances/delete class Real def delete_instance(instance_id) api_method = @sql.instances.delete parameters = { "project" => @project, "instance" => instance_id } request(api_method, parameters) end end class Mock def delete_instance(instance_id) if data[:instances].key?(instance_id) data[:instances].delete(instance_id) data[:ssl_certs].delete(instance_id) data[:backup_runs].delete(instance_id) operation = random_operation data[:operations][instance_id] ||= {} data[:operations][instance_id][operation] = { "kind" => 'sql#instanceOperation', "instance" => instance_id, "operation" => operation, "operationType" => "DELETE", "state" => Fog::Google::SQL::Operation::PENDING_STATE, "userEmailAddress" => "google_client_email@developer.gserviceaccount.com", "enqueuedTime" => Time.now.iso8601 } body = { "kind" => 'sql#instancesDelete', "operation" => operation } status = 200 else body = { "error" => { "errors" => [ { "domain" => "global", "reason" => "notAuthorized", "message" => "The client is not authorized to make this request." } ], "code" => 403, "message" => "The client is not authorized to make this request." } } status = 403 end build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/list_ssl_certs.rb0000644000004100000410000000252013145731036024426 0ustar www-datawww-datamodule Fog module Google class SQL ## # Lists all of the current SSL certificates for the instance # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/sslCerts/list class Real def list_ssl_certs(instance_id) api_method = @sql.ssl_certs.list parameters = { "project" => @project, "instance" => instance_id } request(api_method, parameters) end end class Mock def list_ssl_certs(instance_id) if data[:ssl_certs].key?(instance_id) body = { "kind" => 'sql#sslCertsList', "items" => data[:ssl_certs][instance_id].values } status = 200 else body = { "error" => { "errors" => [ { "domain" => "global", "reason" => "notAuthorized", "message" => "The client is not authorized to make this request." } ], "code" => 403, "message" => "The client is not authorized to make this request." } } status = 403 end build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/list_operations.rb0000644000004100000410000000266213145731036024617 0ustar www-datawww-datamodule Fog module Google class SQL ## # Lists all instance operations that have been performed on the given Cloud SQL instance # in the reverse chronological order of the start time # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/operations/list class Real def list_operations(instance_id) api_method = @sql.operations.list parameters = { "project" => @project, "instance" => instance_id } request(api_method, parameters) end end class Mock def list_operations(instance_id) if data[:operations].key?(instance_id) body = { "kind" => 'sql#operationsList', "items" => data[:operations][instance_id].values } status = 200 else body = { "error" => { "errors" => [ { "domain" => "global", "reason" => "notAuthorized", "message" => "The client is not authorized to make this request." } ], "code" => 403, "message" => "The client is not authorized to make this request." } } status = 403 end build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/export_instance.rb0000644000004100000410000000323313145731036024601 0ustar www-datawww-datamodule Fog module Google class SQL ## # Exports data from a Cloud SQL instance to a Google Cloud Storage bucket as a MySQL dump file # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/instances/export class Real def export_instance(instance_id, uri, options = {}) api_method = @sql.instances.export parameters = { "project" => @project, "instance" => instance_id } body = { "exportContext" => { "kind" => 'sql#exportContext', "uri" => uri, "database" => Array(options[:databases]), "table" => Array(options[:tables]) } } request(api_method, parameters, body) end end class Mock def export_instance(instance_id, _uri, _options = {}) operation = random_operation data[:operations][instance_id] ||= {} data[:operations][instance_id][operation] = { "kind" => 'sql#instanceOperation', "instance" => instance_id, "operation" => operation, "operationType" => "EXPORT", "state" => Fog::Google::SQL::Operation::DONE_STATE, "userEmailAddress" => "google_client_email@developer.gserviceaccount.com", "enqueuedTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "endTime" => Time.now.iso8601 } body = { "kind" => 'sql#instancesExport', "operation" => operation } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/insert_ssl_cert.rb0000644000004100000410000001462513145731036024605 0ustar www-datawww-datamodule Fog module Google class SQL ## # Creates an SSL certificate. The new certificate will not be usable until the instance is restarted. # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/sslCerts/insert class Real def insert_ssl_cert(instance_id, common_name) api_method = @sql.ssl_certs.insert parameters = { "project" => @project, "instance" => instance_id } body = { "commonName" => common_name } request(api_method, parameters, body) end end class Mock def insert_ssl_cert(instance_id, common_name) if data[:ssl_certs].key?(instance_id) sha1_fingerprint = Fog::Mock.random_hex(40) data = { "kind" => 'sql#sslCert', "instance" => instance_id, "sha1Fingerprint" => sha1_fingerprint, "commonName" => common_name, "certSerialNumber" => Fog::Mock.random_numbers(9), "cert" => "-----BEGIN CERTIFICATE-----\nMIIC/zCCAeegAwIBAgIELAk5vzANBgkqhkiG9w0BAQUFADBNMSgwJgYDVQQDEx9H\nb29nbGUgQ2xvdWQgU1FMIENsaWVudCBDQSB0ZXN0MRQwEgYDVQQKEwtHb29nbGUs\nIEluYzELMAkGA1UEBhMCVVMwHhcNMTQwNjA0MDY1MjAwWhcNMjQwNjAxMDY1MjAw\nWjAyMQ0wCwYDVQQDEwR0ZXN0MRQwEgYDVQQKEwtHb29nbGUsIEluYzELMAkGA1UE\nBhMCVVMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC9G9ZG19n978EW\n5bQ/TM1Fnb4fd/FRT8XMs2D5C7+dKLEgbeUOvZQt4EsQ6cC+UVhoK7N6DvnXAZ1M\ng+B159Xlqjv8Mh5RihfGjPCdlw2pF7Pu68LyYghvQLhi7yhuNeaN+FBeKvjcW9k0\ni54AM8Ub2a/kxAwMtXm1kGtgc1+qkUlyBxfn1UoKI5Dhvw/InxgI1kS/VUkkk9kv\n0q/oyPrboE/vuSitDq+pHjRFwrIQcS6Pz9DYHhZVyDDkTIh7vLXM0JEQRT1SiA8k\n+4hwXI3WBqPRZRI4H1KmYSSIKvZtci63SbM/rHitXkGipFF1lw0gSqfpM8gG36fl\naITBPI97AgMBAAGjAjAAMA0GCSqGSIb3DQEBBQUAA4IBAQCOvRWYdcaYl/qHgif8\nvD4QEQLiy3+Hn5zSLQEcqP/BymhUw4LSGhu8NJxJ26PvlHzAnWa2/OkTCkgSpM4k\nkebO2vyuU8XY/7FeRO3uNktEAp2Aw1RYJ/IqSDvjpg5/hJTHKADrAkiu2SyCJvoO\nqblzBO7TvLj5BBdvcr1/hfWRuAt5NykOww9AMEAzrfLzrF7f98RntOZzIwwX+UvF\nLXQZwc/b55d97Y249pLRQCBnHdaEtZLQTEQulj1zMx2lkH5CrQWGwDCVFuIyt/rN\nzFJGN09McKrWkBZuwPtkkyb+sBVXZX6cEFgHHA+7D91QRH4lbEjjO8OjQgaA6qWN\n5iGN\n-----END CERTIFICATE-----", "createTime" => Time.now.iso8601, "expirationTime" => Time.now.iso8601 } self.data[:ssl_certs][instance_id][sha1_fingerprint] = data body = { "kind" => 'sql#sslCertsInsert', "serverCaCert" => { "kind" => 'sql#sslCert', "instance" => instance_id, "sha1Fingerprint" => Fog::Mock.random_hex(40), "commonName" => 'C=US,O=Google\\, Inc,CN=Google Cloud SQL Server CA', "certSerialNumber" => "0", "cert" => "-----BEGIN CERTIFICATE-----\nMIIDITCCAgmgAwIBAgIBADANBgkqhkiG9w0BAQUFADBIMSMwIQYDVQQDExpHb29n\nbGUgQ2xvdWQgU1FMIFNlcnZlciBDQTEUMBIGA1UEChMLR29vZ2xlLCBJbmMxCzAJ\nBgNVBAYTAlVTMB4XDTE0MDYwNDA1MjkxMVoXDTI0MDYwMTA1MjkxMVowSDEjMCEG\nA1UEAxMaR29vZ2xlIENsb3VkIFNRTCBTZXJ2ZXIgQ0ExFDASBgNVBAoTC0dvb2ds\nZSwgSW5jMQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\nggEBALlRjq3zccH5ed6NMfCFcTYd9XxYXyvLurxxjDIA6A7/ymVM9qdQC0uckf7C\nsi4uMi2yfK+PHZ0jXC+g0uPx5RTm+nbKl4I++VOh2g6oZHeNdFt4rVJpr+jzGUMf\nr67SymUr70TQOTEVpx2Ud3rBB2szulxWUSXEy2AGA3uNUGe/IgENh7p56s00Sr97\nTRP1S5/JVMalncgNVLH2nNqBQJZTx9t9qvGatoUfmHUU0+M//J5sXLbgdzeEeeot\nHJUyoXjA2sRkH1+F/d6PpFrcr1I8dVmCBEbTAnm7HpKh5Mx2nRYi+t/y9D2Mblwx\n9dBRfr3WIJ1JDxzt3L8CtBGZbvUCAwEAAaMWMBQwEgYDVR0TAQH/BAgwBgEB/wIB\nADANBgkqhkiG9w0BAQUFAAOCAQEAmHuBecPc265sbd26B1HXUAD6FHdzoZLrAZVW\n+1eIK4E669P4y6LkLuoCkLd64/YwA4K2FioksqgHOahbYWJJYPymy4ae+IPXzXcY\nPv3gmBsKk++sHb64D9Cj/k5n8BEiVmmrsUCUiL75nJAzK+El3hvKKWWl76XX/qHP\nk8ZAxIrn8bCiVOaj6NR4+p1OmcZSPNWxz7j/EwQxoABRxgPgt+B/YRseevww7an2\n/rGs0sk7RE0QDjLfZblYGh+xVPBBLuLmf4L5JNJkFEoeGSWrxTzvXnS+2LZeHdM/\nJ9nsiKu5JKPhMUS0vOcTymOkh8tJ6Np8gwg6ca4g6dT3llE6uQ==\n-----END CERTIFICATE-----", "createTime" => Time.now.iso8601, "expirationTime" => Time.now.iso8601 }, "clientCert" => { "certInfo" => data, "certPrivateKey" => "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEAvRvWRtfZ/e/BFuW0P0zNRZ2+H3fxUU/FzLNg+Qu/nSixIG3l\nDr2ULeBLEOnAvlFYaCuzeg751wGdTIPgdefV5ao7/DIeUYoXxozwnZcNqRez7uvC\n8mIIb0C4Yu8objXmjfhQXir43FvZNIueADPFG9mv5MQMDLV5tZBrYHNfqpFJcgcX\n59VKCiOQ4b8PyJ8YCNZEv1VJJJPZL9Kv6Mj626BP77korQ6vqR40RcKyEHEuj8/Q\n2B4WVcgw5EyIe7y1zNCREEU9UogPJPuIcFyN1gaj0WUSOB9SpmEkiCr2bXIut0mz\nP6x4rV5BoqRRdZcNIEqn6TPIBt+n5WiEwTyPewIDAQABAoIBAH89e6+vDL4P05vU\ncrMkufldac9CpNxREIXrLBRmE0drWcK4Lqb8Z/d2MwvuPAHSOendfaVi7jf8nhod\noamzk/gz0qieEEhM4jJ2Im/mcwqTKD5Z45Gy5Hn20hm/UTTWj4p2yZySzV93bW4t\nguIf80AJ+I+0WWczs/C2e4kqF/RrIf4ff7UF/2TPS+sEmkTA74APWIMqjkr0cjTP\nrIJCp8jFn/639dVLeHcw2abduZSV8PkQSNdqPeH2P+GpqkYLREPMAw/jPGZYoVli\npQ57cB1THj/juYFYMS7dlJ3hr0pDo6Vw30L6EcE63dvXzJvhOfPXtFufdfanPiey\nUSICtAECgYEA/qP7ZJ9ohqg4D5v9TM4fVlUpo68/jMaWlPPoLQwNXZ81rTN4yOxm\nUJLhDvQCWYZie1jwn9+UA1bdp4PceSbEWh4iM0h4TcxmhHmos6pxGYb/uw6jGLw4\nqjCqDP69/Jgmkfobs4u/h9xtZEHo6u5rrbDZIu0EezL7ArMrSOYVRsMCgYEAvh5K\n4H5EVMhiHnjvbpToOzGjMpqoBr0XSq63Cx45U5on5Bp8oc/iQPnCzpwcrJb4vwRV\nVYYtD/PWpdjzhTVy6SgVnkTKoo6N/Y9vFAYCf67eb4Yu4L8MonlYU2IY7bA3SChw\nesHlwsVZdlNqieWmOuacA8IbgXW4ftbtZDzBuOkCgYEArA8rn+simtJxxwJVHp+s\nhw5Wa3bQDxRkzVMdz8p0AY3BnD3KYKFz5P/KOOth5xIp20TWmoBdKAB7F2S/BdHP\nHUF9RH+0YoU5xEvcVUJW17PjeobCZ8VO2Ji3Xr6Gq3Y3oa2JKEHGckvcUsFCW/Qs\nKBn2LmZO/9wLxeBA4CovuDcCgYAVGTWEDl807Xv+F7uykPHox8xtrD4jaU6xagxE\nPplsDrqIlOvp5TEdttoIpciE2shGIov5zscncw8KHrZ/vPvApkMn6kh2m81kK0vP\ndA9I7jYfOEvxgyI60a6cqlFL53drGZnJ9cSyxcX03LMBFKxK8xazUBJPXqoX4XA8\n5IU3KQKBgQDCPVBZbZcwcfI+fGRZX8DLE61tscK1uy0ySQPmz/tm3ixDAdQNgGvD\nXjyPvMCEtHx7+ZbykLS7SJZG4924LKyGxF9bw5AYTPyxietOUfoqaS8v3kJ03Ebu\nkVDmZkAiMk5E+oGchYsD613QRFjF4nlmrHfxtRqTPqa/OpNDimdG+w==\n-----END RSA PRIVATE KEY-----" } } status = 200 else body = { "error" => { "errors" => [ { "domain" => "global", "reason" => "notAuthorized", "message" => "The client is not authorized to make this request." } ], "code" => 403, "message" => "The client is not authorized to make this request." } } status = 403 end build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/get_instance.rb0000644000004100000410000000237313145731036024043 0ustar www-datawww-datamodule Fog module Google class SQL ## # Retrieves a resource containing information about a Cloud SQL instance # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/instances/get class Real def get_instance(instance_id) api_method = @sql.instances.get parameters = { "project" => @project, "instance" => instance_id } request(api_method, parameters) end end class Mock def get_instance(instance_id) if data[:instances].key?(instance_id) body = data[:instances][instance_id] status = 200 else body = { "error" => { "errors" => [ { "domain" => "global", "reason" => "notAuthorized", "message" => "The client is not authorized to make this request." } ], "code" => 403, "message" => "The client is not authorized to make this request." } } status = 403 end build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/get_backup_run.rb0000644000004100000410000000144113145731036024363 0ustar www-datawww-datamodule Fog module Google class SQL ## # Retrieves a resource containing information about a backup run # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/backupRuns/get class Real def get_backup_run(instance_id, backup_configuration_id, due_time) api_method = @sql.backup_runs.get parameters = { "project" => @project, "instance" => instance_id, "backupConfiguration" => backup_configuration_id, "dueTime" => due_time } request(api_method, parameters) end end class Mock def get_backup_run(_instance_id, _backup_configuration_id, _due_time) Fog::Mock.not_implemented end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/import_instance.rb0000644000004100000410000000314113145731036024570 0ustar www-datawww-datamodule Fog module Google class SQL ## # Imports data into a Cloud SQL instance from a MySQL dump file in Google Cloud Storage # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/instances/import class Real def import_instance(instance_id, uri, options = {}) api_method = @sql.instances.import parameters = { "project" => @project, "instance" => instance_id } body = { "importContext" => { "kind" => 'sql#importContext', "uri" => Array(uri), "database" => options[:database] } } request(api_method, parameters, body) end end class Mock def import_instance(instance_id, _uri, _options = {}) operation = random_operation data[:operations][instance_id] ||= {} data[:operations][instance_id][operation] = { "kind" => 'sql#instanceOperation', "instance" => instance_id, "operation" => operation, "operationType" => "IMPORT", "state" => Fog::Google::SQL::Operation::DONE_STATE, "userEmailAddress" => "google_client_email@developer.gserviceaccount.com", "enqueuedTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "endTime" => Time.now.iso8601 } body = { "kind" => 'sql#instancesImport', "operation" => operation } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/list_instances.rb0000644000004100000410000000130613145731036024415 0ustar www-datawww-datamodule Fog module Google class SQL ## # Lists instances under a given project in the alphabetical order of the instance name # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/instances/list class Real def list_instances api_method = @sql.instances.list parameters = { "project" => @project } request(api_method, parameters) end end class Mock def list_instances body = { "kind" => 'sql#instancesList', "items" => data[:instances].values } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/insert_instance.rb0000644000004100000410000001711513145731036024570 0ustar www-datawww-datamodule Fog module Google class SQL ## # Creates a new Cloud SQL instance # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/instances/insert class Real def insert_instance(name, tier, options = {}) api_method = @sql.instances.insert parameters = { "project" => @project } body = { "project" => @project, "instance" => name, "settings" => { "tier" => tier } } body["region"] = options[:region] if options[:region] if options[:activation_policy] body["settings"]["activationPolicy"] = options[:activation_policy] end if options[:autorized_gae_applications] body["settings"]["authorizedGaeApplications"] = Array(options[:autorized_gae_applications]) end if options[:backup_configuration] body["settings"]["backupConfiguration"] = options[:backup_configuration] end if options[:ip_configuration_authorized_networks] body["settings"]["ipConfiguration"] ||= {} body["settings"]["ipConfiguration"]["authorizedNetworks"] = Array(options[:ip_configuration_authorized_networks]) end if options[:ip_configuration_enabled] body["settings"]["ipConfiguration"] ||= {} body["settings"]["ipConfiguration"]["enabled"] = options[:ip_configuration_enabled] end if options[:ip_configuration_require_ssl] body["settings"]["ipConfiguration"] ||= {} body["settings"]["ipConfiguration"]["requireSsl"] = options[:ip_configuration_require_ssl] end if options[:location_preference_zone_follow_gae_application] body["settings"]["locationPreference"] ||= {} body["settings"]["locationPreference"]["followGaeApplication"] = options[:location_preference_zone_follow_gae_application] end if options[:location_preference_zone] body["settings"]["locationPreference"] ||= {} body["settings"]["locationPreference"]["zone"] = options[:location_preference_zone] end if options[:pricing_plan] body["settings"]["pricingPlan"] = options[:pricing_plan] end if options[:replication_type] body["settings"]["replicationType"] = options[:replication_type] end request(api_method, parameters, body) end end class Mock def insert_instance(name, tier, options = {}) data = { "kind" => 'sql#instance', "instance" => name, "etag" => Fog::Mock.random_base64(32), "project" => @project, "state" => Fog::Google::SQL::Instance::RUNNABLE_STATE, "databaseVersion" => "MYSQL_5_5", "region" => options[:region] || "us-central", "currentDiskSize" => "86245269", "maxDiskSize" => "268435456000", "settings" => { "kind" => 'sql#settings', "settingsVersion" => "1", "tier" => tier, "backupConfiguration" => [ { "kind" => 'sql#backupConfiguration', "startTime" => "04:00", "enabled" => false, "id" => Fog::Mock.random_hex(32), "binaryLogEnabled" => false } ], "pricingPlan" => options[:pricing_plan] || "PER_USE", "replicationType" => options[:replication_type] || "SYNCHRONOUS", "activationPolicy" => options[:activation_policy] || "ON_DEMAND", "ipConfiguration" => { "enabled" => false }, "locationPreference" => { "kind" => 'sql#locationPreference' } }, "serverCaCert" => { "kind" => 'sql#sslCert', "instance" => name, "sha1Fingerprint" => Fog::Mock.random_hex(40), "commonName" => 'C=US,O=Google\\, Inc,CN=Google Cloud SQL Server CA', "certSerialNumber" => "0", "cert" => "-----BEGIN CERTIFICATE-----\nMIIDITCCAgmgAwIBAgIBADANBgkqhkiG9w0BAQUFADBIMSMwIQYDVQQDExpHb29n\nbGUgQ2xvdWQgU1FMIFNlcnZlciBDQTEUMBIGA1UEChMLR29vZ2xlLCBJbmMxCzAJ\nBgNVBAYTAlVTMB4XDTE0MDYwNDA1MjkxMVoXDTI0MDYwMTA1MjkxMVowSDEjMCEG\nA1UEAxMaR29vZ2xlIENsb3VkIFNRTCBTZXJ2ZXIgQ0ExFDASBgNVBAoTC0dvb2ds\nZSwgSW5jMQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\nggEBALlRjq3zccH5ed6NMfCFcTYd9XxYXyvLurxxjDIA6A7/ymVM9qdQC0uckf7C\nsi4uMi2yfK+PHZ0jXC+g0uPx5RTm+nbKl4I++VOh2g6oZHeNdFt4rVJpr+jzGUMf\nr67SymUr70TQOTEVpx2Ud3rBB2szulxWUSXEy2AGA3uNUGe/IgENh7p56s00Sr97\nTRP1S5/JVMalncgNVLH2nNqBQJZTx9t9qvGatoUfmHUU0+M//J5sXLbgdzeEeeot\nHJUyoXjA2sRkH1+F/d6PpFrcr1I8dVmCBEbTAnm7HpKh5Mx2nRYi+t/y9D2Mblwx\n9dBRfr3WIJ1JDxzt3L8CtBGZbvUCAwEAAaMWMBQwEgYDVR0TAQH/BAgwBgEB/wIB\nADANBgkqhkiG9w0BAQUFAAOCAQEAmHuBecPc265sbd26B1HXUAD6FHdzoZLrAZVW\n+1eIK4E669P4y6LkLuoCkLd64/YwA4K2FioksqgHOahbYWJJYPymy4ae+IPXzXcY\nPv3gmBsKk++sHb64D9Cj/k5n8BEiVmmrsUCUiL75nJAzK+El3hvKKWWl76XX/qHP\nk8ZAxIrn8bCiVOaj6NR4+p1OmcZSPNWxz7j/EwQxoABRxgPgt+B/YRseevww7an2\n/rGs0sk7RE0QDjLfZblYGh+xVPBBLuLmf4L5JNJkFEoeGSWrxTzvXnS+2LZeHdM/\nJ9nsiKu5JKPhMUS0vOcTymOkh8tJ6Np8gwg6ca4g6dT3llE6uQ==\n-----END CERTIFICATE-----", "createTime" => Time.now.iso8601, "expirationTime" => Time.now.iso8601 } } if options[:autorized_gae_applications] data["settings"]["authorizedGaeApplications"] = Array(options[:autorized_gae_applications]) end if options[:backup_configuration] data["settings"]["backupConfiguration"] = options[:backup_configuration] end if options[:ip_configuration_authorized_networks] data["settings"]["ipConfiguration"]["authorizedNetworks"] = Array(options[:ip_configuration_authorized_networks]) end if options[:ip_configuration_enabled] data["settings"]["ipConfiguration"]["enabled"] = options[:ip_configuration_enabled] end if options[:ip_configuration_require_ssl] data["settings"]["ipConfiguration"]["requireSsl"] = options[:ip_configuration_require_ssl] end if options[:location_preference_zone_follow_gae_application] data["settings"]["locationPreference"]["followGaeApplication"] = options[:location_preference_zone_follow_gae_application] end if options[:location_preference_zone] data["settings"]["locationPreference"]["zone"] = options[:location_preference_zone] end self.data[:instances][name] = data self.data[:ssl_certs][name] = {} self.data[:backup_runs][name] = {} operation = random_operation self.data[:operations][name] ||= {} self.data[:operations][name][operation] = { "kind" => 'sql#instanceOperation', "instance" => name, "operation" => operation, "operationType" => "CREATE", "state" => Fog::Google::SQL::Operation::DONE_STATE, "userEmailAddress" => "google_client_email@developer.gserviceaccount.com", "enqueuedTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "endTime" => Time.now.iso8601 } body = { "kind" => 'sql#instancesInsert', "operation" => operation } status = 200 build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/list_backup_runs.rb0000644000004100000410000000147113145731036024745 0ustar www-datawww-datamodule Fog module Google class SQL ## # Lists all backup runs associated with a given instance and configuration in the # reverse chronological order of the enqueued time # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/backupRuns/list class Real def list_backup_runs(instance_id, backup_configuration_id) api_method = @sql.backup_runs.list parameters = { "project" => @project, "instance" => instance_id, "backupConfiguration" => backup_configuration_id } request(api_method, parameters) end end class Mock def list_backup_runs(_instance_id, _backup_configuration_id) Fog::Mock.not_implemented end end end end end fog-google-0.5.3/lib/fog/google/requests/sql/list_flags.rb0000644000004100000410000001105113145731036023520 0ustar www-datawww-datamodule Fog module Google class SQL ## # List all available database flags for Google Cloud SQL instances # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/flags/list class Real def list_flags api_method = @sql.flags.list parameters = {} request(api_method, parameters) end end class Mock def list_flags body = { "kind" => 'sql#flagsList', "items" => [ { "kind" => 'sql#flag', "name" => "log_output", "type" => "STRING", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6), "allowedStringValues" => %w(TABLE NONE) }, { "kind" => 'sql#flag', "name" => "general_log", "type" => "BOOLEAN", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6) }, { "kind" => 'sql#flag', "name" => "log_queries_not_using_indexes", "type" => "BOOLEAN", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6) }, { "kind" => 'sql#flag', "name" => "log_bin_trust_function_creators", "type" => "BOOLEAN", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6) }, { "kind" => 'sql#flag', "name" => "slow_query_log", "type" => "BOOLEAN", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6) }, { "kind" => 'sql#flag', "name" => "read_only", "type" => "BOOLEAN", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6) }, { "kind" => 'sql#flag', "name" => "max_allowed_packet", "type" => "INTEGER", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6), "minValue" => "16384", "maxValue" => "1073741824" }, { "kind" => 'sql#flag', "name" => "long_query_time", "type" => "INTEGER", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6), "minValue" => "0", "maxValue" => "30000000" }, { "kind" => 'sql#flag', "name" => "group_concat_max_len", "type" => "INTEGER", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6), "minValue" => "4", "maxValue" => "17179869184" }, { "kind" => 'sql#flag', "name" => "wait_timeout", "type" => "INTEGER", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6), "minValue" => "1", "maxValue" => "31536000" }, { "kind" => 'sql#flag', "name" => "innodb_lock_wait_timeout", "type" => "INTEGER", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6), "minValue" => "1", "maxValue" => "1073741824" }, { "kind" => 'sql#flag', "name" => "lower_case_table_names", "type" => "INTEGER", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6), "minValue" => "0", "maxValue" => "2" }, { "kind" => 'sql#flag', "name" => "innodb_flush_log_at_trx_commit", "type" => "INTEGER", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6), "minValue" => "0", "maxValue" => "2" }, { "kind" => 'sql#flag', "name" => "skip_show_database", "type" => "NONE", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6) }, { "kind" => 'sql#flag', "name" => "event_scheduler", "type" => "BOOLEAN", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6) }, { "kind" => 'sql#flag', "name" => "character_set_server", "type" => "STRING", "appliesTo" => %w(MYSQL_5_5 MYSQL_5_6), "allowedStringValues" => %w(utf8 utf8mb4) } ] } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/google/requests/pubsub/0000755000004100000410000000000013145731036021547 5ustar www-datawww-datafog-google-0.5.3/lib/fog/google/requests/pubsub/list_topics.rb0000644000004100000410000000165413145731036024436 0ustar www-datawww-datamodule Fog module Google class Pubsub class Real # Gets a list of all topics for a given project. # # @param_name project [#to_s] Project path to list topics under; must # be a project url prefix (e.g. 'projects/my-project'). If nil, the # project configured on the client is used. # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/list def list_topics(project = nil) api_method = @pubsub.projects.topics.list parameters = { "project" => (project.nil? ? "projects/#{@project}" : project.to_s) } request(api_method, parameters) end end class Mock def list_topics(_project = nil) body = { "topics" => data[:topics].values } status = 200 build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/pubsub/delete_topic.rb0000644000004100000410000000130113145731036024527 0ustar www-datawww-datamodule Fog module Google class Pubsub class Real # Delete a topic on the remote service. # # @param topic_name [#to_s] name of topic to delete # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/delete def delete_topic(topic_name) api_method = @pubsub.projects.topics.delete parameters = { "topic" => topic_name.to_s } request(api_method, parameters) end end class Mock def delete_topic(topic_name) data[:topics].delete(topic_name) status = 200 build_excon_response(nil, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/pubsub/acknowledge_subscription.rb0000644000004100000410000000246413145731036027171 0ustar www-datawww-datamodule Fog module Google class Pubsub class Real # Acknowledges a message received from a subscription. # # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/acknowledge def acknowledge_subscription(subscription, ack_ids) api_method = @pubsub.projects.subscriptions.acknowledge parameters = { "subscription" => subscription.to_s } body = { "ackIds" => ack_ids } request(api_method, parameters, body) end end class Mock def acknowledge_subscription(subscription, ack_ids) unless data[:subscriptions].key?(subscription) subscription_resource = subscription.to_s.split("/")[-1] body = { "error" => { "code" => 404, "message" => "Resource not found (resource=#{subscription_resource}).", "status" => "NOT_FOUND" } } status = 404 return build_excon_response(body, status) end sub = data[:subscriptions][subscription] sub[:messages].delete_if { |msg| ack_ids.member?(msg["messageId"]) } build_excon_response(nil, 200) end end end end end fog-google-0.5.3/lib/fog/google/requests/pubsub/delete_subscription.rb0000644000004100000410000000140213145731036026137 0ustar www-datawww-datamodule Fog module Google class Pubsub class Real # Delete a subscription on the remote service. # # @param subscription_name [#to_s] name of subscription to delete # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/delete def delete_subscription(subscription_name) api_method = @pubsub.projects.subscriptions.delete parameters = { "subscription" => subscription_name.to_s } request(api_method, parameters) end end class Mock def delete_subscription(subscription_name) data[:subscriptions].delete(subscription_name) build_excon_response(nil, 200) end end end end end fog-google-0.5.3/lib/fog/google/requests/pubsub/get_topic.rb0000644000004100000410000000211113145731036024044 0ustar www-datawww-datamodule Fog module Google class Pubsub class Real # Retrieves a resource describing a topic. # # @param topic_name [#to_s] name of topic to retrieve # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/get def get_topic(topic_name) api_method = @pubsub.projects.topics.get parameters = { "topic" => topic_name.to_s } request(api_method, parameters) end end class Mock def get_topic(topic_name) if !data[:topics].key?(topic_name) topic_resource = topic_name.split("/")[-1] body = { "error" => { "code" => 404, "message" => "Resource not found (resource=#{topic_resource}).", "status" => "NOT_FOUND" } } status = 404 else body = data[:topics][topic_name].clone status = 200 end build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/pubsub/create_topic.rb0000644000004100000410000000163413145731036024541 0ustar www-datawww-datamodule Fog module Google class Pubsub class Real # Create a topic on the remote service. # # @param topic_name [#to_s] name of topic to create; note that it must # obey the naming rules for a topic (e.g. # 'projects/myProject/topics/my_topic') # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/create def create_topic(topic_name) api_method = @pubsub.projects.topics.create parameters = { "name" => topic_name.to_s } request(api_method, parameters) end end class Mock def create_topic(topic_name) data = { "name" => topic_name } self.data[:topics][topic_name] = data body = data.clone status = 200 build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/pubsub/get_subscription.rb0000644000004100000410000000243713145731036025465 0ustar www-datawww-datamodule Fog module Google class Pubsub class Real # Retrieves a subscription by name from the remote service. # # @param subscription_name [#to_s] name of subscription to retrieve # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/get def get_subscription(subscription_name) api_method = @pubsub.projects.subscriptions.get parameters = { "subscription" => subscription_name.to_s } request(api_method, parameters) end end class Mock def get_subscription(subscription_name) sub = data[:subscriptions][subscription_name] if sub.nil? subscription_resource = subscription_name.split("/")[-1] body = { "error" => { "code" => 404, "message" => "Resource not found (resource=#{subscription_resource}).", "status" => "NOT_FOUND" } } return build_excon_response(body, 404) end body = sub.select do |k, _| %w(name topic pushConfig ackDeadlineSeconds).include?(k) end status = 200 build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/pubsub/publish_topic.rb0000644000004100000410000000346613145731036024751 0ustar www-datawww-datamodule Fog module Google class Pubsub class Real # Publish a list of messages to a topic. # # @param messages [Array] List of messages to be published to a # topic; each hash should have a value defined for 'data' or for # 'attributes' (or both). Note that the value associated with 'data' # must be base64 encoded. # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/publish def publish_topic(topic, messages) api_method = @pubsub.projects.topics.publish parameters = { "topic" => topic } body = { "messages" => messages } request(api_method, parameters, body) end end class Mock def publish_topic(topic, messages) if data[:topics].key?(topic) published_messages = messages.map do |msg| msg.merge("messageId" => Fog::Mock.random_letters(16), "publishTime" => Time.now.iso8601) end # Gather the subscriptions and publish data[:subscriptions].values.each do |sub| next unless sub["topic"] == topic sub[:messages] += published_messages end body = { "messageIds" => published_messages.map { |msg| msg["messageId"] } } status = 200 else topic_resource = topic_name.split("/")[-1] body = { "error" => { "code" => 404, "message" => "Resource not found (resource=#{topic_resource}).", "status" => "NOT_FOUND" } } status = 404 end build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/pubsub/create_subscription.rb0000644000004100000410000000417413145731036026151 0ustar www-datawww-datamodule Fog module Google class Pubsub class Real # Create a subscription resource on a topic. # # @param subscription_name [#to_s] name of the subscription to create. # Note that it must follow the restrictions of subscription names; # specifically it must be named within a project (e.g. # "projects/my-project/subscriptions/my-subscripton") # @param topic [Topic, #to_s] topic instance or name of topic to create # subscription on # @param push_config [Hash] configuration for a push config (if empty # hash, then no push_config is created) # @param ack_deadline_seconds [Number] how long the service waits for # an acknowledgement before redelivering the message; if nil then # service default of 10 is used # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/create def create_subscription(subscription_name, topic, push_config = {}, ack_deadline_seconds = nil) api_method = @pubsub.projects.subscriptions.create parameters = {} parameters["name"] = subscription_name.to_s unless subscription_name.nil? body = { "topic" => (topic.is_a?(Topic) ? topic.name : topic.to_s) } if push_config && push_config.any? body["pushConfig"] = push_config end body["ackDeadlineSeconds"] = ack_deadline_seconds unless ack_deadline_seconds.nil? request(api_method, parameters, body) end end class Mock def create_subscription(subscription_name, topic, push_config = {}, ack_deadline_seconds = nil) subscription = { "name" => subscription_name, "topic" => topic, "pushConfig" => push_config, "ackDeadlineSeconds" => ack_deadline_seconds } # We also track pending messages data[:subscriptions][subscription_name] = subscription.merge(:messages => []) build_excon_response(subscription, 200) end end end end end fog-google-0.5.3/lib/fog/google/requests/pubsub/pull_subscription.rb0000644000004100000410000000573313145731036025664 0ustar www-datawww-datamodule Fog module Google class Pubsub class Real # Pulls from a subscription. If option 'return_immediately' is # false, then this method blocks until one or more messages is # available or the remote server closes the connection. # # @param subscription [Subscription, #to_s] subscription instance or # name of subscription to pull from # @param options [Hash] options to modify the pull request # @option options [Boolean] :return_immediately if true, method returns # after API call; otherwise the connection is held open until # messages are available or the remote server closes the connection # (defaults to true) # @option options [Number] :max_messages maximum number of messages to # retrieve (defaults to 10) # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/pull def pull_subscription(subscription, options = { :return_immediately => true, :max_messages => 10 }) api_method = @pubsub.projects.subscriptions.pull parameters = { "subscription" => Fog::Google::Pubsub.subscription_name(subscription) } body = { "returnImmediately" => options[:return_immediately], "maxMessages" => options[:max_messages] } request(api_method, parameters, body) end end class Mock def pull_subscription(subscription, options = { :return_immediately => true, :max_messages => 10 }) # We're going to ignore return_immediately; feel free to add support # if you need it for testing subscription_name = Fog::Google::Pubsub.subscription_name(subscription) sub = data[:subscriptions][subscription_name] if sub.nil? subscription_resource = subscription_name.split("/")[-1] body = { "error" => { "code" => 404, "message" => "Resource not found (resource=#{subscription_resource}).", "status" => "NOT_FOUND" } } return build_excon_response(body, 404) end # This implementation is a bit weak; instead of "hiding" messages for # some period of time after they are pulled, instead we always return # them until acknowledged. This might cause issues with clients that # refuse to acknowledge. # # Also, note that here we use the message id as the ack id - again, # this might cause problems with some strange-behaving clients. msgs = sub[:messages].take(options[:max_messages]).map do |msg| { "ackId" => msg["messageId"], "message" => msg } end body = { "receivedMessages" => msgs } status = 200 build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/pubsub/list_subscriptions.rb0000644000004100000410000000232013145731036026033 0ustar www-datawww-datamodule Fog module Google class Pubsub class Real # Gets a list of all subscriptions for a given project. # # @param_name project [#to_s] Project path to list subscriptions under; # must be a project url prefix (e.g. 'projects/my-project'). If nil, # the project configured on the client is used. # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.topics/list def list_subscriptions(project = nil) api_method = @pubsub.projects.subscriptions.list parameters = { "project" => (project.nil? ? "projects/#{@project}" : project.to_s) } request(api_method, parameters) end end class Mock def list_subscriptions(_project = nil) subs = data[:subscriptions].values.map do |sub| # Filter out any keys that aren't part of the response object sub.select do |k, _| %w(name topic pushConfig ackDeadlineSeconds).include?(k) end end body = { "subscriptions" => subs } status = 200 build_excon_response(body, status) end end end end end fog-google-0.5.3/lib/fog/google/requests/monitoring/0000755000004100000410000000000013145731036022434 5ustar www-datawww-datafog-google-0.5.3/lib/fog/google/requests/monitoring/list_timeseries_descriptors.rb0000644000004100000410000000710113145731036030605 0ustar www-datawww-datamodule Fog module Google class Monitoring ## # List the descriptors of the time series that match the metric and labels values and that have data points # in the interval. # # @see https://developers.google.com/cloud-monitoring/v2beta1/timeseriesDescriptors/list class Real def list_timeseries_descriptors(metric, youngest, options = {}) api_method = @monitoring.timeseries_descriptors.list parameters = { "project" => @project, "metric" => metric, "youngest" => youngest } parameters["count"] = options[:count] if options.key?(:count) parameters["labels"] = options[:labels] if options.key?(:labels) parameters["oldest"] = options[:oldest] if options.key?(:oldest) parameters["pageToken"] = options[:page_token] if options.key?(:page_token) parameters["timespan"] = options[:timespan] if options.key?(:timespan) request(api_method, parameters) end end class Mock def list_timeseries_descriptors(metric, youngest, _options = {}) body = { "kind" => 'cloudmonitoring#listTimeseriesDescriptorsResponse', "youngest" => youngest, "oldest" => youngest, "timeseries" => [ { "project" => @project, "metric" => metric, "labels" => { "cloud.googleapis.com/service" => "compute.googleapis.com", "compute.googleapis.com/resource_type" => "instance", "cloud.googleapis.com/location" => "us-central1-a", "compute.googleapis.com/resource_id" => Fog::Mock.random_numbers(20).to_s, "compute.googleapis.com/instance_name" => Fog::Mock.random_hex(40) } }, { "project" => @project, "metric" => metric, "labels" => { "cloud.googleapis.com/service" => "compute.googleapis.com", "compute.googleapis.com/resource_type" => "instance", "cloud.googleapis.com/location" => "us-central1-a", "compute.googleapis.com/resource_id" => Fog::Mock.random_numbers(20).to_s, "compute.googleapis.com/instance_name" => Fog::Mock.random_hex(40) } }, { "project" => @project, "metric" => metric, "labels" => { "cloud.googleapis.com/service" => "compute.googleapis.com", "compute.googleapis.com/resource_type" => "instance", "cloud.googleapis.com/location" => "us-central1-a", "compute.googleapis.com/resource_id" => Fog::Mock.random_numbers(20).to_s, "compute.googleapis.com/instance_name" => Fog::Mock.random_hex(40) } }, { "project" => @project, "metric" => metric, "labels" => { "cloud.googleapis.com/service" => "compute.googleapis.com", "compute.googleapis.com/resource_type" => "instance", "cloud.googleapis.com/location" => "us-central1-a", "compute.googleapis.com/resource_id" => Fog::Mock.random_numbers(20).to_s, "compute.googleapis.com/instance_name" => Fog::Mock.random_hex(40) } } ] } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/google/requests/monitoring/list_metric_descriptors.rb0000644000004100000410000002323213145731036027722 0ustar www-datawww-datamodule Fog module Google class Monitoring ## # List metric descriptors that match the query. If the query is not set, then all of the metric descriptors # will be returned. # # @see https://cloud.google.com/monitoring/v2beta2/metricDescriptors/list class Real def list_metric_descriptors(options = {}) api_method = @monitoring.metric_descriptors.list parameters = { "project" => @project } parameters["count"] = options[:count] if options.key?(:count) parameters["pageToken"] = options[:page_token] if options.key?(:page_token) parameters["query"] = options[:query] if options.key?(:query) request(api_method, parameters) end end class Mock def list_metric_descriptors(_options = {}) body = { "kind" => 'cloudmonitoring#listMetricDescriptorsResponse', "metrics" => [ { "name" => "compute.googleapis.com/instance/cpu/reserved_cores", "project" => @project, "labels" => [ { "key" => "compute.googleapis.com/instance_name" }, { "key" => "cloud.googleapis.com/location" }, { "key" => "compute.googleapis.com/resource_id" }, { "key" => "compute.googleapis.com/resource_type" }, { "key" => "cloud.googleapis.com/service" } ], "typeDescriptor" => { "metricType" => "gauge", "valueType" => "double" }, "description" => "Number of cores reserved on the host of the instance." }, { "name" => "compute.googleapis.com/instance/cpu/usage_time", "project" => @project, "labels" => [ { "key" => "compute.googleapis.com/instance_name" }, { "key" => "cloud.googleapis.com/location" }, { "key" => "compute.googleapis.com/resource_id" }, { "key" => "compute.googleapis.com/resource_type" }, { "key" => "cloud.googleapis.com/service" } ], "typeDescriptor" => { "metricType" => "delta", "valueType" => "double" }, "description" => "Delta CPU usage time. Units are seconds. You can get the per-core CPU utilization ratio by performing a rate operation on a point: doubleValue/(end-start), then divide by compute.googleapis.com/instance/cpu/reserved_cores at the corresponding end timestamp." }, { "name" => "compute.googleapis.com/instance/disk/read_bytes_count", "project" => @project, "labels" => [ { "key" => "compute.googleapis.com/instance_name" }, { "key" => "compute.googleapis.com/device_name" }, { "key" => "compute.googleapis.com/device_type" }, { "key" => "cloud.googleapis.com/location" }, { "key" => "compute.googleapis.com/resource_id" }, { "key" => "compute.googleapis.com/resource_type" }, { "key" => "cloud.googleapis.com/service" } ], "typeDescriptor" => { "metricType" => "delta", "valueType" => "int64" }, "description" => "Delta count of bytes read from disk." }, { "name" => "compute.googleapis.com/instance/disk/read_ops_count", "project" => @project, "labels" => [ { "key" => "compute.googleapis.com/instance_name" }, { "key" => "compute.googleapis.com/device_name" }, { "key" => "compute.googleapis.com/device_type" }, { "key" => "cloud.googleapis.com/location" }, { "key" => "compute.googleapis.com/resource_id" }, { "key" => "compute.googleapis.com/resource_type" }, { "key" => "cloud.googleapis.com/service" } ], "typeDescriptor" => { "metricType" => "delta", "valueType" => "int64" }, "description" => "Delta count of disk read IO operations." }, { "name" => "compute.googleapis.com/instance/disk/write_bytes_count", "project" => @project, "labels" => [ { "key" => "compute.googleapis.com/instance_name" }, { "key" => "compute.googleapis.com/device_name" }, { "key" => "compute.googleapis.com/device_type" }, { "key" => "cloud.googleapis.com/location" }, { "key" => '"compute.googleapis.com/resource_id' }, { "key" => "compute.googleapis.com/resource_type" }, { "key" => "cloud.googleapis.com/service" } ], "typeDescriptor" => { "metricType" => "delta", "valueType" => "int64" }, "description" => "Delta count of bytes written to disk." }, { "name" => "compute.googleapis.com/instance/disk/write_ops_count", "project" => @project, "labels" => [ { "key" => "compute.googleapis.com/instance_name" }, { "key" => "compute.googleapis.com/device_name" }, { "key" => '"compute.googleapis.com/device_type' }, { "key" => "cloud.googleapis.com/location" }, { "key" => "compute.googleapis.com/resource_id" }, { "key" => "compute.googleapis.com/resource_type" }, { "key" => "cloud.googleapis.com/service" } ], "typeDescriptor" => { "metricType" => "delta", "valueType" => "int64" }, "description" => "Delta count of disk write IO operations." }, { "name" => "compute.googleapis.com/instance/network/received_bytes_count", "project" => @project, "labels" => [ { "key" => "compute.googleapis.com/instance_name" }, { "key" => "compute.googleapis.com/loadbalanced" }, { "key" => "cloud.googleapis.com/location" }, { "key" => "compute.googleapis.com/resource_id" }, { "key" => "compute.googleapis.com/resource_type" }, { "key" => "cloud.googleapis.com/service" } ], "typeDescriptor" => { "metricType" => "delta", "valueType" => "int64" }, "description" => "Delta count of bytes received from network." }, { "name" => "compute.googleapis.com/instance/network/received_packets_count", "project" => @project, "labels" => [ { "key" => "compute.googleapis.com/instance_name" }, { "key" => "compute.googleapis.com/loadbalanced" }, { "key" => "cloud.googleapis.com/location" }, { "key" => "compute.googleapis.com/resource_id" }, { "key" => "compute.googleapis.com/resource_type" }, { "key" => "cloud.googleapis.com/service" } ], "typeDescriptor" => { "metricType" => "delta", "valueType" => "int64" }, "description" => "Delta count of packets received from network." }, { "name" => "compute.googleapis.com/instance/network/sent_bytes_count", "project" => @project, "labels" => [ { "key" => "compute.googleapis.com/instance_name" }, { "key" => "compute.googleapis.com/loadbalanced" }, { "key" => "cloud.googleapis.com/location" }, { "key" => "compute.googleapis.com/resource_id" }, { "key" => "compute.googleapis.com/resource_type" }, { "key" => "cloud.googleapis.com/service" } ], "typeDescriptor" => { "metricType" => "delta", "valueType" => "int64" }, "description" => "Delta count of bytes sent over network." }, { "name" => "compute.googleapis.com/instance/network/sent_packets_count", "project" => @project, "labels" => [ { "key" => "compute.googleapis.com/instance_name" }, { "key" => "compute.googleapis.com/loadbalanced" }, { "key" => "cloud.googleapis.com/location" }, { "key" => "compute.googleapis.com/resource_id" }, { "key" => "compute.googleapis.com/resource_type" }, { "key" => "cloud.googleapis.com/service" } ], "typeDescriptor" => { "metricType" => "delta", "valueType" => "int64" }, "description" => "Delta count of packets sent over network." }, { "name" => "compute.googleapis.com/instance/uptime", "project" => @project, "labels" => [ { "key" => "compute.googleapis.com/instance_name" }, { "key" => "cloud.googleapis.com/location" }, { "key" => "compute.googleapis.com/resource_id" }, { "key" => "compute.googleapis.com/resource_type" }, { "key" => "cloud.googleapis.com/service" } ], "typeDescriptor" => { "metricType" => "delta", "valueType" => "double" }, "description" => "Indicates the VM running time in seconds." } ] } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/google/requests/monitoring/list_timeseries.rb0000644000004100000410000000460613145731036026173 0ustar www-datawww-datamodule Fog module Google class Monitoring ## # List the data points of the time series that match the metric and labels values and that have data points # in the interval # # https://developers.google.com/cloud-monitoring/v2beta1/timeseries class Real def list_timeseries(metric, youngest, options = {}) api_method = @monitoring.timeseries.list parameters = { "project" => @project, "metric" => metric, "youngest" => youngest } parameters["count"] = options[:count] if options.key?(:count) parameters["labels"] = options[:labels] if options.key?(:labels) parameters["oldest"] = options[:oldest] if options.key?(:oldest) parameters["pageToken"] = options[:page_token] if options.key?(:page_token) parameters["timespan"] = options[:timespan] if options.key?(:timespan) request(api_method, parameters) end end class Mock def list_timeseries(metric, youngest, _options = {}) body = { "kind" => 'cloudmonitoring#listTimeseriesResponse', "youngest" => youngest, "oldest" => youngest, "timeseries" => [ { "timeseriesDesc" => { "project" => @project, "metric" => metric, "labels" => { "cloud.googleapis.com/service" => "compute.googleapis.com", "compute.googleapis.com/resource_type" => "instance", "cloud.googleapis.com/location" => "us-central1-a", "compute.googleapis.com/resource_id" => Fog::Mock.random_numbers(20).to_s, "compute.googleapis.com/instance_name" => Fog::Mock.random_hex(40) } }, "points" => [ { "start" => "2014-07-17T20:06:58.000Z", "end" => "2014-07-17T20:07:58.000Z", "doubleValue" => 60.0 }, { "start" => "2014-07-17T20:05:58.000Z", "end" => "2014-07-17T20:06:58.000Z", "doubleValue" => 60.0 } ] } ] } build_excon_response(body) end end end end end fog-google-0.5.3/lib/fog/google/shared.rb0000644000004100000410000002016513145731036020173 0ustar www-datawww-datamodule Fog module Google module Shared attr_reader :project, :api_version, :api_url ## # Initializes shared attributes # # @param [String] project Google Cloud Project # @param [String] api_version Google API version # @param [String] base_url Google API base url # @return [void] def shared_initialize(project, api_version, base_url) @project = project @api_version = api_version @api_url = base_url + api_version + "/projects/" end ## # Initializes the Google API Client # # @param [Hash] options Google API options # @option options [String] :google_client_email A @developer.gserviceaccount.com email address to use # @option options [String] :google_key_location The location of a pkcs12 key file # @option options [String] :google_key_string The content of the pkcs12 key file # @option options [String] :google_json_key_location The location of a JSON key file # @option options [String] :google_json_key_string The content of the JSON key file # @option options [String] :google_api_scope_url The access scope URLs # @option options [String] :app_name The app name to set in the user agent # @option options [String] :app_version The app version to set in the user agent # @option options [Google::APIClient] :google_client Existing Google API Client # @option options [Hash] :google_client_options A hash to send adition options to Google API Client # @return [Google::APIClient] Google API Client # @raises [ArgumentError] If there is any missing argument def initialize_google_client(options) # NOTE: loaded here to avoid requiring this as a core Fog dependency begin require "google/api_client" rescue LoadError => error Fog::Logger.warning("Please install the google-api-client gem before using this provider") raise error end # User can provide an existing Google API Client client = options[:google_client] return client unless client.nil? # Create a signing key signing_key = create_signing_key(options) # Validate required arguments unless options[:google_client_email] raise ArgumentError.new("Missing required arguments: google_client_email") end unless options[:google_api_scope_url] raise ArgumentError.new("Missing required arguments: google_api_scope_url") end # Create a new Google API Client new_pk12_google_client( options[:google_client_email], signing_key, options[:google_api_scope_url], options[:app_name], options[:app_version], options[:google_client_options] || {} ) end ## # Creates a Google signing key # def create_signing_key(options) if options[:google_json_key_location] || options[:google_json_key_string] if options[:google_json_key_location] json_key_location = File.expand_path(options[:google_json_key_location]) json_key = File.open(json_key_location, "r", &:read) else json_key = options[:google_json_key_string] end json_key_hash = Fog::JSON.decode(json_key) unless json_key_hash.key?("client_email") || json_key_hash.key?("private_key") raise ArgumentError.new("Invalid Google JSON key") end options[:google_client_email] = json_key_hash["client_email"] ::Google::APIClient::KeyUtils.load_from_pem(json_key_hash["private_key"], "notasecret") elsif options[:google_key_location] || options[:google_key_string] google_key = if options[:google_key_location] File.expand_path(options[:google_key_location]) else options[:google_key_string] end ::Google::APIClient::KeyUtils.load_from_pkcs12(google_key, "notasecret") else raise ArgumentError.new("Missing required arguments: google_key_location, google_key_string, " \ "google_json_key_location or google_json_key_string") end end ## # Create a Google API Client with a user email and a pkcs12 key # # @param google_client_email [String] A @developer.gserviceaccount.com. # email address to use # @param signing_key [OpenSSL::PKey] The private key for signing # @param google_api_scope_url [String] Access scope URLs # @param app_name [String] The app name to set in the user agent # @param app_version [String] The app version to set in the user agent # @param google_client_options [Hash] additional options to pass to the # underlying google client # @return [Google::APIClient] a newly-constructed Google API Client def new_pk12_google_client(google_client_email, signing_key, google_api_scope_url, app_name = nil, app_version = nil, google_client_options = {}) application_name = app_name.nil? ? "fog" : "#{app_name}/#{app_version || '0.0.0'} fog" api_client_options = { :application_name => application_name, :application_version => Fog::Google::VERSION }.merge(google_client_options) client = ::Google::APIClient.new(api_client_options) client.authorization = Signet::OAuth2::Client.new( :audience => "https://accounts.google.com/o/oauth2/token", :auth_provider_x509_cert_url => "https://www.googleapis.com/oauth2/v1/certs", :client_x509_cert_url => "https://www.googleapis.com/robot/v1/metadata/x509/#{google_client_email}", :issuer => google_client_email, :scope => google_api_scope_url, :signing_key => signing_key, :token_credential_uri => "https://accounts.google.com/o/oauth2/token" ) client.authorization.fetch_access_token! client end ## # Executes a request and wraps it in a result object # # @param [Google::APIClient::Method] api_method The method object or the RPC name of the method being executed # @param [Hash] parameters The parameters to send to the method # @param [Hash] body_object The body object of the request # @return [Excon::Response] The result from the API def request(api_method, parameters, body_object = nil, media = nil) client_parms = { :api_method => api_method, :parameters => parameters } # The Google API complains when given null values for enums, so just don't pass it any null fields # XXX It may still balk if we have a nested object, e.g.: # {:a_field => "string", :a_nested_field => { :an_empty_nested_field => nil } } client_parms[:body_object] = body_object.reject { |_k, v| v.nil? } if body_object client_parms[:media] = media if media result = @client.execute(client_parms) build_excon_response(result.body.nil? || result.body.empty? ? nil : Fog::JSON.decode(result.body), result.status) end ## # Builds an Excon response # # @param [Hash] Response body # @param [Integer] Response status # @return [Excon::Response] Excon response def build_excon_response(body, status = 200) response = Excon::Response.new(:body => body, :status => status) if body && body.key?("error") msg = "Google Cloud did not return an error message" if body["error"].is_a?(Hash) response.status = body["error"]["code"] if body["error"].key?("errors") msg = body["error"]["errors"].map { |error| error["message"] }.join(", ") elsif body["error"].key?("message") msg = body["error"]["message"] end elsif body["error"].is_a?(Array) msg = body["error"].map { |error| error["code"] }.join(", ") end case response.status when 404 raise Fog::Errors::NotFound.new(msg) else raise Fog::Errors::Error.new(msg) end end response end end end end fog-google-0.5.3/lib/fog/google/pubsub.rb0000644000004100000410000000342313145731036020223 0ustar www-datawww-datamodule Fog module Google class Pubsub < Fog::Service autoload :Mock, File.expand_path("../pubsub/mock", __FILE__) autoload :Real, File.expand_path("../pubsub/real", __FILE__) requires :google_project recognizes( :app_name, :app_version, :google_client, :google_client_email, :google_client_options, :google_json_key_location, :google_json_key_string, :google_key_location, :google_key_string ) GOOGLE_PUBSUB_API_VERSION = "v1".freeze GOOGLE_PUBSUB_BASE_URL = "https://www.googleapis.com/pubsub".freeze GOOGLE_PUBSUB_API_SCOPE_URLS = %w(https://www.googleapis.com/auth/pubsub).freeze ## # MODELS model_path "fog/google/models/pubsub" # Topic model :topic collection :topics # Subscription model :subscription collection :subscriptions # ReceivedMessage model :received_message ## # REQUESTS request_path "fog/google/requests/pubsub" # Topic request :list_topics request :get_topic request :create_topic request :delete_topic request :publish_topic # Subscription request :list_subscriptions request :get_subscription request :create_subscription request :delete_subscription request :pull_subscription request :acknowledge_subscription # Helper class for getting a subscription name # # @param subscription [Subscription, #to_s] subscription instance or name # of subscription # @return [String] name of subscription def self.subscription_name(subscription) subscription.is_a?(Subscription) ? subscription.name : subscription.to_s end end end end fog-google-0.5.3/lib/fog/google/mock.rb0000644000004100000410000000032113145731036017646 0ustar www-datawww-datamodule Fog module Google class Mock def self.etag hex(32) end def self.hex(length) max = ("f" * length).to_i(16) rand(max).to_s(16) end end end end fog-google-0.5.3/lib/fog/google/version.rb0000644000004100000410000000010213145731036020377 0ustar www-datawww-datamodule Fog module Google VERSION = "0.5.3".freeze end end fog-google-0.5.3/lib/fog/google/sql/0000755000004100000410000000000013145731036017173 5ustar www-datawww-datafog-google-0.5.3/lib/fog/google/sql/mock.rb0000644000004100000410000000156113145731036020454 0ustar www-datawww-datamodule Fog module Google class SQL class Mock include Fog::Google::Shared def initialize(options) shared_initialize(options[:google_project], GOOGLE_SQL_API_VERSION, GOOGLE_SQL_BASE_URL) end def self.data @data ||= Hash.new do |hash, key| hash[key] = { :backup_runs => {}, :instances => {}, :operations => {}, :ssl_certs => {} } end end def self.reset @data = nil end def data self.class.data[project] end def reset_data self.class.data.delete(project) end def random_operation "operation-#{Fog::Mock.random_numbers(13)}-#{Fog::Mock.random_hex(13)}-#{Fog::Mock.random_hex(8)}" end end end end end fog-google-0.5.3/lib/fog/google/sql/real.rb0000644000004100000410000000101113145731036020434 0ustar www-datawww-datamodule Fog module Google class SQL class Real include Fog::Google::Shared attr_accessor :client attr_reader :sql def initialize(options) shared_initialize(options[:google_project], GOOGLE_SQL_API_VERSION, GOOGLE_SQL_BASE_URL) options[:google_api_scope_url] = GOOGLE_SQL_API_SCOPE_URLS.join(" ") @client = initialize_google_client(options) @sql = @client.discovered_api("sqladmin", api_version) end end end end end fog-google-0.5.3/lib/fog/google/models/0000755000004100000410000000000013145731036017657 5ustar www-datawww-datafog-google-0.5.3/lib/fog/google/models/sql/0000755000004100000410000000000013145731036020456 5ustar www-datawww-datafog-google-0.5.3/lib/fog/google/models/sql/backup_runs.rb0000644000004100000410000000254113145731036023321 0ustar www-datawww-datarequire "fog/core/collection" require "fog/google/models/sql/backup_run" module Fog module Google class SQL class BackupRuns < Fog::Collection model Fog::Google::SQL::BackupRun ## # Lists all backup runs associated with a given instance and configuration # # @param [String] instance_id Instance ID # @param [String] backup_configuration_id Backup Configuration ID # @return [Array] List of Backup run resources def all(instance_id, backup_configuration_id) data = service.list_backup_runs(instance_id, backup_configuration_id).body["items"] || [] load(data) end ## # Retrieves a resource containing information about a backup run # # @param [String] instance_id Instance ID # @param [String] backup_configuration_id Backup Configuration ID # @param [String] due_time The time when this run is due to start in RFC 3339 format # @return [Fog::Google::SQL::BackupRun] Backup run resource def get(instance_id, backup_configuration_id, due_time) if backup_run = service.get_backup_run(instance_id, backup_configuration_id, due_time).body new(backup_run) end rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/google/models/sql/flag.rb0000644000004100000410000000110613145731036021712 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class SQL ## # A Google Cloud SQL service flag resource # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/flags class Flag < Fog::Model identity :name attribute :allowed_string_values, :aliases => "allowedStringValues" attribute :applies_to, :aliases => "appliesTo" attribute :kind attribute :max_value, :aliases => "maxValue" attribute :min_value, :aliases => "minValue" attribute :type end end end end fog-google-0.5.3/lib/fog/google/models/sql/operation.rb0000644000004100000410000000340213145731036023002 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class SQL ## # An Operation resource contains information about database instance operations # such as create, delete, and restart # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/operations class Operation < Fog::Model identity :operation attribute :end_time, :aliases => "endTime" attribute :enqueued_time, :aliases => "enqueuedTime" attribute :error attribute :export_context, :aliases => "exportContext" attribute :import_context, :aliases => "importContext" attribute :instance attribute :kind attribute :operation_type, :aliases => "operationType" attribute :start_time, :aliases => "startTime" attribute :state attribute :user_email_address, :aliases => "userEmailAddress" DONE_STATE = "DONE" PENDING_STATE = "PENDING" RUNNING_STATE = "RUNNING" UNKNOWN_STATE = "UNKNOWN" ## # Checks if the instance operation is pending # # @return [Boolean] True if the operation is pending; False otherwise def pending? state == PENDING_STATE end ## # Checks if the instance operation is done # # @return [Boolean] True if the operation is done; False otherwise def ready? state == DONE_STATE end ## # Reloads an instance operation # # @return [Fog::Google::SQL::Operation] Instance operation resource def reload requires :identity data = collection.get(instance, identity) merge_attributes(data.attributes) self end end end end end fog-google-0.5.3/lib/fog/google/models/sql/ssl_certs.rb0000644000004100000410000000330213145731036023002 0ustar www-datawww-datarequire "fog/core/collection" require "fog/google/models/sql/ssl_cert" module Fog module Google class SQL class SslCerts < Fog::Collection model Fog::Google::SQL::SslCert ## # Lists all of the current SSL certificates for the instance # # @param [String] instance_id Instance ID # @return [Array] List of SSL certificate resources def all(instance_id) data = [] begin data = service.list_ssl_certs(instance_id).body["items"] || [] rescue Fog::Errors::Error => e # Google SQL returns a 403 if we try to access a non-existing resource # The default behaviour in Fog is to return an empty Array raise e unless e.message == "The client is not authorized to make this request." end load(data) end ## # Retrieves a particular SSL certificate (does not include the private key) # # @param [String] instance_id Instance ID # @param [String] sha1_fingerprint Sha1 FingerPrint # @return [Fog::Google::SQL::SslCert] SSL certificate resource def get(instance_id, sha1_fingerprint) if ssl_cert = service.get_ssl_cert(instance_id, sha1_fingerprint).body new(ssl_cert) end rescue Fog::Errors::NotFound nil rescue Fog::Errors::Error => e # Google SQL returns a 403 if we try to access a non-existing resource # The default behaviour in Fog is to return a nil return nil if e.message == "The client is not authorized to make this request." raise e end end end end end fog-google-0.5.3/lib/fog/google/models/sql/backup_run.rb0000644000004100000410000000162613145731036023141 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class SQL ## # A database instance backup run resource # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/backupRuns class BackupRun < Fog::Model identity :backup_configuration, :aliases => "backupConfiguration" attribute :due_time, :aliases => "dueTime" attribute :end_time, :aliases => "endTime" attribute :enqueued_time, :aliases => "enqueuedTime" attribute :error attribute :instance attribute :kind attribute :start_time, :aliases => "startTime" attribute :status DONE_STATE = "DONE" ## # Checks if the instance backup run is done # # @return [Boolean] True if the backup run is done; False otherwise def ready? state == DONE_STATE end end end end end fog-google-0.5.3/lib/fog/google/models/sql/tier.rb0000644000004100000410000000067413145731036021755 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class SQL ## # A Google Cloud SQL service tier resource # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/tiers class Tier < Fog::Model identity :tier attribute :disk_quota, :aliases => "DiskQuota" attribute :kind attribute :ram, :aliases => "RAM" attribute :region end end end end fog-google-0.5.3/lib/fog/google/models/sql/flags.rb0000644000004100000410000000067513145731036022107 0ustar www-datawww-datarequire "fog/core/collection" require "fog/google/models/sql/flag" module Fog module Google class SQL class Flags < Fog::Collection model Fog::Google::SQL::Flag ## # List all available database flags # # @return [Array] List of flags def all data = service.list_flags.body["items"] || [] load(data) end end end end end fog-google-0.5.3/lib/fog/google/models/sql/tiers.rb0000644000004100000410000000067513145731036022141 0ustar www-datawww-datarequire "fog/core/collection" require "fog/google/models/sql/tier" module Fog module Google class SQL class Tiers < Fog::Collection model Fog::Google::SQL::Tier ## # Lists all available service tiers # # @return [Array] List of tiers def all data = service.list_tiers.body["items"] || [] load(data) end end end end end fog-google-0.5.3/lib/fog/google/models/sql/instances.rb0000644000004100000410000000213313145731036022771 0ustar www-datawww-datarequire "fog/core/collection" require "fog/google/models/sql/instance" module Fog module Google class SQL class Instances < Fog::Collection model Fog::Google::SQL::Instance ## # Lists all instance # # @return [Array] List of instance resources def all data = service.list_instances.body["items"] || [] load(data) end ## # Retrieves an instance # # @param [String] instance_id Instance ID # @return [Fog::Google::SQL::Instance] Instance resource def get(instance_id) if instance = service.get_instance(instance_id).body new(instance) end rescue Fog::Errors::NotFound nil rescue Fog::Errors::Error => e # Google SQL returns a 403 if we try to access a non-existing resource # The default behaviour in Fog is to return a nil return nil if e.message == "The client is not authorized to make this request." raise e end end end end end fog-google-0.5.3/lib/fog/google/models/sql/operations.rb0000644000004100000410000000333513145731036023172 0ustar www-datawww-datarequire "fog/core/collection" require "fog/google/models/sql/operation" module Fog module Google class SQL class Operations < Fog::Collection model Fog::Google::SQL::Operation ## # Lists all instance operations that have been performed on the given instance # # @param [String] instance_id Instance ID # @return [Array] List of instance operation resources def all(instance_id) data = [] begin data = service.list_operations(instance_id).body["items"] || [] rescue Fog::Errors::Error => e # Google SQL returns a 403 if we try to access a non-existing resource # The default behaviour in Fog is to return an empty Array raise e unless e.message == "The client is not authorized to make this request." end load(data) end ## # Retrieves an instance operation that has been performed on an instance # # @param [String] instance_id Instance ID # @param [String] operation_id Instance operation ID # @return [Fog::Google::SQL::Operation] Instance operation resource def get(instance_id, operation_id) if operation = service.get_operation(instance_id, operation_id).body new(operation) end rescue Fog::Errors::NotFound nil rescue Fog::Errors::Error => e # Google SQL returns a 403 if we try to access a non-existing resource # The default behaviour in Fog is to return a nil return nil if e.message == "The client is not authorized to make this request." raise e end end end end end fog-google-0.5.3/lib/fog/google/models/sql/ssl_cert.rb0000644000004100000410000000517413145731036022630 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class SQL ## # A SSL certificate resource # # @see https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/sslCerts class SslCert < Fog::Model identity :sha1_fingerprint, :aliases => "sha1Fingerprint" attribute :cert attribute :cert_serial_number, :aliases => "certSerialNumber" attribute :common_name, :aliases => "commonName" attribute :create_time, :aliases => "createTime" attribute :expiration_time, :aliases => "expirationTime" attribute :instance attribute :kind # These attributes are not available in the representation of a 'SSL Certificate' returned by the SQL API. # These attributes are only available as a reponse to a create operation attribute :server_ca_cert, :aliases => "serverCaCert" attribute :cert_private_key, :aliases => "certPrivateKey" ## # Deletes a SSL certificate. The change will not take effect until the instance is restarted. # # @param [Hash] options Method options # @option options [Boolean] :async If the operation must be performed asynchronously (true by default) # @return [Fog::Google::SQL::Operation] A Operation resource def destroy(options = {}) requires :instance, :identity data = service.delete_ssl_cert(instance, identity) operation = Fog::Google::SQL::Operations.new(:service => service).get(instance, data.body["operation"]) operation.wait_for { ready? } unless options.fetch(:async, true) operation end ## # Reloads a SSL certificate # # @return [Fog::Google::SQL::SslCert] SSL certificate resource def reload requires :instance, :identity data = collection.get(instance, identity) merge_attributes(data.attributes) self end ## # Creates a SSL certificate. The new certificate will not be usable until the instance is restarted. # # @raise [Fog::Errors::Error] If SSL certificate already exists def save requires :instance, :common_name raise Fog::Errors::Error.new("Resaving an existing object may create a duplicate") if persisted? data = service.insert_ssl_cert(instance, common_name).body merge_attributes(data["clientCert"]["certInfo"]) self.server_ca_cert = Fog::Google::SQL::SslCert.new(data["serverCaCert"]) self.cert_private_key = data["clientCert"]["certPrivateKey"] self end end end end end fog-google-0.5.3/lib/fog/google/models/sql/instance.rb0000644000004100000410000003224513145731036022615 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class SQL class Instance < Fog::Model identity :instance attribute :current_disk_size, :aliases => "currentDiskSize" attribute :database_version, :aliases => "databaseVersion" attribute :etag attribute :ip_addresses, :aliases => "ipAddresses" attribute :kind attribute :max_disk_size, :aliases => "maxDiskSize" attribute :project attribute :region attribute :server_ca_cert, :aliases => "serverCaCert" attribute :settings attribute :state # These attributes are not available in the representation of an 'Instance' returned by the Google SQL API. attribute :activation_policy attribute :autorized_gae_applications attribute :backup_configuration attribute :database_flags attribute :ip_configuration_authorized_networks attribute :ip_configuration_enabled attribute :ip_configuration_require_ssl attribute :location_preference_zone_follow_gae_application attribute :location_preference_zone attribute :pricing_plan attribute :replication_type attribute :settings_version attribute :tier MAINTENANCE_STATE = "MAINTENANCE" PENDING_CREATE_STATE = "PENDING_CREATE" RUNNABLE_STATE = "RUNNABLE" SUSPENDED_STATE = "SUSPENDED" UNKNOWN_STATE = "UNKNOWN_STATE" ## # Returns the activation policy for this instance # # @return [String] The activation policy for this instance def activation_policy settings["activationPolicy"] end ## # Returns the AppEngine app ids that can access this instance # # @return [Array] The AppEngine app ids that can access this instance def autorized_gae_applications settings["authorizedGaeApplications"] end ## # Returns the daily backup configuration for the instance # # @return [Array] The daily backup configuration for the instance def backup_configuration settings["backupConfiguration"] end ## # Creates a Cloud SQL instance as a clone of the source instance # # @param [String] destination_name Name of the Cloud SQL instance to be created as a clone # @param [Hash] options Method options # @option options [String] :log_filename Name of the binary log file for a Cloud SQL instance # @option options [Integer] :log_position Position (offset) within the binary log file # @option options [Boolean] :async If the operation must be performed asynchronously (true by default) # @return [Fog::Google::SQL::Operation] A Operation resource def clone(destination_name, options = {}) requires :identity data = service.clone_instance(identity, destination_name, options) operation = Fog::Google::SQL::Operations.new(:service => service).get(instance, data.body["operation"]) operation.wait_for { ready? } unless options.fetch(:async, true) operation end ## # Creates a Cloud SQL instance # # @return [Fog::Google::SQL::Instance] Instance resource def create requires :identity data = service.insert_instance(identity, attributes[:tier], attributes) operation = Fog::Google::SQL::Operations.new(:service => service).get(instance, data.body["operation"]) operation.wait_for { !pending? } reload end ## # Returns the database flags passed to the instance at startup # # @return [Array] The database flags passed to the instance at startup def database_flags settings["databaseFlags"] end ## # Deletes a Cloud SQL instance # # @param [Hash] options Method options # @option options [Boolean] :async If the operation must be performed asynchronously (true by default) # @return [Fog::Google::SQL::Operation] A Operation resource def destroy(options = {}) requires :identity data = service.delete_instance(identity) operation = Fog::Google::SQL::Operations.new(:service => service).get(instance, data.body["operation"]) unless options.fetch(:async, true) # DISABLED: A delete instance operation never reachs a 'DONE' state (bug?) # operation.wait_for { ready? } end operation end ## # Exports data from a Cloud SQL instance to a Google Cloud Storage bucket as a MySQL dump file # # @param [String] uri The path to the file in Google Cloud Storage where the export will be stored, # or where it was already stored # @param [Hash] options Method options # @option options [Array] :databases Databases (for example, guestbook) from which the export is made. # If unspecified, all databases are exported. # @option options [Array] :tables Tables to export, or that were exported, from the specified database. # If you specify tables, specify one and only one database. # @option options [Boolean] :async If the operation must be performed asynchronously (true by default) # @return [Fog::Google::SQL::Operation] A Operation resource def export(uri, options = {}) requires :identity data = service.export_instance(identity, uri, options) operation = Fog::Google::SQL::Operations.new(:service => service).get(instance, data.body["operation"]) operation.wait_for { ready? } unless options.fetch(:async, true) operation end ## # Imports data into a Cloud SQL instance from a MySQL dump file in Google Cloud Storage # # @param [Array] uri A path to the MySQL dump file in Google Cloud Storage from which the import is # made # @param [Hash] options Method options # @option options [String] :database The database (for example, guestbook) to which the import is made. # If not set, it is assumed that the database is specified in the file to be imported. # @option options [Boolean] :async If the operation must be performed asynchronously (true by default) # @return [Fog::Google::SQL::Operation] A Operation resource def import(uri, options = {}) requires :identity data = service.import_instance(identity, uri, options) operation = Fog::Google::SQL::Operations.new(:service => service).get(instance, data.body["operation"]) operation.wait_for { ready? } unless options.fetch(:async, true) operation end ## # Returns the list of external networks that are allowed to connect to the instance using the IP # # @return [Array] The list of external networks that are allowed to connect to the instance using the IP def ip_configuration_authorized_networks settings.fetch("ipConfiguration", {})["authorizedNetworks"] end ## # Returns whether the instance should be assigned an IP address or not # # @return [Boolean] Whether the instance should be assigned an IP address or not def ip_configuration_enabled settings.fetch("ipConfiguration", {})["enabled"] end ## # Returns whether the mysqld should default to 'REQUIRE X509' for users connecting over IP # # @return [Boolean] Whether the mysqld should default to 'REQUIRE X509' for users connecting over IP def ip_configuration_require_ssl settings.fetch("ipConfiguration", {})["requireSsl"] end ## # Returns the AppEngine application to follow # # @return [String] The AppEngine application to follow def location_preference_zone_follow_gae_application settings.fetch("locationPreference", {})["followGaeApplication"] end ## # Returns the preferred Compute Engine zone # # @return [String] The preferred Compute Engine zone def location_preference_zone settings.fetch("locationPreference", {})["zone"] end ## # Returns the pricing plan for this instance # # @return [String] The pricing plan for this instance def pricing_plan settings["pricingPlan"] end ## # Checks if the instance is running # # @return [Boolean] True if the instance is running; False otherwise def ready? state == RUNNABLE_STATE end ## # Returns the type of replication this instance uses # # @return [String] The type of replication this instance uses def replication_type settings["replicationType"] end ## # Deletes all client certificates and generates a new server SSL certificate for the instance # # @param [Hash] options Method options # @option options [Boolean] :async If the operation must be performed asynchronously (true by default) # @return [Fog::Google::SQL::Operation] A Operation resource def reset_ssl_config(options = {}) requires :identity data = service.reset_instance_ssl_config(identity) operation = Fog::Google::SQL::Operations.new(:service => service).get(instance, data.body["operation"]) operation.wait_for { ready? } unless options.fetch(:async, true) operation end ## # Restarts a Cloud SQL instance # # @param [Hash] options Method options # @option options [Boolean] :async If the operation must be performed asynchronously (true by default) # @return [Fog::Google::SQL::Operation] A Operation resource def restart(options = {}) requires :identity data = service.restart_instance(identity) operation = Fog::Google::SQL::Operations.new(:service => service).get(instance, data.body["operation"]) operation.wait_for { ready? } unless options.fetch(:async, true) operation end ## # Restores a backup of a Cloud SQL instance # # @param [String] backup_configuration The identifier of the backup configuration # @param [String] due_time The time when this run is due to start in RFC 3339 format # @param [Hash] options Method options # @option options [Boolean] :async If the operation must be performed asynchronously (true by default) # @return [Fog::Google::SQL::Operation] A Operation resource def restore_backup(backup_configuration, due_time, options = {}) requires :identity data = service.restore_instance_backup(identity, backup_configuration, due_time) operation = Fog::Google::SQL::Operations.new(:service => service).get(instance, data.body["operation"]) operation.wait_for { ready? } unless options.fetch(:async, true) operation end ## # Saves a Cloud SQL instance # # @return [Fog::Google::SQL::Instance] Instance resource def save etag ? update : create end ## # Sets the password for the root user # # @param [String] password The password for the root user # @param [Hash] options Method options # @option options [Boolean] :async If the operation must be performed asynchronously (true by default) # @return [Fog::Google::SQL::Operation] A Operation resource def set_root_password(password, options = {}) requires :identity data = service.set_instance_root_password(identity, password) operation = Fog::Google::SQL::Operations.new(:service => service).get(instance, data.body["operation"]) operation.wait_for { ready? } unless options.fetch(:async, true) operation end ## # Returns the version of instance settings # # @return [String] The version of instance settings def settings_version settings["settingsVersion"] end ## # Lists all of the current SSL certificates for the instance # # @return [Array] List of SSL certificate resources def ssl_certs requires :identity service.ssl_certs.all(identity) end ## # Returns the tier of service for this instance # # @return [String] The tier of service for this instance def tier settings["tier"] end ## # Updates settings of a Cloud SQL instance # # @return [Fog::Google::SQL::Instance] Instance resource def update requires :identity data = service.update_instance(identity, settings_version, tier, attributes) operation = Fog::Google::SQL::Operations.new(:service => service).get(instance, data.body["operation"]) operation.wait_for { !pending? } reload end end end end end fog-google-0.5.3/lib/fog/google/models/pubsub/0000755000004100000410000000000013145731036021157 5ustar www-datawww-datafog-google-0.5.3/lib/fog/google/models/pubsub/topic.rb0000644000004100000410000000417013145731036022624 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class Pubsub # Represents a Pubsub topic resource # # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.topics#Topic class Topic < Fog::Model identity :name # Creates this topic resource on the service. # # @return [Fog::Google::Pubsub::Topic] this instance def create requires :name service.create_topic(name) self end # Deletes this topic resource on the service. # # @return [Fog::Google::Pubsub::Topic] this instance def destroy requires :name service.delete_topic(name) self end # Publish a message to this topic. This method will automatically # encode the message via base64 encoding. # # @param messages [Array String}, #to_s>] list of messages # to send; if it's a hash, then the value of key "data" will be sent # as the message. Additionally, if the hash contains a value for key # "attributes", then they will be sent as well as attributes on the # message. # @return [Array] list of message ids def publish(messages) requires :name # Ensure our messages are base64 encoded encoded_messages = [] messages.each do |message| encoded_message = {} if message.is_a?(Hash) encoded_message["attributes"] = message["attributes"] if message.key?("data") encoded_message["data"] = Base64.strict_encode64(message["data"]) end else encoded_message["data"] = Base64.strict_encode64(message.to_s) end encoded_messages << encoded_message end service.publish_topic(name, encoded_messages).body["messageIds"] end # Save the instance (does the same thing as #create) # @return [Fog::Google::Pubsub::Topic] this instance def save create end end end end end fog-google-0.5.3/lib/fog/google/models/pubsub/received_message.rb0000644000004100000410000000231713145731036025001 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class Pubsub # Represents a ReceivedMessage retrieved from a Google Pubsub # subscription. Note that ReceivedMessages are immutable. # # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/pull#ReceivedMessage class ReceivedMessage < Fog::Model identity :ack_id, :aliases => "ackId" attribute :message def initialize(new_attributes = {}) # Here we secretly store the subscription name we were received on # in order to support #acknowledge attributes = new_attributes.clone @subscription_name = attributes.delete(:subscription_name) super(attributes) end # Acknowledges a message. # # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/acknowledge def acknowledge requires :ack_id service.acknowledge_subscription(@subscription_name, [ack_id]) nil end def reload # Message is immutable - do nothing Fog::Logger.warning("#reload called on immutable ReceivedMessage") end end end end end fog-google-0.5.3/lib/fog/google/models/pubsub/topics.rb0000644000004100000410000000146213145731036023010 0ustar www-datawww-datarequire "fog/core/collection" require "fog/google/models/pubsub/topic" module Fog module Google class Pubsub class Topics < Fog::Collection model Fog::Google::Pubsub::Topic # Lists all topics that exist on the project. # # @return [Array] list of topics def all data = service.list_topics.body["topics"] || [] load(data) end # Retrieves a topic by name # # @param topic_name [String] name of topic to retrieve # @return [Fog::Google::Pubsub::Topic] topic found, or nil if not found def get(topic_name) topic = service.get_topic(topic_name).body new(topic) rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/google/models/pubsub/subscription.rb0000644000004100000410000000705013145731036024232 0ustar www-datawww-datamodule Fog module Google class Pubsub # Represents a Pubsub subscription resource # # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions class Subscription < Fog::Model identity :name attribute :topic attribute :push_config, :aliases => "pushConfig" attribute :ack_deadline_seconds, :aliases => "ackDeadlineSeconds" # Pulls from this subscription, returning any available messages. By # default, this method returns immediately with up to 10 messages. The # option 'return_immediately' allows the method to block until a # message is received, or the remote service closes the connection. # # Note that this method automatically performs a base64 decode on the # 'data' field. # # @param options [Hash] options to modify the pull request # @option options [Boolean] :return_immediately If true, method returns # after checking for messages. Otherwise the method blocks until one # or more messages are available, or the connection is closed. # @option options [Number] :max_messages maximum number of messages to # receive # @return [Array] list of # received messages, or an empty list if no messages are available. # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/pull def pull(options = { :return_immediately => true, :max_messages => 10 }) requires :name data = service.pull_subscription(name, options).body return [] unless data.key?("receivedMessages") # Turn into a list of ReceivedMessage, but ensure we perform a base64 decode first data["receivedMessages"].map do |recv_message| attrs = { :service => service, :subscription_name => name }.merge(recv_message) attrs["message"]["data"] = Base64.decode64(recv_message["message"]["data"]) if recv_message["message"].key?("data") ReceivedMessage.new(attrs) end end # Acknowledges a list of received messages for this subscription. # # @param messages [Array] # A list containing either ReceivedMessage instances to acknowledge, # or a list of ackIds (@see # https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/pull#ReceivedMessage). # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/acknowledge def acknowledge(messages) return if messages.empty? ack_ids = messages.map { |m| m.is_a?(ReceivedMessage) ? m.ack_id : m.to_s } service.acknowledge_subscription(name, ack_ids) nil end # Save this instance on the remove service. # # @return [Fog::Google::Pubsub::Subscription] this instance # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/create def save requires :name, :topic data = service.create_subscription(name, topic, push_config, ack_deadline_seconds).body merge_attributes(data) end # Deletes this subscription on the remote service. # # @see https://cloud.google.com/pubsub/reference/rest/v1/projects.subscriptions/delete def destroy requires :name service.delete_subscription(name) end end end end end fog-google-0.5.3/lib/fog/google/models/pubsub/subscriptions.rb0000644000004100000410000000165613145731036024423 0ustar www-datawww-datarequire "fog/core/collection" require "fog/google/models/pubsub/subscription" module Fog module Google class Pubsub class Subscriptions < Fog::Collection model Fog::Google::Pubsub::Subscription # Lists all subscriptions that exist on the project. # # @return [Array] list of # subscriptions def all data = service.list_subscriptions.body["subscriptions"] || [] load(data) end # Retrieves a subscription by name # # @param subscription_name [String] name of subscription to retrieve # @return [Fog::Google::Pubsub::Topic] topic found, or nil if not found def get(subscription_name) subscription = service.get_subscription(subscription_name).body new(subscription) rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/google/models/monitoring/0000755000004100000410000000000013145731036022044 5ustar www-datawww-datafog-google-0.5.3/lib/fog/google/models/monitoring/timeseries_descriptors.rb0000644000004100000410000000276313145731036027173 0ustar www-datawww-datarequire "fog/core/collection" require "fog/google/models/monitoring/timeseries_descriptor" module Fog module Google class Monitoring class TimeseriesDescriptors < Fog::Collection model Fog::Google::Monitoring::TimeseriesDescriptor ## # Lists all Timeseries Descriptors. # # @param [String] metric The name of the metric (Metric names are protocol-free URLs). # @param [String] youngest End of the time interval (inclusive), which is expressed as an RFC 3339 timestamp. # @param [Hash] options Optional query parameters. # @option options [String] count Maximum number of time series descriptors per page. Used for pagination. # @option options [String] labels A collection of labels for the matching time series. # @option options [String] oldest Start of the time interval (exclusive), which is expressed as an RFC 3339 # timestamp. # @options options [String] page_token The pagination token, which is used to page through large result sets. # @options options [String] timespan Length of the time interval to query, which is an alternative way to # declare the interval. # @return [Array] List of Timeseries Descriptors. def all(metric, youngest, options = {}) data = service.list_timeseries_descriptors(metric, youngest, options).body["timeseries"] || [] load(data) end end end end end fog-google-0.5.3/lib/fog/google/models/monitoring/metric_descriptors.rb0000644000004100000410000000234213145731036026276 0ustar www-datawww-datarequire "fog/core/collection" require "fog/google/models/monitoring/metric_descriptor" module Fog module Google class Monitoring class MetricDescriptors < Fog::Collection model Fog::Google::Monitoring::MetricDescriptor ## # Lists all Metric Descriptors. # # @param [Hash] options Optional query parameters. # @option options [String] count Maximum number of time series descriptors per page. Used for pagination. # @option options [String] page_token The pagination token, which is used to page through large result sets. # @option options [String] query The query used to search against existing metrics. Separate keywords with a space; # the service joins all keywords with AND, meaning that all keywords must match for a metric to be returned. # If this field is omitted, all metrics are returned. If an empty string is passed with this field, # no metrics are returned. # @return [Array] List of Metric Descriptors. def all(options = {}) data = service.list_metric_descriptors(options).body["metrics"] || [] load(data) end end end end end fog-google-0.5.3/lib/fog/google/models/monitoring/metric_descriptor.rb0000644000004100000410000000100113145731036026102 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class Monitoring ## # A metricDescriptor defines the name, label keys, and data type of a particular metric. # # @see https://cloud.google.com/monitoring/v2beta2/metricDescriptors#resource class MetricDescriptor < Fog::Model identity :name attribute :description attribute :labels attribute :project attribute :type_descriptor, :aliases => "typeDescriptor" end end end end fog-google-0.5.3/lib/fog/google/models/monitoring/timeseries_descriptor.rb0000644000004100000410000000114313145731036026777 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class Monitoring ## # A time series is a collection of data points that represents the value of a metric of a project over time. # The metric is described by the time-series descriptor. Each time-series descriptor is uniquely identified by # its metric name and a set of labels. # # @see https://developers.google.com/cloud-monitoring/v2beta1/timeseriesDescriptors class TimeseriesDescriptor < Fog::Model identity :metric attribute :labels attribute :project end end end end fog-google-0.5.3/lib/fog/google/models/monitoring/timeseries.rb0000644000004100000410000000067113145731036024546 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class Monitoring ## # A time series is a collection of data points that represents the value of a metric of a project over time. # # @see https://developers.google.com/cloud-monitoring/v2beta1/timeseries class Timeseries < Fog::Model identity :time_series_desc, :aliases => "timeseriesDesc" attribute :points end end end end fog-google-0.5.3/lib/fog/google/models/monitoring/timeseries_collection.rb0000644000004100000410000000265713145731036026767 0ustar www-datawww-datarequire "fog/core/collection" require "fog/google/models/monitoring/timeseries" module Fog module Google class Monitoring class TimeseriesCollection < Fog::Collection model Fog::Google::Monitoring::Timeseries ## # Lists all Timeseries. # # @param [String] metric The name of the metric (Metric names are protocol-free URLs). # @param [String] youngest End of the time interval (inclusive), which is expressed as an RFC 3339 timestamp. # @param [Hash] options Optional query parameters. # @option options [String] count Maximum number of time series descriptors per page. Used for pagination. # @option options [String] labels A collection of labels for the matching time series. # @option options [String] oldest Start of the time interval (exclusive), which is expressed as an RFC 3339 # timestamp. # @options options [String] page_token The pagination token, which is used to page through large result sets. # @options options [String] timespan Length of the time interval to query, which is an alternative way to # declare the interval. # @return [Array] List of Timeseries. def all(metric, youngest, options = {}) data = service.list_timeseries(metric, youngest, options).body["timeseries"] || [] load(data) end end end end end fog-google-0.5.3/lib/fog/google/pubsub/0000755000004100000410000000000013145731036017674 5ustar www-datawww-datafog-google-0.5.3/lib/fog/google/pubsub/mock.rb0000644000004100000410000000124113145731036021150 0ustar www-datawww-datamodule Fog module Google class Pubsub class Mock include Fog::Google::Shared def initialize(options) shared_initialize(options[:google_project], GOOGLE_PUBSUB_API_VERSION, GOOGLE_PUBSUB_BASE_URL) end def self.data @data ||= Hash.new do |hash, key| hash[key] = { :topics => {}, :subscriptions => {} } end end def self.reset @data = nil end def data self.class.data[project] end def reset_data self.class.data.delete(project) end end end end end fog-google-0.5.3/lib/fog/google/pubsub/real.rb0000644000004100000410000000103113145731036021137 0ustar www-datawww-datamodule Fog module Google class Pubsub class Real include Fog::Google::Shared attr_accessor :client attr_reader :pubsub def initialize(options) shared_initialize(options[:google_project], GOOGLE_PUBSUB_API_VERSION, GOOGLE_PUBSUB_BASE_URL) options[:google_api_scope_url] = GOOGLE_PUBSUB_API_SCOPE_URLS.join(" ") @client = initialize_google_client(options) @pubsub = @client.discovered_api("pubsub", api_version) end end end end end fog-google-0.5.3/lib/fog/google/monitoring.rb0000644000004100000410000000256413145731036021115 0ustar www-datawww-datamodule Fog module Google class Monitoring < Fog::Service autoload :Mock, File.expand_path("../monitoring/mock", __FILE__) autoload :Real, File.expand_path("../monitoring/real", __FILE__) requires :google_project recognizes( :app_name, :app_version, :google_client, :google_client_email, :google_client_options, :google_key_location, :google_key_string, :google_json_key_location, :google_json_key_string ) GOOGLE_MONITORING_API_VERSION = "v2beta2".freeze GOOGLE_MONITORING_BASE_URL = "https://www.googleapis.com/cloudmonitoring/" GOOGLE_MONITORING_API_SCOPE_URLS = %w(https://www.googleapis.com/auth/monitoring) ## # MODELS model_path "fog/google/models/monitoring" # Timeseries model :timeseries collection :timeseries_collection # TimeseriesDescriptors model :timeseries_descriptor collection :timeseries_descriptors # MetricDescriptors model :metric_descriptor collection :metric_descriptors ## # REQUESTS request_path "fog/google/requests/monitoring" # Timeseries request :list_timeseries # TimeseriesDescriptors request :list_timeseries_descriptors # MetricDescriptors request :list_metric_descriptors end end end fog-google-0.5.3/lib/fog/google/monitoring/0000755000004100000410000000000013145731036020561 5ustar www-datawww-datafog-google-0.5.3/lib/fog/google/monitoring/mock.rb0000644000004100000410000000134313145731036022040 0ustar www-datawww-datamodule Fog module Google class Monitoring class Mock include Fog::Google::Shared def initialize(options) shared_initialize(options[:google_project], GOOGLE_MONITORING_API_VERSION, GOOGLE_MONITORING_BASE_URL) end def self.data @data ||= Hash.new do |hash, key| hash[key] = { :timeseries => {}, :timeseries_descriptors => {}, :metric_descriptors => {} } end end def self.reset @data = nil end def data self.class.data[project] end def reset_data self.class.data.delete(project) end end end end end fog-google-0.5.3/lib/fog/google/monitoring/real.rb0000644000004100000410000000107213145731036022031 0ustar www-datawww-datamodule Fog module Google class Monitoring class Real include Fog::Google::Shared attr_accessor :client attr_reader :monitoring def initialize(options) shared_initialize(options[:google_project], GOOGLE_MONITORING_API_VERSION, GOOGLE_MONITORING_BASE_URL) options[:google_api_scope_url] = GOOGLE_MONITORING_API_SCOPE_URLS.join(" ") @client = initialize_google_client(options) @monitoring = @client.discovered_api("cloudmonitoring", api_version) end end end end end fog-google-0.5.3/lib/fog/compute/0000755000004100000410000000000013145731036016574 5ustar www-datawww-datafog-google-0.5.3/lib/fog/compute/google.rb0000644000004100000410000001662113145731036020403 0ustar www-datawww-datamodule Fog module Compute class Google < Fog::Service autoload :Mock, File.expand_path("../google/mock", __FILE__) autoload :Real, File.expand_path("../google/real", __FILE__) requires :google_project recognizes( :app_name, :app_version, :google_client, :google_client_email, :google_client_options, :google_extra_global_projects, :google_key_location, :google_key_string, :google_json_key_location, :google_json_key_string ) GOOGLE_COMPUTE_API_VERSION = "v1" GOOGLE_COMPUTE_BASE_URL = "https://www.googleapis.com/compute/" GOOGLE_COMPUTE_API_SCOPE_URLS = %w(https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.read_write https://www.googleapis.com/auth/ndev.cloudman https://www.googleapis.com/auth/cloud-platform) GOOGLE_COMPUTE_DEFAULT_NETWORK = "default" RUNNING = "RUNNING".freeze PROVISIONING = "PROVISIONING".freeze request_path "fog/compute/google/requests" request :add_backend_service_backends request :add_instance_group_instances request :add_region_view_resources request :add_server_access_config request :add_target_pool_health_checks request :add_target_pool_instances request :add_url_map_host_rules request :add_url_map_path_matchers request :add_zone_view_resources request :delete_address request :delete_backend_service request :delete_disk request :delete_firewall request :delete_forwarding_rule request :delete_global_forwarding_rule request :delete_global_operation request :delete_http_health_check request :delete_image request :delete_instance_group request :delete_network request :delete_region_operation request :delete_region_view request :delete_route request :delete_server request :delete_server_access_config request :delete_snapshot request :delete_subnetwork request :delete_target_http_proxy request :delete_target_instance request :delete_target_pool request :delete_url_map request :delete_zone_operation request :delete_zone_view request :get_address request :get_backend_service request :get_backend_service_health request :get_disk request :get_disk_type request :get_firewall request :get_forwarding_rule request :get_global_forwarding_rule request :get_global_operation request :get_http_health_check request :get_image request :get_image_from_family request :get_instance_group request :get_machine_type request :get_network request :get_project request :get_region request :get_region_operation request :get_region_view request :get_route request :get_server request :get_server_serial_port_output request :get_snapshot request :get_subnetwork request :get_target_http_proxy request :get_target_instance request :get_target_pool request :get_target_pool_health request :get_url_map request :get_zone request :get_zone_operation request :get_zone_view request :insert_address request :insert_backend_service request :insert_disk request :insert_firewall request :update_firewall request :insert_forwarding_rule request :insert_global_forwarding_rule request :insert_http_health_check request :insert_image request :insert_instance_group request :insert_network request :insert_region_view request :insert_route request :insert_server request :insert_snapshot request :insert_subnetwork request :insert_target_http_proxy request :insert_target_instance request :insert_target_pool request :insert_url_map request :insert_zone_view request :list_addresses request :list_aggregated_addresses request :list_aggregated_disk_types request :list_aggregated_disks request :list_aggregated_instance_groups request :list_aggregated_machine_types request :list_aggregated_servers request :list_aggregated_subnetworks request :list_aggregated_target_instances request :list_backend_services request :list_disk_types request :list_disks request :list_firewalls request :list_forwarding_rules request :list_global_forwarding_rules request :list_global_operations request :list_http_health_checks request :list_images request :list_instance_group_instances request :list_instance_groups request :list_machine_types request :list_networks request :list_region_operations request :list_region_view_resources request :list_region_views request :list_regions request :list_routes request :list_servers request :list_snapshots request :list_subnetworks request :list_target_http_proxies request :list_target_instances request :list_target_pools request :list_url_maps request :list_zone_operations request :list_zone_view_resources request :list_zone_views request :list_zones request :remove_instance_group_instances request :remove_target_pool_health_checks request :remove_target_pool_instances request :set_common_instance_metadata request :set_forwarding_rule_target request :set_global_forwarding_rule_target request :set_metadata request :set_server_disk_auto_delete request :set_server_scheduling request :set_tags request :set_target_http_proxy_url_map request :attach_disk request :detach_disk request :reset_server request :start_server request :stop_server request :update_url_map request :validate_url_map model_path "fog/compute/google/models" model :server collection :servers model :image collection :images model :flavor collection :flavors model :disk collection :disks model :disk_type collection :disk_types model :address collection :addresses model :operation collection :operations model :snapshot collection :snapshots model :zone collection :zones model :region collection :regions model :http_health_check collection :http_health_checks model :target_pool collection :target_pools model :forwarding_rule collection :forwarding_rules model :project collection :projects model :firewall collection :firewalls model :network collection :networks model :route collection :routes model :backend_service collection :backend_services model :target_http_proxy collection :target_http_proxies model :url_map collection :url_maps model :global_forwarding_rule collection :global_forwarding_rules model :resource_view collection :resource_views model :target_instance collection :target_instances model :instance_group collection :instance_groups model :subnetwork collection :subnetworks end end end fog-google-0.5.3/lib/fog/compute/google/0000755000004100000410000000000013145731036020050 5ustar www-datawww-datafog-google-0.5.3/lib/fog/compute/google/requests/0000755000004100000410000000000013145731036021723 5ustar www-datawww-datafog-google-0.5.3/lib/fog/compute/google/requests/set_common_instance_metadata.rb0000644000004100000410000000133213145731036030136 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_common_instance_metadata(_identity, _current_fingerprint, _metadata = {}) Fog::Mock.not_implemented end end class Real def set_common_instance_metadata(identity, current_fingerprint, metadata = {}) api_method = @compute.projects.set_common_instance_metadata parameters = { :project => identity } body_object = { :fingerprint => current_fingerprint, :items => Array(metadata).map { |pair| { :key => pair[0], :value => pair[1] } } } request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_subnetwork.rb0000644000004100000410000000353213145731036025315 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_subnetwork(subnetwork_name, region_name) subnetwork_name = subnetwork_name.split("/")[-1] if subnetwork_name.start_with? "http" region_name = region_name.split("/")[-1] if region_name.start_with? "http" subnetwork = data[:subnetworks][subnetwork_name] unless subnetwork && subnetwork["region"].split("/")[-1] == region_name return build_excon_response("error" => { "errors" => [ { "domain" => "global", "reason" => "notFound", "message" => "The resource 'projects/#{@project}/regions/#{region_name}/subnetworks/#{subnetwork_name}' was not found" } ], "code" => 404, "message" => "The resource 'projects/#{@project}/regions/#{region_name}/subnetworks/#{subnetwork_name}' was not found" }) end build_excon_response(subnetwork) end end class Real def get_subnetwork(subnetwork_name, region_name) subnetwork_name = subnetwork_name.split("/")[-1] if subnetwork_name.start_with? "http" region_name = region_name.split("/")[-1] if region_name.start_with? "http" api_method = @compute.subnetworks.get parameters = { "project" => @project, "region" => region_name, "subnetwork" => subnetwork_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/add_instance_group_instances.rb0000644000004100000410000000171713145731036030155 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def add_instance_group_instances(_group_name, _zone, _instances) Fog::Mock.not_implemented end end class Real def add_instance_group_instances(group_name, zone, instances) api_method = @compute.instance_groups.add_instances parameters = { "project" => @project, "instanceGroup" => group_name, "zone" => zone } instances.map! do |instance| if instance.start_with?("https:") { "instance" => instance } else { "instance" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone}/instances/#{instance}\n" } end end body_object = { "instances" => instances } request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/add_region_view_resources.rb0000644000004100000410000000122613145731036027470 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def add_region_view_resources(_region_view, _resources) Fog::Mock.not_implemented end end class Real def add_region_view_resources(region_view, resources, region) api_method = @resourceviews.region_views.add_resources parameters = { "projectName" => @project, "resourceViewName" => region_view, "region" => region } body = { "resources" => resources } request(api_method, parameters, body_object = body) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_zone_view.rb0000644000004100000410000000123613145731036025643 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_zone_view(_zone_view_name, _zone_name) Fog::Mock.not_implemented end end class Real def insert_zone_view(zone_view_name, zone_name, opts = {}) api_method = @resourceviews.zone_views.insert parameters = { "projectName" => @project, "zone" => zone_name # 'zone' => zone_name } body_object = { "name" => zone_view_name } body_object.merge!(opts) request(api_method, parameters, body_object = body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_server.rb0000755000004100000410000003215013145731036025146 0ustar www-datawww-datamodule Fog module Compute class Google class Mock include Shared def handle_disks(options, zone_name) disks = [] i = 0 options.delete("disks").each do |disk| disk = Disk.new(disk) unless disk.is_a? Disk disks << { "kind" => "compute#attachedDisk", "index" => i, "type" => "PERSISTENT", "mode" => "READ_WRITE", "source" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/disks/#{disk.name}", "deviceName" => "persistent-disk-#{i}", "boot" => true } i += 1 end disks end # (see Fog::Compute::Google::Real#insert_server) def insert_server(server_name, zone_name, options = {}, *_deprecated_args) # check that zone exists get_zone(zone_name) if options["disks"].nil? || options["disks"].empty? raise ArgumentError.new "Empty value for field 'disks'. Boot disk must be specified" end id = Fog::Mock.random_numbers(19).to_s data[:servers][server_name] = { "kind" => "compute#instance", "id" => id, "creationTimestamp" => Time.now.iso8601, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}", "status" => "PROVISIONING", "name" => server_name, "tags" => { "fingerprint" => "42WmSpB8rSM=" }, "machineType" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/machineTypes/#{options['machineType']}", "canIpForward" => false, "networkInterfaces" => [ { "network" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/networks/default", "networkIP" => Fog::Mock.random_ip, "name" => "nic0", "accessConfigs" => [ { "kind" => "compute#accessConfig", "type" => "ONE_TO_ONE_NAT", "name" => "External NAT", "natIP" => Fog::Mock.random_ip } ] } ], "disks" => handle_disks(options, zone_name), "metadata" => { "kind" => "compute#metadata", "fingerprint" => "5_hasd_gC3E=", "items" => [ { "key" => "ssh-keys", "value" => "sysadmin:ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAgEA1zc7mx+0H8Roywet/L0aVX6MUdkDfzd/17kZhprAbpUXYOILv9AG4lIzQk6xGxDIltghytjfVGme/4A42Sb0Z9LN0pxB4KnWTNoOSHPJtp6jbXpq6PdN9r3Z5NKQg0A/Tfw7gt2N0GDsj6vpK8VbHHdW78JAVUxql18ootJxjaksdocsiHNK8iA6/v9qiLRhX3fOgtK7KpxxdZxLRzFg9vkp8jcGISgpZt27kOgXWhR5YLhi8pRJookzphO5O4yhflgoHoAE65XkfrsRCe0HU5QTbY2jH88rBVkq0KVlZh/lEsuwfmG4d77kEqaCGGro+j1Wrvo2K3DSQ+rEcvPp2CYRUySjhaeLF18UzQLtxNeoN14QOYqlm9ITdkCnmq5w4Wn007MjSOFp8LEq2RekrnddGXjg1/vgmXtaVSGzJAlXwtVfZor3dTRmF0JCpr7DsiupBaDFtLUlGFFlSKmPDVMPOOB5wajexmcvSp2Vu4U3yP8Lai/9/ZxMdsGPhpdCsWVL83B5tF4oYj1HVIycbYIxIIfFqOxZcCru3CMfe9jmzKgKLv2UtkfOS8jpS/Os2gAiB3wPweH3agvtwYAYBVMDwt5cnrhgHYWoOz7ABD8KgmCrD7Y9HikiCqIUNkgUFd9YmjcYi5FkU5rFXIawN7efs341lsdf923lsdf923fs= johndoe@acme" } ] }, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/instances/#{server_name}" } operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}", "operationType" => "insert", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/instances/#{server_name}", "targetId" => id, "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real include Shared def handle_disks(options) disks = [] # An array of persistent disks. You must supply a boot disk as the first disk in # this array and mark it as a boot disk using the disks[].boot property. options.delete("disks").each do |disk| if disk.is_a? Disk disks << disk.get_object else disks << disk end end disks.first["boot"] = true disks end def handle_networks(options, region_name) # Only one access config, ONE_TO_ONE_NAT, is supported per instance. # If there are no accessConfigs specified, then this instance will have no external internet access. access_config = { "type" => "ONE_TO_ONE_NAT", "name" => "External NAT" } # If natIP is undefined VM will get an IP from a shared ephemeral IP address pool if options.key? "externalIp" access_config["natIP"] = options.delete "externalIp" # If :external_ip is set to 'false', do not allow _any_ external networking access_config = nil if access_config["natIP"] == false end # If no networking options are specified, assume default network if options.key? "network" network = options.delete "network" else network = GOOGLE_COMPUTE_DEFAULT_NETWORK end # Objectify the network if needed unless network.is_a?(Network) network = networks.get(network) end network_interfaces = network.get_as_interface_config(access_config) if options.key? "subnetwork" subnetwork = options.delete "subnetwork" # Objectify the subnetwork if needed unless subnetwork.is_a?(Subnetwork) subnetwork = subnetworks.get(subnetwork, region_name) end network_interfaces = subnetwork.update_interface_config(network_interfaces) end # Return a networkInterfaces array [network_interfaces] end def format_metadata(metadata) { "items" => metadata.map { |k, v| { "key" => k, "value" => v } } } end ## # Create a new instance (virtual machine). You can provision a server # using low-level request options via this method (if you don't need to # modify low-level request options, consider using the 'servers' # collection object instead - see Fog::Compute::Google::Servers). # This method should directly take any of the API parameters/options for # the GCP endpoint (passed through the +options+ parameter). # # @see https://cloud.google.com/compute/docs/reference/latest/instances/insert # @example minimal server creation # require 'fog/google' # client = Fog::Compute::Google.new # my_result = client.insert_server('my-server', # 'us-central1-b', # 'machineType' => 'f1-micro', # 'disks' => [ # 'initializeParams' => { # 'sourceImage' => 'projects/debian-cloud/global/images/family/debian-8' # } # ]) # # @param server_name [String] Name to assign to the created server. Must # be unique within the specified zone. # @param zone_name [String] Name of zone containing the created server. # See Fog::Compute::Google#zones for a list of available zones. # @param options [Hash] options to use when creating a server. You can # use any of the options documented at # https://cloud.google.com/compute/docs/reference/latest/instances/insert. # Additionally accepts some nonstandard parameters documented below. # @option options [String] 'machineType' Required: the machine type to use - see # https://cloud.google.com/compute/docs/machine-types for a list. # @option options [String] 'externalIp' An IP address to assign to the # server. See # https://cloud.google.com/compute/docs/configure-instance-ip-addresses # for more information about assigning instance ip addresses. # @option options [Boolean] 'auto_restart' (false) if true, then the # server will be automatically restarted if terminated by Google Compute # Engine. Note that this value cannot be set to true if the VM is # preemptible. # @option options [Boolean] 'preemptible' (false) if true, then the # created server will be preemptible and therefore only run for at # most 24 hours. See # https://cloud.google.com/compute/docs/instances/preemptible for more # information about preemptible instances. # @option options ["MIGRATE", "TERMINATE"] 'on_host_maintenance' if # "MIGRATE", then the VM will be migrated to different hardware during # a maintenance event. If "TERMINATE", then the VM will be terminated. # Note that if the VM is preemptible, then this option MUST be # "TERMINATE". # @option options [Boolean] 'can_ip_forward' (false) if true, then the # created instance will allow forwarding packets that don't originate # with the assigned host ip address. See # https://cloud.google.com/compute/docs/networking#canipforward for # more information. # @return [Excon::Response] response object that represents the result. def insert_server(server_name, zone_name, options = {}, *deprecated_args) if !deprecated_args.empty? || !options.is_a?(Hash) raise ArgumentError.new "Too many parameters specified. This may be the cause of code written for an outdated"\ " version of fog. Usage: server_name, zone_name, [options]" end api_method = @compute.instances.insert parameters = { "project" => @project, "zone" => zone_name } body_object = { :name => server_name } body_object["machineType"] = @api_url + @project + "/zones/#{zone_name}/machineTypes/#{options.delete 'machineType'}" scheduling = { "automaticRestart" => false, "onHostMaintenance" => "MIGRATE", "preemptible" => false } if options.key? "auto_restart" scheduling["automaticRestart"] = options.delete "auto_restart" scheduling["automaticRestart"] = scheduling["automaticRestart"].class == TrueClass end if options.key? "preemptible" scheduling["preemptible"] = options.delete "preemptible" scheduling["preemptible"] = scheduling["preemptible"].class == TrueClass # If we don't have an explicit value for "on_host_maintenance, then # force the value to be 'TERMINATE' as it's the default and # only-accepted value for preemptible vms scheduling["onHostMaintenance"] = "TERMINATE" unless options.key? "on_host_maintenance" end if options.key? "on_host_maintenance" ohm = options.delete "on_host_maintenance" scheduling["onHostMaintenance"] = (ohm.respond_to?("upcase") && ohm.upcase == "MIGRATE" && "MIGRATE") || "TERMINATE" end body_object["scheduling"] = scheduling # @see https://developers.google.com/compute/docs/networking#canipforward if options.key? "can_ip_forward" body_object["canIpForward"] = options.delete "can_ip_forward" end # TODO: add other networks body_object["networkInterfaces"] = handle_networks(options, get_zone(zone_name).body["region"].split("/")[-1]) if options["disks"].nil? || options["disks"].empty? raise ArgumentError.new "Empty value for field 'disks'. Boot disk must be specified" end body_object["disks"] = handle_disks(options) options["metadata"] = format_metadata options["metadata"] if options["metadata"] body_object["tags"] = { "items" => options.delete("tags") } if options["tags"] body_object.merge!(options) # Adds in all remaining options that weren't explicitly handled. request(api_method, parameters, body_object = body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_global_forwarding_rule.rb0000644000004100000410000000364613145731036030314 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_global_forwarding_rule(name, _region_name = "global") get_global_forwarding_rule(name) global_forwarding_rule = data[:global_forwarding_rules][name] global_forwarding_rule["mock-deletionTimestamp"] = Time.now.iso8601 global_forwarding_rule["status"] = "DONE" operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global", "operationType" => "delete", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/forwardingRules/#{name}", "targetId" => data[:global_forwarding_rules][name]["id"], "status" => "DONE", "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def delete_global_forwarding_rule(global_forwarding_rule_name, region_name = "global") if region_name.start_with? "http" region_name = region_name.split("/")[-1] end api_method = @compute.global_forwarding_rules.delete parameters = { "project" => @project, "forwardingRule" => global_forwarding_rule_name, "region" => region_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/add_backend_service_backends.rb0000644000004100000410000000141113145731036030016 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def add_backend_service_backends(_backend_service, _new_backends) Fog::Mock.not_implemented end end class Real def add_backend_service_backends(backend_service, new_backends) api_method = @compute.backend_services.patch parameters = { "project" => @project, "backendService" => backend_service.name } if backend_service.backends backend_service.backends.concat(new_backends) else backend_service.backends = new_backends end body_object = backend_service request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_aggregated_target_instances.rb0000644000004100000410000000413713145731036031017 0ustar www-datawww-datamodule Fog module Compute class Google # XXX @ihmccreery added this mock to get the Shindo tests to pass. I don't really understand how mocks are supposed to work; I'm in the process of moving # all testing over to Minitest, but in the meantime, the Shindo tests need to pass. This Mock should be considered with a *lot* of skepticism. class Mock def list_aggregated_target_instances(options = {}) # Create a Hash of unique zones from the target_instances Array previously filled when target_instances are created zones = Hash[data[:target_instances].values.map { |target_instance| ["zones/#{target_instance['zone'].split('/')[-1]}", { "targetInstances" => [] }] }] if options[:filter] # Look up for the target_instance name target_instance = data[:target_instances][options[:filter].gsub(/name eq \.\*/, "")] # Fill the zones Hash with the target_instance (if it's found) zones["zones/#{target_instance['zone'].split('/')[-1]}"]["targetInstances"].concat([target_instance]) if target_instance else # Fill the zones Hash with the target_instances attached to each zone data[:target_instances].values.each { |target_instance| zones["zones/#{target_instance['zone'].split('/')[-1]}"]["targetInstances"].concat([target_instance]) } end build_excon_response("kind" => "compute#targetInstanceAggregatedList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/aggregated/targetInstances", "id" => "projects/#{@project}/aggregated/targetInstances", "items" => zones) end end class Real def list_aggregated_target_instances(options = {}) api_method = @compute.target_instances.aggregated_list parameters = { "project" => @project } parameters["filter"] = options[:filter] if options[:filter] request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_zone_view.rb0000644000004100000410000000100013145731036025566 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_zone_view(_zone_view) Fog::Mock.not_implemented end end class Real def delete_zone_view(zone_view, zone) api_method = @resourceviews.zone_views.delete parameters = { "projectName" => @project, "resourceViewName" => zone_view, "zone" => zone } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/add_target_pool_instances.rb0000644000004100000410000000127513145731036027453 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def add_target_pool_instances(_target_pool, _instances) Fog::Mock.not_implemented end end class Real def add_target_pool_instances(target_pool, instances) api_method = @compute.target_pools.add_instance parameters = { "project" => @project, "targetPool" => target_pool.name, "region" => target_pool.region.split("/")[-1] } body = { "instances" => instances.map { |i| { "instance" => i } } } request(api_method, parameters, body_object = body) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_instance_group_instances.rb0000644000004100000410000000103713145731036030373 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_instance_group_instances(_group, _zone) Fog::Mock.not_implemented end end class Real def list_instance_group_instances(group_name, zone) api_method = @compute.instance_groups.list_instances parameters = { "instanceGroup" => group_name, "project" => @project, "zone" => zone } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/add_target_pool_health_checks.rb0000644000004100000410000000133313145731036030244 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def add_target_pool_health_checks(_target_pool, _health_checks) Fog::Mock.not_implemented end end class Real def add_target_pool_health_checks(target_pool, health_checks) api_method = @compute.target_pools.add_health_check parameters = { "project" => @project, "targetPool" => target_pool.name, "region" => target_pool.region.split("/")[-1] } body = { "healthChecks" => health_checks.map { |i| { "healthCheck" => i } } } request(api_method, parameters, body_object = body) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_machine_types.rb0000644000004100000410000000160013145731036026130 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_machine_types(zone_name) get_zone(zone_name) machine_types = data[:machine_types][zone_name].values build_excon_response("kind" => "compute#machineTypeList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/machineTypes", "id" => "projects/high-cistern-340/zones/us-central1-a/machineTypes", "items" => machine_types) end end class Real def list_machine_types(zone_name) api_method = @compute.machine_types.list parameters = { "project" => @project, "zone" => zone_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_address.rb0000644000004100000410000000101713145731036025216 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_address(_address_name, _region_name) Fog::Mock.not_implemented end end class Real def delete_address(address_name, region_name) api_method = @compute.addresses.delete parameters = { "project" => @project, "address" => address_name, "region" => region_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_zone.rb0000644000004100000410000000162713145731036024070 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_zone(zone_name) zone = data[:zones][zone_name] || { "error" => { "errors" => [ { "domain" => "global", "reason" => "notFound", "message" => "The resource 'projects/#{project}/zones/#{zone_name}' was not found" } ], "code" => 404, "message" => "The resource 'projects/#{project}/zones/#{zone_name}' was not found" } } build_excon_response(zone) end end class Real def get_zone(zone_name) api_method = @compute.zones.get parameters = { "project" => @project, "zone" => zone_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_instance_group.rb0000644000004100000410000000233113145731036026653 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_instance_group(_group_name, _zone, _options = {}) Fog::Mock.not_implemented end end class Real def insert_instance_group(group_name, zone, options = {}) api_method = @compute.instance_groups.insert parameters = { "project" => @project, "zone" => zone } id = Fog::Mock.random_numbers(19).to_s body = { "name" => group_name } body["description"] = options["description"] if options["description"] network_name = options["network"] ? options["network"].split("/")[-1] : GOOGLE_COMPUTE_DEFAULT_NETWORK body["network"] = "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/networks/#{network_name}" unless options["subnetwork"].nil? subnetwork_name = options["subnetwork"].split("/")[-1] body["subnetwork"] = "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{@region}/subnetworks/#{subnetwork_name}" end request(api_method, parameters, body) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_server.rb0000644000004100000410000000504713145731036024423 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_server(server_name, zone_name) server = data[:servers][server_name] get_zone(zone_name) zone = data[:zones][zone_name] if server.nil? || server["zone"] != zone["selfLink"] return build_excon_response("error" => { "errors" => [ { "domain" => "global", "reason" => "notFound", "message" => "The resource 'projects/#{@project}/zones/#{zone_name}/instances/#{server_name}' was not found" } ], "code" => 404, "message" => "The resource 'projects/#{@project}/zones/#{zone_name}/instances/#{server_name}' was not found" }) end # transition the server through the provisioning -> staging -> running states creation_time = Time.iso8601(server["creationTimestamp"]) case server["status"] when "PROVISIONING" if Time.now - creation_time > Fog::Mock.delay / 2 server["status"] = "STAGING" end when "STAGING" if Time.now - creation_time > Fog::Mock.delay server["status"] = "RUNNING" end when "STOPPED" if server["mock-deletionTimestamp"] # stopped -> terminated if Time.now - Time.iso8601(server["mock-deletionTimestamp"]) > Fog::Mock.delay server["status"] = "TERMINATED" end end when "TERMINATED" if Time.now - Time.iso8601(server["mock-deletionTimestamp"]) > Fog::Mock.delay data[:servers][server_name] = nil end end build_excon_response(server) end end class Real def get_server(server_name, zone_name) if zone_name.is_a? Excon::Response zone = zone_name.body["name"] else zone = zone_name end api_method = @compute.instances.get parameters = { "project" => @project, "zone" => zone, "instance" => server_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_zone_view_resources.rb0000644000004100000410000000104113145731036027376 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_zone_view_resources(_zone_view) Fog::Mock.not_implemented end end class Real def list_zone_view_resources(zone_view) api_method = @resourceviews.zone_views.list_resources parameters = { "projectName" => @project, "zone" => zone_view.zone, "resourceViewName" => zone_view.name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_region_operations.rb0000644000004100000410000000105213145731036027027 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_region_operations(_region) Fog::Mock.not_implemented end end class Real # https://developers.google.com/compute/docs/reference/latest/regionOperations def list_region_operations(region) api_method = @compute.region_operations.list parameters = { "region" => region, "project" => @project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_target_pool.rb0000644000004100000410000000451113145731036026154 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_target_pool(name, region_name, opts = {}) # check that region exists get_region(region_name) id = Fog::Mock.random_numbers(19).to_s data[:target_pools][name] = { "kind" => "compute#targetPools", "id" => id, "creationTimestamp" => Time.now.iso8601, "name" => name, "description" => "", "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}", "instances" => opts["instances"], "healthChecks" => opts["healthChecks"], "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/targetPools/#{name}" } operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}", "operationType" => "insert", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/targetPools/#{name}", "targetId" => id, "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def insert_target_pool(target_pool_name, region_name, opts = {}) api_method = @compute.target_pools.insert parameters = { "project" => @project, "region" => region_name } body_object = { "name" => target_pool_name } body_object.merge!(opts) request(api_method, parameters, body_object = body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_target_instance.rb0000644000004100000410000000346013145731036026747 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_target_instance(name, zone) get_target_instance(name, zone) target_instance = data[:target_instances][name] target_instance["mock-deletionTimestamp"] = Time.now.iso8601 target_instance["status"] = "DONE" operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone}", "operationType" => "delete", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone}/targetInstances/#{name}", "targetId" => data[:target_instances][name]["id"], "status" => "DONE", "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone}/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def delete_target_instance(target_instance_name, zone_name) zone_name = zone_name.split("/")[-1] if zone_name.start_with? "http" api_method = @compute.target_instances.delete parameters = { "project" => @project, "targetInstance" => target_instance_name, "zone" => zone_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_target_pools.rb0000644000004100000410000000162113145731036026005 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_target_pools(region_name) target_pools = data[:target_pools].values.select { |d| d["region"].split("/")[-1] == region_name } build_excon_response("kind" => "compute#forwardingRuleList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/targetPools", "id" => "projects/#{@project}/regions/#{region_name}/regions", "items" => target_pools) end end class Real def list_target_pools(region_name) api_method = @compute.target_pools.list parameters = { "project" => @project, "region" => region_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_region_view.rb0000644000004100000410000000120513145731036026147 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_region_view(_region_view_name, _region_name) Fog::Mock.not_implemented end end class Real def insert_region_view(region_view_name, region_name, opts = {}) api_method = @resourceviews.region_views.insert parameters = { "projectName" => @project, "region" => region_name } body_object = { "name" => region_view_name } body_object.merge!(opts) request(api_method, parameters, body_object = body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_region_operation.rb0000644000004100000410000000335313145731036026456 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_region_operation(region_name, operation) operation = data[:operations][operation] if operation case operation["status"] when Fog::Compute::Google::Operation::PENDING_STATE operation["status"] = Fog::Compute::Google::Operation::RUNNING_STATE operation["progress"] = 50 else operation["status"] = Fog::Compute::Google::Operation::DONE_STATE operation["progress"] = 100 end else operation = { "error" => { "errors" => [ { "domain" => "global", "reason" => "notFound", "message" => "The resource 'projects/#{project}/regions/#{region_name}/operations/#{operation}' was not found" } ], "code" => 404, "message" => "The resource 'projects/#{project}/regions/#{region_name}/operations/#{operation}' was not found" } } end build_excon_response(operation) end end class Real # https://developers.google.com/compute/docs/reference/latest/regionOperations def get_region_operation(region_name, operation) if region_name.start_with? "http" region_name = region_name.split("/")[-1] end api_method = @compute.region_operations.get parameters = { "project" => @project, "region" => region_name, "operation" => operation } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_region_operation.rb0000644000004100000410000000134413145731036027137 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_region_operation(_region, _operation) Fog::Mock.not_implemented end end class Real # https://developers.google.com/compute/docs/reference/latest/regionOperations def delete_region_operation(region_name, operation) if region_name.start_with? "http" region_name = region_name.split("/")[-1] end api_method = @compute.region_operations.delete parameters = { "project" => @project, "region" => region_name, "operation" => operation } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_address.rb0000644000004100000410000000100613145731036024531 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_address(_address_name, _region_name) Fog::Mock.not_implemented end end class Real def get_address(address_name, region_name) api_method = @compute.addresses.get parameters = { "project" => @project, "address" => address_name, "region" => region_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_target_instance.rb0000644000004100000410000000134613145731036026265 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_target_instance(name, _zone_name) target_instance = data[:target_instances][name] return nil if target_instance.nil? build_excon_response(target_instance) end end class Real def get_target_instance(target_instance_name, zone_name) zone_name = zone_name.split("/")[-1] if zone_name.start_with? "http" api_method = @compute.target_instances.get parameters = { "project" => @project, "targetInstance" => target_instance_name, "zone" => zone_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_server.rb0000644000004100000410000000442313145731036025103 0ustar www-datawww-datamodule Fog module Compute class Google module Shared def find_zone(zone_name) if zone_name.nil? list_zones.body["items"].each do |zone| if get_server(server_name, zone["name"]).status == 200 return zone["name"] end end else return zone_name.body["name"] if zone_name.is_a? Excon::Response end zone_name end end class Mock include Shared def delete_server(server_name, zone_name = nil) zone_name = find_zone(zone_name) get_server(server_name, zone_name) server = data[:servers][server_name] server["status"] = "STOPPED" server["mock-deletionTimestamp"] = Time.now.iso8601 operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}", "operationType" => "delete", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/instances/#{server_name}", "targetId" => data[:servers][server_name]["id"], "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real include Shared def delete_server(server_name, zone_name = nil) zone_name = find_zone(zone_name) api_method = @compute.instances.delete parameters = { "project" => @project, "zone" => zone_name, "instance" => server_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_disk_type.rb0000644000004100000410000000270313145731036025104 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_disk_type(identity, zone) disk_types = list_disk_types(zone).body["items"] disk_type = disk_types.select { |dt| dt["name"] == identity } || [] if disk_type.empty? return build_excon_response("error" => { "errors" => [ { "domain" => "global", "reason" => "notFound", "message" => "The resource 'projects/#{@project}/zones/#{zone}/diskTypes/#{identity}' was not found" } ], "code" => 404, "message" => "The resource 'projects/#{@project}/zones/#{zone}/diskTypes/#{identity}' was not found" }) end build_excon_response(disk_type.first) end end class Real def get_disk_type(identity, zone) api_method = @compute.disk_types.get parameters = { "project" => @project, "zone" => zone.split("/")[-1], "diskType" => identity } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_snapshots.rb0000644000004100000410000000100713145731036025323 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_snapshots Fog::Mock.not_implemented end end class Real def list_snapshots(project = nil, next_page_token = nil) api_method = @compute.snapshots.list project = @project if project.nil? parameters = { "project" => project, "pageToken" => next_page_token } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_images.rb0000644000004100000410000000143413145731036024552 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_images(project = @project) images = data(project)[:images].values build_excon_response("kind" => "compute#imageList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{project}/global/images", "id" => "projects/#{project}/global/images", "items" => images) end end class Real def list_images(project = nil) api_method = @compute.images.list project = @project if project.nil? parameters = { "project" => project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_network.rb0000644000004100000410000000070513145731036024602 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_network(_network_name) Fog::Mock.not_implemented end end class Real def get_network(network_name) api_method = @compute.networks.get parameters = { "project" => @project, "network" => network_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/detach_disk.rb0000644000004100000410000000107413145731036024514 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def detach_disk(_instance, _zone, _deviceName) Fog::Mock.not_implemented end end class Real def detach_disk(instance, zone, deviceName) api_method = @compute.instances.detach_disk parameters = { "project" => @project, "instance" => instance, "zone" => zone.split("/")[-1], "deviceName" => deviceName } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_aggregated_instance_groups.rb0000644000004100000410000000103713145731036030661 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_instance_groups(_options = {}) Fog::Mock.not_implemented end end class Real def list_aggregated_instance_groups(options = {}) api_method = @compute.instance_groups.aggregated_list parameters = { "project" => @project } parameters["filter"] = options[:filter] if options[:filter] request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_forwarding_rules.rb0000644000004100000410000000165513145731036026666 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_forwarding_rules(region_name) forwarding_rules = data[:forwarding_rules].values.select { |d| d["region"].split("/")[-1] == region_name } build_excon_response("kind" => "compute#forwardingRuleList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/forwardingRules", "id" => "projects/#{@project}/regions/#{region_name}/regions", "items" => forwarding_rules) end end class Real def list_forwarding_rules(region_name) api_method = @compute.forwarding_rules.list parameters = { "project" => @project, "region" => region_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_forwarding_rule.rb0000644000004100000410000000331513145731036026302 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_forwarding_rule(name, region_name) forwarding_rule = data[:forwarding_rules][name] region_name = get_region(region_name).body["name"] region = data[:regions][region_name] if forwarding_rule.nil? || forwarding_rule["region"] != region["selfLink"] return build_excon_response("error" => { "errors" => [ { "domain" => "global", "reason" => "notFound", "message" => "The resource 'projects/#{@project}/regions/#{region_name}/forwarding_rules/#{name}' was not found" } ], "code" => 404, "message" => "The resource 'projects/#{@project}/regions/#{region_name}/forwarding_rules/#{name}' was not found" }) end build_excon_response(forwarding_rule) end end class Real def get_forwarding_rule(forwarding_rule_name, region_name) if region_name.start_with? "http" region_name = region_name.split("/")[-1] end api_method = @compute.forwarding_rules.get parameters = { "project" => @project, "forwardingRule" => forwarding_rule_name, "region" => region_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_machine_type.rb0000644000004100000410000000257613145731036025566 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_machine_type(machine_type_name, zone_name = nil) zone_name = data[:zones].keys.first if zone_name.nil? get_zone(zone_name) machine_type = data[:machine_types][zone_name][machine_type_name] || { "error" => { "errors" => [ { "domain" => "global", "reason" => "notFound", "message" => "The resource 'projects/#{@project}/zones/#{zone_name}/machineTypes/#{machine_type_name}' was not found" } ], "code" => 404, "message" => "The resource 'projects/#{@project}/zones/#{zone_name}/machineTypes/#{machine_type_name}' was not found" } } build_excon_response(machine_type) end end class Real def get_machine_type(machine_type_name, zone_name = nil) zone_name = list_zones.body["items"].first["name"] if zone_name.nil? zone_name = zone_name.split("/")[-1] if zone_name.start_with? "http" api_method = @compute.machine_types.get parameters = { "zone" => zone_name, "project" => @project, "machineType" => machine_type_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_address.rb0000644000004100000410000000123313145731036025260 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_address(_address_name, _region_name, _options = {}) Fog::Mock.not_implemented end end class Real def insert_address(address_name, region_name, options = {}) api_method = @compute.addresses.insert parameters = { "project" => @project, "region" => region_name } body_object = { "name" => address_name } body_object["description"] = options[:description] if options[:description] request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_zone_operations.rb0000644000004100000410000000103213145731036026515 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_zone_operations(_zone) Fog::Mock.not_implemented end end class Real # https://developers.google.com/compute/docs/reference/latest/zoneOperations def list_zone_operations(zone) api_method = @compute.zone_operations.list parameters = { "zone" => zone, "project" => @project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_target_http_proxies.rb0000644000004100000410000000143513145731036027404 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_target_http_proxies proxies = data[:target_http_proxies].values build_excon_response("kind" => "compute#targetHttpProxyList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/targetHttpProxies", "id" => "projects/#{@project}/global/targetHttpProxies", "items" => proxies) end end class Real def list_target_http_proxies api_method = @compute.target_http_proxies.list parameters = { "project" => @project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/remove_target_pool_instances.rb0000644000004100000410000000130613145731036030213 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def remove_target_pool_instances(_target_pool, _instances) Fog::Mock.not_implemented end end class Real def remove_target_pool_instances(target_pool, instances) api_method = @compute.target_pools.remove_instance parameters = { "project" => @project, "targetPool" => target_pool.name, "region" => target_pool.region.split("/")[-1] } body = { "instances" => instances.map { |i| { "instance" => i } } } request(api_method, parameters, body_object = body) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_forwarding_rule.rb0000644000004100000410000000347413145731036026773 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_forwarding_rule(name, region_name) get_forwarding_rule(name, region_name) id = Fog::Mock.random_numbers(19).to_s operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}", "operationType" => "delete", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/forwardingRules/#{name}", "targetId" => id, "status" => "DONE", "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real # https://developers.google.com/compute/docs/reference/latest/regionOperations def delete_forwarding_rule(forwarding_rule_name, region_name) if region_name.start_with? "http" region_name = region_name.split("/")[-1] end api_method = @compute.forwarding_rules.delete parameters = { "project" => @project, "forwardingRule" => forwarding_rule_name, "region" => region_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_instance_groups.rb0000644000004100000410000000070413145731036026507 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_instance_groups(_zone) Fog::Mock.not_implemented end end class Real def list_instance_groups(zone) api_method = @compute.instance_groups.list parameters = { "project" => @project, "zone" => zone } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_disk.rb0000644000004100000410000001013713145731036024570 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_disk(disk_name, zone_name, image_name = nil, options = {}) # check that image and zone exist image = nil if image_name image = images.get(image_name) raise ArgumentError.new("Invalid image specified: #{image_name}") unless image end get_zone(zone_name) id = Fog::Mock.random_numbers(19).to_s object = { "kind" => "compute#disk", "id" => id, "creationTimestamp" => Time.now.iso8601, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}", "status" => "READY", "name" => disk_name, "sizeGb" => options["sizeGb"] || "10", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/disks/#{disk_name}" } if image object.merge("sourceImage" => image.self_link, "sourceImageId" => image.id) end data[:disks][disk_name] = object if image object.merge!("sourceImage" => image.self_link, "sourceImageId" => image.id) end if disk_type = options.delete(:type) object["type"] = type else object["type"] = "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/diskTypes/pd-standard" end data[:disks][disk_name] = object operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => object["zone"], "operationType" => "insert", "targetLink" => object["selfLink"], "targetId" => id, "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "#{object['zone']}/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def insert_disk(disk_name, zone_name, image_name = nil, opts = {}) api_method = @compute.disks.insert parameters = { "project" => @project, "zone" => zone_name } if image_name # New disk from image image = images.get(image_name) raise ArgumentError.new("Invalid image specified: #{image_name}") unless image @image_url = @api_url + image.resource_url parameters["sourceImage"] = @image_url end body_object = { "name" => disk_name } body_object["type"] = opts.delete("type") # According to Google docs, if image name is not present, only one of # sizeGb or sourceSnapshot need to be present, one will create blank # disk of desired size, other will create disk from snapshot if image_name.nil? if opts.key?("sourceSnapshot") # New disk from snapshot snap = snapshots.get(opts.delete("sourceSnapshot")) raise ArgumentError.new("Invalid source snapshot") unless snap body_object["sourceSnapshot"] = @api_url + snap.resource_url elsif opts.key?("sizeGb") # New blank disk body_object["sizeGb"] = opts.delete("sizeGb") else raise ArgumentError.new("Must specify image OR snapshot OR "\ "disk size when creating a disk.") end end # Merge in any remaining options (only 'description' should remain) body_object.merge!(opts) request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/add_zone_view_resources.rb0000644000004100000410000000121013145731036027151 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def add_zone_view_resources(_zone_view, _resources) Fog::Mock.not_implemented end end class Real def add_zone_view_resources(zone_view, resources, zone) api_method = @resourceviews.zone_views.addresources parameters = { "projectName" => @project, "resourceViewName" => zone_view.name, "zone" => zone } body = { "resources" => resources } request(api_method, parameters, body_object = body) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_global_forwarding_rule.rb0000644000004100000410000000426013145731036030347 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_global_forwarding_rule(name, opts = {}) id = Fog::Mock.random_numbers(19).to_s data[:global_forwarding_rules][name] = { "kind" => "compute#forwardingRule", "id" => id, "creationTimestamp" => Time.now.iso8601, "name" => name, "description" => "", "region" => "global", "IPAddress" => "", "IPProtocol" => "", "portRange" => "", "target" => opts["target"], "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/forwardingRules/#{name}" } operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global", "operationType" => "insert", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/forwardingRules/#{name}", "targetId" => id, "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def insert_global_forwarding_rule(global_forwarding_rule_name, opts = {}) api_method = @compute.global_forwarding_rules.insert parameters = { "project" => @project } body_object = { "name" => global_forwarding_rule_name, "region" => "global" } body_object.merge!(opts) request(api_method, parameters, body_object = body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_route.rb0000644000004100000410000000067213145731036024735 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_route(_identity) Fog::Mock.not_implemented end end class Real def delete_route(identity) api_method = @compute.routes.delete parameters = { "project" => @project, "route" => identity } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/stop_server.rb0000644000004100000410000000076413145731036024632 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def stop_server(_identity, _zone_name) Fog::Mock.not_implemented end end class Real def stop_server(identity, zone_name) api_method = @compute.instances.stop parameters = { "project" => @project, "zone" => zone_name, "instance" => identity } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_aggregated_subnetworks.rb0000644000004100000410000000233113145731036030042 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_subnetworks(_options = {}) subnetworks_by_region = data[:subnetworks].each_with_object({}) do |(_, subnetwork), memo| region = subnetwork["region"].split("/")[-2..-1].join("/") memo[region] ||= { "subnetworks" => [] } memo[region]["subnetworks"].push subnetwork end build_excon_response("kind" => "compute#subnetworkAggregatedList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/aggregated/subnetworks", "items" => subnetworks_by_region) end end class Real def list_aggregated_subnetworks(options = {}) api_method = @compute.subnetworks.aggregated_list parameters = { "project" => @project } parameters["filter"] = options[:filter] if options[:filter] parameters["maxResults"] = options[:max_results] if options[:max_results] parameters["pageToken"] = options[:page_token] if options[:page_token] request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/set_metadata.rb0000644000004100000410000000245213145731036024706 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_metadata(_instance, _zone, _fingerprint, _metadata = {}) Fog::Mock.not_implemented end end class Real # Set an instance metadata # # ==== Parameters # * instance<~String> - Instance name (identity) # * zone<~String> - Zone short name (without the full path) # * fingerprint<~String> - The fingerprint of the last metadata. Can be retrieved by reloading the compute object, and checking the metadata fingerprint field. # instance.reload # fingerprint = instance.metadata['fingerprint'] # * metadata<~Hash> - A new metadata # # ==== Returns # * response<~Excon::Response> def set_metadata(instance, zone, fingerprint, metadata = {}) api_method = @compute.instances.set_metadata parameters = { "project" => @project, "instance" => instance, "zone" => zone } body_object = { "fingerprint" => fingerprint, "items" => metadata.to_a.map { |pair| { :key => pair[0], :value => pair[1] } } } request(api_method, parameters, body_object = body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/set_forwarding_rule_target.rb0000644000004100000410000000117513145731036027666 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_forwarding_rule_target(_rule, _target) Fog::Mock.not_implemented end end class Real def set_forwarding_rule_target(rule, target) api_method = @compute.forwarding_rules.set_target parameters = { "project" => @project, "forwardingRule" => rule.name, "region" => rule.region.split("/")[-1] } body = { "target" => target } request(api_method, parameters, body_object = body) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/set_server_disk_auto_delete.rb0000644000004100000410000000126713145731036030023 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_server_disk_auto_delete(_identity, _zone, _auto_delete, _device_name) Fog::Mock.not_implemented end end class Real def set_server_disk_auto_delete(identity, zone, auto_delete, device_name) api_method = @compute.instances.set_disk_auto_delete parameters = { "project" => @project, "instance" => identity, "zone" => zone.split("/")[-1], "autoDelete" => auto_delete, "deviceName" => device_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_zone_view.rb0000644000004100000410000000100113145731036025104 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_zone_view(_zone_view) Fog::Mock.not_implemented end end class Real def get_zone_view(zone_view_name, zone) api_method = @resourceviews.zone_views.get parameters = { "projectName" => @project, "resourceViewName" => zone_view_name, "zone" => zone } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_global_operation.rb0000644000004100000410000000107213145731036027112 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_global_operation(_operation) Fog::Mock.not_implemented end end class Real # https://developers.google.com/compute/docs/reference/latest/globalOperations def delete_global_operation(operation) api_method = @compute.global_operations.delete parameters = { "project" => @project, "operation" => operation } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/remove_target_pool_instance.rb0000644000004100000410000000131413145731036030027 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_metadata(_instance, _zone, _fingerprint, _metadata = {}) Fog::Mock.not_implemented end end class Real def remove_target_pool_instances(target_pool, instances) api_method = @compute.target_pools.remove_instance parameters = { "project" => @project, "targetPool" => target_pool.name, "region" => target_pool.region.split("/")[-1] } body = { "instances" => instances.map { |i| { "instance" => i } } } request(api_method, parameters, body_object = body) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_forwarding_rule.rb0000644000004100000410000000462013145731036027027 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_forwarding_rule(name, region_name, opts = {}) # check that region exists get_region(region_name) id = Fog::Mock.random_numbers(19).to_s data[:forwarding_rules][name] = { "kind" => "compute#forwardingRule", "id" => id, "creationTimestamp" => Time.now.iso8601, "name" => name, "description" => "", "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}", "IPAddress" => "", "IPProtocol" => "", "portRange" => "", "target" => opts["target"], "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/forwardingRules/#{name}" } operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}", "operationType" => "insert", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/forwardingRules/#{name}", "targetId" => id, "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def insert_forwarding_rule(forwarding_rule_name, region_name, opts = {}) api_method = @compute.forwarding_rules.insert parameters = { "project" => @project, "region" => region_name } body_object = { "name" => forwarding_rule_name } body_object.merge!(opts) request(api_method, parameters, body_object = body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_aggregated_servers.rb0000644000004100000410000000312213145731036027144 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_servers(options = {}) # Create a Hash of unique zones from the servers Array previously filled when servers are created zones = Hash[data[:servers].values.map { |server| ["zones/#{server['zone'].split('/')[-1]}", { "instances" => [] }] }] if options[:filter] # Look up for the server name server = data[:servers][options[:filter].gsub(/name eq \.\*/, "")] # Fill the zones Hash with the server (if it's found) zones["zones/#{server['zone'].split('/')[-1]}"]["instances"].concat([server]) if server else # Fill the zones Hash with the servers attached to each zone data[:servers].values.each { |server| zones["zones/#{server['zone'].split('/')[-1]}"]["instances"].concat([server]) } end build_excon_response("kind" => "compute#instanceAggregatedList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/aggregated/instances", "id" => "projects/#{@project}/aggregated/instances", "items" => zones) end end class Real def list_aggregated_servers(options = {}) api_method = @compute.instances.aggregated_list parameters = { "project" => @project } parameters["filter"] = options[:filter] if options[:filter] request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_disk.rb0000644000004100000410000000324013145731036024523 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_disk(disk_name, zone_name) get_disk(disk_name, zone_name) operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}", "operationType" => "delete", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/disks/#{disk_name}", "targetId" => data[:disks][disk_name]["id"], "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/operations/#{operation}" } data[:disks].delete disk_name build_excon_response(data[:operations][operation]) end end class Real def delete_disk(disk_name, zone_name) zone_name = zone_name.split("/")[-1] if zone_name.start_with? "http" api_method = @compute.disks.delete parameters = { "project" => @project, "disk" => disk_name, "zone" => zone_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_url_maps.rb0000644000004100000410000000132613145731036025127 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_url_maps url_maps = data[:url_maps].values build_excon_response("kind" => "compute#urlMapList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/urlMaps", "id" => "projects/#{@project}/global/urlMaps", "items" => url_maps) end end class Real def list_url_maps api_method = @compute.url_maps.list parameters = { "project" => @project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_server_access_config.rb0000644000004100000410000000134313145731036027747 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_server_access_config(_identity, _zone, _nic, _options = {}) Fog::Mock.not_implemented end end class Real def delete_server_access_config(identity, zone, nic, options = {}) api_method = @compute.instances.delete_access_config parameters = { "project" => @project, "instance" => identity, "zone" => zone.split("/")[-1], "networkInterface" => nic, "accessConfig" => options[:access_config].nil? ? "External NAT" : options[:access_config] } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/reset_server.rb0000644000004100000410000000077413145731036024770 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def reset_server(_identity, _zone) Fog::Mock.not_implemented end end class Real def reset_server(identity, zone) api_method = @compute.instances.reset parameters = { "project" => @project, "instance" => identity, "zone" => zone.split("/")[-1] } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_routes.rb0000644000004100000410000000061713145731036024630 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_routes(_options = {}) Fog::Mock.not_implemented end end class Real def list_routes api_method = @compute.routes.list parameters = { "project" => @project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_firewall.rb0000644000004100000410000000072513145731036025403 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_firewall(_firewall_name) Fog::Mock.not_implemented end end class Real def delete_firewall(firewall_name) api_method = @compute.firewalls.delete parameters = { "project" => @project, "firewall" => firewall_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/update_firewall.rb0000644000004100000410000000263613145731036025426 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def update_firewall(_firewall_name, _allowed, _network = GOOGLE_COMPUTE_DEFAULT_NETWORK, _options = {}) Fog::Mock.not_implemented end end class Real def update_firewall(firewall_name, allowed, network = GOOGLE_COMPUTE_DEFAULT_NETWORK, options = {}) unless network.start_with? "http" network = "#{@api_url}#{@project}/global/networks/#{network}" end api_method = @compute.firewalls.update parameters = { "project" => @project, "firewall" => firewall_name } body_object = { "allowed" => allowed, "network" => network } unless options[:description].nil? body_object["description"] = options[:description] end unless options[:source_ranges].nil? || options[:source_ranges].empty? body_object["sourceRanges"] = options[:source_ranges] end unless options[:source_tags].nil? || options[:source_tags].empty? body_object["sourceTags"] = options[:source_tags] end unless options[:target_tags].nil? || options[:target_tags].empty? body_object["targetTags"] = options[:target_tags] end request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/add_url_map_host_rules.rb0000644000004100000410000000121213145731036026762 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def add_url_map_host_rules(_url_map, _host_rules) Fog::Mock.not_implemented end end class Real def add_url_map_host_rules(url_map, host_rules) api_method = @compute.url_maps.update parameters = { "project" => @project, "urlMap" => url_map.name } if url_map.hostRules then url_map.hostRules.concat(host_rules) else url_map.hostRules = host_rules end body = url_map request(api_method, parameters, body_object = body) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_backend_service.rb0000644000004100000410000000113513145731036026216 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_backend_service(service_name) backend_service = data[:backend_services][service_name] return nil if backend_service.nil? build_excon_response(backend_service) end end class Real def get_backend_service(service_name) api_method = @compute.backend_services.get parameters = { "project" => @project, "backendService" => service_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/set_global_forwarding_rule_target.rb0000644000004100000410000000120013145731036031173 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_global_forwarding_rule_target(_rule, _target) Fog::Mock.not_implemented end end class Real def set_global_forwarding_rule_target(rule, target) api_method = @compute.global_forwarding_rules.set_target parameters = { "project" => @project, "forwardingRule" => rule.name, "region" => "global" } body = { "target" => target } request(api_method, parameters, body_object = body) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_target_pool_health.rb0000644000004100000410000000244113145731036026754 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_target_pool_health(_target_pool, _instance) Fog::Mock.not_implemented end end class Real def get_target_pool_health(target_pool, instance = nil) api_method = @compute.target_pools.get_health parameters = { "project" => @project, "targetPool" => target_pool.name, "region" => target_pool.region.split("/")[-1] } if instance body = { "instance" => instance } resp = request(api_method, parameters, body_object = body) [instance, resp.data[:body]["healthStatus"]] else # TODO: Remove (introduced after 0.4.2) Fog::Logger.deprecation( "Do not use raw requests, use Fog::Compute::Google::TargetPool.get_health instead [light_black](#{caller.first})[/]" ) health_results = target_pool.instances.map do |instance_object| body = { "instance" => instance_object } resp = request(api_method, parameters, body_object = body) [instance_object, resp.data[:body]["healthStatus"]] end Hash[health_results] end end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_snapshot.rb0000644000004100000410000000072513145731036025435 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_snapshot(_snapshot_name) Fog::Mock.not_implemented end end class Real def delete_snapshot(snapshot_name) api_method = @compute.snapshots.delete parameters = { "project" => @project, "snapshot" => snapshot_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_aggregated_addresses.rb0000644000004100000410000000101513145731036027427 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_addresses(_options = {}) Fog::Mock.not_implemented end end class Real def list_aggregated_addresses(options = {}) api_method = @compute.addresses.aggregated_list parameters = { "project" => @project } parameters["filter"] = options[:filter] if options[:filter] request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/set_tags.rb0000644000004100000410000000115313145731036024061 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_tags(_instance, _zone, _tags = []) Fog::Mock.not_implemented end end class Real def set_tags(instance, zone, fingerprint, tags = []) api_method = @compute.instances.set_tags parameters = { "project" => @project, "instance" => instance, "zone" => zone } body_object = { "fingerprint" => fingerprint, "items" => tags } request(api_method, parameters, body_object = body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_network.rb0000644000004100000410000000140313145731036025323 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_network(_network_name, _ip_range, _options = {}) Fog::Mock.not_implemented end end class Real def insert_network(network_name, ip_range, options = {}) api_method = @compute.networks.insert parameters = { "project" => @project } body_object = { "name" => network_name, "IPv4Range" => ip_range } body_object["description"] = options[:description] if options[:description] body_object["gatewayIPv4"] = options[:gateway_ipv4] if options[:gateway_ipv4] request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_http_health_check.rb0000644000004100000410000000300313145731036027227 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_http_health_check(name) get_http_health_check(name) check = data[:http_health_checks][name] operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global", "operationType" => "delete", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/httpHealthChecks/#{name}", "targetId" => data[:http_health_checks][name]["id"], "status" => "DONE", "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def delete_http_health_check(name) api_method = @compute.http_health_checks.delete parameters = { "project" => @project, "httpHealthCheck" => name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_global_operation.rb0000644000004100000410000000303413145731036026427 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_global_operation(operation) operation = data[:operations][operation] if operation case operation["status"] when Fog::Compute::Google::Operation::PENDING_STATE operation["status"] = Fog::Compute::Google::Operation::RUNNING_STATE operation["progress"] = 50 else operation["status"] = Fog::Compute::Google::Operation::DONE_STATE operation["progress"] = 100 end else operation = { "error" => { "errors" => [ { "domain" => "global", "reason" => "notFound", "message" => "The resource 'projects/#{project}/global/operations/#{operation}' was not found" } ], "code" => 404, "message" => "The resource 'projects/#{project}/global/operations/#{operation}' was not found" } } end build_excon_response(operation) end end class Real # https://developers.google.com/compute/docs/reference/latest/globalOperations def get_global_operation(operation) api_method = @compute.global_operations.get parameters = { "project" => @project, "operation" => operation } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_zones.rb0000644000004100000410000000125713145731036024446 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_zones zones = data[:zones].values build_excon_response("kind" => "compute#zoneList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones", "id" => "projects/#{@project}/zones", "items" => zones) end end class Real def list_zones api_method = @compute.zones.list parameters = { "project" => @project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/set_server_scheduling.rb0000644000004100000410000000151713145731036026642 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_server_scheduling(_identity, _zone, _on_host_maintenance, _automatic_restart, _preemptible) Fog::Mock.not_implemented end end class Real def set_server_scheduling(identity, zone, on_host_maintenance, automatic_restart, preemptible) api_method = @compute.instances.set_scheduling parameters = { "project" => @project, "instance" => identity, "zone" => zone.split("/")[-1] } body_object = { "onHostMaintenance" => on_host_maintenance, "automaticRestart" => automatic_restart, "preemptible" => preemptible } request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_url_map.rb0000644000004100000410000000406713145731036025302 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_url_map(url_map_name, opts) id = Fog::Mock.random_numbers(19).to_s data[:url_maps][url_map_name] = { "kind" => "compute#urlMap", "id" => id, "creationTimestamp" => Time.now.iso8601, "name" => url_map_name, "description" => "", "hostRules" => [], "pathMatchers" => [], "tests" => [], "defaultService" => opts["defaultService"], "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/urlMaps/#{url_map_name}" } operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global", "operationType" => "insert", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/urlMaps/#{url_map_name}", "targetId" => id, "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def insert_url_map(url_map_name, opts = {}) api_method = @compute.url_maps.insert parameters = { "project" => @project } body_object = { "name" => url_map_name } body_object.merge!(opts) request(api_method, parameters, body_object = body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/start_server.rb0000644000004100000410000000076713145731036025005 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def start_server(_identity, _zone_name) Fog::Mock.not_implemented end end class Real def start_server(identity, zone_name) api_method = @compute.instances.start parameters = { "project" => @project, "zone" => zone_name, "instance" => identity } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/set_target_http_proxy_url_map.rb0000644000004100000410000000130313145731036030425 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_target_http_proxy_url_map(_target_http_proxy, _url_map) Fog::Mock.not_implemented end end class Real def set_target_http_proxy_url_map(target_http_proxy, url_map) api_method = @compute.target_http_proxies.set_url_map parameters = { "project" => @project, "targetHttpProxy" => target_http_proxy.name } url_map = url_map.self_link unless url_map.class == String body = { "urlMap" => url_map } request(api_method, parameters, body_object = body) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_image_from_family.rb0000644000004100000410000000171013145731036026554 0ustar www-datawww-datamodule Fog module Compute class Google # Returns the latest non-deprecated image that is part of an image family. # # ==== Parameters # * family<~String> - Name of the image resource to return. # # ==== Returns # * response<~Excon::Response>: # * body<~Hash> - corresponding compute#image resource # # ==== See also: # https://cloud.google.com/compute/docs/reference/latest/images/getFromFamily class Mock def get_image_from_family(_family, _project = @project) Fog::Mock.not_implemented end end class Real def get_image_from_family(family, project = nil) api_method = @compute.images.get_from_family project = @project if project.nil? parameters = { "family" => family, "project" => project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_firewall.rb0000644000004100000410000000071413145731036024716 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_firewall(_firewall_name) Fog::Mock.not_implemented end end class Real def get_firewall(firewall_name) api_method = @compute.firewalls.get parameters = { "project" => @project, "firewall" => firewall_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_disks.rb0000644000004100000410000000150113145731036024415 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_disks(zone_name) disks = data[:disks].values.select { |d| d["zone"].split("/")[-1] == zone_name } build_excon_response("kind" => "compute#diskList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/disks", "id" => "projects/#{@project}/zones/#{zone_name}/disks", "items" => disks) end end class Real def list_disks(zone_name) api_method = @compute.disks.list parameters = { "project" => @project, "zone" => zone_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_http_health_check.rb0000644000004100000410000000251613145731036026554 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_http_health_check(name) http_health_check = data[:http_health_checks][name] if http_health_check.nil? return build_excon_response("error" => { "errors" => [ { "domain" => "global", "reason" => "notFound", "message" => "The resource 'projects/#{@project}/global/httpHealthChecks/#{name}' was not found" } ], "code" => 404, "message" => "The resource 'projects/#{@project}/global/httpHealthChecks/#{name}' was not found" }) end build_excon_response(http_health_check) end end class Real def get_http_health_check(name) api_method = @compute.http_health_checks.get parameters = { "project" => @project, "httpHealthCheck" => name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/add_url_map_path_matchers.rb0000644000004100000410000000126713145731036027427 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def add_url_map_path_matchers(_url_map, _path_matchers) Fog::Mock.not_implemented end end class Real def add_url_map_path_matchers(url_map, path_matchers) api_method = @compute.url_maps.update parameters = { "project" => @project, "urlMap" => url_map.name } if url_map.pathMatchers url_map.pathMatchers.concat(path_matchers) else url_map.pathMatchers = path_matchers end request(api_method, parameters, body_object = url_map) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_servers.rb0000644000004100000410000000163213145731036024776 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_servers(zone_name) get_zone(zone_name) zone = data[:zones][zone_name] servers = data[:servers].values.select { |s| s["zone"] == zone["selfLink"] } build_excon_response("kind" => "compute#instanceList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/instances", "id" => "projects/#{@project}/zones/#{zone_name}/instances", "items" => servers) end end class Real def list_servers(zone_name) api_method = @compute.instances.list parameters = { "project" => @project, "zone" => zone_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_zone_operation.rb0000644000004100000410000000126413145731036026630 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_zone_operation(_zone, _operation) Fog::Mock.not_implemented end end class Real # https://developers.google.com/compute/docs/reference/latest/zoneOperations def delete_zone_operation(zone_name, operation) zone_name = zone_name.split("/")[-1] if zone_name.start_with? "http" api_method = @compute.zone_operations.delete parameters = { "project" => @project, "zone" => zone_name, "operation" => operation } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_global_forwarding_rules.rb0000644000004100000410000000163613145731036030205 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_global_forwarding_rules(_region_name = "global") global_forwarding_rules = data[:global_forwarding_rules].values build_excon_response("kind" => "compute#forwardingRuleList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/forwardingRules", "id" => "projects/#{@project}/global/forwardingRules", "items" => global_forwarding_rules) end end class Real def list_global_forwarding_rules(region_name = "global") api_method = @compute.global_forwarding_rules.list parameters = { "project" => @project, "region" => region_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_project.rb0000644000004100000410000000062513145731036024560 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_project(_identity) Fog::Mock.not_implemented end end class Real def get_project(identity) api_method = @compute.projects.get parameters = { :project => identity } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_disk.rb0000644000004100000410000000320413145731036024040 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_disk(disk_name, zone_name) disk = data[:disks][disk_name] zone_name = zone_name.split("/")[-1] if zone_name.start_with? "http" get_zone(zone_name) zone = data[:zones][zone_name] if disk.nil? || disk["zone"] != zone["selfLink"] return build_excon_response("error" => { "errors" => [ { "domain" => "global", "reason" => "notFound", "message" => "The resource 'projects/#{@project}/zones/#{zone_name}/disks/#{disk_name}' was not found" } ], "code" => 404, "message" => "The resource 'projects/#{@project}/zones/#{zone_name}/disks/#{disk_name}' was not found" }) end # TODO: transition the disk through the states build_excon_response(disk) end end class Real def get_disk(disk_name, zone_name) zone_name = zone_name.split("/")[-1] if zone_name.start_with? "http" api_method = @compute.disks.get parameters = { "project" => @project, "disk" => disk_name, "zone" => zone_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_target_instances.rb0000644000004100000410000000171513145731036026644 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_target_instances(zone_name = "us-central1-a") zone = data[:zones][zone_name] target_instances = data[:target_instances].values.select { |s| s["zone"] == zone_name } build_excon_response("kind" => "compute#targetInstanceList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/targetInstances", "id" => "projects/#{@project}/zones/#{zone_name}/targetInstances", "items" => target_instances) end end class Real def list_target_instances(zone_name) api_method = @compute.target_instances.list parameters = { "project" => @project, "zone" => zone_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_target_http_proxy.rb0000644000004100000410000000372713145731036027433 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_target_http_proxy(name, options = {}) id = Fog::Mock.random_numbers(19).to_s data[:target_http_proxies][name] = { "kind" => "compute#targetHttpProxy", "id" => id, "creationTimestamp" => Time.now.iso8601, "name" => name, "description" => "", "urlMap" => options["urlMap"], "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/targetHttpProxies/#{name}" } operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global", "operationType" => "insert", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/targetHttpProxies/#{name}", "targetId" => id, "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def insert_target_http_proxy(name, opts = {}) api_method = @compute.target_http_proxies.insert parameters = { "project" => @project } body_object = { "name" => name } body_object.merge!(opts) request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_backend_services.rb0000644000004100000410000000103713145731036026402 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_backend_services(_service_name) Fog::Mock.not_implemented end end class Real def get_backend_services(service_name) api_method = @compute.backend_services.get parameters = { "project" => @project, "backendService" => service_name } result = build_result(api_method, parameters) response = build_response(result) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_image.rb0000644000004100000410000000174413145731036024177 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_image(image_name, project = @project) image = data(project)[:images][image_name] || { "error" => { "errors" => [ { "domain" => "global", "reason" => "notFound", "message" => "The resource 'projects/#{project}/global/images/#{image_name}' was not found" } ], "code" => 404, "message" => "The resource 'projects/#{project}/global/images/#{image_name}' was not found" } } build_excon_response(image) end end class Real def get_image(image_name, project = @project) api_method = @compute.images.get parameters = { "image" => image_name, "project" => project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_instance_group.rb0000644000004100000410000000105313145731036026126 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_instance_group(_group_name, _zone, _project = @project) Fog::Mock.not_implemented end end class Real def get_instance_group(group_name, zone, project = @project) api_method = @compute.instance_groups.get parameters = { "instanceGroup" => group_name, "project" => project, "zone" => zone } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_snapshot.rb0000644000004100000410000000104613145731036024747 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_snapshot(_snap_name) Fog::Mock.not_implemented end end class Real def get_snapshot(snap_name, project = @project) raise ArgumentError.new "snap_name must not be nil." if snap_name.nil? api_method = @compute.snapshots.get parameters = { "snapshot" => snap_name, "project" => project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_addresses.rb0000644000004100000410000000071113145731036025257 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_addresses(_region_name) Fog::Mock.not_implemented end end class Real def list_addresses(region_name) api_method = @compute.addresses.list parameters = { "project" => @project, "region" => region_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_region_view.rb0000644000004100000410000000102213145731036026102 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_region_view(_region_view) Fog::Mock.not_implemented end end class Real def delete_region_view(region_view, region) api_method = @resourceviews.region_views.delete parameters = { "projectName" => @project, "resourceViewName" => region_view, "region" => region } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_http_health_checks.rb0000644000004100000410000000143213145731036027127 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_http_health_checks health_checks = data[:http_health_checks].values build_excon_response("kind" => "compute#urlMapList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/httpHealthChecks", "id" => "projects/#{@project}/global/httpHealthChecks", "items" => health_checks) end end class Real def list_http_health_checks api_method = @compute.http_health_checks.list parameters = { "project" => @project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_subnetwork.rb0000644000004100000410000000370213145731036025777 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_subnetwork(subnetwork_name, region_name) subnetwork_name = subnetwork_name.split("/")[-1] if subnetwork_name.start_with? "http" region_name = region_name.split("/")[-1] if region_name.start_with? "http" get_subnetwork(subnetwork_name, region_name) operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "operationType" => "delete", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/subnetworks/#{subnetwork_name}", "targetId" => data[:subnetworks][subnetwork_name]["id"], "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/operations/#{operation}", "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}" } data[:subnetworks].delete subnetwork_name build_excon_response(data[:operations][operation]) end end class Real def delete_subnetwork(subnetwork_name, region_name) if region_name.start_with? "http" region_name = region_name.split("/")[-1] end api_method = @compute.subnetworks.delete parameters = { "project" => @project, "region" => region_name, "subnetwork" => subnetwork_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_region_view.rb0000644000004100000410000000104113145731036025420 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_region_view(_region_view_name, _region) Fog::Mock.not_implemented end end class Real def get_region_view(region_view_name, region) api_method = @resourceviews.region_views.get parameters = { "projectName" => @project, "resourceViewName" => region_view_name, "region" => region } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_aggregated_disks.rb0000644000004100000410000000302013145731036026565 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_disks(options = {}) # Create a Hash of unique zones from the disks Array previously filled when disks are created zones = Hash[data[:disks].values.map { |disk| ["zones/#{disk['zone'].split('/')[-1]}", { "disks" => [] }] }] if options[:filter] # Look up for the disk name disk = data[:disks][options[:filter].gsub(/name eq \.\*/, "")] # Fill the zones Hash with the disk (if it's found) zones["zones/#{disk['zone'].split('/')[-1]}"]["disks"].concat([disk]) if disk else # Fill the zones Hash with the disks attached to each zone data[:disks].values.each { |disk| zones["zones/#{disk['zone'].split('/')[-1]}"]["disks"].concat([disk]) } end build_excon_response("kind" => "compute#diskAggregatedList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/aggregated/disks", "id" => "projects/#{@project}/aggregated/disks", "items" => zones) end end class Real def list_aggregated_disks(options = {}) api_method = @compute.disks.aggregated_list parameters = { "project" => @project } parameters["filter"] = options[:filter] if options[:filter] request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/update_url_map.rb0000644000004100000410000000200013145731036025241 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def update_url_map(_url_map, _host_rules) Fog::Mock.not_implemented end end class Real def update_url_map(url_map, host_rules, path_matchers = nil) api_method = @compute.url_maps.update parameters = { "project" => @project, "urlMap" => url_map.name } # add new properties to the url_map resource if url_map.hostRules url_map.hostRules.concat(host_rules) else url_map.hostRules = host_rules end # a path matcher can only be created with a host rule that uses it if path_matchers if url_map.pathMatchers url_map.pathMatchers.concat(path_matchers) else url_map.pathMatchers = path_matchers end end request(api_method, parameters, body_object = url_map) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_zone_views.rb0000644000004100000410000000071613145731036025477 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_zone_views(_zone_name) Fog::Mock.not_implemented end end class Real def list_zone_views(zone_name) api_method = @resourceviews.zone_views.list parameters = { "projectName" => @project, "zone" => zone_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_region_view_resources.rb0000644000004100000410000000106313145731036027712 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_region_view_resources(_region_view) Fog::Mock.not_implemented end end class Real def list_region_view_resources(region_view) api_method = @resourceviews.region_views.list_resources parameters = { "projectName" => @project, "region" => region_view.region, "resourceViewName" => region_view.name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_regions.rb0000644000004100000410000001152013145731036024750 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_regions build_excon_response("kind" => "compute#regionList", "selfLink" => "https://www.googleapis.com/compute/v1/projects/#{@project}/regions", "id" => "projects/#{@project}/regions", "items" => [ { "kind" => "compute#region", "selfLink" => "https://www.googleapis.com/compute/v1/projects/#{@project}/regions/asia-east1", "id" => "2699746309412936080", "creationTimestamp" => "2014-01-28T04:12:16.138-08:00", "name" => "asia-east1", "description" => "asia-east1", "status" => "UP", "zones" => [ "https://www.googleapis.com/compute/v1/projects/#{@project}/zones/asia-east1-a", "https://www.googleapis.com/compute/v1/projects/#{@project}/zones/asia-east1-b" ], "quotas" => [ { "metric" => "CPUS", "limit" => 24.0, "usage" => 0.0 }, { "metric" => "DISKS_TOTAL_GB", "limit" => 5120.0, "usage" => 0.0 }, { "metric" => "STATIC_ADDRESSES", "limit" => 7.0, "usage" => 0.0 }, { "metric" => "IN_USE_ADDRESSES", "limit" => 23.0, "usage" => 0.0 } ] }, { "kind" => "compute#region", "selfLink" => "https://www.googleapis.com/compute/v1/projects/#{@project}/regions/europe-west1", "id" => "10546209748879352030", "creationTimestamp" => "2014-01-14T18:36:29.094-08:00", "name" => "europe-west1", "description" => "europe-west1", "status" => "UP", "zones" => [ "https://www.googleapis.com/compute/v1/projects/#{@project}/zones/europe-west1-a", "https://www.googleapis.com/compute/v1/projects/#{@project}/zones/europe-west1-b" ], "quotas" => [ { "metric" => "CPUS", "limit" => 24.0, "usage" => 0.0 }, { "metric" => "DISKS_TOTAL_GB", "limit" => 5120.0, "usage" => 0.0 }, { "metric" => "STATIC_ADDRESSES", "limit" => 7.0, "usage" => 0.0 }, { "metric" => "IN_USE_ADDRESSES", "limit" => 23.0, "usage" => 0.0 } ] }, { "kind" => "compute#region", "selfLink" => "https://www.googleapis.com/compute/v1/projects/#{@project}/regions/us-central1", "id" => "17971001795365542305", "creationTimestamp" => "2014-01-14T18:36:29.094-08:00", "name" => "us-central1", "description" => "us-central1", "status" => "UP", "zones" => [ "https://www.googleapis.com/compute/v1/projects/#{@project}/zones/us-central1-a", "https://www.googleapis.com/compute/v1/projects/#{@project}/zones/us-central1-b" ], "quotas" => [ { "metric" => "CPUS", "limit" => 24.0, "usage" => 0.0 }, { "metric" => "DISKS_TOTAL_GB", "limit" => 5120.0, "usage" => 0.0 }, { "metric" => "STATIC_ADDRESSES", "limit" => 7.0, "usage" => 0.0 }, { "metric" => "IN_USE_ADDRESSES", "limit" => 23.0, "usage" => 0.0 } ] } ]) end end class Real def list_regions api_method = @compute.regions.list parameters = { "project" => @project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_url_map.rb0000644000004100000410000000303313145731036025230 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_url_map(name) get_url_map(name) url_map = data[:url_maps][name] url_map["mock-deletionTimestamp"] = Time.now.iso8601 url_map["status"] = "DONE" operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global", "operationType" => "delete", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/urlMaps/#{name}", "targetId" => data[:url_maps][name]["id"], "status" => "DONE", "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def delete_url_map(name) api_method = @compute.url_maps.delete parameters = { "project" => @project, "urlMap" => name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_instance_group.rb0000644000004100000410000000101413145731036026606 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_instance_group(_group_name, _zone) Fog::Mock.not_implemented end end class Real def delete_instance_group(group_name, zone) api_method = @compute.instance_groups.delete parameters = { "instanceGroup" => group_name, "project" => @project, "zone" => zone } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_image.rb0000644000004100000410000000262213145731036024656 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_image(image_name) get_image(image_name) operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "operationType" => "delete", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/images/#{image_name}", "targetId" => data[:images][image_name]["id"], "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/operations/#{operation}" } data[:images].delete image_name build_excon_response(data[:operations][operation]) end end class Real def delete_image(image_name) api_method = @compute.images.delete parameters = { "project" => @project, "image" => image_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_url_map.rb0000644000004100000410000000077613145731036024560 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_url_map(name) url_map = data[:url_maps][name] return nil if url_map.nil? build_excon_response(url_map) end end class Real def get_url_map(name) api_method = @compute.url_maps.get parameters = { "project" => @project, "urlMap" => name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_network.rb0000644000004100000410000000071613145731036025267 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_network(_network_name) Fog::Mock.not_implemented end end class Real def delete_network(network_name) api_method = @compute.networks.delete parameters = { "project" => @project, "network" => network_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_http_health_check.rb0000644000004100000410000000423013145731036027274 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_http_health_check(name, _options = {}) id = Fog::Mock.random_numbers(19).to_s data[:http_health_checks][name] = { "kind" => "compute#httpHealthCheck", "id" => id, "creationTimestamp" => Time.now.iso8601, "name" => name, "description" => "", "host" => "0.00.0.0", "requestPath" => "/", "port" => 80, "checkIntervalSec" => 5, "timeoutSec" => 5, "unhealthyThreshold" => 2, "healthyThreshold" => 2, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/httpHealthChecks/#{name}" } operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global", "operationType" => "insert", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/httpHealthChecks/#{name}", "targetId" => id, "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def insert_http_health_check(name, opts = {}) api_method = @compute.http_health_checks.insert parameters = { "project" => @project } body_object = { "name" => name } body_object.merge!(opts) request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_subnetwork.rb0000644000004100000410000000556713145731036026054 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_subnetwork(subnetwork_name, region_name, network, ip_range, _options = {}) subnetwork_name = subnetwork_name.split("/")[-1] if subnetwork_name.start_with? "http" region_name = region_name.split("/")[-1] if region_name.start_with? "http" network_name = network.split("/")[-1] gateway = ip_range.split("/").first.split(".") gateway[-1] = "1" id = Fog::Mock.random_numbers(19).to_s object = { "kind" => "compute#subnetwork", "id" => id, "creationTimestamp" => Time.now.iso8601, "gatewayAddress" => gateway.join("."), "name" => subnetwork_name, "network" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/networks/#{network_name}", "ipCidrRange" => ip_range, "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/subnetworks/#{subnetwork_name}" } data[:subnetworks][subnetwork_name] = object operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "region" => object["region"], "operationType" => "insert", "targetLink" => object["selfLink"], "targetId" => id, "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "#{object['region']}/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def insert_subnetwork(subnetwork_name, region_name, network, ip_range, options = {}) region_name = region_name.split("/")[-1] if region_name.start_with? "http" unless network.start_with? "http" network = "#{@api_url}#{@project}/global/networks/#{network}" end api_method = @compute.subnetworks.insert parameters = { "project" => @project, "region" => region_name } body_object = { "ipCidrRange" => ip_range, "name" => subnetwork_name, "network" => network } body_object["description"] = options[:description] if options[:description] request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_region_views.rb0000644000004100000410000000073413145731036026007 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_region_views(_region_name) Fog::Mock.not_implemented end end class Real def list_region_views(region_name) api_method = @resourceviews.region_views.list parameters = { "projectName" => @project, "region" => region_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/remove_instance_group_instances.rb0000644000004100000410000000172013145731036030714 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def add_instance_group_instances(_group, _zone, _instances) Fog::Mock.not_implemented end end class Real def remove_instance_group_instances(group_name, zone, instances) api_method = @compute.instance_groups.remove_instances parameters = { "project" => @project, "instanceGroup" => group_name, "zone" => zone } instances.map! do |instance| if instance.start_with?("https:") { "instance" => instance } else { "instance" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone}/instances/#{instance}\n" } end end body_object = { "instances" => instances } request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_image.rb0000644000004100000410000000406013145731036024716 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_image(image_name, options = {}) id = Fog::Mock.random_numbers(19).to_s object = { "kind" => "compute#image", "id" => id, "creationTimestamp" => Time.now.iso8601, "sourceType" => "", "rawDisk" => { "source" => options ["source"], "shal1Checksum" => "", "containerType" => "" }, "status" => "READY", "name" => image_name, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/images/#{image_name}" } data[:images][image_name] = object operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "operationType" => "insert", "targetLink" => object["selfLink"], "targetId" => id, "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def insert_image(image_name, options = {}) api_method = @compute.images.insert parameters = { "project" => @project } body_object = { "sourceType" => "RAW", "name" => image_name } # Merge in the remaining params body_object.merge!(options) request(api_method, parameters, body_object = body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_snapshot.rb0000644000004100000410000000234113145731036025473 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_snapshot(_snap_name) Fog::Mock.not_implemented end end class Real def insert_snapshot(disk_name, zone_name, _project = @project, opts = {}) # This is unfortunate, since we might be called from 2 contexts # 1. disk.snapshot <-- here validation of disk_name is not needed # 2. snapshot.create <-- here we must validate the disk_name # # Validation would involve 'get'ing the disk by that name. This is # redundant (and expensive) for case (1) which is likely the common # codepath. So we won't do it. api_method = @compute.disks.create_snapshot parameters = { "disk" => disk_name, "zone" => zone_name, "project" => @project } snap_name = opts.delete("name") raise ArgumentError.new("Must specify snapshot name") unless snap_name body_object = { "name" => snap_name } # Merge in any remaining options (description) body_object.merge!(opts) request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_target_instance.rb0000644000004100000410000000432213145731036027007 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_target_instance(target_instance, zone_name, opts = {}) id = Fog::Mock.random_numbers(19).to_s data[:target_instances][target_instance] = { "kind" => "compute#targetInstance", "id" => id, "creationTimestamp" => Time.now.iso8601, "name" => target_instance, "description" => "", "natPolicy" => "", "zone" => zone_name, "instance" => opts["instance"], "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/targetInstances/#{target_instance}" } operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}", "operationType" => "insert", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/targetInstances/#{target_instance}", "targetId" => id, "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone_name}/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def insert_target_instance(target_instance_name, zone_name, opts = {}) api_method = @compute.target_instances.insert parameters = { "project" => @project, "zone" => zone_name } body_object = { "name" => target_instance_name } body_object.merge!(opts) request(api_method, parameters, body_object = body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_global_forwarding_rule.rb0000644000004100000410000000154313145731036027623 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_global_forwarding_rule(name, _region_name = "global") global_forwarding_rule = data[:global_forwarding_rules][name] return nil if global_forwarding_rule.nil? build_excon_response(global_forwarding_rule) end end class Real def get_global_forwarding_rule(global_forwarding_rule_name, region_name = "global") if region_name.start_with? "http" region_name = region_name.split("/")[-1] end api_method = @compute.global_forwarding_rules.get parameters = { "project" => @project, "forwardingRule" => global_forwarding_rule_name, "region" => region_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_route.rb0000644000004100000410000000223213145731036024771 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_route(_name, _network, _dest_range, _priority, _options = {}) Fog::Mock.not_implemented end end class Real def insert_route(name, network, dest_range, priority, options = {}) api_method = @compute.routes.insert parameters = { "project" => @project } body_object = { "name" => name, "network" => network, "destRange" => dest_range, "priority" => priority } body_object["description"] = options[:description] if options[:description] unless options[:tags].nil? || options[:tags].empty? body_object["tags"] = options[:tags] end body_object["nextHopInstance"] = options[:next_hop_instance] if options[:next_hop_instance] body_object["nextHopGateway"] = options[:next_hop_gateway] if options[:next_hop_gateway] body_object["nextHopIp"] = options[:next_hop_ip] if options[:next_hop_ip] request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/attach_disk.rb0000644000004100000410000000170113145731036024525 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def attach_disk(_instance, _zone, _source, _options = {}) Fog::Mock.not_implemented end end class Real def attach_disk(instance, zone, source, options = {}) api_method = @compute.instances.attach_disk parameters = { "project" => @project, "instance" => instance, "zone" => zone.split("/")[-1] } writable = options.delete(:writable) body_object = { "type" => "PERSISTENT", "source" => source, "mode" => writable ? "READ_WRITE" : "READ_ONLY", "deviceName" => options.delete(:deviceName), "boot" => options.delete(:boot), "autoDelete" => options.delete(:autoDelete) } request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_disk_types.rb0000644000004100000410000000411713145731036025464 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_disk_types(zone) build_excon_response("kind" => 'compute#diskTypeList', "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone}/diskTypes", "items" => [ { "kind" => 'compute#diskType', "creationTimestamp" => "2014-06-02T18:07:28.530Z", "name" => "pd-standard", "description" => "Standard Persistent Disk", "validDiskSize" => "10GB-10TB", "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone}", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone}/diskTypes/pd-standard" }, { "kind" => 'compute#diskType', "creationTimestamp" => "2014-06-02T18:07:28.529Z", "name" => "pd-ssd", "description" => "SSD Persistent Disk", "validDiskSize" => "10GB-1TB", "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone}", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone}/diskTypes/pd-ssd" } ]) end end class Real def list_disk_types(zone) api_method = @compute.disk_types.list parameters = { "project" => @project, "zone" => zone.split("/")[-1] } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_firewalls.rb0000644000004100000410000000061113145731036025271 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_firewalls Fog::Mock.not_implemented end end class Real def list_firewalls api_method = @compute.firewalls.list parameters = { "project" => @project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_firewall.rb0000644000004100000410000000263213145731036025444 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_firewall(_firewall_name, _allowed, _network = GOOGLE_COMPUTE_DEFAULT_NETWORK, _options = {}) Fog::Mock.not_implemented end end class Real def insert_firewall(firewall_name, allowed, network = GOOGLE_COMPUTE_DEFAULT_NETWORK, options = {}) unless network.start_with? "http" network = "#{@api_url}#{@project}/global/networks/#{network}" end api_method = @compute.firewalls.insert parameters = { "project" => @project } body_object = { "name" => firewall_name, "network" => network, "allowed" => allowed } unless options[:description].nil? body_object["description"] = options[:description] end unless options[:source_ranges].nil? || options[:source_ranges].empty? body_object["sourceRanges"] = options[:source_ranges] end unless options[:source_tags].nil? || options[:source_tags].empty? body_object["sourceTags"] = options[:source_tags] end unless options[:target_tags].nil? || options[:target_tags].empty? body_object["targetTags"] = options[:target_tags] end request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/validate_url_map.rb0000644000004100000410000000101013145731036025550 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def validate_url_map(_url_map) Fog::Mock.not_implemented end end class Real def validate_url_map(url_map) api_method = @compute.url_maps.validate parameters = { "project" => @project, "urlMap" => url_map.name } body = { "resource" => url_map } request(api_method, parameters, body_object = body) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_route.rb0000644000004100000410000000066113145731036024250 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_route(_identity) Fog::Mock.not_implemented end end class Real def get_route(identity) api_method = @compute.routes.get parameters = { "project" => @project, "route" => identity } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_aggregated_disk_types.rb0000644000004100000410000000257213145731036027641 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_disk_types(options = {}) disk_types_items = {} if options[:filter] disk_type = options[:filter].gsub(/name eq \.\*/, "") data[:zones].keys.each do |zone| disk_types = list_disk_types(zone).body["items"].select { |dt| dt["name"] == disk_type } || [] disk_types_items["zones/#{zone}"] = { "diskTypes" => disk_types } unless disk_types.empty? end else data[:zones].keys.each do |zone| disk_types = list_disk_types(zone).body["items"] disk_types_items["zones/#{zone}"] = { "diskTypes" => disk_types } end end build_excon_response("kind" => 'compute#diskTypeAggregatedList', "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/aggregated/diskTypes", "items" => disk_types_items) end end class Real def list_aggregated_disk_types(options = {}) api_method = @compute.disk_types.aggregated_list parameters = { "project" => @project } parameters["filter"] = options[:filter] if options[:filter] request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_backend_service_health.rb0000644000004100000410000000141113145731036027540 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_backend_service_health(_backend_service) Fog::Mock.not_implemented end end class Real def get_backend_service_health(backend_service) api_method = @compute.backend_services.get_health parameters = { "project" => @project, "backendService" => backend_service.name } health_results = backend_service.backends.map do |backend| body = { "group" => backend["group"] } resp = request(api_method, parameters, body_object = body) [backend["group"], resp.data[:body]["healthStatus"]] end Hash[health_results] end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_zone_operation.rb0000644000004100000410000000326313145731036026146 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_zone_operation(zone_name, operation) operation = data[:operations][operation] if operation case operation["status"] when Fog::Compute::Google::Operation::PENDING_STATE operation["status"] = Fog::Compute::Google::Operation::RUNNING_STATE operation["progress"] = 50 else operation["status"] = Fog::Compute::Google::Operation::DONE_STATE operation["progress"] = 100 end else operation = { "error" => { "errors" => [ { "domain" => "global", "reason" => "notFound", "message" => "The resource 'projects/#{project}/zones/#{zone_name}/operations/#{operation}' was not found" } ], "code" => 404, "message" => "The resource 'projects/#{project}/zones/#{zone_name}/operations/#{operation}' was not found" } } end build_excon_response(operation) end end class Real # https://developers.google.com/compute/docs/reference/latest/zoneOperations def get_zone_operation(zone_name, operation) zone_name = zone_name.split("/")[-1] if zone_name.start_with? "http" api_method = @compute.zone_operations.get parameters = { "project" => @project, "zone" => zone_name, "operation" => operation } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_target_pool.rb0000644000004100000410000000225513145731036025432 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_target_pool(name, region_name) region = get_region(region_name) target_pool = data[:target_pools][name] || { "error" => { "errors" => [{ "domain" => "global", "reason" => "notFound", "message" => "The resource 'projects/#{project}/regions/#{region_name}/targetPools/#{name}' was not found" }], "code" => 404, "message" => "The resource 'projects/#{project}/regions/#{region_name}/targetPools/#{name}' was not found" } } build_excon_response(target_pool) end end class Real def get_target_pool(target_pool_name, region_name) if region_name.start_with? "http" region_name = region_name.split("/")[-1] end api_method = @compute.target_pools.get parameters = { "project" => @project, "targetPool" => target_pool_name, "region" => region_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_networks.rb0000644000004100000410000000060613145731036025161 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_networks Fog::Mock.not_implemented end end class Real def list_networks api_method = @compute.networks.list parameters = { "project" => @project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_backend_services.rb0000644000004100000410000000143613145731036026601 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_backend_services backend_services = data[:backend_services].values build_excon_response("kind" => "compute#backendServiceList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/backendServices", "id" => "projects/#{@project}/global/backendServices", "items" => backend_services) end end class Real def list_backend_services api_method = @compute.backend_services.list parameters = { "project" => @project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_subnetworks.rb0000644000004100000410000000246213145731036025675 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_subnetworks(region_name) region_name = region_name.split("/")[-1] if region_name.start_with? "http" subnetworks = data[:subnetworks].values.select { |d| d["region"].split("/")[-1] == region_name } build_excon_response("kind" => "compute#subnetworkList", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/subnetworks", "id" => "projects/#{@project}/regions/#{region_name}/subnetworks", "items" => subnetworks) end end class Real def list_subnetworks(region_name, options = {}) region_name = region_name.split("/")[-1] if region_name.start_with? "http" api_method = @compute.subnetworks.list parameters = { "project" => @project, "region" => region_name } parameters["filter"] = options[:filter] if options[:filter] parameters["maxResults"] = options[:max_results] if options[:max_results] parameters["pageToken"] = options[:page_token] if options[:page_token] request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_target_http_proxy.rb0000644000004100000410000000321313145731036027357 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_target_http_proxy(name) get_target_http_proxy(name) target_http_proxy = data[:target_http_proxies][name] target_http_proxy["mock-deletionTimestamp"] = Time.now.iso8601 target_http_proxy["status"] = "DONE" operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global", "operationType" => "delete", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/targetHttpProxies/#{name}", "targetId" => data[:target_http_proxies][name]["id"], "status" => "DONE", "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def delete_target_http_proxy(name) api_method = @compute.target_http_proxies.delete parameters = { "project" => @project, "targetHttpProxy" => name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_backend_service.rb0000644000004100000410000000336513145731036026710 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_backend_service(backend_service_name, _zone_name = nil) get_backend_service(backend_service_name) backend_service = data[:backend_services][backend_service_name] backend_service["mock-deletionTimestamp"] = Time.now.iso8601 backend_service["status"] = "DONE" operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global", "operationType" => "delete", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/backendServices/#{backend_service_name}", "targetId" => data[:backend_services][backend_service_name]["id"], "status" => "DONE", "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def delete_backend_service(backend_service_name) api_method = @compute.backend_services.delete parameters = { "project" => @project, "backendService" => backend_service_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_global_operations.rb0000644000004100000410000000077113145731036027013 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_global_operations Fog::Mock.not_implemented end end class Real # https://developers.google.com/compute/docs/reference/latest/globalOperations def list_global_operations api_method = @compute.global_operations.list parameters = { "project" => @project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_server_serial_port_output.rb0000644000004100000410000000105713145731036030443 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_server_serial_port_output(_identity, _zone) Fog::Mock.not_implemented end end class Real def get_server_serial_port_output(identity, zone) api_method = @compute.instances.get_serial_port_output parameters = { "project" => @project, "instance" => identity, "zone" => zone.split("/")[-1] } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/list_aggregated_machine_types.rb0000644000004100000410000000066613145731036030315 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_machine_types Fog::Mock.not_implemented end end class Real def list_aggregated_machine_types api_method = @compute.machine_types.aggregated_list parameters = { "project" => @project } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/delete_target_pool.rb0000644000004100000410000000343413145731036026115 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_target_pool(name, region_name) get_target_pool(name, region_name) id = Fog::Mock.random_numbers(19).to_s operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}", "operationType" => "delete", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/targetPools/#{name}", "targetId" => id, "status" => "DONE", "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/#{region_name}/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real # https://developers.google.com/compute/docs/reference/latest/regionOperations def delete_target_pool(target_pool_name, region_name) if region_name.start_with? "http" region_name = region_name.split("/")[-1] end api_method = @compute.target_pools.delete parameters = { "project" => @project, "targetPool" => target_pool_name, "region" => region_name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_target_http_proxy.rb0000644000004100000410000000105313145731036026674 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_target_http_proxy(name) proxy = data[:target_http_proxies][name] return nil if proxy.nil? build_excon_response(proxy) end end class Real def get_target_http_proxy(name) api_method = @compute.target_http_proxies.get parameters = { "project" => @project, "targetHttpProxy" => name } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/insert_backend_service.rb0000644000004100000410000000500713145731036026745 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_backend_service(backend_service_name, opts = {}) id = Fog::Mock.random_numbers(19).to_s data[:backend_services][backend_service_name] = { "kind" => "compute#backendService", "id" => id, "creationTimestamp" => Time.now.iso8601, "name" => backend_service_name, "description" => "", "backends" => [ { "description" => "", "group" => 'https://www.googleapis.com/resourceviews/v1beta1/projects#{@project}/zones/us-central1-a/zoneViews/name', "balancingMode" => "RATE", "capacityScaler" => 1.1, "maxRate" => 0.5 }], "healthChecks" => [opts["health_check"]], "timeoutSec" => 30, "port" => 80, "protocol" => "TCP", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/backendServices/#{backend_service_name}" } operation = random_operation data[:operations][operation] = { "kind" => "compute#operation", "id" => Fog::Mock.random_numbers(19).to_s, "name" => operation, "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global", "operationType" => "insert", "targetLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/backendServces/#{backend_service_name}", "targetId" => id, "status" => Fog::Compute::Google::Operation::PENDING_STATE, "user" => "123456789012-qwertyuiopasdfghjkl1234567890qwe@developer.gserviceaccount.com", "progress" => 0, "insertTime" => Time.now.iso8601, "startTime" => Time.now.iso8601, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/operations/#{operation}" } build_excon_response(data[:operations][operation]) end end class Real def insert_backend_service(backend_service_name, opts = {}) api_method = @compute.backend_services.insert parameters = { "project" => @project } body_object = { "name" => backend_service_name } body_object.merge!(opts) request(api_method, parameters, body_object = body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/get_region.rb0000755000004100000410000000172313145731036024400 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_region(identity) rname = identity.split("/")[-1] region = data[:regions][rname] || { "error" => { "errors" => [ { "domain" => "global", "reason" => "notFound", "message" => "The resource 'projects/#{project}/regions/#{rname}' was not found" } ], "code" => 404, "message" => "The resource 'projects/#{project}/regions/#{rname}' was not found" } } build_excon_response(region) end end class Real def get_region(identity) api_method = @compute.regions.get parameters = { "project" => @project, "region" => identity.split("/")[-1] } request(api_method, parameters) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/add_server_access_config.rb0000644000004100000410000000154413145731036027240 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def add_server_access_config(_identity, _zone, _nic, _options = {}) Fog::Mock.not_implemented end end class Real def add_server_access_config(identity, zone, nic, options = {}) api_method = @compute.instances.add_access_config parameters = { "project" => @project, "instance" => identity, "zone" => zone.split("/")[-1], "networkInterface" => nic } body_object = { "type" => "ONE_TO_ONE_NAT" } body_object["name"] = options[:name] ? options[:name] : "External NAT" body_object["natIP"] = options[:address] if options[:address] request(api_method, parameters, body_object) end end end end end fog-google-0.5.3/lib/fog/compute/google/requests/remove_target_pool_health_checks.rb0000644000004100000410000000134413145731036031013 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def remove_target_pool_health_checks(_target_pool, _health_checks) Fog::Mock.not_implemented end end class Real def remove_target_pool_health_checks(target_pool, health_checks) api_method = @compute.target_pools.remove_health_check parameters = { "project" => @project, "targetPool" => target_pool.name, "region" => target_pool.region.split("/")[-1] } body = { "healthChecks" => health_checks.map { |i| { "healthCheck" => i } } } request(api_method, parameters, body_object = body) end end end end end fog-google-0.5.3/lib/fog/compute/google/mock.rb0000644000004100000410000014050113145731036021327 0ustar www-datawww-datamodule Fog module Compute class Google class Mock include Fog::Google::Shared attr_reader :extra_global_projects def initialize(options) shared_initialize(options[:google_project], GOOGLE_COMPUTE_API_VERSION, GOOGLE_COMPUTE_BASE_URL) @extra_global_projects = options.fetch(:google_extra_global_projects, []) end def self.data(api_version) @data ||= Hash.new do |hash, key| hash[key] = case key when "debian-cloud" { :images => { "debian-8-jessie-v20161215" => { "archiveSizeBytes" => "3436783050", "creationTimestamp" => "2016-12-15T12 =>53 =>12.508-08 =>00", "description" => "Debian, Debian GNU/Linux, 8 (jessie), amd64 built on 2016-12-15", "diskSizeGb" => "10", "family" => "debian-8", "id" => "7187216073735715927", "kind" => "compute#image", "licenses" => [ "https://www.googleapis.com/compute/#{api_version}/projects/debian-cloud/global/licenses/debian-8-jessie" ], "name" => "debian-8-jessie-v20161215", "rawDisk" => { "containerType" => "TAR", "source" => "" }, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/debian-cloud/global/images/debian-8-jessie-v20161215", "sourceType" => "RAW", "status" => "READY" } } } when "centos-cloud" { :images => { "centos-6-v20161212" => { "archiveSizeBytes" => "3942360630", "creationTimestamp" => "2016-12-14T10 =>30 =>52.053-08 =>00", "description" => "CentOS, CentOS, 6, x86_64 built on 2016-12-12", "diskSizeGb" => "10", "family" => "centos-6", "id" => "5262726857160929587", "kind" => "compute#image", "licenses" => [ "https://www.googleapis.com/compute/#{api_version}/projects/centos-cloud/global/licenses/centos-6" ], "name" => "centos-6-v20161212", "rawDisk" => { "containerType" => "TAR", "source" => "" }, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/centos-cloud/global/images/centos-6-v20161212", "sourceType" => "RAW", "status" => "READY" }, "centos-7-v20161212" => { "archiveSizeBytes" => "4491098988", "creationTimestamp" => "2016-12-14T10 =>29 =>44.741-08 =>00", "description" => "CentOS, CentOS, 7, x86_64 built on 2016-12-12", "diskSizeGb" => "10", "family" => "centos-7", "id" => "8650499281020268919", "kind" => "compute#image", "licenses" => [ "https://www.googleapis.com/compute/#{api_version}/projects/centos-cloud/global/licenses/centos-7" ], "name" => "centos-7-v20161212", "rawDisk" => { "containerType" => "TAR", "source" => "" }, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/centos-cloud/global/images/centos-7-v20161212", "sourceType" => "RAW", "status" => "READY" } } } else { :target_http_proxies => { "test-target-http-proxy" => { "kind" => "compute#targetHttpProxy", "id" => "1361932147851415729", "creationTimestamp" => "2014-08-23T10:06:13.951-07:00", "name" => "test-target-http-proxy", "description" => "", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/targetHttpProxies/test-target-http-proxy", "urlMap" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/urlMaps/test-url-map" } }, :url_maps => { "test-url-map" => { "kind" => "compute#urlMap", "id" => "1361932147851415729", "creationTimestamp" => "2014-08-23T10:06:13.951-07:00", "name" => "test-url-map", "description" => "", "hostRules" => [], "pathMatchers" => [], "tests" => [], "defaultService" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/backendServices/fog-backend-service-test", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/urlMaps/test-url-map" } }, :target_pools => { "test-target-pool" => { "kind" => "compute#targetPool", "id" => "1361932147851415729", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/us-central1/targetPools/test-target-pool", "creationTimestamp" => "2014-08-23T10:06:13.951-07:00", "name" => "test-target-pool", "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/us-central1", "healthChecks" => ["https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/httpHealthChecks/test-check"], "instances" => ["https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/us-central1-a/instances/test-instance"] } }, :http_health_checks => { "test-http-health-check" => { "checkIntervalSec" => 5, "creationTimestamp" => "2014-08-23T10:06:13.951-07:00", "healthyThreshold" => 2, "id" => "1361932147851415729", "kind" => "compute#httphealthCheck", "name" => "test-http-health-check", "port" => 80, "requestPath" => "/", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/httpHealthChecks/test-http-health-check", "timeoutSec" => 5, "unhealthyThreshold" => 2 } }, :global_forwarding_rules => { "test-global-forwarding-rule" => { "kind" => "compute#forwardingRule", "id" => "1361932147851415729", "creationTimestamp" => "2014-08-23T10:06:13.951-07:00", "name" => "test-global-forwarding-rule", "IPAddress" => "107.178.255.155", "IPProtocol" => "TCP", "portRange" => "80-80", "target" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/targetHttpProxies/proxy", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/forwardngRules/test-global-forwarding-rule" } }, :forwarding_rules => { "test-forwarding-rule" => { "kind" => "compute#forwardingRule", "id" => "1361932147851415729", "creationTimestamp" => "2014-08-23T10:06:13.951-07:00", "name" => "test-forwarding-rule", "IPAddress" => "107.178.255.155", "IPProtocol" => "TCP", "portRange" => "80-80", "target" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/us-central1/targetPools/target_pool", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/us-central1/forwardngRules/test-forwarding-rule", "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/regions/us-central1" } }, :target_instances => { "test-target-instance" => { "kind" => "compute#targetInstance", "name" => "test-target-instance", "natPolicy" => "NO_NAT", "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/us-central1-a", "instance" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/us-central1-a/instances/test-instance", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/us-central1-a/targetInstances/test-target-instance", "id" => "1361932147851415729", "creationTimestamp" => "2014-08-23T10:06:13.951-07:00" } }, :backend_services => { "test-backend-service" => { "kind" => "compute#backend_service", "id" => "1361932147851415729", "creationTimestamp" => "2014-08-23T10:06:13.951-07:00", "name" => "test-backend-service", "description" => "", "backends" => [ { "description" => "", "group" => "https://www.googleapis.com/resourceviews/v1beta1/projects#{@project}/zones/us-central1-a/zoneViews/name", "balancingMode" => "RATE", "capacityScaler" => 1.1, "maxRate" => 0.5 }], "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/backendServices/test-backend-service" } }, :servers => { "fog-1" => { "kind" => "compute#instance", "id" => "1361932147851415727", "creationTimestamp" => "2013-09-26T04:55:43.881-07:00", "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-a", "status" => "RUNNING", "name" => "fog-1380196541", "tags" => { "fingerprint" => "42WmSpB8rSM=" }, "machineType" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-a/machineTypes/n1-standard-1", "canIpForward" => false, "networkInterfaces" => [ { "network" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/global/networks/default", "networkIP" => "10.240.121.54", "name" => "nic0", "accessConfigs" => [ { "kind" => "compute#accessConfig", "type" => "ONE_TO_ONE_NAT", "name" => "External NAT", "natIP" => "108.59.81.28" } ] } ], "disks" => [ { "kind" => "compute#attachedDisk", "index" => 0, "type" => "PERSISTENT", "mode" => "READ_WRITE", "source" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-a/disks/fog-1", "deviceName" => "persistent-disk-0", "boot" => true } ], "metadata" => { "kind" => "compute#metadata", "fingerprint" => "5_hasd_gC3E=", "items" => [ { "key" => "ssh-keys", "value" => "sysadmin:ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAgEA1zc7mx+0H8Roywet/L0aVX6MUdkDfzd/17kZhprAbpUXYOILv9AG4lIzQk6xGxDIltghytjfVGme/4A42Sb0Z9LN0pxB4KnWTNoOSHPJtp6jbXpq6PdN9r3Z5NKQg0A/Tfw7gt2N0GDsj6vpK8VbHHdW78JAVUxql18ootJxjaksdocsiHNK8iA6/v9qiLRhX3fOgtK7KpxxdZxLRzFg9vkp8jcGISgpZt27kOgXWhR5YLhi8pRJookzphO5O4yhflgoHoAE65XkfrsRCe0HU5QTbY2jH88rBVkq0KVlZh/lEsuwfmG4d77kEqaCGGro+j1Wrvo2K3DSQ+rEcvPp2CYRUySjhaeLF18UzQLtxNeoN14QOYqlm9ITdkCnmq5w4Wn007MjSOFp8LEq2RekrnddGXjg1/vgmXtaVSGzJAlXwtVfZor3dTRmF0JCpr7DsiupBaDFtLUlGFFlSKmPDVMPOOB5wajexmcvSp2Vu4U3yP8Lai/9/ZxMdsGPhpdCsWVL83B5tF4oYj1HVIycbYIxIIfFqOxZcCru3CMfe9jmzKgKLv2UtkfOS8jpS/Os2gAiB3wPweH3agvtwYAYBVMDwt5cnrhgHYWoOz7ABD8KgmCrD7Y9HikiCqIUNkgUFd9YmjcYi5FkU5rFXIawN7efs341lsdf923lsdf923fs= johndoe@acme" } ] }, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-a/instances/fog-1380196541" } }, :zones => { "europe-west1-a" => { "kind" => "compute#zone", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/europe-west1-a", "id" => "10419676573632995924", "creationTimestamp" => "2013-09-26T02:56:13.115-07:00", "name" => "europe-west1-a", "description" => "europe-west1-a", "status" => "UP", "maintenanceWindows" => [ { "name" => "2014-01-18-planned-outage", "description" => "maintenance zone", "beginTime" => "2014-01-18T12:00:00.000-08:00", "endTime" => "2014-02-02T12:00:00.000-08:00" } ], "quotas" => [ { "metric" => "INSTANCES", "limit" => 16.0, "usage" => 0.0 }, { "metric" => "CPUS", "limit" => 24.0, "usage" => 0.0 }, { "metric" => "DISKS", "limit" => 16.0, "usage" => 0.0 }, { "metric" => "DISKS_TOTAL_GB", "limit" => 2048.0, "usage" => 0.0 } ], "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/regions/europe-west1" }, "us-central1-a" => { "kind" => "compute#zone", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-a", "id" => "6562457277909136262", "creationTimestamp" => "2013-09-26T02:56:13.116-07:00", "name" => "us-central1-a", "description" => "us-central1-a", "status" => "UP", "maintenanceWindows" => nil, "quotas" => [ { "metric" => "INSTANCES", "limit" => 16.0, "usage" => 1.0 }, { "metric" => "CPUS", "limit" => 24.0, "usage" => 1.0 }, { "metric" => "DISKS", "limit" => 16.0, "usage" => 0.0 }, { "metric" => "DISKS_TOTAL_GB", "limit" => 2048.0, "usage" => 0.0 } ], "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/regions/us-central1" }, "us-central1-b" => { "kind" => "compute#zone", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-b", "id" => "8701502109626061015", "creationTimestamp" => "2013-09-26T02:56:13.124-07:00", "name" => "us-central1-b", "description" => "us-central1-b", "status" => "UP", "maintenanceWindows" => [{ "name" => "2013-10-26-planned-outage", "description" => "maintenance zone", "beginTime" => "2013-10-26T12:00:00.000-07:00", "endTime" => "2013-11-10T12:00:00.000-08:00" }], "quotas" => [ { "metric" => "INSTANCES", "limit" => 16.0, "usage" => 0.0 }, { "metric" => "CPUS", "limit" => 24.0, "usage" => 0.0 }, { "metric" => "DISKS", "limit" => 16.0, "usage" => 0.0 }, { "metric" => "DISKS_TOTAL_GB", "limit" => 2048.0, "usage" => 0.0 } ], "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/regions/us-central1" }, "us-central2-a" => { "kind" => "compute#zone", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central2-a", "id" => "13611654493253680292", "creationTimestamp" => "2013-09-26T02:56:13.125-07:00", "name" => "us-central2-a", "description" => "us-central2-a", "status" => "UP", "maintenanceWindows" => [ { "name" => "2013-10-12-planned-outage", "description" => "maintenance zone", "beginTime" => "2013-10-12T12:00:00.000-07:00", "endTime" => "2013-10-27T12:00:00.000-07:00" } ], "quotas" => [ { "metric" => "INSTANCES", "limit" => 16.0, "usage" => 0.0 }, { "metric" => "CPUS", "limit" => 24.0, "usage" => 0.0 }, { "metric" => "DISKS", "limit" => 16.0, "usage" => 0.0 }, { "metric" => "DISKS_TOTAL_GB", "limit" => 2048.0, "usage" => 0.0 } ], "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/regions/us-central2" } }, :regions => { "us-central1" => { "creationTimestamp" => "2014-01-21T10:30:54.895-08:00", "description" => "us-central1", "id" => "18201118976141502843", "kind" => "compute#region", "name" => "us-central1", "quotas" => [ { "metric" => "CPUS", "limit" => 1050.0, "usage" => 28.0 }, { "metric" => "DISKS_TOTAL_GB", "limit" => 10_000.0, "usage" => 292.0 }, { "metric" => "STATIC_ADDRESSES", "limit" => 10.0, "usage" => 0.0 }, { "metric" => "IN_USE_ADDRESSES", "limit" => 1050.0, "usage" => 30.0 }, { "metric" => "SSD_TOTAL_GB", "limit" => 1024.0, "usage" => 0.0 } ], "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/regions/us-central1", "status" => "UP", "zones" => [ "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-a", "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-b", "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-f" ] }, "europe-west1" => { "creationTimestamp" => "2014-01-21T10:30:54.891-08:00", "description" => "europe-west1", "id" => "18201118976141502843", "kind" => "compute#region", "name" => "europe-west1", "quotas" => [ { "metric" => "CPUS", "limit" => 24.0, "usage" => 0.0 }, { "metric" => "DISKS_TOTAL_GB", "limit" => 2048.0, "usage" => 0.0 }, { "metric" => "STATIC_ADDRESSES", "limit" => 7.0, "usage" => 0.0 }, { "metric" => "IN_USE_ADDRESSES", "limit" => 23.0, "usage" => 0.0 }, { "metric" => "SSD_TOTAL_GB", "limit" => 1024.0, "usage" => 0.0 } ], "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/regions/erope-west1", "status" => "UP", "zones" => [ "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/europe-west1-a", "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/europe-west1-b" ] }, "asia-east1" => { "creationTimestamp" => "2014-01-21T10:30:54.895-08:00", "description" => "asia-east1", "id" => "18201118976141502843", "kind" => "compute#region", "name" => "asia-east1", "quotas" => [ { "metric" => "CPUS", "limit" => 1050.0, "usage" => 28.0 }, { "metric" => "DISKS_TOTAL_GB", "limit" => 10_000.0, "usage" => 292.0 }, { "metric" => "STATIC_ADDRESSES", "limit" => 10.0, "usage" => 0.0 }, { "metric" => "IN_USE_ADDRESSES", "limit" => 1050.0, "usage" => 30.0 }, { "metric" => "SSD_TOTAL_GB", "limit" => 1024.0, "usage" => 0.0 } ], "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/regions/asia-east1", "status" => "UP", "zones" => [ "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/asia-east1-a", "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/asia-east1-b", "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/asia-east1-c" ] } }, :machine_types => Hash.new do |machine_types_hash, zone| machine_types_hash[zone] = { "f1-micro" => { "kind" => "compute#machineType", "id" => "4618642685664990776", "creationTimestamp" => "2013-04-25T13:32:49.088-07:00", "name" => "f1-micro", "description" => "1 vCPU (shared physical core) and 0.6 GB RAM", "guestCpus" => 1, "memoryMb" => 614, "imageSpaceGb" => 0, "maximumPersistentDisks" => 4, "maximumPersistentDisksSizeGb" => "3072", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/f1-micro" }, "g1-small" => { "kind" => "compute#machineType", "id" => "7224129552184485774", "creationTimestamp" => "2013-04-25T13:32:45.550-07:00", "name" => "g1-small", "description" => "1 vCPU (shared physical core) and 1.7 GB RAM", "guestCpus" => 1, "memoryMb" => 1740, "imageSpaceGb" => 0, "maximumPersistentDisks" => 4, "maximumPersistentDisksSizeGb" => "3072", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/g1-small" }, "n1-highcpu-2" => { "kind" => "compute#machineType", "id" => "13043554592196512955", "creationTimestamp" => "2012-11-16T11:46:10.572-08:00", "name" => "n1-highcpu-2", "description" => "2 vCPUs, 1.8 GB RAM", "guestCpus" => 2, "memoryMb" => 1843, "imageSpaceGb" => 10, "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-highcpu-2" }, "n1-highcpu-2-d" => { "kind" => "compute#machineType", "id" => "13043555176034896271", "creationTimestamp" => "2012-11-16T11:47:07.825-08:00", "name" => "n1-highcpu-2-d", "description" => "2 vCPUs, 1.8 GB RAM, 1 scratch disk (870 GB)", "guestCpus" => 2, "memoryMb" => 1843, "imageSpaceGb" => 10, "scratchDisks" => [ { "diskGb" => 870 } ], "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-highcpu-2-d" }, "n1-highcpu-4" => { "kind" => "compute#machineType", "id" => "13043555705736970382", "creationTimestamp" => "2012-11-16T11:48:06.087-08:00", "name" => "n1-highcpu-4", "description" => "4 vCPUs, 3.6 GB RAM", "guestCpus" => 4, "memoryMb" => 3686, "imageSpaceGb" => 10, "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-highcpu-4" }, "n1-highcpu-4-d" => { "kind" => "compute#machineType", "id" => "13043556330284250611", "creationTimestamp" => "2012-11-16T11:49:07.563-08:00", "name" => "n1-highcpu-4-d", "description" => "4 vCPUS, 3.6 GB RAM, 1 scratch disk (1770 GB)", "guestCpus" => 4, "memoryMb" => 3686, "imageSpaceGb" => 10, "scratchDisks" => [ { "diskGb" => 1770 } ], "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-highcpu-4-d" }, "n1-highcpu-8" => { "kind" => "compute#machineType", "id" => "13043556949665240937", "creationTimestamp" => "2012-11-16T11:50:15.128-08:00", "name" => "n1-highcpu-8", "description" => "8 vCPUs, 7.2 GB RAM", "guestCpus" => 8, "memoryMb" => 7373, "imageSpaceGb" => 10, "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-highcpu-8" }, "n1-highcpu-8-d" => { "kind" => "compute#machineType", "id" => "13043557458004959701", "creationTimestamp" => "2012-11-16T11:51:04.549-08:00", "name" => "n1-highcpu-8-d", "description" => "8 vCPUS, 7.2 GB RAM, 2 scratch disks (1770 GB, 1770 GB)", "guestCpus" => 8, "memoryMb" => 7373, "imageSpaceGb" => 10, "scratchDisks" => [ { "diskGb" => 1770 }, { "diskGb" => 1770 } ], "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-highcpu-8-d" }, "n1-highmem-2" => { "kind" => "compute#machineType", "id" => "13043551079318055993", "creationTimestamp" => "2012-11-16T11:40:06.129-08:00", "name" => "n1-highmem-2", "description" => "2 vCPUs, 13 GB RAM", "guestCpus" => 2, "memoryMb" => 13_312, "imageSpaceGb" => 10, "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-highmem-2" }, "n1-highmem-2-d" => { "kind" => "compute#machineType", "id" => "13043551625558644085", "creationTimestamp" => "2012-11-16T11:40:59.630-08:00", "name" => "n1-highmem-2-d", "description" => "2 vCPUs, 13 GB RAM, 1 scratch disk (870 GB)", "guestCpus" => 2, "memoryMb" => 13_312, "imageSpaceGb" => 10, "scratchDisks" => [ { "diskGb" => 870 } ], "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-highmem-2-d" }, "n1-highmem-4" => { "kind" => "compute#machineType", "id" => "13043552263604939569", "creationTimestamp" => "2012-11-16T11:42:08.983-08:00", "name" => "n1-highmem-4", "description" => "4 vCPUs, 26 GB RAM", "guestCpus" => 4, "memoryMb" => 26_624, "imageSpaceGb" => 10, "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-highmem-4" }, "n1-highmem-4-d" => { "kind" => "compute#machineType", "id" => "13043552953632709737", "creationTimestamp" => "2012-11-16T11:43:17.400-08:00", "name" => "n1-highmem-4-d", "description" => "4 vCPUs, 26 GB RAM, 1 scratch disk (1770 GB)", "guestCpus" => 4, "memoryMb" => 26_624, "imageSpaceGb" => 10, "scratchDisks" => [ { "diskGb" => 1770 } ], "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-highmem-4-d" }, "n1-highmem-8" => { "kind" => "compute#machineType", "id" => "13043553584275586275", "creationTimestamp" => "2012-11-16T11:44:25.985-08:00", "name" => "n1-highmem-8", "description" => "8 vCPUs, 52 GB RAM", "guestCpus" => 8, "memoryMb" => 53_248, "imageSpaceGb" => 10, "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-highmem-8" }, "n1-highmem-8-d" => { "kind" => "compute#machineType", "id" => "13043554021673472746", "creationTimestamp" => "2012-11-16T11:45:08.195-08:00", "name" => "n1-highmem-8-d", "description" => "8 vCPUs, 52 GB RAM, 2 scratch disks (1770 GB, 1770 GB)", "guestCpus" => 8, "memoryMb" => 53_248, "imageSpaceGb" => 10, "scratchDisks" => [ { "diskGb" => 1770 }, { "diskGb" => 1770 } ], "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-highmem-8-d" }, "n1-standard-1" => { "kind" => "compute#machineType", "id" => "12907738072351752276", "creationTimestamp" => "2012-06-07T13:48:14.670-07:00", "name" => "n1-standard-1", "description" => "1 vCPU, 3.75 GB RAM", "guestCpus" => 1, "memoryMb" => 3840, "imageSpaceGb" => 10, "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-standard-1" }, "n1-standard-1-d" => { "kind" => "compute#machineType", "id" => "12908559201265214706", "creationTimestamp" => "2012-06-07T13:48:34.258-07:00", "name" => "n1-standard-1-d", "description" => "1 vCPU, 3.75 GB RAM, 1 scratch disk (420 GB)", "guestCpus" => 1, "memoryMb" => 3840, "imageSpaceGb" => 10, "scratchDisks" => [ { "diskGb" => 420 } ], "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-standard-1-d" }, "n1-standard-2" => { "kind" => "compute#machineType", "id" => "12908559320241551184", "creationTimestamp" => "2012-06-07T13:48:56.867-07:00", "name" => "n1-standard-2", "description" => "2 vCPUs, 7.5 GB RAM", "guestCpus" => 2, "memoryMb" => 7680, "imageSpaceGb" => 10, "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-standard-2" }, "n1-standard-2-d" => { "kind" => "compute#machineType", "id" => "12908559582417967837", "creationTimestamp" => "2012-06-07T13:49:19.448-07:00", "name" => "n1-standard-2-d", "description" => "2 vCPUs, 7.5 GB RAM, 1 scratch disk (870 GB)", "guestCpus" => 2, "memoryMb" => 7680, "imageSpaceGb" => 10, "scratchDisks" => [ { "diskGb" => 870 } ], "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-standard-2-d" }, "n1-standard-4" => { "kind" => "compute#machineType", "id" => "12908559692070444049", "creationTimestamp" => "2012-06-07T13:49:40.050-07:00", "name" => "n1-standard-4", "description" => "4 vCPUs, 15 GB RAM", "guestCpus" => 4, "memoryMb" => 15_360, "imageSpaceGb" => 10, "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-standard-4" }, "n1-standard-4-d" => { "kind" => "compute#machineType", "id" => "12908559991903153608", "creationTimestamp" => "2012-06-07T13:50:05.677-07:00", "name" => "n1-standard-4-d", "description" => "4 vCPUs, 15 GB RAM, 1 scratch disk (1770 GB)", "guestCpus" => 4, "memoryMb" => 15_360, "imageSpaceGb" => 10, "scratchDisks" => [ { "diskGb" => 1770 } ], "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-standard-4-d" }, "n1-standard-8" => { "kind" => "compute#machineType", "id" => "12908560197989714867", "creationTimestamp" => "2012-06-07T13:50:42.334-07:00", "name" => "n1-standard-8", "description" => "8 vCPUs, 30 GB RAM", "guestCpus" => 8, "memoryMb" => 30_720, "imageSpaceGb" => 10, "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-standard-8" }, "n1-standard-8-d" => { "kind" => "compute#machineType", "id" => "12908560709887590691", "creationTimestamp" => "2012-06-07T13:51:19.936-07:00", "name" => "n1-standard-8-d", "description" => "8 vCPUs, 30 GB RAM, 2 scratch disks (1770 GB, 1770 GB)", "guestCpus" => 8, "memoryMb" => 30_720, "imageSpaceGb" => 10, "scratchDisks" => [ { "diskGb" => 1770 }, { "diskGb" => 1770 } ], "maximumPersistentDisks" => 16, "maximumPersistentDisksSizeGb" => "10240", "zone" => zone, "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/#{zone}/machineTypes/n1-standard-8-d" } } end, :images => {}, :disks => { "fog-1" => { "kind" => "compute#disk", "id" => "3338131294770784461", "creationTimestamp" => "2013-12-18T19:47:10.583-08:00", "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-a", "status" => "READY", "name" => "fog-1", "sizeGb" => "10", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-a/disks/fog-1", "sourceImage" => "https://www.googleapis.com/compute/#{api_version}/projects/debian-cloud/global/images/debian-7-wheezy-v20131120", "sourceImageId" => "17312518942796567788", "type" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-a/diskTypes/pd-standard" }, "fog-2" => { "kind" => "compute#disk", "id" => "3338131294770784462", "creationTimestamp" => "2013-12-18T19:47:10.583-08:00", "zone" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-a", "status" => "READY", "name" => "fog-2", "sizeGb" => "10", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-a/disks/fog-1", "type" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/zones/us-central1-a/diskTypes/pd-ssd" } }, :subnetworks => { "fog-1" => { "kind" => "compute#subnetwork", "id" => "6680781458098159920", "creationTimestamp" => "2016-03-19T19:13:51.613-07:00", "gatewayAddress" => "10.1.0.1", "name" => "fog-1", "network" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/global/networks/fog-example", "ipCidrRange" => "10.1.0.0/20", "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/regions/us-central1", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/regions/us-central1/subnetworks/fog-1" }, "fog-2" => { "kind" => "compute#subnetwork", "id" => "6680781458098159921", "creationTimestamp" => "2016-03-19T19:13:51.613-07:00", "gatewayAddress" => "10.1.16.1", "name" => "fog-2", "network" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/global/networks/fog-example", "ipCidrRange" => "10.1.16.0/20", "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/regions/europe-west1", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/regions/europe-west1/subnetworks/fog-2" }, "fog-3" => { "kind" => "compute#subnetwork", "id" => "6680781458098159923", "creationTimestamp" => "2016-03-19T19:13:51.613-07:00", "gatewayAddress" => "192.168.20.1", "name" => "fog-3", "network" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/global/networks/fog-elsewhere-example", "ipCidrRange" => "192.168.20.0/20", "region" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/regions/us-central1", "selfLink" => "https://www.googleapis.com/compute/#{api_version}/projects/#{key}/regions/us-central1/subnetworks/fog-3" } }, :operations => {} } end end end def self.reset @data = nil end def data(project = @project) self.class.data(api_version)[project] end def reset_data # not particularly useful because it deletes zones self.class.data(api_version).delete(@project) end def random_operation "operation-#{Fog::Mock.random_numbers(13)}-#{Fog::Mock.random_hex(13)}-#{Fog::Mock.random_hex(8)}" end end end end end fog-google-0.5.3/lib/fog/compute/google/real.rb0000644000004100000410000000132613145731036021322 0ustar www-datawww-datamodule Fog module Compute class Google class Real include Fog::Google::Shared attr_accessor :client attr_reader :compute, :extra_global_projects def initialize(options) shared_initialize(options[:google_project], GOOGLE_COMPUTE_API_VERSION, GOOGLE_COMPUTE_BASE_URL) options[:google_api_scope_url] = GOOGLE_COMPUTE_API_SCOPE_URLS.join(" ") @client = initialize_google_client(options) @compute = @client.discovered_api("compute", api_version) @resourceviews = @client.discovered_api("resourceviews", "v1beta1") @extra_global_projects = options[:google_extra_global_projects] || [] end end end end end fog-google-0.5.3/lib/fog/compute/google/models/0000755000004100000410000000000013145731036021333 5ustar www-datawww-datafog-google-0.5.3/lib/fog/compute/google/models/regions.rb0000755000004100000410000000067613145731036023342 0ustar www-datawww-datamodule Fog module Compute class Google class Regions < Fog::Collection model Fog::Compute::Google::Region def all data = service.list_regions.body load(data["items"] || []) end def get(identity) if region = service.get_region(identity).body new(region) end rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/address.rb0000755000004100000410000000575513145731036023324 0ustar www-datawww-datamodule Fog module Compute class Google ## # Represents an Address resource # # @see https://developers.google.com/compute/docs/reference/latest/addresses class Address < Fog::Model identity :name attribute :kind attribute :id attribute :address attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :region attribute :self_link, :aliases => "selfLink" attribute :status attribute :users IN_USE_STATE = "IN_USE" RESERVED_STATE = "RESERVED" def server return nil if !in_use? || users.nil? || users.empty? service.servers.get(users.first.split("/")[-1]) end def server=(server) requires :identity, :region server ? associate(server) : disassociate end def save requires :identity, :region data = service.insert_address(identity, region, attributes) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], nil, data.body["region"]) operation.wait_for { !pending? } reload end def destroy(async = true) requires :identity, :region data = service.delete_address(identity, region.split("/")[-1]) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], nil, data.body["region"]) operation.wait_for { ready? } unless async operation end def reload requires :identity, :region data = collection.get(identity, region.split("/")[-1]) merge_attributes(data.attributes) self end def in_use? status == IN_USE_STATE end private def associate(server) nic = server.network_interfaces.first["name"] data = service.add_server_access_config(server.name, server.zone_name, nic, :address => address) Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) end def disassociate return nil if !in_use? || users.nil? || users.empty? # An address can only be associated with one server at a time server = service.servers.get(users.first.split("/")[-1]) nic = server.network_interfaces.first["name"] unless server.network_interfaces.first["accessConfigs"].nil? || server.network_interfaces.first["accessConfigs"].empty? access_config = server.network_interfaces.first["accessConfigs"].first["name"] data = service.delete_server_access_config(server.name, server.zone_name, nic, :access_config => access_config) Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) end end end end end end fog-google-0.5.3/lib/fog/compute/google/models/addresses.rb0000755000004100000410000000302413145731036023637 0ustar www-datawww-datamodule Fog module Compute class Google class Addresses < Fog::Collection model Fog::Compute::Google::Address def all(filters = {}) if filters[:region] data = service.list_addresses(filters[:region]).body["items"] || [] else data = [] service.list_aggregated_addresses.body["items"].each_value do |region| data.concat(region["addresses"]) if region["addresses"] end end load(data) end def get(identity, region) if address = service.get_address(identity, region).body new(address) end rescue Fog::Errors::NotFound nil end def get_by_ip_address(ip_address) addresses = service.list_aggregated_addresses(:filter => "address eq .*#{ip_address}").body["items"] address = addresses.each_value.select { |region| region.key?("addresses") } return nil if address.empty? new(address.first["addresses"].first) end def get_by_name(ip_name) names = service.list_aggregated_addresses(:filter => "name eq .*#{ip_name}").body["items"] name = names.each_value.select { |region| region.key?("addresses") } return nil if name.empty? new(name.first["addresses"].first) end def get_by_ip_address_or_name(ip_address_or_name) get_by_ip_address(ip_address_or_name) || get_by_name(ip_address_or_name) end end end end end fog-google-0.5.3/lib/fog/compute/google/models/subnetwork.rb0000755000004100000410000000332713145731036024073 0ustar www-datawww-datamodule Fog module Compute class Google ## # Represents a Subnetwork resource # # @see https://developers.google.com/compute/docs/reference/latest/subnetworks class Subnetwork < Fog::Model identity :name attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :gateway_address, :aliases => "gatewayAddress" attribute :id attribute :ip_cidr_range, :aliases => "ipCidrRange" attribute :kind attribute :network attribute :region attribute :self_link, :aliases => "selfLink" def save requires :identity, :network, :region, :ip_cidr_range data = service.insert_subnetwork(identity, region, network, ip_cidr_range, attributes) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], nil, data.body["region"]) operation.wait_for { !pending? } reload end def destroy(async = true) requires :identity, :region data = service.delete_subnetwork(identity, region) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], nil, data.body["region"]) operation.wait_for { ready? } unless async operation end def update_interface_config(network_interface) network_interface["subnetwork"] = self_link if network_interface network_interface end def reload requires :identity, :region data = collection.get(identity, region.split("/")[-1]) merge_attributes(data.attributes) self end end end end end fog-google-0.5.3/lib/fog/compute/google/models/images.rb0000644000004100000410000000472513145731036023135 0ustar www-datawww-datamodule Fog module Compute class Google class Images < Fog::Collection model Fog::Compute::Google::Image # NOTE: some of these operating systems are premium and users will be # charged a license fee beyond the base Google Compute Engine VM # charges. See https://cloud.google.com/compute/docs/operating-systems/ # for more info. GLOBAL_PROJECTS = [ "centos-cloud", "coreos-cloud", "debian-cloud", "google-containers", "opensuse-cloud", "rhel-cloud", "suse-cloud", "ubuntu-os-cloud", "windows-cloud" ] def all data = [] all_projects.each do |project| begin images = service.list_images(project).body["items"] || [] # Keep track of the project in which we found the image(s) images.each { |img| img[:project] = project } data += images rescue Fog::Errors::NotFound # Not everyone has access to every Global Project. Requests # return 404 if you don't have access. next end end load(data) end # Only return the non-deprecated list of images def current data = [] all_images = all all_images.each { |img| data.push(img) unless img.deprecated } data end def get(identity) data = nil all_projects.each do |project| begin data = service.get_image(identity, project).body data[:project] = project rescue Fog::Errors::NotFound next else break end end return nil if data.nil? new(data) end def get_from_family(family) data = nil all_projects.each do |project| begin data = service.get_image_from_family(family, project).body data[:project] = project rescue Fog::Errors::NotFound next else break end end return nil if data.nil? new(data) end private def all_projects # Search own project before global projects [service.project] + GLOBAL_PROJECTS + service.extra_global_projects end end end end end fog-google-0.5.3/lib/fog/compute/google/models/project.rb0000644000004100000410000000154113145731036023327 0ustar www-datawww-datamodule Fog module Compute class Google ## # Represents a Project resource # # @see https://developers.google.com/compute/docs/reference/latest/projects class Project < Fog::Model identity :name attribute :kind attribute :id attribute :common_instance_metadata, :aliases => "commonInstanceMetadata" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :quotas attribute :self_link, :aliases => "selfLink" def set_metadata(metadata = {}) requires :identity data = service.set_common_instance_metadata(identity, common_instance_metadata["fingerprint"], metadata) Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"]) end end end end end fog-google-0.5.3/lib/fog/compute/google/models/backend_service.rb0000644000004100000410000000475413145731036025001 0ustar www-datawww-datamodule Fog module Compute class Google class BackendService < Fog::Model identity :name attribute :backends, :aliases => "backends" attribute :creation_timestamp, :aliases => "kind" attribute :description, :aliases => "description" attribute :fingerprint, :aliases => "fingerprint" attribute :health_checks, :aliases => "healthChecks" attribute :id, :aliases => "id" attribute :kind, :aliases => "kind" attribute :port, :aliases => "port" attribute :protocol, :aliases => "protocol" attribute :self_link, :aliases => "selfLink" attribute :timeout_sec, :aliases => "timeoutSec" def save requires :name, :health_checks options = { "description" => description, "backends" => backends, "fingerprint" => fingerprint, "healthChecks" => health_checks, "port" => port, "protocol" => protocol, "timeoutSec" => timeout_sec } data = service.insert_backend_service(name, options).body operation = Fog::Compute::Google::Operations.new(:service => service).get(data["name"]) operation.wait_for { !pending? } reload end def destroy(async = true) requires :name data = service.delete_backend_service(name) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"]) operation.wait_for { ready? } unless async operation end def get_health service.get_backend_service_health self end def add_backend(backend) # ensure backend is an array of hashes backend = [backend] unless backend.class == Array backend.map! { |resource| resource.class == String ? { "group" => resource } : resource } service.add_backend_service_backends(self, backend) reload end def ready? service.get_backend_service(name) true rescue Fog::Errors::NotFound false end def reload requires :name return unless data = begin collection.get(name) rescue Excon::Errors::SocketError nil end new_attributes = data.attributes merge_attributes(new_attributes) self end RUNNING_STATE = "READY" end end end end fog-google-0.5.3/lib/fog/compute/google/models/zones.rb0000644000004100000410000000063713145731036023024 0ustar www-datawww-datamodule Fog module Compute class Google class Zones < Fog::Collection model Fog::Compute::Google::Zone def all data = service.list_zones.body["items"] || [] load(data) end def get(identity) data = service.get_zone(identity).body new(data) rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/servers.rb0000644000004100000410000000454213145731036023356 0ustar www-datawww-datamodule Fog module Compute class Google class Servers < Fog::Collection model Fog::Compute::Google::Server def all(filters = {}) if filters["zone"] data = service.list_servers(filters["zone"]).body["items"] || [] else data = [] service.list_aggregated_servers.body["items"].each_value do |zone| data.concat(zone["instances"]) if zone["instances"] end end load(data) end def get(identity, zone = nil) response = nil if zone response = service.get_server(identity, zone).body else servers = service.list_aggregated_servers(:filter => "name eq .*#{identity}").body["items"] server = servers.each_value.select { |zone| zone.key?("instances") } # It can only be 1 server with the same name across all regions response = server.first["instances"].first unless server.empty? end return nil if response.nil? new(response) rescue Fog::Errors::NotFound nil end def bootstrap(new_attributes = {}) name = "fog-#{Time.now.to_i}" zone = "us-central1-f" disks = new_attributes[:disks] if disks.nil? || disks.empty? # create the persistent boot disk disk_defaults = { :name => name, :size_gb => 10, :zone_name => zone, :source_image => "debian-8-jessie-v20161215" } # backwards compatibility to pre-v1 new_attributes[:source_image] = new_attributes[:image_name] if new_attributes[:image_name] disk = service.disks.create(disk_defaults.merge(new_attributes)) disk.wait_for { disk.ready? } disks = [disk] end defaults = { :name => name, :disks => disks, :machine_type => "n1-standard-1", :zone_name => zone, :private_key_path => File.expand_path("~/.ssh/id_rsa"), :public_key_path => File.expand_path("~/.ssh/id_rsa.pub"), :username => ENV["USER"] } server = create(defaults.merge(new_attributes)) server.wait_for { sshable? } server end end end end end fog-google-0.5.3/lib/fog/compute/google/models/subnetworks.rb0000644000004100000410000000142713145731036024252 0ustar www-datawww-datamodule Fog module Compute class Google class Subnetworks < Fog::Collection model Fog::Compute::Google::Subnetwork def all(filters = {}) if filters[:region] data = service.list_subnetworks(filters[:region]).body["items"] || [] else data = [] service.list_aggregated_subnetworks(filters).body["items"].each_value do |region| data.concat(region["subnetworks"]) if region["subnetworks"] end end load(data || []) end def get(identity, region) if subnetwork = service.get_subnetwork(identity, region).body new(subnetwork) end rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/target_instance.rb0000644000004100000410000000364413145731036025041 0ustar www-datawww-datamodule Fog module Compute class Google class TargetInstance < Fog::Model identity :name attribute :kind, :aliases => "kind" attribute :self_link, :aliases => "selfLink" attribute :id, :aliases => "id" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description, :aliases => "description" attribute :zone, :aliases => "zone" attribute :instance, :aliases => "instance" attribute :nat_policy, :aliases => "natPolicy" def save requires :name, :zone options = { "description" => description, "zone" => zone, "natPolicy" => nat_policy, "instance" => instance } data = service.insert_target_instance(name, zone, options) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) operation.wait_for { !pending? } reload end def destroy(async = true) requires :name, :zone operation = service.delete_target_instance(name, zone) unless async # wait until "DONE" to ensure the operation doesn't fail, raises # exception on error Fog.wait_for do operation.body["status"] == "DONE" end end operation end def ready? service.get_target_instance(name, zone) true rescue Fog::Errors::NotFound false end def reload requires :name, :zone begin data = collection.get(name, zone) new_attributes = data.attributes merge_attributes(new_attributes) return self rescue Excon::Errors::SocketError return nil end end RUNNING_STATE = "READY" end end end end fog-google-0.5.3/lib/fog/compute/google/models/firewall.rb0000644000004100000410000000316613145731036023473 0ustar www-datawww-datamodule Fog module Compute class Google ## # Represents a Firewall resource # # @see https://developers.google.com/compute/docs/reference/latest/firewalls class Firewall < Fog::Model identity :name attribute :kind attribute :id attribute :allowed attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :network attribute :self_link, :aliases => "selfLink" attribute :source_ranges, :aliases => "sourceRanges" attribute :source_tags, :aliases => "sourceTags" attribute :target_tags, :aliases => "targetTags" def save requires :identity, :allowed, :network data = service.insert_firewall(identity, allowed, network, attributes) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"]) operation.wait_for { !pending? } reload end def update requires :identity, :allowed, :network data = service.update_firewall(identity, allowed, network, attributes) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"]) operation.wait_for { !pending? } reload end def destroy(async = true) requires :identity data = service.delete_firewall(identity) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"]) operation.wait_for { ready? } unless async operation end end end end end fog-google-0.5.3/lib/fog/compute/google/models/operation.rb0000644000004100000410000000377213145731036023671 0ustar www-datawww-datamodule Fog module Compute class Google class Operation < Fog::Model identity :name attribute :kind attribute :id attribute :client_operation_id, :aliases => "clientOperationId" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :end_time, :aliases => "endTime" attribute :error attribute :http_error_message, :aliases => "httpErrorMessage" attribute :http_error_status_code, :aliases => "httpErrorStatusCode" attribute :insert_time, :aliases => "insertTime" attribute :operation_type, :aliases => "operationType" attribute :progress attribute :region attribute :self_link, :aliases => "selfLink" attribute :start_time, :aliases => "startTime" attribute :status attribute :status_message, :aliases => "statusMessage" attribute :target_id, :aliases => "targetId" attribute :target_link, :aliases => "targetLink" attribute :user attribute :warnings attribute :zone def ready? status == DONE_STATE end def pending? status == PENDING_STATE end def region_name region.nil? ? nil : region.split("/")[-1] end def zone_name zone.nil? ? nil : zone.split("/")[-1] end def destroy requires :identity if zone service.delete_zone_operation(zone, identity) elsif region service.delete_region_operation(region, identity) else service.delete_global_operation(identity) end true end def reload requires :identity data = collection.get(identity, zone, region) new_attributes = data.attributes merge_attributes(new_attributes) self end PENDING_STATE = "PENDING" RUNNING_STATE = "RUNNING" DONE_STATE = "DONE" end end end end fog-google-0.5.3/lib/fog/compute/google/models/resource_view.rb0000644000004100000410000000710313145731036024542 0ustar www-datawww-datamodule Fog module Compute class Google # the resource view model creates either a region view or zone view depending on which is parameter is passed class ResourceView < Fog::Model identity :name attribute :kind, :aliases => "kind" attribute :self_link, :aliases => "selfLink" attribute :id, :aliases => "id" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description, :aliases => "description" attribute :region, :aliases => "region" # string, required for region views attribute :labels, :aliases => "labels" # array of hashes including 'key' and 'value' as keys attribute :zone, :aliases => "zone" # string, required for zone views attribute :last_modified, :aliases => "lastModified" attribute :members, :aliases => "members" # array of members of resource view attribute :num_members, :aliases => "numMemebers" # integer def save requires :name labels ||= [] members ||= [] if region options = { "description" => description, "labels" => labels, "lastModified" => last_modified, "members" => members, "numMembers" => num_members } @region = region data = service.insert_region_view(name, region, options).body operation = service.get_region_view(data["resource"]["name"], nil, @region).body end if zone options = { "description" => description, "labels" => labels, "lastModified" => last_modified, "members" => members, "numMembers" => num_members } @zone = zone data = service.insert_zone_view(name, zone, options).body operation = service.get_zone_view(data["resource"]["name"], @zone).body end reload end def destroy(async = false) requires :name # parse the self link to get the zone or region selflink = self_link.split("/") if selflink[7] == "regions" operation = service.delete_region_view(name, selflink[8]) end if selflink[7] == "zones" operation = service.delete_zone_view(name, selflink[8]) end unless async # wait until "DONE" to ensure the operation doesn't fail, raises # exception on error Fog.wait_for do operation.body.nil? end end operation end def add_resources(resources) resources = [resources] unless resources.class == Array resources.map { |resource| resource.class == String ? resource : resource.self_link } service.add_zone_view_resources(self, resources, @zone) if @zone service.add_region_view_resources(self, resources, @region) if @region reload end def ready? service.get_zone_view(name, @zone) if @zone service.get_region_view(name, @region) if @region true rescue Fog::Errors::NotFound false end def reload requires :name return unless data = begin collection.get(name, region, zone) rescue Excon::Errors::SocketError nil end new_attributes = data.attributes merge_attributes(new_attributes) self end RUNNING_STATE = "READY" end end end end fog-google-0.5.3/lib/fog/compute/google/models/target_http_proxy.rb0000644000004100000410000000352513145731036025453 0ustar www-datawww-datamodule Fog module Compute class Google class TargetHttpProxy < Fog::Model identity :name attribute :kind, :aliases => "kind" attribute :self_link, :aliases => "selfLink" attribute :id, :aliases => "id" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description, :aliases => "description" attribute :url_map, :aliases => "urlMap" def save requires :name options = { "description" => description, "urlMap" => url_map } data = service.insert_target_http_proxy(name, options).body operation = Fog::Compute::Google::Operations.new(:service => service).get(data["name"], data["zone"]) operation.wait_for { !pending? } reload end def destroy(async = true) requires :name operation = service.delete_target_http_proxy(name) unless async # wait until "DONE" to ensure the operation doesn't fail, raises # exception on error Fog.wait_for do operation.body["status"] == "DONE" end end operation end def set_url_map(urlMap) operation = service.set_target_http_proxy_url_map(self, urlMap) reload end def ready? service.get_target_http_proxy(name) true rescue Fog::Errors::NotFound false end def reload requires :name return unless data = begin collection.get(name) rescue Excon::Errors::SocketError nil end new_attributes = data.attributes merge_attributes(new_attributes) self end RUNNING_STATE = "READY" end end end end fog-google-0.5.3/lib/fog/compute/google/models/network.rb0000755000004100000410000000323113145731036023353 0ustar www-datawww-datamodule Fog module Compute class Google ## # Represents a Network resource # # @see https://developers.google.com/compute/docs/reference/latest/networks class Network < Fog::Model identity :name attribute :kind attribute :id attribute :ipv4_range, :aliases => "IPv4Range" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :gateway_ipv4, :aliases => "gatewayIPv4" attribute :self_link, :aliases => "selfLink" def save requires :identity, :ipv4_range data = service.insert_network(identity, ipv4_range, attributes) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"]) # Since network has no "state" we can query, we have to wait for the operation to finish # TODO: change back to async when there's a proper state API operation.wait_for { ready? } reload end def destroy(async = true) requires :identity data = service.delete_network(identity) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"]) operation.wait_for { ready? } unless async operation end # Returns a ready API structure for insert_instance, used in insert_server request. def get_as_interface_config(access_config = nil) network_interface = { "network" => self_link } network_interface["accessConfigs"] = [access_config] if access_config network_interface end end end end end fog-google-0.5.3/lib/fog/compute/google/models/snapshot.rb0000644000004100000410000000244213145731036023521 0ustar www-datawww-datamodule Fog module Compute class Google class Snapshot < Fog::Model identity :name attribute :kind attribute :self_link, :aliases => "selfLink" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :disk_size_gb, :aliases => "diskSizeGb" attribute :source_disk, :aliases => "sourceDisk" attribute :source_disk_id, :aliases => "sourceDiskId" attribute :description attribute :status attribute :id attribute :storage_bytes, :aliases => "storageBytes" attribute :storage_bytes_status, :aliases => "storageBytesStatus" CREATING_STATE = "CREATING" DELETING_STATE = "DELETING" FAILED_STATE = "FAILED" READY_STATE = "READY" UPLOADING_STATE = "UPLOADING" def destroy(async = true) requires :identity data = service.delete_snapshot(identity) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"]) operation.wait_for { ready? } unless async operation end def ready? status == READY_STATE end def resource_url "#{service.project}/global/snapshots/#{name}" end end end end end fog-google-0.5.3/lib/fog/compute/google/models/global_forwarding_rules.rb0000644000004100000410000000106513145731036026556 0ustar www-datawww-datamodule Fog module Compute class Google class GlobalForwardingRules < Fog::Collection model Fog::Compute::Google::GlobalForwardingRule def all data = service.list_global_forwarding_rules.body["items"] || [] load(data) end def get(identity, region = "global") if global_forwarding_rule = service.get_global_forwarding_rule(identity, region).body new(global_forwarding_rule) end rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/projects.rb0000644000004100000410000000052713145731036023515 0ustar www-datawww-datamodule Fog module Compute class Google class Projects < Fog::Collection model Fog::Compute::Google::Project def get(identity) if project = service.get_project(identity).body new(project) end rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/url_map.rb0000644000004100000410000000510313145731036023316 0ustar www-datawww-datamodule Fog module Compute class Google class UrlMap < Fog::Model identity :name attribute :kind, :aliases => "kind" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :default_service, :aliases => "defaultService" attribute :description, :aliases => "description" attribute :fingerprint, :aliases => "fingerprint" attribute :host_rules, :aliases => "hostRules" attribute :id, :aliases => "id" attribute :path_matchers, :aliases => "pathMatchers" attribute :self_link, :aliases => "selfLink" attribute :tests, :aliases => "tests" def save requires :name, :default_service options = { "defaultService" => default_service, "description" => description, "fingerprint" => fingerprint, "hostRules" => host_rules, "pathMatchers" => path_matchers, "tests" => tests } data = service.insert_url_map(name, options).body operation = Fog::Compute::Google::Operations.new(:service => service).get(data["name"]) operation.wait_for { !pending? } reload end def destroy(async = true) requires :name operation = service.delete_url_map(name) unless async Fog.wait_for do operation = service.get_global_operation(operation.body["name"]) operation.body["status"] == "DONE" end end operation end def validate service.validate_url_map self end def add_host_rules(hostRules) hostRules = [hostRules] unless hostRules.class == Array service.update_url_map(self, hostRules) reload end def add_path_matchers(pathMatchers, hostRules) pathMatchers = [pathMatchers] unless pathMatchers.class == Array hostRules = [hostRules] unless hostRules.class == Array service.update_url_map(self, hostRules, pathMatchers) reload end def ready? service.get_url_map(name) true rescue Fog::Errors::NotFound false end def reload requires :name return unless data = begin collection.get(name) rescue Excon::Errors::SocketError nil end new_attributes = data.attributes merge_attributes(new_attributes) self end RUNNING_STATE = "READY" end end end end fog-google-0.5.3/lib/fog/compute/google/models/disk_types.rb0000644000004100000410000000215613145731036024042 0ustar www-datawww-datamodule Fog module Compute class Google class DiskTypes < Fog::Collection model Fog::Compute::Google::DiskType def all(filters = {}) if filters["zone"] data = service.list_disk_types(filters["zone"]).body["items"] || [] else data = [] service.list_aggregated_disk_types.body["items"].each_value do |zone| data.concat(zone["diskTypes"]) if zone["diskTypes"] end end load(data) end def get(identity, zone = nil) response = nil if zone response = service.get_disk_type(identity, zone).body else disk_types = service.list_aggregated_disk_types(:filter => "name eq .*#{identity}").body["items"] || {} disk_type = disk_types.each_value.detect { |zone| zone.key?("diskTypes") } || {} response = disk_type["diskTypes"].first unless disk_type.empty? end return nil if response.nil? new(response) rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/backend_services.rb0000644000004100000410000000100113145731036025142 0ustar www-datawww-datamodule Fog module Compute class Google class BackendServices < Fog::Collection model Fog::Compute::Google::BackendService def all(_filters = {}) data = service.list_backend_services.body["items"] || [] load(data) end def get(identity) if backend_service = service.get_backend_service(identity).body new(backend_service) end rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/flavors.rb0000644000004100000410000000134513145731036023337 0ustar www-datawww-datamodule Fog module Compute class Google class Flavors < Fog::Collection model Fog::Compute::Google::Flavor def all(filters = {}) if filters[:zone] data = service.list_machine_types(filters[:zone]).body["items"] else data = [] service.list_aggregated_machine_types.body["items"].each_value do |zone| data.concat(zone["machineTypes"]) if zone["machineTypes"] end end load(data) end def get(identity, zone_name = nil) data = service.get_machine_type(identity, zone_name).body new(data) rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/operations.rb0000644000004100000410000000174113145731036024046 0ustar www-datawww-datamodule Fog module Compute class Google class Operations < Fog::Collection model Fog::Compute::Google::Operation def all(filters = {}) if filters["zone"] data = service.list_zone_operations(filters["zone"]).body elsif filters["region"] data = service.list_region_operations(filters["region"]).body else data = service.list_global_operations.body end load(data["items"] || []) end def get(identity, zone = nil, region = nil) if !zone.nil? response = service.get_zone_operation(zone, identity) elsif !region.nil? response = service.get_region_operation(region, identity) else response = service.get_global_operation(identity) end return nil if response.nil? new(response.body) rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/target_pool.rb0000644000004100000410000000730713145731036024206 0ustar www-datawww-datamodule Fog module Compute class Google class TargetPool < Fog::Model identity :name attribute :kind, :aliases => "kind" attribute :self_link, :aliases => "selfLink" attribute :id, :aliases => "id" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description, :aliases => "description" attribute :region, :aliases => "region" attribute :health_checks, :aliases => "healthChecks" attribute :instances, :aliases => "instances" attribute :session_affinity, :aliases => "sessionAffinity" attribute :failover_ratio, :aliases => "failoverRatio" attribute :backup_pool, :aliases => "backupPool" def save requires :name, :region options = { "description" => description, "region" => region, "healthChecks" => health_checks, "instances" => instances, "sessionAffinity" => session_affinity, "failoverRatio" => failover_ratio, "backupPool" => backup_pool } data = service.insert_target_pool(name, region, options).body operation = Fog::Compute::Google::Operations.new(:service => service).get(data["name"], nil, data["region"]) operation.wait_for { !pending? } reload end def destroy(async = true) requires :name, :region operation = service.delete_target_pool(name, region) unless async # wait until "DONE" to ensure the operation doesn't fail, raises # exception on error Fog.wait_for do operation = service.get_region_operation(region, operation.body["name"]) operation.body["status"] == "DONE" end end operation end def add_instance(instance) instance = instance.self_link unless instance.class == String service.add_target_pool_instances(self, [instance]) reload end def remove_instance(instance) instance = instance.self_link unless instance.class == String service.remove_target_pool_instances(self, [instance]) reload end def add_health_check(health_check) health_check = health_check.self_link unless health_check.class == String service.add_target_pool_health_checks(self, [health_check]) reload end def remove_health_check(health_check) health_check = health_check.self_link unless health_check.class == String service.remove_target_pool_health_checks(self, [health_check]) reload end def get_health(instance_name = nil) if instance_name instance = service.servers.get(instance_name) health_results = [service.get_target_pool_health(self, instance.self_link)] else health_results = instances.map do |instance_selflink| service.get_target_pool_health(self, instance_selflink) end end Hash[health_results] end def ready? service.get_target_pool(name, region) true rescue Fog::Errors::NotFound false end def region_name region.nil? ? nil : region.split("/")[-1] end def reload requires :name, :region return unless data = begin collection.get(name, region) rescue Excon::Errors::SocketError nil end new_attributes = data.attributes merge_attributes(new_attributes) self end RUNNING_STATE = "READY" end end end end fog-google-0.5.3/lib/fog/compute/google/models/disks.rb0000644000004100000410000000215513145731036023000 0ustar www-datawww-datamodule Fog module Compute class Google class Disks < Fog::Collection model Fog::Compute::Google::Disk def all(filters = {}) if filters["zone"] data = service.list_disks(filters["zone"]).body["items"] || [] else data = [] service.list_aggregated_disks.body["items"].each_value do |zone| data.concat(zone["disks"]) if zone["disks"] end end load(data) end def get(identity, zone = nil) response = nil if zone response = service.get_disk(identity, zone).body else disks = service.list_aggregated_disks(:filter => "name eq .*#{identity}").body["items"] disk = disks.each_value.select { |zone| zone.key?("disks") } # It can only be 1 disk with the same name across all regions response = disk.first["disks"].first unless disk.empty? end return nil if response.nil? new(response) rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/routes.rb0000644000004100000410000000067013145731036023204 0ustar www-datawww-datamodule Fog module Compute class Google class Routes < Fog::Collection model Fog::Compute::Google::Route def all data = service.list_routes.body load(data["items"] || []) end def get(identity) if route = service.get_route(identity).body new(route) end rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/http_health_checks.rb0000644000004100000410000000104513145731036025504 0ustar www-datawww-datamodule Fog module Compute class Google class HttpHealthChecks < Fog::Collection model Fog::Compute::Google::HttpHealthCheck def all(_filters = {}) data = service.list_http_health_checks.body["items"] || [] load(data) end def get(identity) response = nil response = service.get_http_health_check(identity) return nil if response.nil? new(response.body) rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/http_health_check.rb0000644000004100000410000000466713145731036025336 0ustar www-datawww-datamodule Fog module Compute class Google class HttpHealthCheck < Fog::Model identity :name attribute :kind, :aliases => "kind" attribute :self_link, :aliases => "selfLink" attribute :id, :aliases => "id" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description, :aliases => "description" attribute :host, :aliases => "host" attribute :request_path, :aliases => "requestPath" attribute :port, :aliases => "port" attribute :check_interval_sec, :aliases => "checkIntervalSec" attribute :timeout_sec, :aliases => "timeoutSec" attribute :unhealthy_threshold, :aliases => "unhealthyThreshold" attribute :healthy_threshold, :aliases => "healthyThreshold" def save requires :name options = { "description" => description, "host" => host, "requestPath" => request_path || "/", "port" => port || 80, "checkIntervalSec" => check_interval_sec || 5, "timeoutSec" => timeout_sec || 5, "unhealthyThreshold" => unhealthy_threshold || 2, "healthyThreshold" => healthy_threshold || 2 } data = service.insert_http_health_check(name, options).body operation = Fog::Compute::Google::Operations.new(:service => service).get(data["name"], data["zone"]) operation.wait_for { !pending? } reload end def destroy(async = true) requires :name operation = service.delete_http_health_check(name) unless async # wait until "DONE" to ensure the operation doesn't fail, raises # exception on error Fog.wait_for do operation = service.get_global_operation(operation.body["name"]) operation.body["status"] == "DONE" end end operation end def ready? service.get_http_health_check(name) true rescue Fog::Errors::NotFound false end def reload requires :name return unless data = begin collection.get(name) rescue Excon::Errors::SocketError nil end new_attributes = data.attributes merge_attributes(new_attributes) self end RUNNING_STATE = "READY" end end end end fog-google-0.5.3/lib/fog/compute/google/models/instance_groups.rb0000644000004100000410000000405613145731036025070 0ustar www-datawww-datamodule Fog module Compute class Google class InstanceGroups < Fog::Collection model Fog::Compute::Google::InstanceGroup def all(filters = {}) if filters[:zone] data = service.list_instance_groups(filters[:zone]).body else data = [] service.list_aggregated_instance_groups.body["items"].each_value do |group| data.concat(group["instanceGroups"]) if group["instanceGroups"] end end load(data) end def get(identity, zone = nil) if zone.nil? zones = service.list_aggregated_instance_groups(:filter => "name eq .*#{identity}").body["items"] target_zone = zones.each_value.select { |zone| zone.key?("instanceGroups") } response = target_zone.first["instanceGroups"].first unless target_zone.empty? zone = response["zone"].split("/")[-1] end if instance_group = service.get_instance_group(identity, zone).body new(instance_group) end rescue Fog::Errors::NotFound nil end # TODO: To be deprecated def add_instance(params) Fog::Logger.deprecation( "#{self.class}.#{__method__} is deprecated, use Fog::Compute::Google::InstanceGroup.#{__method__} instead [light_black](#{caller.first})[/]" ) params[:instance] = [params[:instance]] unless params[:instance] == Array service.add_instance_group_instances(params[:group], params[:zone], params[:instance]) end # TODO: To be deprecated def remove_instance(params) Fog::Logger.deprecation( "#{self.class}.#{__method__} is deprecated, use Fog::Compute::Google::InstanceGroup.#{__method__} instead [light_black](#{caller.first})[/]" ) params[:instance] = [params[:instance]] unless params[:instance] == Array service.remove_instance_group_instances(params[:group], params[:zone], params[:instance]) end end end end end fog-google-0.5.3/lib/fog/compute/google/models/region.rb0000755000004100000410000000125513145731036023151 0ustar www-datawww-datamodule Fog module Compute class Google ## # Represents a Region resource # # @see https://developers.google.com/compute/docs/reference/latest/regions class Region < Fog::Model identity :name attribute :kind attribute :id attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :deprecated attribute :description attribute :quotas attribute :self_link, :aliases => "selfLink" attribute :status attribute :zones DOWN_STATE = "DOWN" UP_STATE = "UP" def up? status == UP_STATE end end end end end fog-google-0.5.3/lib/fog/compute/google/models/zone.rb0000644000004100000410000000101113145731036022624 0ustar www-datawww-datamodule Fog module Compute class Google class Zone < Fog::Model identity :name attribute :description attribute :status attribute :maintenance_windows, :aliases => "maintenanceWindows" attribute :begin_time, :aliases => "beginTime" attribute :end_time, :aliases => "endTime" attribute :quotas attribute :region attribute :self_link, :aliases => "selfLink" def up? status == "UP" end end end end end fog-google-0.5.3/lib/fog/compute/google/models/target_pools.rb0000644000004100000410000000210213145731036024355 0ustar www-datawww-datamodule Fog module Compute class Google class TargetPools < Fog::Collection model Fog::Compute::Google::TargetPool def all(filters = {}) if filters["region"].nil? data = [] service.list_regions.body["items"].each do |region| data += service.list_target_pools(region["name"]).body["items"] || [] end else data = service.list_target_pools(filters["region"]).body["items"] || [] end load(data) end def get(identity, region = nil) response = nil if region.nil? service.regions.all.each do |region| begin response = service.get_target_pool(identity, region.name) break if response.status == 200 rescue Fog::Errors::Error end end else response = service.get_target_pool(identity, region) end return nil if response.nil? new(response.body) end end end end end fog-google-0.5.3/lib/fog/compute/google/models/forwarding_rules.rb0000644000004100000410000000215413145731036025236 0ustar www-datawww-datamodule Fog module Compute class Google class ForwardingRules < Fog::Collection model Fog::Compute::Google::ForwardingRule def all(filters = {}) if filters["region"].nil? data = [] service.list_regions.body["items"].each do |region| data += service.list_forwarding_rules(region["name"]).body["items"] || [] end else data = service.list_forwarding_rules(filters["region"]).body["items"] || [] end load(data) end def get(identity, region = nil) response = nil if region.nil? service.list_regions.body["items"].each do |region| begin response = service.get_forwarding_rule(identity, region["name"]) break if response.status == 200 rescue Fog::Errors::Error end end else response = service.get_forwarding_rule(identity, region) end return nil if response.nil? new(response.body) end end end end end fog-google-0.5.3/lib/fog/compute/google/models/resource_views.rb0000644000004100000410000000337513145731036024734 0ustar www-datawww-datamodule Fog module Compute class Google class ResourceViews < Fog::Collection model Fog::Compute::Google::ResourceView def all(filters = {}) if filters["region"].nil? && filters["zone"].nil? data = [] service.list_regions.body["items"].each do |region| data += service.list_region_views(region["name"]).body["items"] || [] end service.list_zones.body["items"].each do |zone| data += service.list_zone_views(zone["name"]).body["items"] || [] end elsif filters["zone"] data = service.list_zone_views(filters["zone"]).body["items"] || [] else data = service.list_region_views(filters["region"]).body["items"] || [] end load(data) end def get(identity, region = nil, zone = nil) response = nil if region.nil? & zone.nil? service.list_regions.body["items"].each do |region| begin response = service.get_region_view(identity, region["name"]) break if response.status == 200 rescue Fog::Errors::Error end end service.list_zones.body["items"].each do |zone| begin response = service.get_zone_view(identity, zone["name"]) break if response.status == 200 rescue Fog::Errors::Error end end elsif region response = service.get_region_view(identity, region) else response = service.get_zone_view(identity, zone) end return nil if response.nil? new(response.body) end end end end end fog-google-0.5.3/lib/fog/compute/google/models/disk.rb0000644000004100000410000000741213145731036022616 0ustar www-datawww-datamodule Fog module Compute class Google class Disk < Fog::Model identity :name attribute :kind attribute :id attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :zone, :aliases => :zone_name attribute :status attribute :description attribute :size_gb, :aliases => "sizeGb" attribute :self_link, :aliases => "selfLink" attribute :source_image, :aliases => "sourceImage" attribute :source_image_id, :aliases => "sourceImageId" attribute :source_snapshot, :aliases => "sourceSnapshot" attribute :source_snapshot_id, :aliases => "sourceSnapshotId" attribute :type def save requires :name, :zone, :size_gb options = {} my_description = "Created with fog" unless source_image.nil? my_description = "Created from image: #{source_image}" end if source_image.nil? && !source_snapshot.nil? options["sourceSnapshot"] = source_snapshot my_description = "Created from snapshot: #{source_snapshot}" end options["sizeGb"] = size_gb options["description"] = description || my_description options["type"] = type data = service.insert_disk(name, zone, source_image, options) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) operation.wait_for { !pending? } reload end def destroy(async = true) requires :name, :zone data = service.delete_disk(name, zone_name) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) operation.wait_for { ready? } unless async operation end def zone_name zone.nil? ? nil : zone.split("/")[-1] end # auto_delete can only be applied to disks created before instance creation. # auto_delete = true will automatically delete disk upon instance termination. def get_object(writable = true, boot = false, device_name = nil, auto_delete = false) mode = writable ? "READ_WRITE" : "READ_ONLY" value = { "autoDelete" => auto_delete, "boot" => boot, "source" => self_link, "mode" => mode, "deviceName" => device_name, "type" => "PERSISTENT" }.select { |_k, v| !v.nil? } Hash[value] end def get_as_boot_disk(writable = true, auto_delete = false) get_object(writable, true, nil, auto_delete) end def ready? status == RUNNING_STATE end def reload requires :identity, :zone return unless data = begin collection.get(identity, zone_name) rescue Excon::Errors::SocketError nil end new_attributes = data.attributes merge_attributes(new_attributes) self end def create_snapshot(snapshot_name, snapshot_description = "") requires :name, :zone if snapshot_name.nil? || snapshot_name.empty? raise ArgumentError, "Invalid snapshot name" end options = { "name" => snapshot_name, "description" => snapshot_description } data = service.insert_snapshot(name, zone_name, service.project, options) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) operation.wait_for { !pending? } service.snapshots.get(snapshot_name) end RUNNING_STATE = "READY" end end end end fog-google-0.5.3/lib/fog/compute/google/models/flavor.rb0000644000004100000410000000170513145731036023154 0ustar www-datawww-datamodule Fog module Compute class Google class Flavor < Fog::Model identity :name attribute :kind attribute :id attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :deprecated attribute :description attribute :guest_cpus, :aliases => "guestCpus" attribute :image_space_gb, :aliases => "imageSpaceGb" attribute :maximum_persistent_disks, :aliases => "maximumPersistentDisks" attribute :maximum_persistent_disks_size, :aliases => "maximumPersistentDisksSizeGb" attribute :memory_mb, :aliases => "memoryMb" attribute :scratch_disks, aliases => "scratchDisks" attribute :self_link, :aliases => "selfLink" attribute :zone def reload requires :identity, :zone data = collection.get(identity, zone) merge_attributes(data.attributes) self end end end end end fog-google-0.5.3/lib/fog/compute/google/models/url_maps.rb0000644000004100000410000000070213145731036023501 0ustar www-datawww-datamodule Fog module Compute class Google class UrlMaps < Fog::Collection model Fog::Compute::Google::UrlMap def all data = service.list_url_maps.body["items"] || [] load(data) end def get(identity) if url_map = service.get_url_map(identity).body new(url_map) end rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/forwarding_rule.rb0000644000004100000410000000472613145731036025062 0ustar www-datawww-datamodule Fog module Compute class Google class ForwardingRule < Fog::Model identity :name attribute :kind, :aliases => "kind" attribute :self_link, :aliases => "selfLink" attribute :id, :aliases => "id" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description, :aliases => "description" attribute :region, :aliases => "region" attribute :ip_address, :aliases => "IPAddress" attribute :ip_protocol, :aliases => "IPProtocol" attribute :port_range, :aliases => "portRange" attribute :target, :aliases => "target" def save requires :name, :region, :target options = { "description" => description, "region" => region, "IPAddress" => ip_address, "IPProtocol" => ip_protocol || "TCP", "portRange" => port_range, "target" => target } data = service.insert_forwarding_rule(name, region, options).body operation = Fog::Compute::Google::Operations.new(:service => service).get(data["name"], nil, data["region"]) operation.wait_for { !pending? } reload end def set_target(new_target) new_target = new_target.self_link unless new_target.class == String self.target = new_target service.set_forwarding_rule_target(self, new_target) reload end def destroy(async = true) requires :name, :region operation = service.delete_forwarding_rule(name, region) unless async # wait until "RUNNING" or "DONE" to ensure the operation doesn't # fail, raises exception on error Fog.wait_for do operation = service.get_region_operation(region, operation.body["name"]) operation.body["status"] == "DONE" end end operation end def ready? service.get_forwarding_rule(name, region) true rescue Fog::Errors::NotFound false end def reload requires :name, :region return unless data = begin collection.get(name, region) rescue Excon::Errors::SocketError nil end new_attributes = data.attributes merge_attributes(new_attributes) self end RUNNING_STATE = "READY" end end end end fog-google-0.5.3/lib/fog/compute/google/models/global_forwarding_rule.rb0000644000004100000410000000474513145731036026403 0ustar www-datawww-datamodule Fog module Compute class Google class GlobalForwardingRule < Fog::Model identity :name attribute :kind, :aliases => "kind" attribute :self_link, :aliases => "selfLink" attribute :id, :aliases => "id" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description, :aliases => "description" attribute :region, :aliases => "region" # should always be 'global' attribute :ip_address, :aliases => "IPAddress" # string attribute :ip_protocol, :aliases => "IPProtocol" # string attribute :port_range, :aliases => "portRange" # string attribute :target, :aliases => "target" # string, URL of global target http proxy def save requires :name options = { "description" => description, "region" => "global", "IPAddress" => ip_address, "IPProtocol" => ip_protocol || "TCP", "portRange" => port_range || 80, "target" => target } data = service.insert_global_forwarding_rule(name, options).body operation = Fog::Compute::Google::Operations.new(:service => service).get(data["name"], nil, data["region"]) operation.wait_for { !pending? } reload end def destroy(async = true) requires :name operation = service.delete_global_forwarding_rule(name, "global") unless async # wait until "RUNNING" or "DONE" to ensure the operation doesn't # fail, raises exception on error Fog.wait_for do operation.body["status"] == "DONE" end end operation end def set_target(new_target) new_target = new_target.self_link unless new_target.class == String self.target = new_target service.set_global_forwarding_rule_target(self, new_target) reload end def ready? service.get_global_forwarding_rule(name, "global") true rescue Fog::Errors::NotFound false end def reload requires :name return unless data = begin collection.get(name, "global") rescue Excon::Errors::SocketError nil end new_attributes = data.attributes merge_attributes(new_attributes) self end RUNNING_STATE = "READY" end end end end fog-google-0.5.3/lib/fog/compute/google/models/route.rb0000644000004100000410000000277113145731036023025 0ustar www-datawww-datamodule Fog module Compute class Google ## # Represents a Route resource # # @see https://developers.google.com/compute/docs/reference/latest/routes class Route < Fog::Model identity :name attribute :kind attribute :id attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :dest_range, :aliases => "destRange" attribute :network attribute :next_hop_gateway, :aliases => "nextHopGateway" attribute :next_hop_instance, :aliases => "nextHopInstance" attribute :next_hop_ip, :aliases => "nextHopIp" attribute :next_hop_network, :aliases => "nextHopNetwork" attribute :priority attribute :self_link, :aliases => "selfLink" attribute :tags attribute :warnings def save requires :identity, :network, :dest_range, :priority data = service.insert_route(identity, network, dest_range, priority, attributes) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"]) operation.wait_for { !pending? } reload end def destroy(async = true) requires :identity data = service.delete_route(identity) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"]) operation.wait_for { ready? } unless async operation end end end end end fog-google-0.5.3/lib/fog/compute/google/models/instance_group.rb0000644000004100000410000000425613145731036024707 0ustar www-datawww-datamodule Fog module Compute class Google class InstanceGroup < Fog::Model identity :name attribute :id attribute :kind attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :fingerprint attribute :namedPorts attribute :network attribute :subnetwork attribute :self_link, :aliases => "selfLink" attribute :size attribute :zone, :aliases => :zone_name def save requires :name, :zone options = { "network" => network_name, "subnetwork" => subnetwork_name } service.insert_instance_group(name, zone, options) end def destroy(_async = true) requires :name, :zone service.delete_instance_group(name, zone_name) end def add_instances(instances) requires :identity, :zone service.add_instance_group_instances( identity, zone_name, format_instance_list(instances) ) end def remove_instances(instances) requires :identity, :zone service.remove_instance_group_instances( identity, zone_name, format_instance_list(instances) ) end def list_instances requires :identity, :zone instance_list = [] data = service.list_instance_group_instances(identity, zone_name).body if data["items"] data["items"].each do |instance| instance_list << service.servers.get(instance["instance"].split("/")[-1], zone_name) end end instance_list end def zone_name zone.nil? ? nil : zone.split("/")[-1] end def network_name network.nil? ? nil : network.split("/")[-1] end def subnetwork_name subnetwork.nil? ? nil : subnetwork.split("/")[-1] end private def format_instance_list(instance_list) instance_list = Array(instance_list) instance_list.map { |i| i.class == String ? i : i.self_link } end end end end end fog-google-0.5.3/lib/fog/compute/google/models/snapshots.rb0000644000004100000410000000133713145731036023706 0ustar www-datawww-datamodule Fog module Compute class Google class Snapshots < Fog::Collection model Fog::Compute::Google::Snapshot def all items = [] next_page_token = nil loop do data = service.list_snapshots(nil, next_page_token) items.concat(data.body["items"]) next_page_token = data.body["nextPageToken"] break if next_page_token.nil? || next_page_token.empty? end load(items) end def get(snap_id) response = service.get_snapshot(snap_id) return nil if response.nil? new(response.body) rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/server.rb0000644000004100000410000002446513145731036023201 0ustar www-datawww-datarequire "fog/compute/models/server" module Fog module Compute class Google class Server < Fog::Compute::Server identity :name attribute :kind attribute :id attribute :can_ip_forward, :aliases => "canIpForward" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :disks attribute :machine_type, :aliases => "machineType" attribute :metadata attribute :network_interfaces, :aliases => "networkInterfaces" attribute :scheduling attribute :self_link, :aliases => "selfLink" attribute :service_accounts, :aliases => "serviceAccounts" attribute :state, :aliases => "status" attribute :status_message, :aliases => "statusMessage" attribute :tags attribute :zone, :aliases => :zone_name # These attributes are not available in the representation of an 'instance' returned by the GCE API. # They are useful only for the create process attribute :network, :aliases => "network" attribute :subnetwork, :aliases => "subnetwork" attribute :external_ip, :aliases => "externalIP" attribute :auto_restart attribute :on_host_maintenance attribute :preemptible # Security account scope aliases used by official gcloud utility # List derived from 'gcloud compute instances create --help' GCE_SCOPE_ALIASES = { "compute-ro" => "compute.readonly", "compute-rw" => "compute", "computeaccounts-ro" => "computeaccounts.readonly", "computeaccounts-rw" => "computeaccounts", "logging-write" => "logging.write", "sql" => "sqlservice", "sql-admin" => "sqlservice.admin", "storage-full" => "devstorage.full_control", "storage-ro" => "devstorage.read_only", "storage-rw" => "devstorage.read_write" } def image_name=(_args) Fog::Logger.deprecation("image_name= is no longer used [light_black](#{caller.first})[/]") end def image_name boot_disk = disks.first unless boot_disk.is_a?(Disk) source = boot_disk["source"] match = source.match(%r{/zones/(.*)/disks/(.*)$}) boot_disk = service.disks.get match[2], match[1] end boot_disk.source_image.nil? ? nil : boot_disk.source_image end def kernel=(_args) Fog::Logger.deprecation("kernel= is no longer used [light_black](#{caller.first})[/]") end def kernel Fog::Logger.deprecation("kernel is no longer used [light_black](#{caller.first})[/]") nil end def flavor_id machine_type end def flavor_id=(flavor_id) machine_type = flavor_id end def destroy(async = true) requires :name, :zone data = service.delete_server(name, zone_name) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) operation.wait_for { ready? } unless async operation end # not used since v1 def image Fog::Logger.deprecation("Server.image is deprecated, get source_image from boot disk") service.get_image(image_name.split("/")[-1]) end def public_ip_address ip = nil if network_interfaces.respond_to? :each network_interfaces.each do |netif| next unless netif["accessConfigs"].respond_to? :each netif["accessConfigs"].each do |access_config| if access_config["name"] == "External NAT" ip = access_config["natIP"] end end end end ip end def private_ip_address ip = nil if network_interfaces.respond_to? :first ip = network_interfaces.first["networkIP"] end ip end def addresses [private_ip_address, public_ip_address] end def attach_disk(disk, options = {}) requires :identity, :zone data = service.attach_disk(identity, zone_name, disk, options) Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) end def detach_disk(device_name) requires :identity, :zone data = service.detach_disk(identity, zone, device_name) Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) end def reboot requires :identity, :zone data = service.reset_server(identity, zone_name) Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) end def start requires :identity, :zone data = service.start_server(identity, zone_name) Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) end def stop requires :identity, :zone data = service.stop_server(identity, zone_name) Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) end def serial_port_output requires :identity, :zone data = service.get_server_serial_port_output(identity, zone_name) data.body["contents"] end def set_disk_auto_delete(auto_delete, device_name = nil) requires :identity, :zone unless device_name if disks.count <= 1 device_name = disks[0]["deviceName"] else raise ArgumentError.new("Device name required if multiple disks are attached") end end data = service.set_server_disk_auto_delete(identity, zone_name, auto_delete, device_name) Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) end def set_scheduling(on_host_maintenance, automatic_restart, preemptible) requires :identity, :zone data = service.set_server_scheduling(identity, zone_name, on_host_maintenance, automatic_restart, preemptible) Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) end def set_metadata(metadata = {}) requires :identity, :zone data = service.set_metadata(identity, zone_name, self.metadata["fingerprint"], metadata) Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) end def set_tags(tags = []) requires :identity, :zone data = service.set_tags(identity, zone_name, self.tags["fingerprint"], tags) Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) end def provisioning? state == PROVISIONING end def ready? state == RUNNING end def zone_name zone.nil? ? nil : zone.split("/")[-1] end def add_ssh_key(username, key) set_metadata(generate_ssh_key_metadata(username, key)) end def map_service_accounts(scope_array) scope_array_expanded = scope_array.map do |e| if GCE_SCOPE_ALIASES[e] GCE_SCOPE_ALIASES[e] else e end end scope_array_finalized = scope_array_expanded.map do |e| if e.start_with?("https://") e else "https://www.googleapis.com/auth/#{e}" end end scope_array_finalized end def reload data = service.get_server(name, zone_name).body merge_attributes(data) end def save requires :name requires :machine_type requires :zone_name requires :disks unless service.zones.detect { |zone| zone.name == zone_name } raise ArgumentError.new "#{zone_name.inspect} is either down or you don't have permission to use it." end generate_ssh_key_metadata(username, public_key) if public_key options = { "machineType" => machine_type, "networkInterfaces" => network_interfaces, "network" => network, "subnetwork" => subnetwork, "externalIp" => external_ip, "disks" => disks, "metadata" => metadata, "serviceAccounts" => service_accounts, "tags" => tags, "auto_restart" => auto_restart, "on_host_maintenance" => on_host_maintenance, "preemptible" => preemptible, "can_ip_forward" => can_ip_forward }.delete_if { |_key, value| value.nil? } if service_accounts options["serviceAccounts"] = [{ "kind" => "compute#serviceAccount", "email" => "default", "scopes" => map_service_accounts(service_accounts) }] end data = service.insert_server(name, zone_name, options) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"], data.body["zone"]) operation.wait_for { !pending? } reload end private def generate_ssh_key_metadata(username, key) self.metadata = Hash.new("") if metadata.nil? # The key "sshKeys" is deprecated and will be unsupported in the # future - for now defer to using 'ssh-keys' unless the user is # already using the deprecated version # https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys#deprecated metadata_key = metadata.key?("sshKeys") ? "sshKeys" : "ssh-keys" # You can have multiple SSH keys, seperated by newlines. # https://developers.google.com/compute/docs/console?hl=en#sshkeys metadata[metadata_key] = "" unless metadata[metadata_key] metadata[metadata_key] += "\n" unless metadata[metadata_key].empty? metadata[metadata_key] += "#{username}:#{key.strip}" metadata end end end end end fog-google-0.5.3/lib/fog/compute/google/models/image.rb0000644000004100000410000000506413145731036022747 0ustar www-datawww-datamodule Fog module Compute class Google class Image < Fog::Model identity :name attribute :id attribute :kind attribute :archive_size_bytes, :aliases => "archiveSizeBytes" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :deprecated attribute :description attribute :disk_size_gb, :aliases => "diskSizeGb" attribute :family attribute :licenses attribute :self_link, :aliases => "selfLink" attribute :source_type, :aliases => "sourceType" attribute :status # This attribute is not available in the representation of an # 'image' returned by the GCE servser (see GCE API). However, # images are a global resource and a user can query for images # across projects. Therefore we try to remember which project # the image belongs to by tracking it in this attribute. attribute :project # A RawDisk, e.g. - # { # :source => url_to_gcs_file, # :container_type => 'TAR', # :sha1Checksum => , # } attribute :raw_disk, :aliases => "rawDisk" def preferred_kernel=(_args) Fog::Logger.deprecation("preferred_kernel= is no longer used [light_black](#{caller.first})[/]") end def preferred_kernel Fog::Logger.deprecation("preferred_kernel is no longer used [light_black](#{caller.first})[/]") nil end READY_STATE = "READY" def ready? status == READY_STATE end def destroy(async = true) data = service.delete_image(name) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"]) operation.wait_for { ready? } unless async operation end def reload requires :name self.project = service.project data = service.get_image(name, project).body merge_attributes(data) self end def save requires :name requires :raw_disk options = { "rawDisk" => raw_disk, "description" => description } data = service.insert_image(name, options) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.body["name"]) operation.wait_for { !pending? } reload end def resource_url "#{project}/global/images/#{name}" end end end end end fog-google-0.5.3/lib/fog/compute/google/models/target_http_proxies.rb0000644000004100000410000000101513145731036025753 0ustar www-datawww-datamodule Fog module Compute class Google class TargetHttpProxies < Fog::Collection model Fog::Compute::Google::TargetHttpProxy def all(_filters = {}) data = service.list_target_http_proxies.body["items"] || [] load(data) end def get(identity) if target_http_proxy = service.get_target_http_proxy(identity).body new(target_http_proxy) end rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/target_instances.rb0000644000004100000410000000242713145731036025222 0ustar www-datawww-datamodule Fog module Compute class Google class TargetInstances < Fog::Collection model Fog::Compute::Google::TargetInstance def all(filters = {}) if filters["zone"] data = service.list_target_instances(filters["zone"]).body["items"] || [] else data = [] service.list_aggregated_target_instances.body["items"].each_value do |zone| data.concat(zone["targetInstances"]) if zone["targetInstances"] end end load(data) end def get(identity, zone = nil) response = nil if zone response = service.get_target_instance(identity, zone).body else target_instances = service.list_aggregated_target_instances(:filter => "name eq .*#{identity}").body["items"] target_instance = target_instances.each_value.select { |zone| zone.key?("targetInstances") } # It can only be 1 target_instance with the same name across all regions response = target_instance.first["targetInstances"].first unless target_instance.empty? end return nil if response.nil? new(response) rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/disk_type.rb0000644000004100000410000000116213145731036023653 0ustar www-datawww-datamodule Fog module Compute class Google class DiskType < Fog::Model identity :name attribute :kind attribute :id attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :deprecated attribute :description attribute :self_link, :aliases => "selfLink" attribute :valid_disk_size, :aliases => "validDiskSize" attribute :zone def reload requires :identity, :zone data = collection.get(identity, zone) merge_attributes(data.attributes) self end end end end end fog-google-0.5.3/lib/fog/compute/google/models/firewalls.rb0000644000004100000410000000071213145731036023650 0ustar www-datawww-datamodule Fog module Compute class Google class Firewalls < Fog::Collection model Fog::Compute::Google::Firewall def all data = service.list_firewalls.body load(data["items"] || []) end def get(identity) if firewall = service.get_firewall(identity).body new(firewall) end rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/lib/fog/compute/google/models/networks.rb0000644000004100000410000000070413145731036023535 0ustar www-datawww-datamodule Fog module Compute class Google class Networks < Fog::Collection model Fog::Compute::Google::Network def all data = service.list_networks.body load(data["items"] || []) end def get(identity) if network = service.get_network(identity).body new(network) end rescue Fog::Errors::NotFound nil end end end end end fog-google-0.5.3/.rubocop.yml0000644000004100000410000001736513145731036016065 0ustar www-datawww-data# Fog custom enforced styles Metrics/LineLength: Enabled: false Style/ConditionalAssignment: SingleLineConditionsOnly: true Style/Encoding: EnforcedStyle: when_needed Style/FormatString: Enabled: false Style/RegexpLiteral: Enabled: false #TODO: this needs to be adressed not through the linter Style/FrozenStringLiteralComment: Enabled: false Style/HashSyntax: EnforcedStyle: hash_rockets # HoundCI config AllCops: Exclude: - "vendor/**/*" - "db/schema.rb" UseCache: false Style/CollectionMethods: Description: Preferred collection methods. StyleGuide: https://github.com/bbatsov/ruby-style-guide#map-find-select-reduce-size Enabled: true PreferredMethods: collect: map collect!: map! find: detect find_all: select reduce: inject Style/DotPosition: Description: Checks the position of the dot in multi-line method calls. StyleGuide: https://github.com/bbatsov/ruby-style-guide#consistent-multi-line-chains Enabled: true EnforcedStyle: trailing SupportedStyles: - leading - trailing Style/FileName: Description: Use snake_case for source file names. StyleGuide: https://github.com/bbatsov/ruby-style-guide#snake-case-files Enabled: false Exclude: [] Style/GuardClause: Description: Check for conditionals that can be replaced with guard clauses StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals Enabled: false MinBodyLength: 1 Style/IfUnlessModifier: Description: Favor modifier if/unless usage when you have a single-line body. StyleGuide: https://github.com/bbatsov/ruby-style-guide#if-as-a-modifier Enabled: false MaxLineLength: 80 Style/OptionHash: Description: Don't use option hashes when you can use keyword arguments. Enabled: false Style/PercentLiteralDelimiters: Description: Use `%`-literal delimiters consistently StyleGuide: https://github.com/bbatsov/ruby-style-guide#percent-literal-braces Enabled: false PreferredDelimiters: "%": "()" "%i": "()" "%q": "()" "%Q": "()" "%r": "{}" "%s": "()" "%w": "()" "%W": "()" "%x": "()" Style/PredicateName: Description: Check the names of predicate methods. StyleGuide: https://github.com/bbatsov/ruby-style-guide#bool-methods-qmark Enabled: true NamePrefix: - is_ - has_ - have_ NamePrefixBlacklist: - is_ Exclude: - spec/**/* Style/RaiseArgs: Description: Checks the arguments passed to raise/fail. StyleGuide: https://github.com/bbatsov/ruby-style-guide#exception-class-messages Enabled: false EnforcedStyle: exploded SupportedStyles: - compact - exploded Style/SignalException: Description: Checks for proper usage of fail and raise. StyleGuide: https://github.com/bbatsov/ruby-style-guide#fail-method Enabled: false EnforcedStyle: semantic SupportedStyles: - only_raise - only_fail - semantic Style/SingleLineBlockParams: Description: Enforces the names of some block params. StyleGuide: https://github.com/bbatsov/ruby-style-guide#reduce-blocks Enabled: false Methods: - reduce: - a - e - inject: - a - e Style/SingleLineMethods: Description: Avoid single-line methods. StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-single-line-methods Enabled: false AllowIfMethodIsEmpty: true Style/StringLiterals: Description: Checks if uses of quotes match the configured preference. StyleGuide: https://github.com/bbatsov/ruby-style-guide#consistent-string-literals Enabled: true EnforcedStyle: double_quotes SupportedStyles: - single_quotes - double_quotes Style/StringLiteralsInInterpolation: Description: Checks if uses of quotes inside expressions in interpolated strings match the configured preference. Enabled: true EnforcedStyle: single_quotes SupportedStyles: - single_quotes - double_quotes Metrics/AbcSize: Description: A calculated magnitude based on number of assignments, branches, and conditions. Enabled: false Max: 15 Metrics/ClassLength: Description: Avoid classes longer than 100 lines of code. Enabled: false CountComments: false Max: 100 Metrics/ModuleLength: CountComments: false Max: 100 Description: Avoid modules longer than 100 lines of code. Enabled: false Metrics/CyclomaticComplexity: Description: A complexity metric that is strongly correlated to the number of test cases needed to validate a method. Enabled: false Max: 6 Metrics/MethodLength: Description: Avoid methods longer than 10 lines of code. StyleGuide: https://github.com/bbatsov/ruby-style-guide#short-methods Enabled: false CountComments: false Max: 10 Metrics/ParameterLists: Description: Avoid parameter lists longer than three or four parameters. StyleGuide: https://github.com/bbatsov/ruby-style-guide#too-many-params Enabled: false Max: 5 CountKeywordArgs: true Metrics/PerceivedComplexity: Description: A complexity metric geared towards measuring complexity for a human reader. Enabled: false Max: 7 Lint/AssignmentInCondition: Description: Don't use assignment in conditions. StyleGuide: https://github.com/bbatsov/ruby-style-guide#safe-assignment-in-condition Enabled: false AllowSafeAssignment: true Style/InlineComment: Description: Avoid inline comments. Enabled: false Style/AccessorMethodName: Description: Check the naming of accessor methods for get_/set_. Enabled: false Style/Alias: Description: Use alias_method instead of alias. StyleGuide: https://github.com/bbatsov/ruby-style-guide#alias-method Enabled: false Style/Documentation: Description: Document classes and non-namespace modules. Enabled: false Style/DoubleNegation: Description: Checks for uses of double negation (!!). StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-bang-bang Enabled: false Style/EachWithObject: Description: Prefer `each_with_object` over `inject` or `reduce`. Enabled: false Style/EmptyLiteral: Description: Prefer literals to Array.new/Hash.new/String.new. StyleGuide: https://github.com/bbatsov/ruby-style-guide#literal-array-hash Enabled: false Style/ModuleFunction: Description: Checks for usage of `extend self` in modules. StyleGuide: https://github.com/bbatsov/ruby-style-guide#module-function Enabled: false Style/OneLineConditional: Description: Favor the ternary operator(?:) over if/then/else/end constructs. StyleGuide: https://github.com/bbatsov/ruby-style-guide#ternary-operator Enabled: false Style/PerlBackrefs: Description: Avoid Perl-style regex back references. StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-perl-regexp-last-matchers Enabled: false Style/Send: Description: Prefer `Object#__send__` or `Object#public_send` to `send`, as `send` may overlap with existing methods. StyleGuide: https://github.com/bbatsov/ruby-style-guide#prefer-public-send Enabled: false Style/SpecialGlobalVars: Description: Avoid Perl-style global variables. StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-cryptic-perlisms Enabled: false Style/VariableInterpolation: Description: Don't interpolate global, instance and class variables directly in strings. StyleGuide: https://github.com/bbatsov/ruby-style-guide#curlies-interpolate Enabled: false Style/WhenThen: Description: Use when x then ... for one-line cases. StyleGuide: https://github.com/bbatsov/ruby-style-guide#one-line-cases Enabled: false Lint/EachWithObjectArgument: Description: Check for immutable argument given to each_with_object. Enabled: true Lint/HandleExceptions: Description: Don't suppress exception. StyleGuide: https://github.com/bbatsov/ruby-style-guide#dont-hide-exceptions Enabled: false Lint/LiteralInCondition: Description: Checks of literals used in conditions. Enabled: false Lint/LiteralInInterpolation: Description: Checks for literals used in interpolation. Enabled: false fog-google-0.5.3/test/0000755000004100000410000000000013145731036014556 5ustar www-datawww-datafog-google-0.5.3/test/integration/0000755000004100000410000000000013145731036017101 5ustar www-datawww-datafog-google-0.5.3/test/integration/factories/0000755000004100000410000000000013145731036021060 5ustar www-datawww-datafog-google-0.5.3/test/integration/factories/collection_factory.rb0000644000004100000410000000161013145731036025265 0ustar www-datawww-dataclass CollectionFactory PREFIX = "fog-test" def initialize(subject, example) @subject = subject @example = example @resource_counter = 0 end def cleanup resources = @subject.all.select { |resource| resource.name.start_with? PREFIX } resources.each(&:destroy) resources.each { |r| Fog.wait_for { !@subject.all.map(&:identity).include? r.identity } } end def create @subject.create(params) end def resource_name(base = @example, prefix = PREFIX) index = @resource_counter += 1 # In prefix, convert - to _ to make sure that it doesn't get stripped by the \W strip below. # Then, concatenate prefix, index, and base; strip all non-alphanumerics except _; # convert _ to -; downcase; truncate to 62 characters; delete trailing - ([prefix.tr("-", "_"), index, base].join("_")).gsub(/\W/, "").tr("_", "-").downcase[0..61].chomp("-") end end fog-google-0.5.3/test/integration/factories/images_factory.rb0000644000004100000410000000043413145731036024402 0ustar www-datawww-datarequire "integration/factories/collection_factory" class ImagesFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].images, example) end def params { :name => resource_name, :raw_disk => { :source => TEST_RAW_DISK_SOURCE } } end end fog-google-0.5.3/test/integration/factories/target_pools_factory.rb0000644000004100000410000000124613145731036025641 0ustar www-datawww-datarequire "integration/factories/collection_factory" require "integration/factories/servers_factory" require "integration/factories/http_health_checks_factory" class TargetPoolsFactory < CollectionFactory def initialize(example) @http_health_checks = HttpHealthChecksFactory.new(example) @servers = ServersFactory.new(example) super(Fog::Compute[:google].target_pools, example) end def cleanup super @servers.cleanup @http_health_checks.cleanup end def params { :name => resource_name, :region => TEST_REGION, :instances => [@servers.create.self_link], :healthChecks => [@http_health_checks.create.self_link] } end end fog-google-0.5.3/test/integration/factories/backend_services_factory.rb0000644000004100000410000000076013145731036026431 0ustar www-datawww-datarequire "integration/factories/collection_factory" require "integration/factories/http_health_checks_factory" class BackendServicesFactory < CollectionFactory def initialize(example) @http_health_checks = HttpHealthChecksFactory.new(example) super(Fog::Compute[:google].backend_services, example) end def cleanup super @http_health_checks.cleanup end def params { :name => resource_name, :health_checks => [@http_health_checks.create.self_link] } end end fog-google-0.5.3/test/integration/factories/target_http_proxies_factory.rb0000644000004100000410000000067413145731036027241 0ustar www-datawww-datarequire "integration/factories/collection_factory" require "integration/factories/url_maps_factory" class TargetHttpProxiesFactory < CollectionFactory def initialize(example) @url_maps = UrlMapsFactory.new(example) super(Fog::Compute[:google].target_http_proxies, example) end def cleanup super @url_maps.cleanup end def params { :name => resource_name, :url_map => @url_maps.create.self_link } end end fog-google-0.5.3/test/integration/factories/servers_factory.rb0000644000004100000410000000072713145731036024633 0ustar www-datawww-datarequire "integration/factories/collection_factory" require "integration/factories/disks_factory" class ServersFactory < CollectionFactory def initialize(example) @disks = DisksFactory.new(example) super(Fog::Compute[:google].servers, example) end def cleanup super @disks.cleanup end def params { :name => resource_name, :zone_name => TEST_ZONE, :machine_type => TEST_MACHINE_TYPE, :disks => [@disks.create] } end end fog-google-0.5.3/test/integration/factories/forwarding_rules_factory.rb0000644000004100000410000000075013145731036026512 0ustar www-datawww-datarequire "integration/factories/collection_factory" require "integration/factories/target_pools_factory" class ForwardingRulesFactory < CollectionFactory def initialize(example) @target_pools = TargetPoolsFactory.new(example) super(Fog::Compute[:google].forwarding_rules, example) end def cleanup super @target_pools.cleanup end def params { :name => resource_name, :region => TEST_REGION, :target => @target_pools.create.self_link } end end fog-google-0.5.3/test/integration/factories/url_maps_factory.rb0000644000004100000410000000072713145731036024764 0ustar www-datawww-datarequire "integration/factories/collection_factory" require "integration/factories/backend_services_factory" class UrlMapsFactory < CollectionFactory def initialize(example) @backend_services = BackendServicesFactory.new(example) super(Fog::Compute[:google].url_maps, example) end def cleanup super @backend_services.cleanup end def params { :name => resource_name, :default_service => @backend_services.create.self_link } end end fog-google-0.5.3/test/integration/factories/http_health_checks_factory.rb0000644000004100000410000000037213145731036026762 0ustar www-datawww-datarequire "integration/factories/collection_factory" class HttpHealthChecksFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].http_health_checks, example) end def params { :name => resource_name } end end fog-google-0.5.3/test/integration/factories/target_instances_factory.rb0000644000004100000410000000070413145731036026472 0ustar www-datawww-datarequire "integration/factories/collection_factory" require "integration/factories/servers_factory" class TargetInstancesFactory < CollectionFactory def initialize(example) @servers = ServersFactory.new(example) super(Fog::Compute[:google].target_instances, example) end def cleanup super @servers.cleanup end def params { :name => resource_name, :zone => TEST_ZONE, :instance => @servers.create } end end fog-google-0.5.3/test/integration/factories/global_forwarding_rules_factory.rb0000644000004100000410000000072513145731036030034 0ustar www-datawww-datarequire "integration/factories/collection_factory" require "integration/factories/target_http_proxies_factory" class GlobalForwardingRulesFactory < CollectionFactory def initialize(example) @targets = TargetHttpProxiesFactory.new(example) super(Fog::Compute[:google].global_forwarding_rules, example) end def cleanup super @targets.cleanup end def params { :name => resource_name, :target => @targets.create.self_link } end end fog-google-0.5.3/test/integration/factories/disks_factory.rb0000644000004100000410000000044113145731036024250 0ustar www-datawww-datarequire "integration/factories/collection_factory" class DisksFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].disks, example) end def params { :name => resource_name, :zone_name => TEST_ZONE, :size_gb => TEST_SIZE_GB } end end fog-google-0.5.3/test/integration/storage/0000755000004100000410000000000013145731036020545 5ustar www-datawww-datafog-google-0.5.3/test/integration/storage/test_buckets.rb0000644000004100000410000000314713145731036023576 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestBuckets < FogIntegrationTest begin @@connection = Fog::Storage::Google.new @@connection.delete_bucket("fog-smoke-test") rescue Exception => e # puts e end def setup @connection = @@connection end def teardown @connection.delete_bucket("fog-smoke-test") rescue end def test_put_bucket response = @connection.put_bucket("fog-smoke-test") assert_equal response.status, 200 end def test_put_bucket_acl response = @connection.put_bucket("fog-smoke-test", options: { "x-goog-acl" => "publicReadWrite" }) assert_equal response.status, 200 acl = { :entity => "domain-google.com", :role => "READER" } response = @connection.put_bucket_acl("fog-smoke-test", acl) assert_equal response.status, 200 end def test_delete_bucket response = @connection.put_bucket("fog-smoke-test") assert_equal response.status, 200 response = @connection.delete_bucket("fog-smoke-test") assert_equal response.status, 204 end def test_get_bucket response = @connection.put_bucket("fog-smoke-test") assert_equal response.status, 200 response = @connection.get_bucket("fog-smoke-test") assert_equal response.status, 200 end def test_get_bucket_acl response = @connection.put_bucket("fog-smoke-test", options: { "acl" => [{ :entity => "user-fake@developer.gserviceaccount.com", :role => "OWNER" }] }) assert_equal response.status, 200 response = @connection.get_bucket_acl("fog-smoke-test") assert_equal response.status, 200 end end fog-google-0.5.3/test/integration/storage/test_objects.rb0000644000004100000410000000633013145731036023564 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestObjects < FogIntegrationTest def setup @connection = Fog::Storage::Google.new begin @connection.put_bucket("fog-smoke-test", options: { "x-goog-acl" => "publicReadWrite" }) rescue end end def teardown begin @connection.delete_object("fog-smoke-test", "my file") rescue end begin @connection.delete_object("fog-smoke-test", "my file copy") rescue end begin @connection.delete_bucket("fog-smoke-test") rescue end end def test_put_object response = @connection.put_object("fog-smoke-test", "my file", "THISISATESTFILE") assert_equal response.status, 200 end def test_put_object_acl skip response = @connection.put_object("fog-smoke-test", "my file", "THISISATESTFILE") assert_equal response.status, 200 acl = { :entity => "domain-example.com", :role => "READER" } response = @connection.put_object_acl("fog-smoke-test", "my file", acl) assert_equal response.status, 200 end def test_put_object_url skip # Doesn't actually work response = @connection.put_object_url("fog-smoke-test", "my file url") puts response.inspect assert_equal response.status, 200 end def test_copy_object response = @connection.put_object("fog-smoke-test", "my file", "THISISATESTFILE") assert_equal response.status, 200 response = @connection.copy_object("fog-smoke-test", "my file", "fog-smoke-test", "my file copy") assert_equal response.status, 200 end def test_delete_object response = @connection.put_object("fog-smoke-test", "my file", "THISISATESTFILE") assert_equal response.status, 200 response = @connection.delete_object("fog-smoke-test", "my file") assert_equal response.status, 204 end def test_get_object skip response = @connection.put_object("fog-smoke-test", "my file", "THISISATESTFILE") assert_equal response.status, 200 response = @connection.get_object("fog-smoke-test", "my file") assert_equal response.status, 200 end def test_get_object_acl skip response = @connection.put_object("fog-smoke-test", "my file", "THISISATESTFILE") assert_equal response.status, 200 response = @connection.get_object_acl("fog-smoke-test", "my file") assert_equal response.status, 200 assert_equal response.body["kind"], "storage#objectAccessControls" end def test_get_object_http_url skip end def test_get_object_https_url skip response = @connection.put_object("fog-smoke-test", "my file", "THISISATESTFILE", options: { :predefinedAcl => "publicRead" }) assert_equal response.status, 200 https_url = @connection.get_object_https_url("fog-smoke-test", "my file") assert_match(/https/, https_url) assert_match(/fog-smoke-test/, https_url) assert_match(/my%20file/, https_url) end def test_get_object_url skip response = @connection.put_object("fog-smoke-test", "my file", "THISISATESTFILE") assert_equal response.status, 200 https_url = @connection.get_object_url("fog-smoke-test", "my file") assert_equal https_url, "https://www.googleapis.com/storage/v1/b/fog-smoke-test/o/my%20file" end def test_head_object skip end end fog-google-0.5.3/test/integration/storage/test_directories.rb0000644000004100000410000000275213145731036024453 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestDirectories < FogIntegrationTest begin client_email = Fog.credentials[:google_client_email] @@connection = Fog::Storage::Google.new @@connection.put_bucket("fog-smoke-test", options: { "acl" => [{ :entity => "user-" + client_email, :role => "OWNER" }] }) @@connection.put_bucket_acl("fog-smoke-test", :entity => "allUsers", :role => "READER") @@directory = @@connection.directories.get("fog-smoke-test") rescue Exception => e puts e end Minitest.after_run do begin @connection = Fog::Storage::Google.new @connection.delete_bucket("fog-smoke-test") rescue Exception => e puts e end end def setup @connection = @@connection @directory = @@directory end def test_all_directories skip end def test_get_directory directory_get = @connection.directories.get("fog-smoke-test") assert_instance_of Fog::Storage::Google::Directory, directory_get end def test_create_destroy_directory directory_create = @connection.directories.create(:key => "fog-smoke-test-create-destroy") assert_instance_of Fog::Storage::Google::Directory, directory_create assert directory_create.destroy end def test_public_url public_url = @directory.public_url assert_match(/storage\.googleapis\.com/, public_url) assert_match(/fog-smoke-test/, public_url) end def test_public skip end def test_files skip end def test_acl skip end end fog-google-0.5.3/test/integration/storage/test_files.rb0000644000004100000410000000636713145731036023247 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestFiles < FogIntegrationTest begin client_email = Fog.credentials[:google_client_email] @@connection = Fog::Storage::Google.new @@connection.put_bucket("fog-smoke-test", "acl" => [{ :entity => "user-" + client_email, :role => "OWNER" }]) @@connection.put_bucket_acl("fog-smoke-test", :entity => "allUsers", :role => "READER") rescue StandardError => e puts e puts e.backtrace end begin @directory = @@connection.directories.get("fog-smoke-test") @@connection.put_object("fog-smoke-test", "fog-testfile", "THISISATESTFILE") @file = @directory.files.get("fog-testfile") rescue StandardError => e puts e puts e.backtrace end Minitest.after_run do begin @connection = Fog::Storage::Google.new @connection.delete_object("fog-smoke-test", "fog-testfile") @connection.delete_bucket("fog-smoke-test") rescue StandardError => e puts e end end def setup @connection = @@connection end def test_all_files skip end def test_each_files skip end def test_get get_file = @directory.files.get("fog-testfile") assert_instance_of Fog::Storage::Google::File, get_file assert_equal "THISISATESTFILE", get_file.body end def test_get_https_url https_url = @directory.files.get_https_url("fog-testfile", (Time.now + 1.minute).to_i) assert_match(/https/, https_url) assert_match(/fog-smoke-test/, https_url) assert_match(/fog-testfile/, https_url) end def test_head assert_instance_of Fog::Storage::Google::File, @directory.files.head("fog-testfile") end def test_new new_file = @directory.files.new(:key => "fog-testfile-new", :body => "TESTFILENEW") assert_instance_of Fog::Storage::Google::File, new_file end def test_acl skip end def test_body assert_equal "THISISATESTFILE", @file.body end def test_set_body new_body = "FILEBODYCHANGED" @file.body = new_body assert_equal new_body, @file.body @file.save file_get = @directory.files.get("fog-testfile") assert_instance_of Fog::Storage::Google::File, file_get assert_equal new_body, file_get.body @file.body = "THISISATESTFILE" @file.save end def test_copy copied_file = @file.copy("fog-smoke-test", "fog-testfile-copy") assert_instance_of Fog::Storage::Google::File, copied_file assert copied_file.destroy end def test_create_destroy testfile = @directory.files.create(:key => "fog-testfile-create-destroy") assert_instance_of Fog::Storage::Google::File, testfile assert testfile.destroy end def test_metadata skip end def test_set_metadata skip end def test_set_owner skip end def test_set_public skip end def test_public_url assert_nil @file.public_url # Setting an ACL still fails, but here's some tests that should work when it does. # @file.acl.push({ "entity" => "allUsers", "role" => "READER" }) # public_url = @file.public_url # assert_match /https/, public_url # assert_match /storage\.googleapis\.com/, public_url # assert_match /fog-smoke-test/, public_url # assert_match /fog-testfile/, public_url end def test_url skip end end fog-google-0.5.3/test/integration/compute/0000755000004100000410000000000013145731036020555 5ustar www-datawww-datafog-google-0.5.3/test/integration/compute/test_servers.rb0000644000004100000410000000176513145731036023643 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/servers_factory" class TestServers < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].servers @factory = ServersFactory.new(namespaced_name) end def test_bootstrap_ssh_destroy resource_name = @factory.resource_name instance = @subject.bootstrap(:name => resource_name) assert instance.ready? instance.wait_for { sshable? } assert_match(/Linux/, instance.ssh("uname").first.stdout) assert_equal instance.destroy.operation_type, "delete" Fog.wait_for { !@subject.all.map(&:identity).include? instance.identity } # XXX clean up after bootstrap's automatic creation of disks # This should be removed when # https://github.com/fog/fog-google/issues/17 # is solved disk = Fog::Compute[:google].disks.get(resource_name) disk.destroy Fog.wait_for { !Fog::Compute[:google].disks.all.map(&:identity).include? disk.identity } end end fog-google-0.5.3/test/integration/compute/test_target_http_proxies.rb0000644000004100000410000000047613145731036026246 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/target_http_proxies_factory" class TestTargetHttpProxies < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].target_http_proxies @factory = TargetHttpProxiesFactory.new(namespaced_name) end end fog-google-0.5.3/test/integration/compute/test_compute_networks_collection.rb0000644000004100000410000000515213145731036027767 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "securerandom" class TestComputeNetworksCollection < FogIntegrationTest DEFAULT_REGION = "us-central1".freeze DEFAULT_ZONE = "us-central1-b".freeze RESOURCE_PREFIX = "fog-test-networkscol".freeze # Ensure we clean up any created resources Minitest.after_run do client = Fog::Compute::Google.new client.networks.each { |a| a.destroy if a.name.start_with?(RESOURCE_PREFIX) } client.servers.each { |s| s.destroy if s.name.start_with?(RESOURCE_PREFIX) } end def test_network_workflow client = Fog::Compute::Google.new my_network_name = new_resource_name # An address can be created by specifying a name and a region my_network = client.networks.create( :name => my_network_name, :ipv4_range => "10.240.#{rand(255)}.0/24" ) assert_equal(my_network_name, my_network.name, "My network should have the provided name") # It should also be visible when listing addresses assert_includes(client.networks.all.map(&:name), my_network_name) # Be aware that although the address resource is created, it might not yet # have an ip address. You can poll until the address has been assigned. my_network.wait_for { !my_network.ipv4_range.nil? } assert_match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,2}/, my_network.ipv4_range, "My address's address should have a valid ipv4 address") # Now that we have an address, we can create a server using the static ip my_server = client.servers.create( :name => new_resource_name, :machine_type => "f1-micro", :zone_name => DEFAULT_ZONE, :disks => [ :boot => true, :autoDelete => true, :initializeParams => { :sourceImage => "projects/debian-cloud/global/images/family/debian-8" } ], :network => my_network ) my_server.wait_for { provisioning? } # We need to verify that the network has been correctly assigned assert_equal( my_network.self_link, my_server.network_interfaces[0]["network"], "My created server should have the network specified as the network" ) # Access config needs to be correctly populated assert_equal( "ONE_TO_ONE_NAT", my_server.network_interfaces[0]["accessConfigs"][0]["type"], "Access config type matches the correct default" ) assert_equal( "External NAT", my_server.network_interfaces[0]["accessConfigs"][0]["name"], "Access config name matches the correct default" ) end def new_resource_name "#{RESOURCE_PREFIX}-#{SecureRandom.uuid}" end end fog-google-0.5.3/test/integration/compute/test_disk_types.rb0000644000004100000410000000271213145731036024321 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestDiskTypes < FogIntegrationTest NAMES = %w(local-ssd pd-ssd pd-standard) ZONES = %w(https://www.googleapis.com/compute/v1/projects/graphite-fog/zones/us-central1-a https://www.googleapis.com/compute/v1/projects/graphite-fog/zones/us-central1-b https://www.googleapis.com/compute/v1/projects/graphite-fog/zones/us-central1-c https://www.googleapis.com/compute/v1/projects/graphite-fog/zones/us-central1-f https://www.googleapis.com/compute/v1/projects/graphite-fog/zones/europe-west1-b https://www.googleapis.com/compute/v1/projects/graphite-fog/zones/europe-west1-c https://www.googleapis.com/compute/v1/projects/graphite-fog/zones/europe-west1-d https://www.googleapis.com/compute/v1/projects/graphite-fog/zones/asia-east1-a https://www.googleapis.com/compute/v1/projects/graphite-fog/zones/asia-east1-b https://www.googleapis.com/compute/v1/projects/graphite-fog/zones/asia-east1-c) def setup @subject = Fog::Compute[:google].disk_types end def test_all assert_equal (NAMES.size * ZONES.size), @subject.all.size end def test_get NAMES.each do |name| ZONES.each do |zone| refute_nil @subject.get(name, zone) end end end def test_bad_get assert_nil @subject.get("bad-name") end def test_enumerable assert_respond_to @subject, :each end end fog-google-0.5.3/test/integration/compute/requests/0000755000004100000410000000000013145731036022430 5ustar www-datawww-datafog-google-0.5.3/test/integration/compute/requests/test_compute_address_requests.rb0000644000004100000410000000555213145731036031137 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "helpers/client_helper" require "securerandom" class TestComputeAddressRequests < FogIntegrationTest DEFAULT_REGION = "us-central1".freeze ADDRESS_RESOURCE_PREFIX = "fog-test-address".freeze include ClientHelper # Ensure we clean up any created resources Minitest.after_run do client = Fog::Compute::Google.new addresses = client.list_addresses(DEFAULT_REGION)[:body]["items"] unless addresses.nil? addresses. map { |a| a["name"] }. select { |a| a.start_with?(ADDRESS_RESOURCE_PREFIX) }. each { |a| client.delete_address(a, DEFAULT_REGION) } end end attr_reader :client def setup @client = Fog::Compute::Google.new end def new_address_name "#{ADDRESS_RESOURCE_PREFIX}-#{SecureRandom.uuid}" end def some_address_name # created lazily to speed tests up @some_address ||= new_address_name.tap do |a| result = @client.insert_address(a, DEFAULT_REGION) Fog.wait_for { operation_finished?(result) } end end def test_insert_address result = wait_until_complete { @client.insert_address(new_address_name, DEFAULT_REGION) } assert_equal(200, result.status, "request should be successful") assert_equal(nil, result[:body]["error"], "result should contain no errors") end def test_get_address result = @client.get_address(some_address_name, DEFAULT_REGION) assert_equal(200, result.status, "request should be successful") assert_includes(result[:body].keys, "name", "resulting body should contain expected keys") end def test_list_address # Let's create at least one address so there's something to view wait_until_complete { @client.insert_address(new_address_name, DEFAULT_REGION) } result = @client.list_addresses(DEFAULT_REGION) assert_equal(200, result.status, "request should be successful") assert_includes(result[:body].keys, "items", "resulting body should contain expected keys") assert_operator(result[:body]["items"].size, :>, 0, "address count should be positive") end def test_delete_address # Create something to delete address_to_delete = new_address_name wait_until_complete { @client.insert_address(address_to_delete, DEFAULT_REGION) } result = wait_until_complete { @client.delete_address(address_to_delete, DEFAULT_REGION) } assert_equal(200, result.status, "request should be successful") assert_equal(nil, result[:body]["error"], "result should contain no errors") end def test_list_aggregated_addresses result = @client.list_aggregated_addresses assert_equal(200, result.status, "request should be successful") assert_includes(result[:body].keys, "items", "resulting body should contain expected keys") assert_includes(result[:body]["items"].keys, "global", "resulting body 'items' subset should contain global keyword") end end fog-google-0.5.3/test/integration/compute/test_forwarding_rules.rb0000644000004100000410000000046413145731036025521 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/forwarding_rules_factory" class TestForwardingRules < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].forwarding_rules @factory = ForwardingRulesFactory.new(namespaced_name) end end fog-google-0.5.3/test/integration/compute/test_url_maps.rb0000644000004100000410000000042413145731036023763 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/url_maps_factory" class TestUrlMaps < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].url_maps @factory = UrlMapsFactory.new(namespaced_name) end end fog-google-0.5.3/test/integration/compute/test_target_pools.rb0000644000004100000410000000044413145731036024645 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/target_pools_factory" class TestTargetPools < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].target_pools @factory = TargetPoolsFactory.new(namespaced_name) end end fog-google-0.5.3/test/integration/compute/test_disks.rb0000644000004100000410000000041213145731036023253 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/disks_factory" class TestDisks < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].disks @factory = DisksFactory.new(namespaced_name) end end fog-google-0.5.3/test/integration/compute/test_regions.rb0000644000004100000410000000116013145731036023605 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestRegions < FogIntegrationTest NAMES = %w(asia-east1 asia-northeast1 europe-west1 us-central1 us-east1 us-west1).freeze def setup @subject = Fog::Compute[:google].regions end def test_all assert_equal NAMES.size, @subject.all.size end def test_get NAMES.each do |name| refute_nil @subject.get(name) end end def test_up NAMES.each do |name| assert @subject.get(name).up? end end def test_bad_get assert_nil @subject.get("bad-name") end def test_enumerable assert_respond_to @subject, :each end end fog-google-0.5.3/test/integration/compute/test_target_instances.rb0000644000004100000410000000046413145731036025502 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/target_instances_factory" class TestTargetInstances < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].target_instances @factory = TargetInstancesFactory.new(namespaced_name) end end fog-google-0.5.3/test/integration/compute/test_http_health_checks.rb0000644000004100000410000000047213145731036025770 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/http_health_checks_factory" class TestHttpHealthChecks < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].http_health_checks @factory = HttpHealthChecksFactory.new(namespaced_name) end end fog-google-0.5.3/test/integration/compute/test_backend_services.rb0000644000004100000410000000046413145731036025437 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/backend_services_factory" class TestBackendServices < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].backend_services @factory = BackendServicesFactory.new(namespaced_name) end end fog-google-0.5.3/test/integration/compute/test_images.rb0000644000004100000410000000041613145731036023407 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/images_factory" class TestImages < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].images @factory = ImagesFactory.new(namespaced_name) end end fog-google-0.5.3/test/integration/compute/test_global_forwarding_rules.rb0000644000004100000410000000051613145731036027037 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/global_forwarding_rules_factory" class TestGlobalForwardingRules < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].global_forwarding_rules @factory = GlobalForwardingRulesFactory.new(namespaced_name) end end fog-google-0.5.3/test/integration/compute/test_compute_addresses_collection.rb0000644000004100000410000000513613145731036030072 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "securerandom" class TestComputeAddressesCollection < FogIntegrationTest DEFAULT_REGION = "us-central1".freeze DEFAULT_ZONE = "us-central1-b".freeze RESOURCE_PREFIX = "fog-test-addresscol".freeze # Ensure we clean up any created resources Minitest.after_run do client = Fog::Compute::Google.new client.addresses.each { |a| a.destroy if a.name.start_with?(RESOURCE_PREFIX) } client.servers.each { |s| s.destroy if s.name.start_with?(RESOURCE_PREFIX) } end def test_address_workflow client = Fog::Compute::Google.new my_address_name = new_resource_name # An address can be created by specifying a name and a region my_address = client.addresses.create( :name => my_address_name, :region => DEFAULT_REGION ) # TODO: Shouldn't this be returning an operation object that we have to explicitly wait for? assert_equal(my_address_name, my_address.name, "My address should have the provided name") assert_equal("RESERVED", my_address.status, "My address should not be in use") # It should also be visible when listing addresses assert_includes(client.addresses.all.map(&:name), my_address_name) # Be aware that although the address resource is created, it might not yet # have an ip address. You can poll until the address has been assigned. my_address.wait_for { !my_address.address.nil? } assert_match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/, my_address.address, "My address's address should have a valid ipv4 address") # Now that we have an address, we can create a server using the static ip my_server = client.servers.create( :name => new_resource_name, :machine_type => "f1-micro", :zone_name => DEFAULT_ZONE, :disks => [ :boot => true, :autoDelete => true, :initializeParams => { :sourceImage => "projects/debian-cloud/global/images/family/debian-8" } ], :external_ip => my_address.address ) my_server.wait_for { provisioning? } # And verify that it's correctly assigned assert_equal( my_address.address, my_server.network_interfaces[0]["accessConfigs"][0]["natIP"], "My created server should have the same ip as my address" ) # If we look up the address again by name, we should see that it is now # in use assert_equal( "IN_USE", client.addresses.get(my_address_name, DEFAULT_REGION).status, "Address should now be in use" ) end def new_resource_name "#{RESOURCE_PREFIX}-#{SecureRandom.uuid}" end end fog-google-0.5.3/test/integration/pubsub/0000755000004100000410000000000013145731036020401 5ustar www-datawww-datafog-google-0.5.3/test/integration/pubsub/test_pubsub_requests.rb0000644000004100000410000001350413145731036025223 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "securerandom" require "base64" class TestPubsubRequests < FogIntegrationTest def setup @client = Fog::Google::Pubsub.new # Ensure any resources we create with test prefixes are removed Minitest.after_run do delete_test_resources end end def delete_test_resources topics = @client.list_topics[:body]["topics"] unless topics.nil? topics. map { |t| t["name"] }. select { |t| t.start_with?(topic_resource_prefix) }. each { |t| @client.delete_topic(t) } end subscriptions = @client.list_subscriptions[:body]["subscriptions"] unless subscriptions.nil? subscriptions. map { |s| s["name"] }. select { |s| s.start_with?(subscription_resource_prefix) }. each { |s| @client.delete_subscription(s) } end end def topic_resource_prefix "projects/#{@client.project}/topics/fog-integration-test" end def subscription_resource_prefix "projects/#{@client.project}/subscriptions/fog-integration-test" end def new_topic_name "#{topic_resource_prefix}-#{SecureRandom.uuid}" end def new_subscription_name "#{subscription_resource_prefix}-#{SecureRandom.uuid}" end def some_topic_name # create lazily to speed tests up @some_topic ||= new_topic_name.tap do |t| @client.create_topic(t) end @some_topic end def some_subscription_name # create lazily to speed tests up @some_subscription ||= new_subscription_name.tap do |s| @client.create_subscription(s, some_topic_name) end @some_subscription end def test_create_topic result = @client.create_topic(new_topic_name) assert_equal(200, result.status, "request should be successful") assert_includes(result[:body].keys, "name", "resulting body should contain expected keys") end def test_get_topic result = @client.get_topic(some_topic_name) assert_equal(200, result.status, "request should be successful") assert_includes(result[:body].keys, "name", "resulting body should contain expected keys") end def test_list_topics # Force a topic to be created just so we have at least 1 to list @client.create_topic(new_topic_name) result = @client.list_topics assert_equal(200, result.status, "request should be successful") assert_includes(result[:body].keys, "topics", "resulting body should contain expected keys") assert_operator(result[:body]["topics"].size, :>, 0, "topic count should be positive") end def test_delete_topic topic_to_delete = new_topic_name @client.create_topic(topic_to_delete) result = @client.delete_topic(topic_to_delete) assert_equal(200, result.status, "request should be successful") end def test_publish_topic result = @client.publish_topic(some_topic_name, [:data => Base64.strict_encode64("some message")]) assert_equal(200, result.status, "request should be successful") assert_includes(result[:body].keys, "messageIds", "resulting body should contain expected keys") end def test_create_subscription push_config = {} ack_deadline_seconds = 18 result = @client.create_subscription(new_subscription_name, some_topic_name, push_config, ack_deadline_seconds) assert_equal(200, result.status, "request should be successful") assert((%w{name topic pushConfig ackDeadlineSeconds} - result[:body].keys).empty?, "resulting body should contain expected keys") assert_equal(18, result[:body]["ackDeadlineSeconds"], "ackDeadlineSeconds should be 18") end def test_get_subscription result = @client.get_subscription(some_subscription_name) assert_equal(200, result.status, "request should be successful") assert(%w{name topic pushConfig ackDeadlineSeconds} - result[:body].keys, "resulting body should contain expected keys") end def test_list_subscriptions # Force a subscription to be created just so we have at least 1 to list @client.create_subscription(new_subscription_name, some_topic_name) result = @client.list_subscriptions assert_equal(200, result.status, "request should be successful") assert_includes(result[:body].keys, "subscriptions", "resulting body should contain expected keys") assert_operator(result[:body]["subscriptions"].size, :>, 0, "subscription count should be positive") end def test_delete_subscription subscription_to_delete = new_subscription_name @client.create_subscription(subscription_to_delete, some_topic_name) result = @client.delete_subscription(subscription_to_delete) assert_equal(200, result.status, "request should be successful") end def test_pull_subscription subscription = new_subscription_name @client.create_subscription(subscription, some_topic_name) @client.publish_topic(some_topic_name, [:data => Base64.strict_encode64("some message")]) result = @client.pull_subscription(subscription) assert_equal(200, result.status, "request should be successful") assert_includes(result[:body].keys, "receivedMessages", "resulting body should contain expected keys") assert_equal(1, result[:body]["receivedMessages"].size, "we should have received a message") assert_equal("some message", Base64.strict_decode64(result[:body]["receivedMessages"][0]["message"]["data"]), "received message should be the same as what we sent") end def test_acknowledge_subscription subscription = new_subscription_name @client.create_subscription(subscription, some_topic_name) @client.publish_topic(some_topic_name, [:data => Base64.strict_encode64("some message")]) pull_result = @client.pull_subscription(subscription) result = @client.acknowledge_subscription(subscription, pull_result[:body]["receivedMessages"][0]["ackId"]) assert_equal(200, result.status, "request should be successful") end end fog-google-0.5.3/test/integration/test_authentication.rb0000644000004100000410000000544613145731036023515 0ustar www-datawww-datarequire "helpers/integration_test_helper" # TODO: this is a port over from legacy tests. It shouldn't be scoped under Google, but under Google::Shared. class TestAuthentication < FogIntegrationTest def setup @google_key_location = Fog.credentials[:google_key_location] @google_key_string = File.open(File.expand_path(@google_key_location), "rb", &:read) @google_json_key_location = Fog.credentials[:google_json_key_location] @google_json_key_string = File.open(File.expand_path(@google_json_key_location), "rb", &:read) end def test_authenticates_with_p12_key_location c = Fog::Compute::Google.new(:google_key_location => @google_key_location, :google_key_string => nil, :google_json_key_location => nil, :google_json_key_string => nil) assert_kind_of(Fog::Compute::Google::Real, c) end def test_authenticates_with_p12_key_string c = Fog::Compute::Google.new(:google_key_location => nil, :google_key_string => @google_key_string, :google_json_key_location => nil, :google_json_key_string => nil) assert_kind_of(Fog::Compute::Google::Real, c) end def test_authenticates_with_json_key_location c = Fog::Compute::Google.new(:google_key_location => nil, :google_key_string => nil, :google_json_key_location => @google_json_key_location, :google_json_key_string => nil) assert_kind_of(Fog::Compute::Google::Real, c) end def test_authenticates_with_json_key_string c = Fog::Compute::Google.new(:google_key_location => nil, :google_key_string => nil, :google_json_key_location => nil, :google_json_key_string => @google_json_key_string) assert_kind_of(Fog::Compute::Google::Real, c) end def test_raises_argument_error_when_google_project_is_missing assert_raises(ArgumentError) { Fog::Compute::Google.new(:google_project => nil) } end def test_raises_argument_error_when_google_client_email_is_missing assert_raises(ArgumentError) do Fog::Compute::Google.new(:google_client_email => nil, :google_json_key_location => nil) end # JSON key overrides google_client_email end def test_raises_argument_error_when_google_keys_are_given assert_raises(ArgumentError) do Fog::Compute::Google.new(:google_key_location => nil, :google_key_string => nil, :google_json_key_location => nil, :google_json_key_string => nil) end end end fog-google-0.5.3/test/unit/0000755000004100000410000000000013145731036015535 5ustar www-datawww-datafog-google-0.5.3/test/unit/compute/0000755000004100000410000000000013145731036017211 5ustar www-datawww-datafog-google-0.5.3/test/unit/compute/test_server.rb0000644000004100000410000000136513145731036022110 0ustar www-datawww-datarequire "helpers/test_helper" require File.expand_path("../../../../lib/fog/compute/google/models/server", __FILE__) class UnitTestServer < MiniTest::Test def test_metadata_uses_deprecated_sshKeys_if_exists server = Fog::Compute::Google::Server.new(:metadata => { "sshKeys" => "existing_user:existing_key" }) server.add_ssh_key("my_username", "my_key") assert_match(/my_username/, server.metadata["sshKeys"]) assert_match(/my_key/, server.metadata["sshKeys"]) end def test_add_ssh_key_uses_ssh_keys_by_default server = Fog::Compute::Google::Server.new server.add_ssh_key("my_username", "my_key") assert_match(/my_username/, server.metadata["ssh-keys"]) assert_match(/my_key/, server.metadata["ssh-keys"]) end end fog-google-0.5.3/test/helpers/0000755000004100000410000000000013145731036016220 5ustar www-datawww-datafog-google-0.5.3/test/helpers/test_collection.rb0000644000004100000410000000224113145731036021736 0ustar www-datawww-datamodule TestCollection # Anything that includes TestCollection must, during setup, assign @subject and @factory, where # @subject is the collection under test, (e.g. Fog::Compute[:google].servers) # @factory is a CollectionFactory def test_lifecycle one = @subject.new(@factory.params) one.save two = @subject.create(@factory.params) # XXX HACK compares identities # should be replaced with simple includes? when `==` is properly implemented in fog-core; see fog/fog-core#148 assert_includes @subject.all.map(&:identity), one.identity assert_includes @subject.all.map(&:identity), two.identity assert_equal one.identity, @subject.get(one.identity).identity assert_equal two.identity, @subject.get(two.identity).identity one.destroy two.destroy Fog.wait_for { !@subject.all.map(&:identity).include? one.identity } Fog.wait_for { !@subject.all.map(&:identity).include? two.identity } end def test_get_returns_nil_if_resource_does_not_exist assert_nil @subject.get("fog-test-fake-identity") end def test_enumerable assert_respond_to @subject, :each end def teardown @factory.cleanup end end fog-google-0.5.3/test/helpers/integration_test_helper.rb0000644000004100000410000000136313145731036023471 0ustar www-datawww-datarequire "helpers/test_helper" require "helpers/test_collection" # Use :test credentials in ~/.fog for live integration testing # XXX not sure if this will work on Travis CI or not Fog.credential = :test # Helpers TEST_ZONE = "us-central1-f" TEST_REGION = "us-central1" TEST_SIZE_GB = 10 TEST_MACHINE_TYPE = "n1-standard-1" # XXX This depends on a public image in gs://fog-test-bucket; there may be a better way to do this # The image was created like so: https://cloud.google.com/compute/docs/images#export_an_image_to_google_cloud_storage TEST_RAW_DISK_SOURCE = "http://storage.googleapis.com/fog-test-bucket/fog-test-raw-disk-source.image.tar.gz" class FogIntegrationTest < MiniTest::Test def namespaced_name "#{self.class}_#{name}" end end fog-google-0.5.3/test/helpers/test_helper.rb0000644000004100000410000000067713145731036021075 0ustar www-datawww-data# The next line was added to squelch a warning message in Ruby 1.9. # It ensures we're using the gem, not the built-in Minitest # See https://github.com/seattlerb/minitest/#install gem "minitest" require "minitest/autorun" if ENV["COVERAGE"] require "coveralls" require "simplecov" SimpleCov.start do add_filter "/test/" end end require File.join(File.dirname(__FILE__), "../../lib/fog/google") Coveralls.wear! if ENV["COVERAGE"] fog-google-0.5.3/test/helpers/client_helper.rb0000644000004100000410000000245113145731036021364 0ustar www-datawww-data## # Helper mixin for tests (especially compute-based ones). Provide access to the # client in use via the #client method to use. module ClientHelper # Check to see if an operation is finished. # # @param op [Excon::Response] the operation object returned from an api call # @return [Boolean] true if the operation is no longer executing, false # otherwise def operation_finished?(op) # TODO: support both zone and region operations region = op[:body]["region"] name = op[:body]["name"] result = client.get_region_operation(region, name) !%w(PENDING RUNNING).include?(result[:body]["status"]) end # Pause execution until an operation returned from a passed block is finished. # # @example Pause until server is provisioned # @result = wait_until_complete { client.insert_server(name, zone, opts) } # @yieldreturn [Excon::Response] the resulting operation object from a block. # @return [Excon::Response] the final completed operation object def wait_until_complete result = yield return result unless result[:body]["kind"] == "compute#operation" # TODO: support both zone and region operations region = result[:body]["region"] Fog.wait_for { operation_finished?(result) } client.get_region_operation(region, result[:body]["name"]) end end fog-google-0.5.3/.gitignore0000644000004100000410000000022513145731036015566 0ustar www-datawww-data/.bundle/ /.yardoc /Gemfile.lock /_yardoc/ /coverage/ /doc/ /pkg/ /spec/reports/ /tmp/ *.bundle *.so *.o *.a mkmf.log .ruby-version .idea/ .DS_Store fog-google-0.5.3/tasks/0000755000004100000410000000000013145731036014724 5ustar www-datawww-datafog-google-0.5.3/tasks/lint.rake0000644000004100000410000000007213145731036016535 0ustar www-datawww-datarequire "rubocop/rake_task" RuboCop::RakeTask.new(:lint) fog-google-0.5.3/tasks/console.rake0000644000004100000410000000067213145731036017237 0ustar www-datawww-data# From http://erniemiller.org/2014/02/05/7-lines-every-gems-rakefile-should-have/ # with some modification. desc "Project IRB console" task :console do require "bundler" Bundler.require(:default, :development) # Reload helper to avoid resetting the environment when debugging def reload! files = $LOADED_FEATURES.select { |feat| feat =~ /\/fog-google\// } files.each { |file| load file } end ARGV.clear Pry.start end fog-google-0.5.3/tasks/bundler.rake0000644000004100000410000000015113145731036017220 0ustar www-datawww-data# This installs the tasks that help with gem creation and # publishing. Bundler::GemHelper.install_tasks fog-google-0.5.3/tasks/test.rake0000644000004100000410000000043613145731036016552 0ustar www-datawww-datarequire "rake/testtask" Rake::TestTask.new do |t| t.libs << "test" t.pattern = File.join("test", "**", "test_*.rb") t.warning = false end namespace :test do mock = ENV["FOG_MOCK"] || "true" task :travis do sh("export FOG_MOCK=#{mock} && bundle exec shindont") end end fog-google-0.5.3/CONTRIBUTING.md0000644000004100000410000001354613145731036016041 0ustar www-datawww-data# Getting Involved New contributors are always welcome, and when in doubt please ask questions! We strive to be an open and welcoming community. Please be nice to one another. I recommend heading over to fog's [CONTRIBUTING](https://github.com/fog/fog/blob/master/CONTRIBUTING.md) and having a look around as well. It has information and context about the state of the `fog` project as a whole. ### Coding * Pick a task: * Offer feedback on open [pull requests](https://github.com/fog/fog-google/pulls). * Review open [issues](https://github.com/fog/fog-google/issues) for things to help on. * [Create an issue](https://github.com/fog/fog-google/issues/new) to start a discussion on additions or features. * Fork the project, add your changes and tests to cover them in a topic branch. * [Fork](https://github.com/fog/fog-google/fork) * Create your feature branch (`git checkout -b my-new-feature`) * Commit your changes (`git commit -am 'Add some feature'`) * Push to the branch (`git push origin my-new-feature`) * Create a new pull request * Commit your changes and rebase against `fog/fog-google` to ensure everything is up to date. * [Submit a pull request](https://github.com/fog/fog-google/compare/) ### Non-Coding * Offer feedback on open [issues](https://github.com/fog/fog-google/issues). * Organize or volunteer at events. ## Contributing Code This document is very much a work in progress. Sorry about that. It's worth noting that, if you're looking through the code, and you'd like to know the history of a line, you may not find it in the history of this repository, since most of the code was extracted from [fog/fog](https://github.com/fog/fog). So, you can look at the history from commit [fog/fog#c596e](https://github.com/fog/fog/tree/c596e710952aa9c90713da3fbfb3027db0608413) backward for more information. ### Development environment If you're going to be doing any kind of modifications, I highly recommend using [rbenv](https://github.com/sstephenson/rbenv), [ruby-build](https://github.com/sstephenson/ruby-build), (don't forget the [dependencies](https://github.com/sstephenson/ruby-build/wiki#suggested-build-environment)!) and [bundler](http://bundler.io/). Once you've got that all installed, run ```shell $ bundle install ``` to install the required gems. You might have to [fight a bit](http://www.nokogiri.org/tutorials/installing_nokogiri.html) to get Nokogiri installed. Then, you should be ready to go! If you'd like to drop into an interactive shell, configured with your `:test` credential, use ```shell rake console ``` ### Testing This module is tested with [Minitest](https://github.com/seattlerb/minitest). Right now, the only tests that exist are live integration tests, found in `test/integration/`. After completing the installation in the README, (including setting up your credentials and keys,) make sure you have a `:test` credential in `~/.fog`, something like: ``` test: google_project: my-project google_client_email: xxxxxxxxxxxxx-xxxxxxxxxxxxx@developer.gserviceaccount.com google_key_location: /path/to/my-project-xxxxxxxxxxxxx.p12 google_json_key_location: /path/to/my-project-xxxxxxxxxxxxx.json ``` Note that you need both a `.p12` and a `.json` key file for all the tests to pass. Then you can run all the live tests: ```shell $ rake test ``` or just one: ```shell $ rake test TEST=test/integration/compute/test_servers.rb TESTOPTS="--name=TestServers#test_bootstrap_ssh_destroy" ``` #### The transition from `shindo` to Minitest Previously, [shindo](https://github.com/geemus/shindo) was the primary testing framework. We've started moving away from it, and to Minitest, but some artifacts remain. - The `test` directory contains the new Minitest tests, which currently only cover live integration testing for `compute`. - The `tests` directory contains the old `shindo` tests, which generally pass if mocking is turned on. No promises if mocking is off. - Travis CI runs the mocked `shindo` tests, though hopefully in the long run it will run the unit and integration `Minitest` tests. Currently, Google maintains its own Jenkins instance that runs the Minitest integraiton tests. Follow [#50](https://github.com/fog/fog-google/issues/50) for the status of the transition from `shindo` to Minitest. #### Some notes about the tests as they stand The live integration tests for resources, (servers, disks, etc.,) have a few components: - The `TestCollection` **mixin module** lives in `test/helpers/test_collection.rb` and contains the standard tests to run for all resources, (e.g. `test_lifecycle`). It also calls `cleanup` on the resource's factory during teardown, to make sure that resources are getting destroyed before the next test run. - The **factory**, (e.g. `ServersFactory`, in `test/integration/factories/servers_factory.rb`,) automates the creation of resources and/or supplies parameters for explicit creation of resources. For example, `ServersFactory` initializes a `DisksFactory` to supply disks in order to create servers, and implements the `params` method so that tests can create servers with unique names, correct zones and machine types, and automatically-created disks. `ServersFactory` inherits the `create` method from `CollectionFactory`, which allows tests to create servers on-demand. - The **main test**, (e.g. `TestServers`, in `test/integration/compute/test_servers.rb`,) is the test that actually runs. It mixes in the `TestCollection` module in order to run the tests in that module, it supplies the `setup` method in which it initializes a `ServersFactory`, and it includes any other tests specific to this collection, (e.g. `test_bootstrap_ssh_destroy`). If you want to create another resource, you should add live integration tests; all you need to do is create a factory in `test/integration/factories/my_resource_factory.rb` and a main test in `test/integration/compute/test_my_resource.rb` that mixes in `TestCollection`. fog-google-0.5.3/.ruby-gemset0000644000004100000410000000001313145731036016035 0ustar www-datawww-datafog-google fog-google-0.5.3/README.md0000644000004100000410000001100313145731036015051 0ustar www-datawww-data# Fog::Google [![Gem Version](https://badge.fury.io/rb/fog-google.svg)](http://badge.fury.io/rb/fog-google) [![Build Status](https://travis-ci.org/fog/fog-google.svg?branch=master)](https://travis-ci.org/fog/fog-google) [![Dependency Status](https://gemnasium.com/fog/fog-google.svg)](https://gemnasium.com/fog/fog-google) [![Coverage Status](https://img.shields.io/coveralls/fog/fog-google.svg)](https://coveralls.io/r/fog/fog-google) [![Code Climate](https://codeclimate.com/github/fog/fog-google.png)](https://codeclimate.com/github/fog/fog-google) [![Stories in Ready](https://badge.waffle.io/fog/fog-google.png?label=ready&title=Ready)](https://waffle.io/fog/fog-google) The main maintainers for the Google sections are @icco, @Temikus and @plribeiro3000. Please send pull requests to them. **As of v0.1.1, Google no longer supports Ruby versions less than 2.0.0.** **Currently, `fog-google` does not support versions of `google-api-client` >= 0.9 or <= 0.8.5.** ## Storage There are two ways to access [Google Cloud Storage](https://cloud.google.com/storage/). The old S3 API and the new JSON API. `Fog::Storage::Google` will automatically direct you to the appropriate API based on the credentials you provide it. * The [XML API](https://developers.google.com/storage/docs/xml-api-overview) is almost identical to S3. Use [Google's interoperability keys](https://cloud.google.com/storage/docs/migrating#keys) to access it. * The new [JSON API](https://developers.google.com/storage/docs/json_api/) is faster and uses auth similarly to the rest of the Google Cloud APIs using a [service account private key](https://developers.google.com/identity/protocols/OAuth2ServiceAccount). ## Compute Google Compute Engine is a Virtual Machine hosting service. Currently it is built on version [v1](https://developers.google.com/compute/docs/reference/v1/) of the GCE API. As of 2015-12-07, we believe Fog for Google Compute engine (`Fog::Compute::Google`) is feature complete. If you are using Fog to interact with GCE, please keep Fog up to date and [file issues](https://github.com/fog/fog-google/issues) for any anomalies you see or features you would like. ## SQL Fog implements [v1beta3](https://cloud.google.com/sql/docs/admin-api/v1beta3/) of the Google Cloud SQL Admin API. This is a currently deprecated API. Pull Requests for updates would be greatly appreciated. ## DNS Fog implements [v1](https://cloud.google.com/dns/api/v1/) of the Google Cloud DNS API. We are always looking for people to improve our code and test coverage, so please [file issues](https://github.com/fog/fog-google/issues) for any anomalies you see or features you would like. ## Monitoring Fog implements [v2beta2](https://cloud.google.com/monitoring/v2beta2/) of the Google Cloud Monitoring API. As of 2016-03-15, we believe Fog for Google Cloud Monitoring is feature complete. We are always looking for people to improve our code and test coverage, so please [file issues](https://github.com/fog/fog-google/issues) for any anomalies you see or features you would like. ## Pubsub Note: You **must** have a version of google-api-client > 0.8.5 to use the Pub/Sub API; previous versions will not work. Fog mostly implements [v1](https://cloud.google.com/pubsub/reference/rest/) of the Google Cloud Pub/Sub API; however some less common API methods are missing. Pull requests for additions would be greatly appreciated. ## Installation Add the following two lines to your application's `Gemfile`: ```ruby gem 'fog-google' gem 'google-api-client', '~> 0.8.6' ``` And then execute: ```shell $ bundle ``` Or install it yourself as: ```shell $ gem install fog-google ``` ## Setup #### Credentials Follow the [instructions to generate a private key](https://cloud.google.com/storage/docs/authentication#generating-a-private-key). A sample credentials file can be found in `.fog.example` in this directory: cat .fog.example >> ~/.fog # appends the sample configuration vim ~/.fog # edit file with yout config #### SSH-ing into instances If you want to be able to bootstrap SSH-able instances, (using `servers.bootstrap`,) be sure you have a key in `~/.ssh/id_rsa` and `~/.ssh/id_rsa.pub` ## Quickstart Once you've specified your credentials, you should be good to go! ``` $ bundle exec pry [1] pry(main)> require 'fog/google' => true [2] pry(main)> connection = Fog::Compute::Google.new [3] pry(main)> connection.servers => [