fog-google-1.9.1/0000755000004100000410000000000013451635472013611 5ustar www-datawww-datafog-google-1.9.1/.travis.yml0000644000004100000410000000037413451635472015726 0ustar www-datawww-datalanguage: ruby cache: bundler sudo: false dist: trusty matrix: fast_finish: true include: - rvm: 2.3 - rvm: 2.4 - rvm: 2.5 - rvm: jruby-9.1 - rvm: jruby-head allow_failures: - rvm: jruby-head notifications: email: false fog-google-1.9.1/fog-google.gemspec0000644000004100000410000000313713451635472017207 0ustar www-datawww-datalib = 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", "Artem Yakimenko"] spec.email = ["nat@natwelch.com", "temikus@google.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 Cloud 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" # Locked until https://github.com/fog/fog-google/issues/417 is resolved spec.add_dependency "fog-core", "<= 2.1.0" spec.add_dependency "fog-json", "~> 1.2" spec.add_dependency "fog-xml", "~> 0.1.0" # Hard Requirement as of 1.0 spec.add_dependency "google-api-client", "~> 0.23.0" # Debugger spec.add_development_dependency "pry" # Testing gems spec.add_development_dependency "retriable" spec.add_development_dependency "rake" spec.add_development_dependency "minitest" spec.add_development_dependency "minitest-reporters" spec.add_development_dependency "shindo" spec.add_development_dependency "vcr" spec.add_development_dependency "webmock" end fog-google-1.9.1/test/0000755000004100000410000000000013451635472014570 5ustar www-datawww-datafog-google-1.9.1/test/helpers/0000755000004100000410000000000013451635472016232 5ustar www-datawww-datafog-google-1.9.1/test/helpers/integration_test_helper.rb0000644000004100000410000001050413451635472023500 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 # Enable test debugging, providing additional information in some methods DEBUG = ENV['FOG_TEST_DEBUG'] || false # Helpers TEST_PROJECT = Fog.credentials[:google_project] TEST_ZONE = "us-central1-f".freeze TEST_REGION = "us-central1".freeze TEST_SIZE_GB = 10 TEST_MACHINE_TYPE = "n1-standard-1".freeze TEST_IMAGE = "debian-9-stretch-v20180611".freeze TEST_IMAGE_PROJECT = "debian-cloud".freeze TEST_IMAGE_FAMILY = "debian-9".freeze # 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".freeze TEST_SQL_TIER_FIRST = "D1".freeze TEST_SQL_REGION_FIRST = "us-central".freeze TEST_SQL_TIER_SECOND = "db-n1-standard-1".freeze TEST_SQL_REGION_SECOND = TEST_REGION # Test certificate/key for SSL Proxy tests, generated via: # $ openssl genrsa -out example.key 2048 # $ openssl req -new -key example.key -out example.csr # ... # Common Name (eg, fully qualified host name) []:example.com # Email Address []:admin@example.com # ... # $ openssl x509 -req -in example.csr -signkey example.key -out example.crt TEST_PEM_CERTIFICATE = < "foo", :machine_type => "bar", :disks => ["baz"], :zone => "foo", :public_key_path => key ) assert_equal(server.public_key, key, "Fog::Compute::Google::Server loads public_key properly") end end end fog-google-1.9.1/test/unit/compute/test_common_collections.rb0000644000004100000410000000255213451635472024501 0ustar www-datawww-datarequire "helpers/test_helper" class UnitTestCollections < MiniTest::Test def setup Fog.mock! @client = Fog::Compute.new(provider: "google", google_project: "foo") # Exceptions that do not pass test_common_methods: # # Projects do not have a "list" method in compute API, so 'all' is not implemented @common_method_exceptions = [Fog::Compute::Google::Projects] # Enumerate all descendants of Fog::Collection descendants = ObjectSpace.each_object(Fog::Collection.singleton_class).to_a @collections = descendants.select { |d| d.name.match(/Fog::Compute::Google/) } end def teardown Fog.unmock! end # This tests whether Fog::Compute::Google collections have common lifecycle methods def test_common_methods subjects = @collections - @common_method_exceptions subjects.each do |klass| obj = klass.new assert obj.respond_to?(:all), "#{klass} should have an .all method" assert obj.respond_to?(:get), "#{klass} should have a .get method" assert obj.respond_to?(:each), "#{klass} should behave like Enumerable" end end def test_collection_get_arguments @collections.each do |klass| obj = klass.new assert_operator(obj.method(:get).arity, :<=, 1, "#{klass} should have at most 1 required parameter in get()") end end end fog-google-1.9.1/test/unit/compute/test_common_models.rb0000644000004100000410000000226413451635472023446 0ustar www-datawww-datarequire "helpers/test_helper" class UnitTestModels < MiniTest::Test def setup Fog.mock! @client = Fog::Compute.new(provider: "google", google_project: "foo") # Do not test models that do not have a create method in API exceptions = [Fog::Compute::Google::MachineType, Fog::Compute::Google::Region, Fog::Compute::Google::DiskType, Fog::Compute::Google::Operation, Fog::Compute::Google::Zone, Fog::Compute::Google::Snapshot, Fog::Compute::Google::Project] # Enumerate all descendants of Fog::Model descendants = ObjectSpace.each_object(Fog::Model.singleton_class).to_a @models = descendants.select { |d| d.name.match(/Fog::Compute::Google/) } - exceptions end def teardown Fog.unmock! end def test_common_methods # This tests whether Fog::Compute::Google models have common lifecycle methods @models.each do |klass| obj = klass.new assert obj.respond_to?(:save), "#{klass} should have a .save method" assert obj.respond_to?(:destroy), "#{klass} should have a .destroy method" end end end fog-google-1.9.1/test/unit/monitoring/0000755000004100000410000000000013451635472017734 5ustar www-datawww-datafog-google-1.9.1/test/unit/monitoring/test_comon_collections.rb0000644000004100000410000000261313451635472025033 0ustar www-datawww-datarequire "helpers/test_helper" class UnitTestMonitoringCollections < MiniTest::Test def setup Fog.mock! @client = Fog::Monitoring.new(provider: "google", google_project: "foo") # Exceptions that do not pass test_common_methods: # # TimeSeries API has no 'get' method @common_method_exceptions = [Fog::Google::Monitoring::TimeseriesCollection] # Enumerate all descendants of Fog::Collection descendants = ObjectSpace.each_object(Fog::Collection.singleton_class).to_a @collections = descendants.select { |d| d.name.match(/Fog::Google::Monitoring/) } end def teardown Fog.unmock! end # This tests whether Fog::Compute::Google collections have common lifecycle methods def test_common_methods subjects = @collections - @common_method_exceptions subjects.each do |klass| obj = klass.new assert obj.respond_to?(:all), "#{klass} should have an .all method" assert obj.respond_to?(:get), "#{klass} should have a .get method" assert obj.respond_to?(:each), "#{klass} should behave like Enumerable" end end def test_collection_get_arguments @collections.each do |klass| obj = klass.new if obj.respond_to?(:get) assert_operator(obj.method(:get).arity, :<=, 1, "#{klass} should have at most 1 required parameter in get()") end end end end fog-google-1.9.1/test/unit/storage/0000755000004100000410000000000013451635472017213 5ustar www-datawww-datafog-google-1.9.1/test/unit/storage/test_common_xml_collections.rb0000644000004100000410000000230713451635472025347 0ustar www-datawww-datarequire "helpers/test_helper" class UnitTestStorageXMLCollections < MiniTest::Test def setup Fog.mock! @client = Fog::Storage.new(provider: "google", google_storage_access_key_id: "", google_storage_secret_access_key: "") # Enumerate all descendants of Fog::Collection descendants = ObjectSpace.each_object(Fog::Collection.singleton_class) @collections = descendants.select do |d| d.name.match(/Fog::Storage::GoogleXML/) end end def teardown Fog.unmock! end def test_common_methods # This tests whether Fog::Compute::Google collections have common lifecycle methods @collections.each do |klass| obj = klass.new assert obj.respond_to?(:all), "#{klass} should have an .all method" assert obj.respond_to?(:get), "#{klass} should have a .get method" assert obj.respond_to?(:each), "#{klass} should behave like Enumerable" end end def test_collection_get_arguments @collections.each do |klass| obj = klass.new assert_operator(obj.method(:get).arity, :<=, 1, "#{klass} should have at most 1 required parameter in get()") end end end fog-google-1.9.1/test/unit/storage/test_xml_requests.rb0000644000004100000410000000407713451635472023342 0ustar www-datawww-datarequire "helpers/test_helper" class UnitTestXMLRequests < MiniTest::Test def setup Fog.mock! @client = Fog::Storage.new(provider: "google", google_storage_access_key_id: "", google_storage_secret_access_key: "") end def teardown Fog.unmock! end def test_get_http_url url = @client.get_object_http_url("bucket", "just some file.json", Time.now + 2 * 60) assert_match(/^http:\/\//, url, "URL starts with HTTP") end def test_get_https_url url = @client.get_object_https_url("bucket", "just some file.json", Time.now + 2 * 60) assert_match(/^https:\/\//, url, "URL starts with HTTPS") end def test_get_url_path_has_query_params url = @client.get_object_url("bucket", "just some file.json", Time.now + 2 * 60, query: { "Response-Content-Disposition" => 'inline; filename="test.json"' }) assert_match(/Response-Content-Disposition=inline%3B%20filename%3D%22test.json/, url, "query string should be escaped") end def test_get_url_filter_nil_query_params url = @client.get_object_url("bucket", "just some file.json", Time.now + 2 * 60, query: { "Response-Content-Disposition" => nil }) refute_match(/Response-Content-Disposition/, url, "nil query params should be omitted") end def test_put_url_path_is_properly_escaped url = @client.put_object_url("bucket", "just some file.json", Time.now + 2 * 60, "Content-Type" => "application/json") assert_match(/just%20some%20file\.json/, url, "space should be escaped with '%20'") end end fog-google-1.9.1/test/unit/storage/test_common_json_collections.rb0000644000004100000410000000217113451635472025517 0ustar www-datawww-datarequire "helpers/test_helper" class UnitTestStorageJSONCollections < MiniTest::Test def setup Fog.mock! @client = Fog::Storage.new(provider: "google", google_project: "foo") # Enumerate all descendants of Fog::Collection descendants = ObjectSpace.each_object(Fog::Collection.singleton_class) @collections = descendants.select do |d| d.name.match(/Fog::Storage::GoogleJSON/) end end def teardown Fog.unmock! end def test_common_methods # This tests whether Fog::Compute::Google collections have common lifecycle methods @collections.each do |klass| obj = klass.new assert obj.respond_to?(:all), "#{klass} should have an .all method" assert obj.respond_to?(:get), "#{klass} should have a .get method" assert obj.respond_to?(:each), "#{klass} should behave like Enumerable" end end def test_collection_get_arguments @collections.each do |klass| obj = klass.new assert_operator(obj.method(:get).arity, :<=, 1, "#{klass} should have at most 1 required parameter in get()") end end end fog-google-1.9.1/test/unit/storage/test_json_requests.rb0000644000004100000410000000262413451635472023507 0ustar www-datawww-datarequire "helpers/test_helper" class UnitTestJsonRequests < MiniTest::Test def setup Fog.mock! @client = Fog::Storage.new(provider: "google", google_project: "", google_json_key_location: "") end def teardown Fog.unmock! end def test_get_url_path_has_query_params url = @client.get_object_url("bucket", "just some file.json", Time.now + 2 * 60, query: { "projection" => 'full, noAcl"' }) assert_match(/projection=full%2C%20noAcl/, url, "query string should be escaped") end def test_get_url_filter_nil_query_params url = @client.get_object_url("bucket", "just some file.json", Time.now + 2 * 60, query: { "projection" => nil }) refute_match(/projection/, url, "nil query params should be omitted") end def test_put_url_path_is_properly_escaped url = @client.put_object_url("bucket", "just some file.json", Time.now + 2 * 60, "Content-Type" => "application/json") assert_match(/just%20some%20file\.json/, url, "space should be escaped with '%20'") end end fog-google-1.9.1/test/integration/0000755000004100000410000000000013451635472017113 5ustar www-datawww-datafog-google-1.9.1/test/integration/pubsub/0000755000004100000410000000000013451635472020413 5ustar www-datawww-datafog-google-1.9.1/test/integration/pubsub/test_pubsub_models.rb0000644000004100000410000001051013451635472024637 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/pubsub/pubsub_shared" require "securerandom" require "base64" class TestPubsubModels < PubSubShared def test_topics_create name = new_topic_name result = @client.topics.create(:name => name) assert_equal(result.name, name) end def test_topics_get result = @client.topics.get(some_topic_name) assert_equal(result.name, some_topic_name) end def test_topics_all # Force a topic to be created just so we have at least 1 to list name = new_topic_name @client.create_topic(name) Fog.wait_for(5) do result = @client.topics.all if result.nil? false end result.any? { |topic| topic.name == name } end end def test_topic_publish_string @client.topics.get(some_topic_name) message_ids = @client.topics.get(some_topic_name).publish(["apples"]) assert_operator(message_ids.length, :>, 0) end def test_topic_publish_hash @client.topics.get(some_topic_name) message_ids = @client.topics.get(some_topic_name).publish(["data" => "apples"]) assert_operator(message_ids.length, :>, 0) end def test_topic_delete topic_to_delete = new_topic_name topic = @client.topics.create(:name => topic_to_delete) topic.destroy end def test_subscriptions_create push_config = {} ack_deadline_seconds = 18 subscription_name = new_subscription_name result = @client.subscriptions.create(:name => subscription_name, :topic => some_topic_name, :push_config => push_config, :ack_deadline_seconds => ack_deadline_seconds) assert_equal(result.name, subscription_name) end def test_subscriptions_get subscription_name = some_subscription_name result = @client.subscriptions.get(subscription_name) assert_equal(result.name, subscription_name) end def test_subscriptions_list # Force a subscription to be created just so we have at least 1 to list subscription_name = new_subscription_name @client.subscriptions.create(:name => subscription_name, :topic => some_topic_name) Fog.wait_for(5) do result = @client.subscriptions.all if result.nil? false end result.any? { |subscription| subscription.name == subscription_name } end end def test_subscription_delete push_config = {} ack_deadline_seconds = 18 subscription_name = new_subscription_name subscription = @client.subscriptions.create(:name => subscription_name, :topic => some_topic_name, :push_config => push_config, :ack_deadline_seconds => ack_deadline_seconds) subscription.destroy end def test_subscription_pull subscription_name = new_subscription_name message_bytes = Base64.strict_encode64("some message") subscription = @client.subscriptions.create(:name => subscription_name, :topic => some_topic_name) @client.topics.get(some_topic_name).publish(["data" => message_bytes]) result = subscription.pull assert_operator(result.length, :>, 0) contained = result.any? { |received| received.message[:data] == message_bytes } assert_equal(true, contained, "sent messsage not contained within pulled responses") end def test_subscription_acknowledge subscription_name = new_subscription_name subscription = @client.subscriptions.create(:name => subscription_name, :topic => some_topic_name) @client.topics.get(some_topic_name).publish(["data" => Base64.strict_encode64("some message")]) result = subscription.pull assert_operator(result.length, :>, 0) subscription.acknowledge([result[0].ack_id]) end def test_message_acknowledge subscription_name = new_subscription_name subscription = @client.subscriptions.create(:name => subscription_name, :topic => some_topic_name) @client.topics.get(some_topic_name).publish(["data" => Base64.strict_encode64("some message")]) result = subscription.pull assert_operator(result.length, :>, 0) result[0].acknowledge end end fog-google-1.9.1/test/integration/pubsub/test_pubsub_requests.rb0000644000004100000410000000627013451635472025237 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/pubsub/pubsub_shared" require "securerandom" require "base64" class TestPubsubRequests < PubSubShared def test_create_topic name = new_topic_name result = @client.create_topic(name) assert_equal(result.name, name) end def test_get_topic result = @client.get_topic(some_topic_name) assert_equal(result.name, some_topic_name) end def test_list_topics # Force a topic to be created just so we have at least 1 to list name = new_topic_name @client.create_topic(name) Fog.wait_for(5) do result = @client.list_topics if result.topics.nil? false end result.topics.any? { |topic| topic.name == name } end end def test_delete_topic topic_to_delete = new_topic_name @client.create_topic(topic_to_delete) @client.delete_topic(topic_to_delete) end def test_publish_topic @client.publish_topic(some_topic_name, [:data => Base64.strict_encode64("some message")]) end def test_create_subscription push_config = {} ack_deadline_seconds = 18 subscription_name = new_subscription_name result = @client.create_subscription(subscription_name, some_topic_name, push_config, ack_deadline_seconds) assert_equal(result.name, subscription_name) end def test_get_subscription subscription_name = some_subscription_name result = @client.get_subscription(subscription_name) assert_equal(result.name, subscription_name) end def test_list_subscriptions # Force a subscription to be created just so we have at least 1 to list subscription_name = new_subscription_name @client.create_subscription(subscription_name, some_topic_name) Fog.wait_for(5) do result = @client.list_subscriptions if result.subscriptions.nil? false end result.subscriptions.any? { |sub| sub.name == subscription_name } end end def test_delete_subscription subscription_to_delete = new_subscription_name @client.create_subscription(subscription_to_delete, some_topic_name) @client.delete_subscription(subscription_to_delete) end def test_pull_subscription subscription_name = new_subscription_name message_bytes = Base64.strict_encode64("some message") @client.create_subscription(subscription_name, some_topic_name) @client.publish_topic(some_topic_name, [:data => message_bytes]) result = @client.pull_subscription(subscription_name) contained = result.received_messages.any? { |received| received.message.data == message_bytes } assert_equal(true, contained, "sent messsage not contained within pulled responses") end def test_acknowledge_subscription subscription_name = new_subscription_name @client.create_subscription(subscription_name, some_topic_name) @client.publish_topic(some_topic_name, [:data => Base64.strict_encode64("some message")]) pull_result = @client.pull_subscription(subscription_name) assert_operator(pull_result.received_messages.length, :>, 0) @client.acknowledge_subscription(subscription_name, pull_result.received_messages[0].ack_id) end end fog-google-1.9.1/test/integration/pubsub/test_coverage.rb0000644000004100000410000000042713451635472023575 0ustar www-datawww-datarequire "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:pubsub" if ENV["COVERAGE"] fog-google-1.9.1/test/integration/pubsub/pubsub_shared.rb0000644000004100000410000000462113451635472023571 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "securerandom" require "base64" class PubSubShared < 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_result = @client.list_topics unless topics_result.topics.nil? begin topics_result.topics .map(&:name) .select { |t| t.start_with?(topic_resource_prefix) } .each { |t| @client.delete_topic(t) } # We ignore errors here as list operations may not represent changes applied recently. # Hence, list operations can return a topic which has already been deleted but which we # will attempt to delete again. rescue Google::Apis::Error Fog::Logger.warning("ignoring Google Api error during delete_test_resources") end end subscriptions_result = @client.list_subscriptions unless subscriptions_result.subscriptions.nil? begin subscriptions_result.subscriptions .map(&:name) .select { |s| s.start_with?(subscription_resource_prefix) } .each { |s| @client.delete_subscription(s) } # We ignore errors here as list operations may not represent changes applied recently. # Hence, list operations can return a topic which has already been deleted but which we # will attempt to delete again. rescue Google::Apis::Error Fog::Logger.warning("ignoring Google Api error during delete_test_resources") end 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 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 end end fog-google-1.9.1/test/integration/sql/0000755000004100000410000000000013451635472017712 5ustar www-datawww-datafog-google-1.9.1/test/integration/sql/sqlv2/0000755000004100000410000000000013451635472020761 5ustar www-datawww-datafog-google-1.9.1/test/integration/sql/sqlv2/test_v2_instances.rb0000644000004100000410000000517713451635472024755 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/sql_v2_instances_factory" # Client helper is imported for `wait_until_complete` # TODO: Remove when fog-google#339 or fog-google#340 is resolved require "helpers/client_helper" class TestSQLV2Instances < FogIntegrationTest include TestCollection # TODO: Remove when fog-google#339 or fog-google#340 is resolved include ClientHelper attr_reader :client def setup @subject = Fog::Google[:sql].instances @factory = SqlV2InstancesFactory.new(namespaced_name) @backup_runs = Fog::Google[:sql].backup_runs # TODO: Remove after BackupRuns get save/reload - fog-google#339 # See https://github.com/fog/fog-google/issues/339 @client = Fog::Google::SQL.new end def test_restore_backup_run instance = @factory.create data = { :description => "test", :instance => instance.name } wait_until_complete { @client.insert_backup_run(instance.name, data) } backup_run = @backup_runs.all(instance.name).first # Wait for backup operation to be finished # or fail if it never finishes. instance.restore_backup(backup_run.id, :async => false) end def test_backup_runs # TODO: This probably can get pulled into the test above as those tests # very expensive time-wize (5 minutes or so each) instance = @factory.create description = "test backup run" operation = wait_until_complete do @client.insert_backup_run( instance.name, :description => description ) end assert_equal(operation.operation_type, "BACKUP_VOLUME") runs = @backup_runs.all(instance.name) assert_operator(runs.size, :>, 0, "expected at least one backup run") assert_equal(description, runs.first.description) created_run = @backup_runs.get(instance.name, runs.first.id) assert_equal(created_run, runs.first) wait_until_complete do @client.delete_backup_run(instance.name, runs.first.id) end deleted_run = @backup_runs.get(instance.name, runs.first.id) assert_equal("DELETED", deleted_run.status) end def test_clone instance = @factory.create instance.clone("#{instance.name}-clone", :async => false) cloned = @client.instances.get("#{instance.name}-clone") # Sanity check some attributes compare = %i(current_disk_size project region ip_configuration_require_ssl activation_policy) compare.each do |k| v = instance.attributes[k] cloned_v = cloned.attributes[k] if v.nil? assert_nil(cloned_v) else assert_equal(v, cloned_v, "attribute #{k} in original instance is #{v}, cloned = #{cloned_v}") end end end end fog-google-1.9.1/test/integration/sql/sqlv2/test_coverage.rb0000644000004100000410000000042613451635472024142 0ustar www-datawww-datarequire "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:sqlv2" if ENV["COVERAGE"] fog-google-1.9.1/test/integration/sql/sqlv1/0000755000004100000410000000000013451635472020760 5ustar www-datawww-datafog-google-1.9.1/test/integration/sql/sqlv1/test_v1_users.rb0000644000004100000410000000212713451635472024115 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/sql_v1_instances_factory" require "integration/factories/sql_v1_users_factory" class TestSQLV1Users < FogIntegrationTest # This test doesn't include TestCollection as Users is not a # classical Fog model, as it's tied to a particular instance # I.e.: # - Fog::Google::SQL.users.all() requires an instance # - API doesn't provide a GET request for Users model # See: https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/users def setup @subject = Fog::Google[:sql].users @factory = SqlV1UsersFactory.new(namespaced_name) end def teardown @factory.cleanup end def test_users # Create user user = @factory.create # Check user was created users = @subject.all(user.instance).select { |u| u.name == user.name } assert_equal(1, users.size, "expected user to have been created") # Delete user users.first.destroy(:async => false) assert_empty( @subject.all(user.instance).select { |u| u.name == user.name }, "expected no user #{user.name}" ) end end fog-google-1.9.1/test/integration/sql/sqlv1/test_common_tiers.rb0000644000004100000410000000135013451635472025041 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestCommonTiers < FogIntegrationTest def setup @subject = Fog::Google[:sql].tiers end def test_all tiers = @subject.all assert_operator(tiers.size, :>, 0, "tier count should be positive") _sanity_check_tier(tiers.first) end def _sanity_check_tier(tier) assert_equal(tier.kind, "sql#tier") refute(tier.tier.nil?, "tier name should not be empty") assert_operator(tier.disk_quota, :>, 0, "tier disk quota should be positive") assert_operator(tier.ram, :>, 0, "tier ram should be positive") assert_operator(tier.region.size, :>, 0, "tier should have regions") end end fog-google-1.9.1/test/integration/sql/sqlv1/test_coverage.rb0000644000004100000410000000042613451635472024141 0ustar www-datawww-datarequire "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:sqlv1" if ENV["COVERAGE"] fog-google-1.9.1/test/integration/sql/sqlv1/test_v1_instances.rb0000644000004100000410000000147413451635472024747 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/sql_v1_instances_factory" class TestSQLV1Instances < FogIntegrationTest include TestCollection def setup @subject = Fog::Google[:sql].instances @factory = SqlV1InstancesFactory.new(namespaced_name) end def test_update instance = @factory.create settings_version = instance.settings_version labels = { :foo => "bar" } instance.settings[:user_labels] = labels instance.save updated = @subject.get(instance.name) assert_equal(labels, updated.settings[:user_labels]) assert_operator(updated.settings_version, :>, settings_version) end def test_default_settings instance = @factory.create assert_equal([], instance.ssl_certs, "new instance should have 0 initial ssl certs") end end fog-google-1.9.1/test/integration/sql/sqlv1/test_v1_certs.rb0000644000004100000410000000312713451635472024075 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/sql_v1_certs_factory" class TestSQLV1Certs < FogIntegrationTest # This test doesn't include TestCollection as certs are not an independent resource. def setup @subject = Fog::Google[:sql].ssl_certs @factory = SqlV1CertsFactory.new(namespaced_name) @client = Fog::Google::SQL.new end def teardown @factory.cleanup end def test_ssl_certs # Create an instance and an SSL cert ssl_cert = @factory.create instance_name = ssl_cert.instance # Create a second cert and attach to the same instance ssl_cert2 = @subject.new(:common_name => "#{ssl_cert.common_name}-2", :instance => instance_name) ssl_cert2.save # Verify it can be retrieved @subject.get(instance_name, ssl_cert2.sha1_fingerprint).tap do |result| assert_equal(ssl_cert2.common_name, result.common_name) assert_equal("sql#sslCert", result.kind) end # Verify instance returns 2 certs list_result = @subject.all(instance_name) assert_equal(2, list_result.size, "expected 2 SSL certs") # Delete one cert ssl_cert2.destroy(:async => false) list_result = @subject.all(instance_name) assert_equal(1, list_result.size, "expected one less SSL cert after deletion") # Test if SSL config is reset correctly instance = @client.instances.get(instance_name) instance.reset_ssl_config(:async => false) assert_equal(0, @subject.all(instance_name).size, "expected no SSL certs after reset") end end fog-google-1.9.1/test/integration/sql/sqlv1/test_common_flags.rb0000644000004100000410000000137313451635472025014 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestCommonFlags < FogIntegrationTest def setup @client = Fog::Google::SQL.new end def test_list resp = @client.list_flags assert_operator(resp.items.size, :>, 0, "resource descriptor count should be positive") _sanity_check_flag(resp.items.first) end def test_all resp = @client.flags.all assert_operator(resp.size, :>, 0, "resource descriptor count should be positive") _sanity_check_flag(resp.first) end def _sanity_check_flag(flag) assert_equal(flag.kind, "sql#flag") refute(flag.name.nil?, "flag name should not be empty") refute_empty(flag.applies_to, "flag should apply to some database version") end end fog-google-1.9.1/test/integration/factories/0000755000004100000410000000000013451635472021072 5ustar www-datawww-datafog-google-1.9.1/test/integration/factories/target_https_proxies_factory.rb0000644000004100000410000000145313451635472027432 0ustar www-datawww-datarequire "integration/factories/collection_factory" require "integration/factories/url_maps_factory" require "integration/factories/ssl_certificates_factory" class TargetHttpsProxiesFactory < CollectionFactory def initialize(example) @ssl_certificates = SslCertificatesFactory.new(example) @url_maps = UrlMapsFactory.new(example) super(Fog::Compute[:google].target_https_proxies, example) end def cleanup # Calling CollectionFactory#cleanup with forced async as # Url Maps need the Https Proxy to be deleted before they # can be destroyed super(false) @ssl_certificates.cleanup @url_maps.cleanup end def params { :name => resource_name, :url_map => @url_maps.create.self_link, :ssl_certificates => [@ssl_certificates.create.self_link] } end end fog-google-1.9.1/test/integration/factories/http_health_checks_factory.rb0000644000004100000410000000037213451635472026774 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-1.9.1/test/integration/factories/backend_services_factory.rb0000644000004100000410000000076013451635472026443 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-1.9.1/test/integration/factories/instance_group_manager_factory.rb0000644000004100000410000000130313451635472027655 0ustar www-datawww-datarequire "integration/factories/collection_factory" require "integration/factories/instance_template_factory" class InstanceGroupManagerFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].instance_group_managers, example) @instance_template = InstanceTemplateFactory.new(example) end def cleanup super @instance_template.cleanup end def get(identity) @subject.get(identity, TEST_ZONE) end def all @subject.all(zone: TEST_ZONE) end def params { :name => resource_name, :zone => TEST_ZONE, :base_instance_name => resource_name, :target_size => 1, :instance_template => @instance_template.create } end end fog-google-1.9.1/test/integration/factories/addresses_factory.rb0000644000004100000410000000060213451635472025121 0ustar www-datawww-datarequire "integration/factories/collection_factory" class AddressesFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].addresses, example) end def get(identity) @subject.get(identity, TEST_REGION) end def all @subject.all(region: TEST_REGION) end def params { :name => resource_name, :region => TEST_REGION } end end fog-google-1.9.1/test/integration/factories/instance_groups_factory.rb0000644000004100000410000000060313451635472026350 0ustar www-datawww-datarequire "integration/factories/collection_factory" class InstanceGroupsFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].instance_groups, example) end def get(identity) @subject.get(identity, TEST_ZONE) end def all @subject.all(zone: TEST_ZONE) end def params { :name => resource_name, :zone => TEST_ZONE } end end fog-google-1.9.1/test/integration/factories/sql_v1_certs_factory.rb0000644000004100000410000000105013451635472025547 0ustar www-datawww-datarequire "integration/factories/collection_factory" require "integration/factories/sql_v1_instances_factory" class SqlV1CertsFactory < CollectionFactory def initialize(example) @instances = SqlV1InstancesFactory.new(example) super(Fog::Google[:sql].ssl_certs, example) end def cleanup # Certs will be cleaned up with the test instance. @instances.cleanup end def params # Certificate name should not be longer than 16 characters { :common_name => resource_name, :instance => @instances.create.name } end end fog-google-1.9.1/test/integration/factories/global_forwarding_rules_factory.rb0000644000004100000410000000076313451635472030050 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, :port_range => "80-80", :target => @targets.create.self_link } end end fog-google-1.9.1/test/integration/factories/disks_factory.rb0000644000004100000410000000067013451635472024266 0ustar www-datawww-datarequire "integration/factories/collection_factory" class DisksFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].disks, example) end def get(identity) @subject.get(identity, TEST_ZONE) end def all @subject.all(zone: TEST_ZONE) end def params { :name => resource_name, :zone_name => TEST_ZONE, :source_image => TEST_IMAGE, :size_gb => TEST_SIZE_GB } end end fog-google-1.9.1/test/integration/factories/instance_template_factory.rb0000644000004100000410000000142013451635472026642 0ustar www-datawww-datarequire "integration/factories/collection_factory" class InstanceTemplateFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].instance_templates, example) end def params { :name => resource_name, # TODO: Properties config is convoluted, needs to be refactored :properties => { :machine_type => TEST_MACHINE_TYPE, :disks => [{ :boot => true, :auto_delete => true, :initialize_params => { :source_image => "projects/ubuntu-os-cloud/global/images/ubuntu-1804-bionic-v20180522" } }], :network_interfaces => [{ :network => "global/networks/default" }] } } end end fog-google-1.9.1/test/integration/factories/networks_factory.rb0000644000004100000410000000101413451635472025016 0ustar www-datawww-datarequire "integration/factories/collection_factory" class NetworksFactory < CollectionFactory def initialize(example) # We cannot have 2 networks with the same IP range so instantiating a # class variable holding a generator, ensuring that the factory gives # us a new network every time it's called @octet_generator = (0..255).each super(Fog::Compute[:google].networks, example) end def params { :name => resource_name, :ipv4_range => "172.16.#{@octet_generator.next}.0/24" } end end fog-google-1.9.1/test/integration/factories/forwarding_rules_factory.rb0000644000004100000410000000107513451635472026525 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 all @subject.all(region: TEST_REGION) end def params { :name => resource_name, :port_range => "80-80", :region => TEST_REGION, :target => @target_pools.create.self_link } end end fog-google-1.9.1/test/integration/factories/images_factory.rb0000644000004100000410000000054013451635472024412 0ustar www-datawww-datarequire "integration/factories/collection_factory" class ImagesFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].images, example) end def get(identity) @subject.get(identity, TEST_PROJECT) end def params { :name => resource_name, :raw_disk => { :source => TEST_RAW_DISK_SOURCE } } end end fog-google-1.9.1/test/integration/factories/sql_v1_instances_factory.rb0000644000004100000410000000076313451635472026430 0ustar www-datawww-datarequire "integration/factories/collection_factory" class SqlV1InstancesFactory < CollectionFactory def initialize(example) super(Fog::Google[:sql].instances, example) end def cleanup super end def params # Name has a time suffix due to SQL resources API objects having # a _very_ long life on the backend (n(days)) after deletion. { :name => "#{resource_name}-#{Time.now.to_i}", :region => TEST_SQL_REGION_FIRST, :tier => TEST_SQL_TIER_FIRST } end end fog-google-1.9.1/test/integration/factories/url_maps_factory.rb0000644000004100000410000000072713451635472024776 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-1.9.1/test/integration/factories/collection_factory.rb0000644000004100000410000000403613451635472025304 0ustar www-datawww-dataclass CollectionFactory PREFIX = "fog-test".freeze def initialize(subject, example) @subject = subject @example = example @resource_counter = 0 end # Cleans up all objects created by the factory in the current test suite. # # @param async [FalseClass or TrueClass] perform resource destruction asynchronously def cleanup(async = false) suit_name = @example.gsub(/\W/, "").tr("_", "-").downcase.split('-')[0] resources = @subject.all.select { |resource| resource.name.match(/#{PREFIX}-[0-9]*-#{suit_name}/) } if DEBUG p "Cleanup invoked in #{self} for example: #{@example}" p "Resources to be deleted: #{resources.map { |r| r.name }}" p "All subject resources: #{@subject.all.map { |s| s.name }}" end resources.each { |r| r.destroy(async) } resources.each { |r| Fog.wait_for { !@subject.all.map(&:identity).include? r.identity } } end # Creates a collection object instance e.g. Fog::Compute::Google::Server # # @param custom_params [Hash] override factory creation parameters or provide # additional ones. Useful in tests where you need to create a slightly different # resource than the default one but still want to take advantage of the factory's # cleanup methods, etc. # # @example Create a custom factory # @factory = ServersFactory.new(namespaced_name) # server = @factory.create(:machine_type => "f1-micro") # # @return [Object] collection object instance def create(custom_params = {}) @subject.create(params.merge(custom_params)) end def get(identity) @subject.get(identity) 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-1.9.1/test/integration/factories/sql_v2_instances_factory.rb0000644000004100000410000000076513451635472026433 0ustar www-datawww-datarequire "integration/factories/collection_factory" class SqlV2InstancesFactory < CollectionFactory def initialize(example) super(Fog::Google[:sql].instances, example) end def cleanup super end def params # Name has a time suffix due to SQL resources API objects having # a _very_ long life on the backend (n(days)) after deletion. { :name => "#{resource_name}-#{Time.now.to_i}", :region => TEST_SQL_REGION_SECOND, :tier => TEST_SQL_TIER_SECOND } end end fog-google-1.9.1/test/integration/factories/ssl_certificates_factory.rb0000644000004100000410000000053313451635472026475 0ustar www-datawww-datarequire "integration/factories/collection_factory" class SslCertificatesFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].ssl_certificates, example) end def params { :name => resource_name, :certificate => TEST_PEM_CERTIFICATE, :private_key => TEST_PEM_CERTIFICATE_PRIVATE_KEY } end end fog-google-1.9.1/test/integration/factories/firewalls_factory.rb0000644000004100000410000000050113451635472025132 0ustar www-datawww-datarequire "integration/factories/collection_factory" class FirewallsFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].firewalls, example) end def params { :name => resource_name, :allowed => [{ :ip_protocol => "TCP", :ports => ["201"] }] } end end fog-google-1.9.1/test/integration/factories/target_http_proxies_factory.rb0000644000004100000410000000067413451635472027253 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-1.9.1/test/integration/factories/servers_factory.rb0000644000004100000410000000123213451635472024635 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 # Disk cleanup sometimes fails if server deletion has not been completed super(false) @disks.cleanup end def get(identity) @subject.get(identity, TEST_ZONE) end def all @subject.all(zone: TEST_ZONE) end def params { :name => resource_name, :zone => TEST_ZONE, :machine_type => TEST_MACHINE_TYPE, :disks => [@disks.create] } end end fog-google-1.9.1/test/integration/factories/sql_v1_users_factory.rb0000644000004100000410000000103413451635472025572 0ustar www-datawww-datarequire "integration/factories/collection_factory" require "integration/factories/sql_v1_instances_factory" class SqlV1UsersFactory < CollectionFactory def initialize(example) @instances = SqlV1InstancesFactory.new(example) super(Fog::Google[:sql].users, example) end def cleanup # Users will be cleaned up with the test instance. @instances.cleanup end def params # Username should not be longer than 16 characters { :name => resource_name[0..15], :instance => @instances.create.name } end end fog-google-1.9.1/test/integration/factories/subnetworks_factory.rb0000644000004100000410000000131713451635472025536 0ustar www-datawww-datarequire "integration/factories/collection_factory" class SubnetworksFactory < CollectionFactory def initialize(example) # We cannot have 2 subnetworks with the same CIDR range so instantiating a # class variable holding a generator, ensuring that the factory gives us a # new subnet every time it's called @octet_generator = (0..255).each super(Fog::Compute[:google].subnetworks, example) end def get(identity) @subject.get(identity, TEST_REGION) end def all @subject.all(region: TEST_REGION) end def params { :name => resource_name, :network => "default", :region => TEST_REGION, :ip_cidr_range => "192.168.#{@octet_generator.next}.0/24" } end end fog-google-1.9.1/test/integration/factories/global_addresses_factory.rb0000644000004100000410000000045513451635472026447 0ustar www-datawww-datarequire "integration/factories/collection_factory" class GlobalAddressesFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].global_addresses, example) end def get(identity) @subject.get(identity) end def params { :name => resource_name } end end fog-google-1.9.1/test/integration/factories/target_pools_factory.rb0000644000004100000410000000137113451635472025652 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 all @subject.all(region: TEST_REGION) end def params { :name => resource_name, :region => TEST_REGION, :instances => [@servers.create.self_link, @servers.create.self_link], :health_checks => [@http_health_checks.create.self_link] } end end fog-google-1.9.1/test/integration/factories/target_instances_factory.rb0000644000004100000410000000100113451635472026473 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 all @subject.all(zone: TEST_ZONE) end def params { :name => resource_name, :zone => TEST_ZONE, :instance => @servers.create.self_link } end end fog-google-1.9.1/test/integration/compute/0000755000004100000410000000000013451635472020567 5ustar www-datawww-datafog-google-1.9.1/test/integration/compute/core_networking/0000755000004100000410000000000013451635472023766 5ustar www-datawww-datafog-google-1.9.1/test/integration/compute/core_networking/test_routes.rb0000644000004100000410000000105713451635472026676 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestRoutes < FogIntegrationTest def setup @subject = Fog::Compute[:google].routes end def test_all assert_operator(@subject.all.size, :>=, 2, "Number of all routes should be greater or equal than 2 - default GW and default routes") end def test_get @subject.all do |route| refute_nil @subject.get(route.name) 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-1.9.1/test/integration/compute/core_networking/test_coverage.rb0000644000004100000410000000045013451635472027144 0ustar www-datawww-datarequire "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:compute-core_networking" if ENV["COVERAGE"] fog-google-1.9.1/test/integration/compute/core_networking/test_subnetworks.rb0000644000004100000410000000044213451635472027740 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/subnetworks_factory" class TestSubnetworks < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].subnetworks @factory = SubnetworksFactory.new(namespaced_name) end end fog-google-1.9.1/test/integration/compute/core_networking/test_addresses.rb0000644000004100000410000000500713451635472027331 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/addresses_factory" require "integration/factories/servers_factory" class TestAddresses < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].addresses @servers = ServersFactory.new(namespaced_name) @factory = AddressesFactory.new(namespaced_name) end def teardown # Clean up the server resources used in testing @servers.cleanup super end def test_run_instance address = @factory.create server = @servers.create(:external_ip => address.address) assert_equal( address.address, server.network_interfaces[0][:access_configs][0][:nat_ip], "Created server should have the correct address after initialization" ) assert_equal( "IN_USE", @subject.get(address.name, TEST_REGION).status, "Address should now be in use" ) end def test_bad_get assert_nil @subject.get("bad-name", TEST_REGION) end def test_valid_range address = @factory.create octet = /\d{,2}|1\d{2}|2[0-4]\d|25[0-5]/ re = /\A#{octet}\.#{octet}\.#{octet}\.#{octet}\z/ assert_match(re, address.address, "Adress should be a valid ipv4 address") end def test_addresses_get_address_by_ip address = @factory.create found = @subject.get_by_ip_address(address.address) assert_equal(address.name, found.name, "address should have same name") assert_equal(address.address, found.address, "addresses should match") end def test_addresses_get_address_by_name address = @factory.create found = @subject.get_by_name(address.name) assert_equal(address.name, found.name, "address should have same name") assert_equal(address.address, found.address, "addresses should match") end def test_addresses_get_by_ip_address_or_name # Ensure we find the same addresses through both codepaths address = @factory.create with_name = @subject.get_by_ip_address_or_name(address.name) with_ip = @subject.get_by_ip_address_or_name(address.address) assert_equal(address.name, with_name.name, "address should have same name") assert_equal(address.address, with_name.address, "addresses should match") assert_equal(address.name, with_ip.name, "address should have same name") assert_equal(address.address, with_ip.address, "addresses should match") end def test_addresses_in_use address = @factory.create assert_equal(false, address.in_use?, "example address should not be in use") end end fog-google-1.9.1/test/integration/compute/core_networking/test_networks.rb0000644000004100000410000000211413451635472027224 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/networks_factory" require "integration/factories/servers_factory" class TestNetworks < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].networks @servers = ServersFactory.new(namespaced_name) @factory = NetworksFactory.new(namespaced_name) end def teardown # Clean up the server resources used in testing @servers.cleanup super end def test_valid_range network = @factory.create octet = /\d{,2}|1\d{2}|2[0-4]\d|25[0-5]/ netmask = /(\d{1}|1[0-9]|2[0-9]|3[0-2])/ re = /\A#{octet}\.#{octet}\.#{octet}\.#{octet}\/#{netmask}\z/ assert_match(re, network.ipv4_range, "Network range should be valid") end def test_run_instance network = @factory.create server = @servers.create(:network_interfaces => [network.get_as_interface_config]) assert_equal( network.self_link, server.network_interfaces[0][:network], "Created server should have the network specified on boot" ) end end fog-google-1.9.1/test/integration/compute/core_networking/test_firewalls.rb0000644000004100000410000000043213451635472027341 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/firewalls_factory" class TestFirewalls < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].firewalls @factory = FirewallsFactory.new(namespaced_name) end end fog-google-1.9.1/test/integration/compute/loadbalancing/0000755000004100000410000000000013451635472023345 5ustar www-datawww-datafog-google-1.9.1/test/integration/compute/loadbalancing/test_url_maps.rb0000644000004100000410000000042413451635472026553 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-1.9.1/test/integration/compute/loadbalancing/test_forwarding_rules.rb0000644000004100000410000000046413451635472030311 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-1.9.1/test/integration/compute/loadbalancing/test_target_pools.rb0000644000004100000410000000416213451635472027436 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) @servers = Fog::Compute[:google].servers end # Override to include zone in get request def get_resource(identity) @subject.get(identity, TEST_ZONE) end def test_get_health target_pool = @factory.create server = @servers.get(target_pool.instances[0].split("/").last) server.wait_for { ready? } # XXX This is not partucularly elegant but if the instance doesn't respond # to the healthcheck at all (for example there's nothing listening) it'll # enter "No instance health info was found." state, during which the API # will return an empty health object instead of UNHEALTHY. # To avoid setting up a brittle environment with a live healthcheck we just # stop the instance so health check returns UNHEALTHY and we can test that # all fields are returned correctly. server.stop server.wait_for { stopped? } # There's no way to track the readiness of the instance resource in a target pool, # so wrapping in a soft retry: begin retries ||= 0 target_pool.get_health rescue ::Google::Apis::ClientError sleep 25 retry if (retries += 1) < 3 end refute_empty(target_pool.health_checks, "Target pool should have a health check") assert_equal(2, target_pool.instances.count, "Target pool should have 2 instances") assert_equal([{ :health_state => "UNHEALTHY", :instance => server.self_link }], target_pool.get_health[server.self_link], "Target pool should return a proper health check list") assert_equal({ server.self_link => [{ :health_state => "UNHEALTHY", :instance => server.self_link }] }, target_pool.get_health(server.name), "target_pool should return instance health details when an instance is specified") end end fog-google-1.9.1/test/integration/compute/loadbalancing/test_target_https_proxies.rb0000644000004100000410000000050213451635472031207 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/target_https_proxies_factory" class TestTargetHttpsProxies < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].target_https_proxies @factory = TargetHttpsProxiesFactory.new(namespaced_name) end end fog-google-1.9.1/test/integration/compute/loadbalancing/test_http_health_checks.rb0000644000004100000410000000047213451635472030560 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-1.9.1/test/integration/compute/loadbalancing/test_backend_services.rb0000644000004100000410000000046413451635472030227 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-1.9.1/test/integration/compute/loadbalancing/test_target_instances.rb0000644000004100000410000000046413451635472030272 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-1.9.1/test/integration/compute/loadbalancing/test_coverage.rb0000644000004100000410000000044613451635472026530 0ustar www-datawww-datarequire "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:compute-loadbalancing" if ENV["COVERAGE"] fog-google-1.9.1/test/integration/compute/loadbalancing/test_global_forwarding_rules.rb0000644000004100000410000000051613451635472031627 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-1.9.1/test/integration/compute/loadbalancing/test_global_addresses.rb0000644000004100000410000000046413451635472030232 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/global_addresses_factory" class TestGlobalAddresses < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].global_addresses @factory = GlobalAddressesFactory.new(namespaced_name) end end fog-google-1.9.1/test/integration/compute/loadbalancing/test_target_http_proxies.rb0000644000004100000410000000047613451635472031036 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-1.9.1/test/integration/compute/loadbalancing/test_ssl_certificates.rb0000644000004100000410000000046413451635472030263 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/ssl_certificates_factory" class TestSslCertificates < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].ssl_certificates @factory = SslCertificatesFactory.new(namespaced_name) end end fog-google-1.9.1/test/integration/compute/core_compute/0000755000004100000410000000000013451635472023253 5ustar www-datawww-datafog-google-1.9.1/test/integration/compute/core_compute/test_operations.rb0000644000004100000410000000244013451635472027022 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestOperations < FogIntegrationTest def setup @subject = Fog::Compute[:google].operations end def test_all # TODO: what if this test runs first on a brand new project? assert_operator(@subject.all.size, :>=, 2, "There should be at least 2 operations in the project") end def test_get @subject.all do |operation| refute_nil @subject.get(operation.name) end end def test_zone_scoped_all subject_list = @subject.all scoped_subject_list = @subject.all(zone: TEST_ZONE) # Assert that whatever .all(scope) returns is a subset of .all assert(scoped_subject_list.all? { |x| subject_list.include? x }, "Output of @subject.all(zone:#{TEST_ZONE}) must be a subset of @subject.all") end def test_region_scoped_all subject_list = @subject.all scoped_subject_list = @subject.all(region: TEST_REGION) # Assert that whatever .all(scope) returns is a subset of .all assert(scoped_subject_list.all? { |x| subject_list.include? x }, "Output of @subject.all(region:#{TEST_REGION}) must be a subset of @subject.all") end def test_bad_get assert_nil @subject.get("bad-name") end def test_enumerable assert_respond_to @subject, :each end end fog-google-1.9.1/test/integration/compute/core_compute/test_disk_types.rb0000644000004100000410000000254213451635472027020 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestDiskTypes < FogIntegrationTest NAMES = %w(local-ssd pd-ssd pd-standard).freeze # Testing in one random zone per region (region list as of May 2018) ZONES = %w(asia-east1-a asia-northeast1-b asia-south1-c asia-southeast1-a australia-southeast1-b europe-west1-c europe-west2-a europe-west3-b europe-west4-c northamerica-northeast1-a southamerica-east1-b us-central1-c us-east1-b us-east4-a us-west1-c).freeze def setup @subject = Fog::Compute[:google].disk_types end def test_all assert_operator(@subject.all.size, :>=, NAMES.size * ZONES.size, "Number of all disk type references should be greater or equal to test zones * disk types") end def test_scoped_all subject_list = @subject.all scoped_subject_list = @subject.all(zone: TEST_ZONE) # Assert that whatever .all(scope) returns is a subset of .all assert(scoped_subject_list.all? { |x| subject_list.include? x }, "Output of @subject.all(zone:#{TEST_ZONE}) must be a subset of @subject.all") 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-1.9.1/test/integration/compute/core_compute/test_machine_types.rb0000644000004100000410000000357113451635472027475 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestMachineTypes < FogIntegrationTest # List of machine types - not a complete sampling since beefier ones do not # exist in all zones (list last updated June 2018) NAMES = %w(f1-micro g1-small n1-highcpu-16 n1-highcpu-2 n1-highcpu-4 n1-highcpu-8 n1-highmem-16 n1-highmem-2 n1-highmem-32 n1-highmem-4 n1-highmem-8 n1-standard-1 n1-standard-16 n1-standard-2 n1-standard-32 n1-standard-4 n1-standard-8 ).freeze # Testing in one random zone per region (list last updated May 2018) ZONES = %w(asia-east1-a asia-northeast1-b asia-south1-c asia-southeast1-a australia-southeast1-b europe-west1-c europe-west2-a europe-west3-b europe-west4-c northamerica-northeast1-a southamerica-east1-b us-central1-c us-east1-b us-east4-a us-west1-c).freeze def setup @subject = Fog::Compute[:google].machine_types end def test_all assert_operator(@subject.all.size, :>=, NAMES.size * ZONES.size, "Number of all machine types should be greater or equal to test zones * machine_types") end def test_scoped_all subject_list = @subject.all scoped_subject_list = @subject.all(zone: TEST_ZONE) # Assert that whatever .all(scope) returns is a subset of .all assert(scoped_subject_list.all? { |x| subject_list.include? x }, "Output of @subject.all(zone:#{TEST_ZONE}) must be a subset of @subject.all") end def test_get # This tests only in last zone since not all zones contain all machine types 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", ZONES.first) end def test_enumerable assert_respond_to @subject, :each end def test_nil_get assert_nil @subject.get(nil) end end fog-google-1.9.1/test/integration/compute/core_compute/test_zones.rb0000644000004100000410000000212513451635472025775 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestZones < FogIntegrationTest # Testing one random zone per region (list last updated May 2018) ZONES = %w(asia-east1-a asia-northeast1-b asia-south1-c asia-southeast1-a australia-southeast1-b europe-west1-c europe-west2-a europe-west3-b europe-west4-c northamerica-northeast1-a southamerica-east1-b us-central1-c us-east1-b us-east4-a us-west1-c).freeze def setup @subject = Fog::Compute[:google].zones end def test_all assert_operator(@subject.all.size, :>=, ZONES.size, "Number of all zones should be greater than test zones") end def test_get # This tests only in last zone since not all zones contain all machine types ZONES.each do |name| zone = @subject.get(name) refute_nil(zone, "zones.get() should not return nil") assert(zone.up?, "zones.up? should return up, unless there's an outage") 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-1.9.1/test/integration/compute/core_compute/test_client_options.rb0000644000004100000410000000073113451635472027671 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestComputeClient < FogIntegrationTest def test_client_options # XXX This is a very rudimentary test checking that proxy option is applied client_options = { proxy_url: "https://user:password@host:8080" } connection = Fog::Compute::Google.new(google_client_options: client_options) err = assert_raises(ArgumentError) { connection.servers.all } assert_match(/unsupported proxy/, err.message) end end fog-google-1.9.1/test/integration/compute/core_compute/test_servers.rb0000644000004100000410000001002513451635472026326 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/servers_factory" require "integration/factories/disks_factory" require "resolv" class TestServers < FogIntegrationTest include TestCollection # Cleanup is handled by TestCollection def setup @subject = Fog::Compute[:google].servers @factory = ServersFactory.new(namespaced_name) @servers = ServersFactory.new(namespaced_name) @disks = DisksFactory.new(namespaced_name) end def teardown # Clean up the server resources used in testing @servers.cleanup super end def test_set_metadata server = @factory.create server.wait_for { ready? } server.set_metadata({ "foo" => "bar", "baz" => "foo" }, false) assert_equal [{ :key => "foo", :value => "bar" }, { :key => "baz", :value => "foo" }], server.metadata[:items] end def test_bootstrap key = "ssh-rsa IAMNOTAREALSSHKEYAMA== user@host.subdomain.example.com" user = "username" File.stub :read, key do # XXX Small hack - name is set this way so it will be cleaned up by CollectionFactory # Bootstrap is special so this is something that needs to be done only for this method # Public_key_path is set to avoid stubbing out File.exist? server = @subject.bootstrap(:name => "#{CollectionFactory.new(nil,namespaced_name).resource_name}", :username => user, :public_key_path => "foo") boot_disk = server.disks.detect { |disk| disk[:boot] } assert_equal("RUNNING", server.status, "Bootstrapped server should be running") assert_equal(key, server.public_key, "Bootstrapped server should have a public key set") assert_equal(user, server.username, "Bootstrapped server should have user set to #{user}") assert(boot_disk[:auto_delete], "Bootstrapped server should have disk set to autodelete") network_adapter = server.network_interfaces.detect { |x| x.has_key?(:access_configs) } refute_nil(network_adapter[:access_configs].detect { |x| x[:nat_ip] }, "Bootstrapped server should have an external ip by default") end end def test_bootstrap_fail # Pretend the ssh key does not exist File.stub :exist?, nil do assert_raises(Fog::Errors::Error) { # XXX Small hack - name is set this way so it will be cleaned up by CollectionFactory # Bootstrap is special so this is something that needs to be done only for this method @subject.bootstrap(:name => "#{CollectionFactory.new(nil,namespaced_name).resource_name}", :public_key_path => nil) } end end def test_image_name server = @factory.create assert_equal(TEST_IMAGE, server.image_name.split("/")[-1]) end def test_ip_address_methods # Create a server with ephemeral external IP address server = @factory.create(:network_interfaces => [{ :network => "global/networks/default", :access_configs => [{ :name => "External NAT", :type => "ONE_TO_ONE_NAT" }] }]) assert_match(Resolv::IPv4::Regex, server.public_ip_address, "Server.public_ip_address should return a valid IP address") refute_empty(server.public_ip_addresses) assert_match(Resolv::IPv4::Regex, server.public_ip_addresses.pop) assert_match(Resolv::IPv4::Regex, server.private_ip_address, "Server.public_ip_address should return a valid IP address") refute_empty(server.private_ip_addresses) assert_match(Resolv::IPv4::Regex, server.private_ip_addresses.pop) end def test_start_stop_reboot server = @factory.create server.stop server.wait_for { stopped? } assert server.stopped? server.start server.wait_for { ready? } assert server.ready? server.reboot server.wait_for { ready? } assert server.ready? end end fog-google-1.9.1/test/integration/compute/core_compute/test_images.rb0000644000004100000410000000207313451635472026106 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 def test_get_specific_image image = @subject.get(TEST_IMAGE) refute_nil(image, "Images.get(#{TEST_IMAGE}) should not return nil") assert_equal(image.family, TEST_IMAGE_FAMILY) assert_equal(image.project, TEST_IMAGE_PROJECT) end def test_get_specific_image_from_project image = @subject.get(TEST_IMAGE,TEST_IMAGE_PROJECT) refute_nil(image, "Images.get(#{TEST_IMAGE}) should not return nil") assert_equal(image.family, TEST_IMAGE_FAMILY) assert_equal(image.project, TEST_IMAGE_PROJECT) end def test_get_from_family image = @subject.get_from_family(TEST_IMAGE_FAMILY) refute_nil(image,"Images.get_from_family(#{TEST_IMAGE_FAMILY}) should not return nil") assert_equal(image.family, TEST_IMAGE_FAMILY) assert_equal(image.project, TEST_IMAGE_PROJECT) end end fog-google-1.9.1/test/integration/compute/core_compute/test_disks.rb0000644000004100000410000000303513451635472025755 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 def test_get_as_configs disk = @factory.create disk.wait_for { ready? } example = disk.get_as_boot_disk config = { :auto_delete => false, :boot => true, :source => disk.self_link, :mode => "READ_WRITE", :type => "PERSISTENT" } assert_equal(example, config) example_with_params = disk.get_as_boot_disk(false, true) config_with_params = { :auto_delete => true, :boot => true, :source => disk.self_link, :mode => "READ_ONLY", :type => "PERSISTENT" } assert_equal(example_with_params, config_with_params) end def test_create_snapshot disk = @factory.create disk.wait_for { ready? } snapshot = disk.create_snapshot("fog-test-snapshot") assert(snapshot.is_a?(Fog::Compute::Google::Snapshot), "Resulting snapshot should be a snapshot object.") assert_raises(ArgumentError) { snapshot.set_labels(["bar", "test"]) } snapshot.set_labels(foo: "bar", fog: "test") assert_equal(snapshot.labels[:foo], "bar") assert_equal(snapshot.labels[:fog], "test") # Clean up the snapshot operation = snapshot.destroy operation.wait_for { ready? } end end fog-google-1.9.1/test/integration/compute/core_compute/test_coverage.rb0000644000004100000410000000044513451635472026435 0ustar www-datawww-datarequire "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:compute-core_compute" if ENV["COVERAGE"] fog-google-1.9.1/test/integration/compute/core_compute/test_snapshots.rb0000644000004100000410000000070713451635472026665 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "securerandom" require "base64" class TestComputeSnapshots < FogIntegrationTest def setup @client = Fog::Compute::Google.new # Ensure any resources we create with test prefixes are removed Minitest.after_run do delete_test_resources end end def test_list_empty_snapshots assert_empty @client.snapshots.all end def delete_test_resources # nothing to do end end fog-google-1.9.1/test/integration/compute/core_compute/test_regions.rb0000644000004100000410000000124113451635472026303 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestRegions < FogIntegrationTest EXAMPLE_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_operator(@subject.all.size, :>=, EXAMPLE_NAMES.size) end def test_get EXAMPLE_NAMES.each do |region| refute_nil @subject.get(region) end end def test_up EXAMPLE_NAMES.each do |region| assert @subject.get(region).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-1.9.1/test/integration/compute/core_compute/test_projects.rb0000644000004100000410000000053013451635472026466 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestProjects < FogIntegrationTest def setup @subject = Fog::Compute[:google].projects end def test_get assert @subject.get(TEST_PROJECT) end def test_bad_get assert_nil @subject.get("bad-name") end def test_enumerable assert_respond_to @subject, :each end end fog-google-1.9.1/test/integration/compute/instance_groups/0000755000004100000410000000000013451635472023772 5ustar www-datawww-datafog-google-1.9.1/test/integration/compute/instance_groups/test_coverage.rb0000644000004100000410000000045013451635472027150 0ustar www-datawww-datarequire "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:compute-instance_groups" if ENV["COVERAGE"] fog-google-1.9.1/test/integration/compute/instance_groups/test_instance_groups.rb0000644000004100000410000000046013451635472030561 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/instance_groups_factory" class TestInstanceGroups < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].instance_groups @factory = InstanceGroupsFactory.new(namespaced_name) end end fog-google-1.9.1/test/integration/compute/instance_groups/test_instance_group_managers.rb0000644000004100000410000000051413451635472032253 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/instance_group_manager_factory" class TestInstanceGroupManagers < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].instance_group_managers @factory = InstanceGroupManagerFactory.new(namespaced_name) end end fog-google-1.9.1/test/integration/compute/instance_groups/test_instance_templates.rb0000644000004100000410000000047213451635472031243 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/factories/instance_template_factory" class TestInstanceTemplates < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].instance_templates @factory = InstanceTemplateFactory.new(namespaced_name) end end fog-google-1.9.1/test/integration/monitoring/0000755000004100000410000000000013451635472021300 5ustar www-datawww-datafog-google-1.9.1/test/integration/monitoring/test_monitored_resource_descriptors.rb0000644000004100000410000000174513451635472031223 0ustar www-datawww-datarequire "helpers/integration_test_helper" class TestMetricDescriptors < FogIntegrationTest def setup @client = Fog::Google::Monitoring.new end def test_list_and_get resp = @client.list_monitored_resource_descriptors assert_operator(resp.resource_descriptors.size, :>, 0, "resource descriptor count should be positive") @client.get_monitored_resource_descriptor( resp.resource_descriptors.first.type ) end def test_all resp = @client.monitored_resource_descriptors.all assert_operator(resp.size, :>, 0, "resource descriptor count should be positive") end def test_get resource = "global" descriptor = @client.monitored_resource_descriptors.get(resource) assert_equal( descriptor.name, "projects/#{@client.project}/monitoredResourceDescriptors/#{resource}" ) assert_equal(descriptor.labels.size, 1) assert_equal(descriptor.labels.first[:key], "project_id") end end fog-google-1.9.1/test/integration/monitoring/test_metric_descriptors.rb0000644000004100000410000001115213451635472026570 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "helpers/client_helper" class TestMetricDescriptors < FogIntegrationTest TEST_METRIC_TYPE_PREFIX = "custom.googleapis.com/fog-google-test/test-metric-descriptors".freeze def setup @client = Fog::Google::Monitoring.new # Ensure any resources we create with test prefixes are removed Minitest.after_run do delete_test_resources end end def delete_test_resources test_resources = @client.monitoring.list_project_metric_descriptors( "projects/#{@project}", :filter => "metric.type = starts_with(\"#{TEST_METRIC_TYPE_PREFIX}\")" ) unless test_resources.metric_descriptors.nil? test_resources.metric_descriptors.each do |md| @client.monitoring.delete_project_metric_descriptors(md.name) end end rescue # Do nothing end def test_list_metric_descriptors list_resp = @client.list_metric_descriptors assert_operator(list_resp.metric_descriptors.size, :>, 0, "metric descriptor count should be positive") resp = @client.list_metric_descriptors( :filter => 'metric.type = starts_with("compute.googleapis.com")', :page_size => 5 ) assert_operator(resp.metric_descriptors.size, :<=, 5, "metric descriptor count should be <= page size 5") resp = @client.list_metric_descriptors(:page_size => 1) assert_equal(resp.metric_descriptors.size, 1, "metric descriptor count should be page size 1") next_resp = @client.list_metric_descriptors( :page_size => 1, :page_token => resp.next_page_token ) assert_equal(next_resp.metric_descriptors.size, 1, "metric descriptor count should be page size 1") assert(resp.metric_descriptors[0].name != next_resp.metric_descriptors[0].name, "paginated result should not be the same value") end def test_create_custom_metric_descriptors metric_type = "#{TEST_METRIC_TYPE_PREFIX}/test-create" label = { :key => "foo", :value_type => "INT64", :description => "test label for a metric descriptor" } options = { :metric_type => metric_type, :unit => "1", :value_type => "INT64", :description => "A custom metric descriptor for fog-google metric descriptor tests.", :display_name => "fog-google/test-metric-descriptor", :metric_kind => "GAUGE", :labels => [label] } created = @client.create_metric_descriptor(options) # Check created metric descriptor assert_equal(_full_name(metric_type), created.name) assert_equal(metric_type, created.type) assert_equal(options[:metric_kind], created.metric_kind) assert_equal(options[:value_type], created.value_type) assert_equal(options[:unit], created.unit) assert_equal(options[:description], created.description) assert_equal(options[:display_name], created.display_name) assert_equal(created.labels.size, 1, "expected 1 label, got #{created.labels.size}") label_descriptor = created.labels.first assert_equal(label[:key], label_descriptor.key) assert_equal(label[:value_type], label_descriptor.value_type) assert_equal(label[:description], label_descriptor.description) Fog.wait_for(30) do begin get_resp = @client.get_metric_descriptor(metric_type) return !get_resp.nil? rescue return false end end list_resp = @client.list_metric_descriptor(:filter => "metric.type = \"#{metric_type}\"", :page_size => 1) assert(!list_resp.metric_descriptors.nil?, "expected non-empty list request for metric descriptors") assert_empty(@client.delete_metric_descriptor(metric_type)) end def test_metric_descriptors_all descriptors = @client.metric_descriptors.all assert_operator(descriptors.size, :>, 0, "metric descriptor count should be positive") descriptors = @client.metric_descriptors.all( :filter => 'metric.type = starts_with("compute.googleapis.com")', :page_size => 5 ) assert_operator(descriptors.size, :<=, 5, "metric descriptor count should be <= page size 5") descriptors = @client.metric_descriptors.all(:page_size => 2) assert_equal(descriptors.size, 2, "metric descriptor count should be page size 2") end def test_metric_descriptors_get builtin_test_type = "compute.googleapis.com/instance/cpu/usage_time" descriptor = @client.metric_descriptors.get("compute.googleapis.com/instance/cpu/usage_time") assert_equal(descriptor.type, builtin_test_type) end def _full_name(metric_type) "projects/#{@client.project}/metricDescriptors/#{metric_type}" end end fog-google-1.9.1/test/integration/monitoring/test_coverage.rb0000644000004100000410000000043313451635472024457 0ustar www-datawww-datarequire "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:monitoring" if ENV["COVERAGE"] fog-google-1.9.1/test/integration/monitoring/test_timeseries.rb0000644000004100000410000002006213451635472025035 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "retriable" class TestMetricDescriptors < FogIntegrationTest # Retriable is used to wrap each request in this test due to Stackdriver API being slow with # metric propagation (sometimes 80+ seconds) and client returning # Google::Apis::ClientError: badRequest if the metric hasn't yet been created instead of a 404. RETRIABLE_TRIES = 3 RETRIABLE_BASE_INTERVAL = 50 TEST_METRIC_PREFIX = "custom.googleapis.com/fog-google-test/timeseries".freeze LABEL_DESCRIPTORS = [ { :key => "test_string_label", :value_type => "STRING", :description => "test string label" }, { :key => "test_bool_label", :value_type => "BOOL", :description => "test boolean label" }, { :key => "test_int_label", :value_type => "INT64", :description => "test integer label" } ].freeze def setup @client = Fog::Google::Monitoring.new # Ensure any resources we create with test prefixes are removed Minitest.after_run do _delete_test_resources end end def test_timeseries_collection metric_type = "#{TEST_METRIC_PREFIX}/test_requests" _some_custom_metric_descriptor(metric_type) start_time = Time.now labels = { :test_string_label => "foo", :test_bool_label => "false", :test_int_label => "1" } expected = _some_timeseries(start_time, metric_type, labels) resp = @client.create_timeseries(:timeseries => [expected]) assert_empty(resp.to_h) # Wait for metric to be created # TODO: Dedup retries into a helper method Retriable.retriable(on: Google::Apis::ClientError, tries: RETRIABLE_TRIES, base_interval: RETRIABLE_BASE_INTERVAL) do @client.list_timeseries( :filter => "metric.type = \"#{metric_type}\"", :interval => { # Subtracting one second because timeSeries.list API # doesn't return points that are exactly the same time # as the interval for some reason. :start_time => (start_time - 1).to_datetime.rfc3339, :end_time => Time.now.to_datetime.rfc3339 } ).time_series end series = Retriable.retriable(on: Google::Apis::ClientError, tries: RETRIABLE_TRIES, base_interval: RETRIABLE_BASE_INTERVAL) do @client.timeseries_collection.all( :filter => "metric.type = \"#{metric_type}\"", :interval => { # Subtracting one second because timeSeries.list API # doesn't return points that are exactly the same time # as the interval for some reason. :start_time => (start_time - 1).to_datetime.rfc3339, :end_time => Time.now.to_datetime.rfc3339 } ) end assert_equal(1, series.size) actual = series.first assert_equal(expected[:metric], actual.metric) assert_equal(expected[:metric_kind], actual.metric_kind) assert_equal(expected[:resource], actual.resource) assert_equal(expected[:value_type], actual.value_type) assert_equal(1, actual.points.size) assert_equal(expected[:points].first[:value], actual.points.first[:value]) end def test_multiple_timeseries metric_type = "#{TEST_METRIC_PREFIX}/test_multiple" _some_custom_metric_descriptor(metric_type) start_time = Time.now metric_labels = [ { :test_string_label => "first", :test_bool_label => "true", :test_int_label => "1" }, { :test_string_label => "second", :test_bool_label => "false", :test_int_label => "2" } ] timeseries = metric_labels.map do |labels| _some_timeseries(start_time, metric_type, labels) end Retriable.retriable(on: Google::Apis::ServerError, tries: RETRIABLE_TRIES, base_interval: RETRIABLE_BASE_INTERVAL) do @client.create_timeseries(:timeseries => timeseries) end interval = { # Subtracting one second because timeSeries.list API # doesn't return points that are exactly the same time # as the interval for some reason. :start_time => (start_time - 1).to_datetime.rfc3339, :end_time => Time.now.to_datetime.rfc3339 } # Wait for metric to be created # Retriable is used instead of wait_for due to API client returning Google::Apis::ClientError: badRequest if the # metric hasn't yet been created Retriable.retriable(on: Google::Apis::ClientError, tries: RETRIABLE_TRIES, base_interval: RETRIABLE_BASE_INTERVAL) do @client.list_timeseries( :filter => "metric.type = \"#{metric_type}\"", :interval => interval ).time_series end # Test page size resp = Retriable.retriable(on: Google::Apis::ClientError, tries: RETRIABLE_TRIES, base_interval: RETRIABLE_BASE_INTERVAL) do @client.list_timeseries( :filter => "metric.type = \"#{metric_type}\"", :interval => interval, :page_size => 1 ) end assert_equal(resp.time_series.size, 1, "expected timeseries count to be equal to page size 1") next_resp = @client.list_timeseries( :filter => "metric.type = \"#{metric_type}\"", :interval => interval, :page_size => 1, :page_token => resp.next_page_token ) assert_equal(next_resp.time_series.size, 1, "expected timeseries count to be equal to page size 1") labels = resp.time_series.first.metric.labels labels_next = next_resp.time_series.first.metric.labels assert(labels != labels_next, "expected different timeseries when using page_token") # Test filter series = Retriable.retriable(on: Google::Apis::ClientError, tries: RETRIABLE_TRIES, base_interval: RETRIABLE_BASE_INTERVAL) do @client.timeseries_collection.all( :filter => %[ metric.type = "#{metric_type}" AND metric.label.test_string_label = "first" ], :interval => interval ) end assert_equal(series.size, 1, "expected returned timeseries to be filtered to 1 value") assert_equal("true", series.first.metric[:labels][:test_bool_label]) assert_equal("1", series.first.metric[:labels][:test_int_label]) end def _delete_test_resources list_resp = @client.monitoring.list_project_metric_descriptors( "projects/#{@client.project}", filter: "metric.type = starts_with(\"#{TEST_METRIC_PREFIX}\")" ) unless list_resp.metric_descriptors.nil? list_resp.metric_descriptors.each do |md| @client.monitoring.delete_project_metric_descriptor(md.name) end end rescue # Do nothing end def _some_custom_metric_descriptor(metric_type) # Create custom metric to write test timeseries for. @client.create_metric_descriptor( :labels => LABEL_DESCRIPTORS, :metric_type => metric_type, :unit => "1", :value_type => "INT64", :description => "A custom metric descriptor for fog-google timeseries test.", :display_name => "fog-google-test/#{metric_type}", :metric_kind => "GAUGE" ) # Wait for metric descriptor to be created Fog.wait_for(180, 2) do begin @client.get_metric_descriptor(metric_type) true rescue false end end end def _some_timeseries(start_time, metric_type, labels) { :metric => { :type => metric_type, :labels => labels }, :resource => { :type => "global", :labels => { :project_id => @client.project } }, :metric_kind => "GAUGE", :value_type => "INT64", :points => [ { :interval => { :end_time => start_time.to_datetime.rfc3339, :start_time => start_time.to_datetime.rfc3339 }, :value => { :int64_value => rand(10) } } ] } end end fog-google-1.9.1/test/integration/test_authentication.rb0000644000004100000410000000320413451635472023515 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_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_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_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-1.9.1/test/integration/storage/0000755000004100000410000000000013451635472020557 5ustar www-datawww-datafog-google-1.9.1/test/integration/storage/test_files.rb0000644000004100000410000001157213451635472023253 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/storage/storage_shared" require "securerandom" require "base64" require "tempfile" class TestStorageRequests < StorageShared def test_files_create_file file_name = new_object_name @client.directories.get(some_bucket_name).files.create( :key => file_name, :body => some_temp_file ) object = @client.get_object(some_bucket_name, file_name) assert_equal(object[:body], temp_file_content) end def test_files_create_string expected_body = "A file body" file_name = new_object_name @client.directories.get(some_bucket_name).files.create( :key => file_name, :body => expected_body ) object = @client.get_object(some_bucket_name, file_name) assert_equal(object[:body], expected_body) end def test_files_create_predefined_acl @client.directories.get(some_bucket_name).files.create( :key => new_object_name, :body => some_temp_file, :predefined_acl => "publicRead" ) end def test_files_create_invalid_predefined_acl assert_raises(ArgumentError) do @client.directories.get(some_bucket_name).files.create( :key => new_object_name, :body => some_temp_file, :predefined_acl => "invalidAcl" ) end end def test_files_get content = @client.directories.get(some_bucket_name).files.get(some_object_name) assert_equal(content.body, temp_file_content) end def test_files_set_body_string file_name = new_object_name directory = @client.directories.get(some_bucket_name) file = directory.files.create( :key => file_name, :body => temp_file_content ) assert_equal(file.body, temp_file_content) new_body = "Changed file body" file.body = new_body file.save updated_file = directory.files.get(file_name) assert_equal(updated_file.body, new_body) end def test_files_set_body_file file_name = new_object_name directory = @client.directories.get(some_bucket_name) file = directory.files.create( :key => file_name, :body => some_temp_file ) new_body = "Changed file body" file.body = new_body file.save updated_file = directory.files.get(file_name) assert_equal(updated_file.body, new_body) end def test_files_metadata content = @client.directories.get(some_bucket_name).files.metadata(some_object_name) assert_equal(content.content_length, temp_file_content.length) assert_equal(content.key, some_object_name) end def test_files_destroy file_name = new_object_name @client.directories.get(some_bucket_name).files.create( :key => file_name, :body => some_temp_file ) @client.directories.get(some_bucket_name).files.destroy(file_name) assert_nil(@client.directories.get(some_bucket_name).files.get(file_name)) end def test_files_all file_name = new_object_name @client.directories.get(some_bucket_name).files.create( :key => file_name, :body => some_temp_file ) result = @client.directories.get(some_bucket_name).files.all if result.nil? raise StandardError.new("no files found") end unless result.any? { |file| file.key == file_name } raise StandardError.new("failed to find expected file") end end def test_files_each file_name = new_object_name @client.directories.get(some_bucket_name).files.create( :key => file_name, :body => some_temp_file ) found_file = false @client.directories.get(some_bucket_name).files.each do |file| if file.key == file_name found_file = true end end assert_equal(true, found_file, "failed to find expected file while iterating") end def test_files_copy target_object_name = new_object_name @client.directories.get(some_bucket_name).files.get(some_object_name).copy(some_bucket_name, target_object_name) content = @client.directories.get(some_bucket_name).files.get(target_object_name) assert_equal(content.body, temp_file_content) end def test_files_public_url url = @client.directories.get(some_bucket_name).files.get(some_object_name).public_url assert_match(/storage.googleapis.com/, url) end def test_files_get_https_url directory = @client.directories.get(some_bucket_name) https_url = directory.files.get_https_url("fog-testfile", (Time.now + 60).to_i) assert_match(/https/, https_url) assert_match(/#{bucket_prefix}/, https_url) assert_match(/fog-testfile/, https_url) end def test_files_get_https_url_whitespace directory = @client.directories.get(some_bucket_name) https_url = directory.files.get_https_url("fog -testfile", (Time.now + 60).to_i) assert_match(/https/, https_url) assert_match(/#{bucket_prefix}/, https_url) assert_match(/fog\%20-testfile/, https_url) end end fog-google-1.9.1/test/integration/storage/test_coverage.rb0000644000004100000410000000043013451635472023733 0ustar www-datawww-datarequire "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:storage" if ENV["COVERAGE"] fog-google-1.9.1/test/integration/storage/storage_shared.rb0000644000004100000410000000511413451635472024077 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/pubsub/pubsub_shared" require "securerandom" require "base64" require "tempfile" class StorageShared < FogIntegrationTest def setup @client = Fog::Storage::Google.new # Enable retries during the suite. This prevents us from # having to manually rate limit our requests. ::Google::Apis::RequestOptions.default.retries = 5 # Ensure any resources we create with test prefixes are removed Minitest.after_run do delete_test_resources ::Google::Apis::RequestOptions.default.retries = 0 end end def delete_test_resources unless @some_temp_file.nil? @some_temp_file.unlink end buckets_result = @client.list_buckets unless buckets_result.items.nil? begin buckets_result.items .map(&:name) .select { |t| t.start_with?(bucket_prefix) } .each do |t| object_result = @client.list_objects(t) unless object_result.items.nil? object_result.items.each { |object| @client.delete_object(t, object.name) } end begin @client.delete_bucket(t) # Given that bucket operations are specifically rate-limited, we handle that # by waiting a significant amount of time and trying. rescue Google::Apis::RateLimitError Fog::Logger.warning("encountered rate limit, backing off") sleep(10) @client.delete_bucket(t) end end # We ignore errors here as list operations may not represent changes applied recently. rescue Google::Apis::Error Fog::Logger.warning("ignoring Google Api error during delete_test_resources") end end end def bucket_prefix "fog-integration-test" end def object_prefix "fog-integration-test-object" end def new_bucket_name "#{bucket_prefix}-#{SecureRandom.uuid}" end def new_object_name "#{object_prefix}-#{SecureRandom.uuid}" end def some_bucket_name # create lazily to speed tests up @some_bucket ||= new_bucket_name.tap do |t| @client.put_bucket(t) end end def some_object_name # create lazily to speed tests up @some_object ||= new_object_name.tap do |t| @client.put_object(some_bucket_name, t, some_temp_file) end end def temp_file_content "hello world" end def some_temp_file @some_temp_file ||= Tempfile.new("fog-google-storage").tap do |t| t.write(temp_file_content) t.close end File.open(@some_temp_file.path, "r") end end fog-google-1.9.1/test/integration/storage/test_directories.rb0000644000004100000410000000336613451635472024467 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/storage/storage_shared" require "securerandom" require "base64" require "tempfile" class TestStorageRequests < StorageShared def test_directories_put dir_name = new_bucket_name directory = @client.directories.create(:key => dir_name) assert_equal(directory.key, dir_name) end def test_directories_put_predefined_acl @client.directories.create( :key => new_bucket_name, :predefined_acl => "publicRead" ) end def test_directories_put_invalid_predefined_acl assert_raises(Google::Apis::ClientError) do @client.directories.create( :key => new_bucket_name, :predefined_acl => "invalidAcl" ) end end def test_directories_get directory = @client.directories.get(some_bucket_name) assert_equal(directory.key, some_bucket_name) end def test_directory_files file = @client.directories.get(some_bucket_name).files.get(some_object_name) assert_equal(some_object_name, file.key) end def test_directory_public_url url = @client.directories.get(some_bucket_name).public_url assert_match(/storage.googleapis.com/, url) end def test_directories_destroy dir_name = new_bucket_name @client.directories.create(:key => dir_name) @client.directories.destroy(dir_name) assert_nil(@client.directories.get(dir_name)) end def test_directories_all dir_name = new_bucket_name @client.directories.create(:key => dir_name) result = @client.directories.all if result.nil? raise StandardError.new("no directories found") end unless result.any? { |directory| directory.key == dir_name } raise StandardError.new("failed to find expected directory") end end end fog-google-1.9.1/test/integration/storage/test_buckets.rb0000644000004100000410000000625713451635472023615 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/storage/storage_shared" require "securerandom" require "base64" require "tempfile" class TestStorageRequests < StorageShared def test_put_bucket bucket_name = new_bucket_name bucket = @client.put_bucket(bucket_name) assert_equal(bucket.name, bucket_name) end # We cannot test the state of the ACL as there are two cases to consider # * The authenticated service account has Owner permisions, which allows # it to read the ACLs after the predefined ACL is applied. # * The authenticated service account does not have Owner permissions, # then, we cannot read the ACLs after the predefined ACL is applied. # # As we cannot control the service account used for testing, we'll # just ensure that a valid operation succeeds and an invalid operation fails. def test_put_bucket_predefined_acl @client.put_bucket(new_bucket_name, :predefined_acl => "publicRead") end def test_put_bucket_invalid_predefined_acl assert_raises(Google::Apis::ClientError) do @client.put_bucket(new_bucket_name, :predefined_acl => "invalidAcl") end end def test_get_bucket bucket = @client.get_bucket(some_bucket_name) assert_equal(bucket.name, some_bucket_name) end def test_delete_bucket # Create a new bucket to delete it bucket_to_delete = new_bucket_name @client.put_bucket(bucket_to_delete) @client.delete_bucket(bucket_to_delete) assert_raises(Google::Apis::ClientError) do @client.get_bucket(bucket_to_delete) end end def test_list_buckets # Create a new bucket to ensure at least one exists to find bucket_name = new_bucket_name @client.put_bucket(bucket_name) result = @client.list_buckets if result.items.nil? raise StandardError.new("no buckets found") end contained = result.items.any? { |bucket| bucket.name == bucket_name } assert_equal(true, contained, "expected bucket not present") end def test_put_bucket_acl bucket_name = new_bucket_name @client.put_bucket(bucket_name) acl = { :entity => "allUsers", :role => "READER" } @client.put_bucket_acl(bucket_name, acl) end def test_list_bucket_acl bucket_name = new_bucket_name @client.put_bucket(bucket_name) acl = { :entity => "allUsers", :role => "READER" } @client.put_bucket_acl(bucket_name, acl) result = @client.list_bucket_acl(bucket_name) if result.items.nil? raise StandardError.new("no bucket access controls found") end contained = result.items.any? do |control| control.entity == acl[:entity] && control.role == acl[:role] end assert_equal(true, contained, "expected bucket access control not present") end def test_get_bucket_acl bucket_name = new_bucket_name @client.put_bucket(bucket_name) acl = { :entity => "allUsers", :role => "READER" } @client.put_bucket_acl(bucket_name, acl) result = @client.get_bucket_acl(bucket_name, "allUsers") if result.nil? raise StandardError.new("no bucket access control found") end assert_equal(result.role, acl[:role], "incorrect bucket access control role") end end fog-google-1.9.1/test/integration/storage/test_objects.rb0000644000004100000410000001322713451635472023601 0ustar www-datawww-datarequire "helpers/integration_test_helper" require "integration/storage/storage_shared" require "securerandom" require "base64" require "tempfile" class TestStorageRequests < StorageShared def test_put_object_string object_name = new_object_name @client.put_object(some_bucket_name, object_name, some_temp_file) object = @client.get_object(some_bucket_name, object_name) assert_equal(object_name, object[:name]) assert_equal(temp_file_content, object[:body]) end def test_put_object_nil assert_raises(ArgumentError) do @client.put_object(some_bucket_name, new_object_name, nil) end end def test_put_object_file object_name = new_object_name expected_body = "A file body" @client.put_object(some_bucket_name, object_name, expected_body) object = @client.get_object(some_bucket_name, object_name) assert_equal(object_name, object[:name]) assert_equal(expected_body, object[:body]) end def test_put_object_paperclip object_name = new_object_name paperclip_file = OpenStruct.new(:path => some_temp_file, :content_type => "image/png") @client.put_object(some_bucket_name, object_name, paperclip_file, :content_type => "image/png") object = @client.get_object(some_bucket_name, object_name) assert_equal(object_name, object[:name]) assert_equal("image/png", object[:content_type]) end def test_put_object_contradictory_content_type object_name = new_object_name file = OpenStruct.new(:path => some_temp_file, :content_type => "text/plain") @client.put_object(some_bucket_name, object_name, file, :content_type => "image/png") object = @client.get_object(some_bucket_name, object_name) assert_equal(object_name, object[:name]) assert_equal("image/png", object[:content_type]) end def test_put_object_predefined_acl @client.put_object(some_bucket_name, new_object_name, some_temp_file, :predefined_acl => "publicRead") end def test_put_object_invalid_predefined_acl assert_raises(Google::Apis::ClientError) do @client.put_object(some_bucket_name, new_object_name, some_temp_file, :predefined_acl => "invalidAcl") end end def test_get_object object = @client.get_object(some_bucket_name, some_object_name) assert_equal(temp_file_content, object[:body]) end def test_delete_object object_name = new_object_name @client.put_object(some_bucket_name, object_name, some_temp_file) @client.delete_object(some_bucket_name, object_name) assert_raises(Google::Apis::ClientError) do @client.get_object(some_bucket_name, object_name) end end def test_object_metadata object = @client.get_object_metadata(some_bucket_name, some_object_name) assert_equal(temp_file_content.length, object.size) assert_equal(some_bucket_name, object.bucket) end def test_copy_object target_object_name = new_object_name @client.copy_object(some_bucket_name, some_object_name, some_bucket_name, target_object_name) object = @client.get_object(some_bucket_name, target_object_name) assert_equal(temp_file_content, object[:body]) end def test_list_objects expected_object = some_object_name result = @client.list_objects(some_bucket_name) if result.items.nil? raise StandardError.new("no objects found") end contained = result.items.any? { |object| object.name == expected_object } assert_equal(true, contained, "expected object not present") end def test_put_object_acl object_name = new_object_name @client.put_object(some_bucket_name, object_name, some_temp_file) acl = { :entity => "allUsers", :role => "READER" } @client.put_object_acl(some_bucket_name, object_name, acl) end def test_list_object_acl object_name = new_object_name acls = [ { :entity => "allUsers", :role => "READER" }, { :entity => "allAuthenticatedUsers", :role => "READER" } ] @client.put_object(some_bucket_name, object_name, some_temp_file, :acl => acls) result = @client.list_object_acl(some_bucket_name, object_name) if result.items.nil? raise StandardError.new("no object access controls found") end assert_operator(acls.length, :<=, result.items.length, "expected at least #{acls.length} ACL items") expected_acls = Hash[acls.map { |acl| [acl[:entity], acl[:role]] }] num_found = 0 result.items.each do |actual_acl| if expected_acls[actual_acl.entity] == actual_acl.role num_found += 1 end end assert_equal(acls.length, num_found, "only found #{num_found} of #{acls.length} expected ACLs") end def test_get_object_acl object_name = new_object_name @client.put_object(some_bucket_name, object_name, some_temp_file) data = { :entity => "allUsers", :role => "READER" } @client.put_object_acl(some_bucket_name, object_name, data) result = @client.get_object_acl(some_bucket_name, object_name, "allUsers") if result.nil? raise StandardError.new("expected object access control not found") end end def test_get_object_https_url result = @client.get_object_https_url(some_bucket_name, some_object_name, 0) assert_operator(result.length, :>, 0) end def test_get_object_http_url result = @client.get_object_http_url(some_bucket_name, some_object_name, 0) assert_operator(result.length, :>, 0) end def test_put_object_url result = @client.put_object_url(some_bucket_name, new_object_name, 0) assert_operator(result.length, :>, 0) end end fog-google-1.9.1/.codecov.yml0000644000004100000410000000003713451635472016034 0ustar www-datawww-datacodecov: bot: fog-google-bot fog-google-1.9.1/README.md0000644000004100000410000001442113451635472015072 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) [![codecov](https://codecov.io/gh/fog/fog-google/branch/master/graph/badge.svg)](https://codecov.io/gh/fog/fog-google) [![Doc coverage](https://inch-ci.org/github/fog/fog-google.svg?branch=master)](https://inch-ci.org/github/fog/fog-google) The main maintainers for the Google sections are @icco, @Temikus and @plribeiro3000. Please send pull requests to them. ## Important notices - As of **v1.0.0**, fog-google includes google-api-client as a dependency, there is no need to include it separately anymore. - Fog-google is currently supported on Ruby 2.3+ See [supported ruby versions](#supported-ruby-versions) for more info. See **[MIGRATING.md](MIGRATING.md)** for migration between major versions. ## 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://cloud.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://cloud.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://cloud.google.com/compute/docs/reference/v1/) of the GCE API. As of 2017-12-15, we are still working on making Fog for Google Compute engine (`Fog::Compute::Google`) 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 [v1beta4](https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/) of the Google Cloud SQL Admin API. As of 2017-11-06, Cloud SQL is mostly feature-complete. Please [file issues](https://github.com/fog/fog-google/issues) for any anomalies you see or features you would like as we finish adding remaining features. ## 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 [v3](https://cloud.google.com/monitoring/api/v3/) of the Google Cloud Monitoring API. As of 2017-10-05, we believe Fog for Google Cloud Monitoring is feature complete for metric-related resources and are working on supporting groups. 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 Fog mostly implements [v1](https://cloud.google.com/pubsub/docs/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' ``` And then execute: ```shell $ bundle ``` Or install it yourself as: ```shell $ gem install fog-google ``` ## Testing Integration tests can be kicked off via following rake tasks. **Important note:** As those tests are running against real API's YOU WILL BE BILLED. ``` rake test # Run all integration tests rake test:parallel # Run all integration tests in parallel rake test:compute # Run Compute API tests rake test:monitoring # Run Monitoring API tests rake test:pubsub # Run PubSub API tests rake test:sql # Run SQL API tests rake test:storage # Run Storage API tests ``` Since some resources can be expensive to test, we have a self-hosted CI server. Due to security considerations a repo maintainer needs to add the label `integrate` to kick off the CI. ## 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 ``` As of `1.9.0` fog-google supports Google [application default credentials (ADC)](https://cloud.google.com/docs/authentication/production) The auth method uses [Google::Auth.get_application_default](https://www.rubydoc.info/gems/googleauth/0.6.7/Google%2FAuth.get_application_default) under the hood. Example workflow for a GCE instance with [service account scopes](https://cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances) defined: ``` > connection = Fog::Compute::Google.new(:google_project => "my-project", :google_application_default => true) => # connection.servers => [ require 'fog/google' => true [2] pry(main)> connection = Fog::Compute::Google.new [3] pry(main)> connection.servers => [ ["test:compute", "test:monitoring", "test:pubsub", "test:sql", "test:storage"] Rake::TestTask.new do |t| t.name = "unit" t.description = "Run Unit tests" t.libs << "test" t.pattern = FileList["test/unit/**/test_*.rb"] t.warning = false t.verbose = true end # This autogenerates rake tasks based on test folder structures # This is done to simplify running many test suites in parallel COMPUTE_TEST_TASKS = [] Dir.glob("test/integration/compute/**").each do |task| suite_collection = task.gsub(/test\/integration\/compute\//, "") component_name = task.gsub(/test\/integration\//, "").split("/").first Rake::TestTask.new(:"#{component_name}-#{suite_collection}") do |t| t.libs << "test" t.description = "Autotask - run #{component_name} integration tests - #{suite_collection}" t.pattern = FileList["test/integration/#{component_name}/#{suite_collection}/test_*.rb"] t.warning = false t.verbose = true end COMPUTE_TEST_TASKS << "#{component_name}-#{suite_collection}" end desc "Run Compute API tests" task :compute => COMPUTE_TEST_TASKS desc "Run Compute API tests in parallel" multitask :compute_parallel => COMPUTE_TEST_TASKS Rake::TestTask.new do |t| t.name = "monitoring" t.description = "Run Monitoring API tests" t.libs << "test" t.pattern = FileList["test/integration/monitoring/test_*.rb"] t.warning = false t.verbose = true end Rake::TestTask.new do |t| t.name = "pubsub" t.description = "Run PubSub API tests" t.libs << "test" t.pattern = FileList["test/integration/pubsub/test_*.rb"] t.warning = false t.verbose = true end # This autogenerates rake tasks based on test folder structures # This is done to simplify running many test suites in parallel SQL_TEST_TASKS = [] Dir.glob("test/integration/sql/**").each do |task| suite_collection = task.gsub(/test\/integration\/sql\//, "") component_name = task.gsub(/test\/integration\//, "").split("/").first Rake::TestTask.new(:"#{component_name}-#{suite_collection}") do |t| t.libs << "test" t.description = "Autotask - run #{component_name} integration tests - #{suite_collection}" t.pattern = FileList["test/integration/#{component_name}/#{suite_collection}/test_*.rb"] t.warning = false t.verbose = true end SQL_TEST_TASKS << "#{component_name}-#{suite_collection}" end desc "Run SQL API tests" task :compute => SQL_TEST_TASKS desc "Run SQL API tests in parallel" multitask :compute_parallel => SQL_TEST_TASKS Rake::TestTask.new do |t| t.name = "sql" t.description = "Run SQL API tests" t.libs << "test" t.pattern = FileList["test/integration/sql/test_*.rb"] t.warning = false t.verbose = true end Rake::TestTask.new do |t| t.name = "storage" t.description = "Run Storage API tests" t.libs << "test" t.pattern = FileList["test/integration/storage/test_*.rb"] t.warning = false t.verbose = true end end fog-google-1.9.1/tasks/changelog.rake0000644000004100000410000000132313451635472017530 0ustar www-datawww-datarequire "fileutils" # Helper method to insert text after a line that matches the regex def insert_after_line(file, insert, regex = /^## Next/) tempfile = File.open("#{file}.tmp", "w") f = File.new(file) f.each do |line| tempfile << line next unless line =~ regex tempfile << "\n" tempfile << insert tempfile << "\n" end f.close tempfile.close FileUtils.mv("#{file}.tmp", file) end # Extracts all changes that have been made after the latest pushed tag def changes_since_last_tag `git --no-pager log $(git describe --tags --abbrev=0)..HEAD --oneline` end namespace :changelog do task :generate do insert_after_line("CHANGELOG.md", changes_since_last_tag, /^## Next/) end end fog-google-1.9.1/tasks/bundler.rake0000644000004100000410000000015113451635472017232 0ustar www-datawww-data# This installs the tasks that help with gem creation and # publishing. Bundler::GemHelper.install_tasks fog-google-1.9.1/tasks/console.rake0000644000004100000410000000067213451635472017251 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-1.9.1/LICENSE.md0000644000004100000410000000220013451635472015207 0ustar www-datawww-dataThe MIT License (MIT) Copyright (c) 2014-2018 [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-1.9.1/.fog.example0000644000004100000410000000200513451635472016014 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_json_key_location: /path/to/my-project-xxxxxxxxxxxx.json # You can also provide service account credentials with `google_json_key_string` # 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-1.9.1/CHANGELOG.md0000644000004100000410000002540413451635472015427 0ustar www-datawww-data# Changelog All notable changes to this project will be documented in this file. The format is loosely based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). This project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). ## Next ## 1.9.1 ### User-facing #### Fixed - \#448 Add `:google_application_default` as recognized argument in Fog::Compute::Google client [mavin] ### Development changes #### Added - \#449 Add a helper rake task to populate changelog [temikus] ## 1.9.0 ### User-facing #### Added - \#442 Add support for Application Default credentials [mavin] - This change allows the use of Application Default Credentials so that end users can authenticate without a service account for development, testing, and one-off interactions by using `:google_application_default`client option. See README for more details. ### Fixed - \#444 Remove deprecated `google_client_email` option from client parameters [temikus] - \#446 Updating service parameters to avoid "unrecognised parameter" warnings when initializing Fog client with application default auth [temikus] ### Development changes #### Fixed - \#441 Update CI pipeline to Concourse V4 [temikus] - \#444 Rework client authentication workflow [temikus] - Separate different auth streams into private helper methods - Add a fallback auth option - Google Application Default credentials - Minor fixes and performance optimizations ## 1.8.2 ### User-facing #### Added - \#435 Added additional examples for attached disks usage. [temikus] #### Fixed - \#433 Allow the api to close Tempfiles inline, improving disk utilization. [itopalov] ### Development changes #### Added - \#425 Integration on Jruby + disk snapshot tests: [temikus] - Adding JRuby 9.1 into Travis - Added integration tests for disk snapshots #### Fixed - \#432 Relax fog-json constraint to minor version. [pravi] - \#425 Miscellaneous dev improvements around JRuby and disk handling: [temikus] - Fix bundling in development environment on JRuby - Remove EOL versions of ruby from Travis - Consolidated logic of `Disk.get_as_boot_disk` and increase doc coverage of disk-associated methods. - Add a guard a guard method for `Snapshot.add_labels` ## 1.8.1 ### User-facing #### Fixed - \#428 Relax fog-core lower version constraint for ManageIQ [temikus] ## 1.8.0 ### User-facing #### Added - \#418 Reintroduce client options for proxy support, etc. [AlexanderZagaynov] #### Fixed - \#419 Locked down fog upstream dependencies to alleviate deprecation warnings until they can be properly dealt with. [temikus] - \#400 Small `%Collection%.get` and `%Collection%.all` behaviour fixes [temikus] - `Fog::Google::SQL::Instances.get(nil)` no longer returns an invalid `sql#instancesList` object. - `Fog::Compute::Google::InstanceGroups.get` and `.all` methods now support more than just `:filter` option, fixed `.all` output without `zone` option. - Fix a typo causing `Operations.get(region:REGION)` to fail. - `Fog::Compute::Google::Images.get(IMAGE, PROJECT)`, now returns `nil` if image is not found rather than throwing `Google::Apis::ClientError`. ### Development changes #### Added - \#400 Additional test coverage [temikus] - Expanded tests for `%Collection%.get` behavior - scoped requests (e.g. `get(zone:ZONE)`) and their corresponding code paths are now also properly tested. - Increase `Fog::Compute::Google::Images` integration test coverage. - Unit tests now work without a `~/.fog` config file set up. - Expanded unit test coverage. - \#424 Add simple integration tests to check client proxy options being applied. #### Changed - \#400 Refactored most compute `get()` and `all()` methods to common format. [temikus] #### Fixed - \#400 Removed the Travis Ruby 2.5 workaround. [temikus] ## 1.7.1 ### User-facing #### Fixed - \#412 Fixed `Fog::Storage::GoogleXML::GetObjectHttpUrl#get_object_http_url` request ## 1.7.0 ### User-facing #### Added - \#409 Support query parameters in `Fog::Storage::Google` GET requests [stanhu] - \#394 Add some helper methods to `Fog::Compute::Google::Server` [temikus] - `.private_ip_address` - `.stopped?` - \#375 Add timeout options to `Fog::Storage::GoogleJSON` client [dosuken123] #### Changed - \#394 `save/update/destroy` and other operations now wait until they are in a DONE state, instead of !PENDING. This should be a no-op for users but should safeguard from issues in the future. [temikus] - \#383 `Fog::Compute::Google::Address` resources are now created synchronously by default. [temikus] ### Development changes #### Added - \#409 Expand `Fog::Storage::Google` unit tests [stanhu] - \#370 Introducing test coverage back, integrating with codecov.io [temikus] - \#373 Increase integration test coverage. [temikus] - Add Firewall factory and tests. - Add InstanceGroup factory and tests. - Add MachineType tests. - \#376 Add doc coverage tracking. [temikus] - \#383 Increase integration test coverage further. [temikus] - Add collection tests and factories (when mutable) for following resources: - Addresses - Disks - Projects - Routes - Operations - Networks - Subnetworks - Fix compute tests Rake task. - Remove old tests and helpers for Disk, Addresses and Networks. - \#394 Improve `Server` model test coverage + miscellaneous improvements. [temikus] - Add source_image parameter to `DiskFactory` so the Servers factory creates properly running instances. - `CollectionFactory.cleanup` method is now cleaning up resources per-suite instead of using a global prefix. - Add new test formatter improving observability of CI logs. - Add debug logs to test. - Improve doc coverage. ## 1.6.0 ### User-facing #### Changed - \#338 `Fog::Google::SQL` resources are now created and destroyed synchronously by default. You can override it in a standard manner by passing a parameter to async method, e.g.: `Fog::Google::SQL::Instance.create(true)` [temikus] - \#367 `Fog::Compute::Google::Server.bootstrap` changes [temikus] - Now creates instances with disks that automatically delete on instance shutdown. - Now creates instances with a public IP address by default. #### Added - \#361 `Fog::Compute::Google::Server` now recognises `network_ip` attribute to specify internal IP. [mattimatti] #### Fixed - \#338 Fixed SQL Users model workflow [temikus] - \#359 Fix whitespace escaping in XML Storage methods [temikus] - \#366 Fixing `Server` model to properly accept `:private_key_path` and `:public_key_path` attributes again. [temikus] - \#367 `Fog::Compute::Google::Server.bootstrap` parameters are now properly merged with default ones. [tesmikus] ### Development changes #### Added - \#338 Major refactor of SQLv1 and SQLv2 tests + a lot of small test fixes/improvements (see PR/commit messages for full set of changes) [temikus] #### Fixed - \#363 Fixed flaky Monitoring tests [temikus] ## 1.5.0 ### User-facing - \#348 Added Instance Group Manager and Instance Templates [bpaquet] - `Fog::Compute::Google::InstanceGroupManager` model and associated requests: - `:get_instance_group_manager` - `:insert_instance_group_manager` - `:delete_instance_group_manager` - `:list_instance_group_managers` - `:list_aggregated_instance_group_managers` - `:recreate_instances` - `:abandon_instances` - `Fog::Compute::Google::InstanceTemplate` model and associated requests: - `:list_instance_templates` - `:get_instance_template` - `:insert_instance_template` - `:delete_instance_template` - `:set_instance_template` #### Fixed - \#356 Hotfix - removing buggy deprecated 'google-containers' project, causing 403 errors on `images.all` call. [tumido] ### Development changes #### Added - \#350 Added InstanceGroupManager and InstanceTemplate integration tests [temikus] ## 1.4.0 ### User-facing #### Added - \#336 `Fog::Compute::Google::Server.set_metadata` is now working properly and adopted a simpler format, e.g. `{'foo' => 'bar', 'baz'=>'foo'}` - \#334 Added a new helper method: `Fog::Compute::Google::Server.public_ip_address` [temikus] - \#314 Added `Fog::Compute::Google::InstanceGroup.add_instance` method back [temikus] - \#326 Added support for using predefined ACLs, refactor valid ACLs [vimutter] - \#318 Added fog_public support in Storage JSON API [jayhsu21] #### Fixed - \#354 Bump Google API client to 0.23 [temikus] - \#346 Fixed get_health when called with an instance name [bpaquet] - \#317 Fixed source_image selection to get the image from name if the format is not compatible with new Google API Client [temikus] - \#321 Fix string key instead of symbol for subnetworks listing [tumido] - \#351 Fixed trailing spaces and added data presence check to `Fog::Storage::GoogleJSON.put_object` [vimutter] ### Development changes #### Added - \#353 Added collection/model unit tests to be run by Travis CI [temikus] - \#347 Added target pool tests [temikus] #### Fixed - \#322 Fixed all broken integration tests, all tests now pass in CI [temikus] - \#344 Updated CI pipeline to run in parallel, broke out test tasks [temikus] ## 1.0.1 \#290 - Fixes paperclip integration \#288 - Fixes typo in server network code ## 1.0.0 1.0.0!!!!!!!!!!!! This rewrites everything except for the legacy storage backend! Shoutout to @emilymye, @Temikus, @DawidJanczak, @Everlag and everyone who has been asking for this for ~forever. We did this major refactor because as of version 0.9, google-api-client rewrote their entire api, thus limiting our ability to integrate with google APIs, and also running into a bunch of deprecated gem collisions. You no longer need to require google-api-client, we are now doing that for you. HELP: We need help testing. Please report bugs! As this is a complete rewrite of the request layer, there are undoubetedly bugs. We had to throw away most of our tests, and due to the time this has taken us, we chose to ship, instead of writing tests for everything all over again. If you would like to write tests, we would love your PRs, as well as any ideas you have about how we can test this code better. Thanks! ## 0.6.0 NOTE: New Monitoring models are not compatible in any way to old ones because of significant rewrite to monitoring api since v2beta2. ## 0.5.5 Adds support for SSL certificates, https proxies and global IP addresses: #244 ## 0.5.4 Fixes a storage bug #224 and fixes an issue with compute snapshots #240 ## 0.5.3 Fixes a bunch of bugs and adds subnetworks support. PRs that change functionality: #212, #215, #203, #198, #201, #221, #222, #216 ## 0.5.2 Rapid-releasing 0.5.2 due to regression fixed by #190 still present in v0.5.1 We encourage people using 0.5.1 to upgrade. ## Template to use ### User-facing #### Changed #### Added #### Fixed ### Development changes #### Added #### Fixedfog-google-1.9.1/.rubocop.yml0000644000004100000410000001745213451635472016074 0ustar www-datawww-data# Fog custom enforced styles Metrics/LineLength: Enabled: false Style/ConditionalAssignment: SingleLineConditionsOnly: true EnforcedStyle: assign_inside_condition Style/RedundantReturn: Enabled: false Style/FormatString: Enabled: false Style/RegexpLiteral: Enabled: false #TODO: this needs to be adressed not through the linter Style/FrozenStringLiteralComment: Enabled: false Style/MutableConstant: Enabled: false Style/HashSyntax: EnforcedStyle: no_mixed_keys # Do not enforce %i syntax Style/SymbolArray: Enabled: false # HoundCI config AllCops: Exclude: - "vendor/**/*" - "db/schema.rb" UseCache: false TargetRubyVersion: 2.3 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 Layout/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: leading SupportedStyles: - leading - trailing Naming/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 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": "()" Naming/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: true Naming/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/LiteralInInterpolation: Description: Checks for literals used in interpolation. Enabled: false fog-google-1.9.1/CONTRIBUTORS.md0000644000004100000410000000731413451635472016075 0ustar www-datawww-dataWith also previous help from unnamed Google employees and [Fog contributors](https://github.com/fog/fog/blob/master/CONTRIBUTORS.md) * Akshay Moghe * Alessio Caiazza * Alex Coomans * Alexander Kolesen * Alexander Lomov * Alexander Stuart-Kregor * Andrew Leonard * Antonio <0x414f@gmail.com> * Ariel Zavala * Artem Yakimenko * Benson Kalahar * Bertrand Paquet * Bob Lail and Luke Booth * Brett Porter * Brian D. Burns * Carlos Sanchez * Chris Gianelloni * Dan Prince * Daniel Broudy * Daniel van Gils * David Salgado * Dawid Janczak * Dean Putney * Dean Putney * Dima * Doug Henderson * Emily Ye * Eric Johnson * Ervin Weber * Ferran Rodenas * Frederick Cheung * Imri Zvik * Isaac Hollander McCreery * Isaac Hollander McCreery * Jacob Mattingley * Jakob Krigovsky * James Herdman * Jared * Jeffrey Dang * Joe Selman * Jonathan Yankovich * Julian Cheal * Juris Galang * Kyle Boutette * Kyle Boutette * Lance Ivy * Leila * Leila-Kuntar * Marcel Hild * Marcin Owsiany * Mark Huk * Martin Lazarov * Matt Darby * Matteo Monti * Michael Elfassy * Miguel Martinez * Misha Brukman * Myosotis * Nat Welch * Nicolas Leger * Paul Thornthwaite * Paul Thornthwaite * Paulo Henrique Lopes Ribeiro * Paulo Henrique Lopes Ribeiro * Paulo Ribeiro * Pradeep G * Rama McIntosh * Riccardo Carlesso * Riccardo Carlesso * Richard Wallace * Romain Haenni * Romain Vrignaud * Sean Malloy * Shinya Maeda * Stephen von Takach * Tim Downey * Timur Alperovich * Tomas Coufal * Vadim Shaulski * Wesley Beary * Zach Robinson * althras * ashmrtnz * canausa * geemus * jayhsu * jordangbull * kbockmanrs * leonidlm * lkuntar * neillturner * scott rushforth * snyquist2 fog-google-1.9.1/.gitignore0000644000004100000410000000025713451635472015605 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 .env .fog .byebug_history fog-google-1.9.1/.editorconfig0000644000004100000410000000031013451635472016260 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-1.9.1/examples/0000755000004100000410000000000013451635472015427 5ustar www-datawww-datafog-google-1.9.1/examples/precreated_client.rb0000644000004100000410000000134713451635472021435 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-1.9.1/examples/network.rb0000644000004100000410000000320413451635472017444 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-9-stretch-v20180611" ) 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-1.9.1/examples/metadata.rb0000644000004100000410000000211213451635472017530 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-9-stretch-v20180611" ) 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-1.9.1/examples/dns/0000755000004100000410000000000013451635472016213 5ustar www-datawww-datafog-google-1.9.1/examples/dns/zones.rb0000644000004100000410000000217613451635472017704 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-1.9.1/examples/dns/project.rb0000644000004100000410000000025513451635472020210 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-1.9.1/examples/get_list_snapshots.rb0000644000004100000410000000147213451635472021674 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-1.9.1/examples/get_list_images.rb0000644000004100000410000000303213451635472021111 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-9-stretch-v20180611") 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-1.9.1/examples/bootstrap.rb0000644000004100000410000000160513451635472017773 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 # Code can be ran by simply invoking `ruby bootstrap.rb` # Note: this example will require 'net-ssh' gem to be installed require "bundler" Bundler.require(:default, :development) p "Connecting to google..." p "=======================" connection = Fog::Compute.new(:provider => "Google") p "Bootstrapping a server..." p "=========================" server = connection.servers.bootstrap p "Waiting for server to be sshable..." p "===================================" server.wait_for { sshable? } p "Trying to send an SSH command..." p "================================" raise "Could not bootstrap sshable server." unless server.ssh("whoami") p "Deleting a server..." p "====================" raise "Could not delete server." unless server.destroy fog-google-1.9.1/examples/l7_load_balance.rb0000644000004100000410000000572413451635472020752 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-1.9.1/examples/create_instance.rb0000644000004100000410000000440413451635472021105 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) def example p "Connecting to Google API" connection = Fog::Compute.new(:provider => "Google") p "Creating disk" disk = connection.disks.create( :name => "fog-smoke-test-#{Time.now.to_i}", :size_gb => 10, :zone => "us-central1-f", :source_image => "debian-9-stretch-v20180611" ) p "Waiting for disk to be ready" disk.wait_for { disk.ready? } p "Creating a server" 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 => "us-central1-f", # Will be simplified, see https://github.com/fog/fog-google/issues/360 :network_interfaces => [{ :network => "global/networks/default", :access_configs => [{ :name => "External NAT", :type => "ONE_TO_ONE_NAT" }] }], :username => ENV["USER"], :metadata => { :items => [{ :key => "foo", :value => "bar" }] }, :tags => ["fog"], :service_accounts => { :scopes => %w(sql-admin bigquery https://www.googleapis.com/auth/compute) } ) p "Waiting for server to be ready" # .sshable? requires 'net-ssh' gem to be added to the gemfile begin 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") rescue NameError server.wait_for { ready? } end p "Deleting server" raise "Could not delete server." unless server.destroy end example fog-google-1.9.1/examples/pubsub/0000755000004100000410000000000013451635472016727 5ustar www-datawww-datafog-google-1.9.1/examples/pubsub/topics.rb0000644000004100000410000000154713451635472020564 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-1.9.1/examples/pubsub/subscriptions.rb0000644000004100000410000000314513451635472022166 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-1.9.1/examples/sql/0000755000004100000410000000000013451635472016226 5ustar www-datawww-datafog-google-1.9.1/examples/sql/tiers.rb0000644000004100000410000000020113451635472017672 0ustar www-datawww-datadef test connection = Fog::Google::SQL.new puts "Listing all Tiers..." puts "--------------------" connection.tiers end fog-google-1.9.1/examples/sql/ssl_certs.rb0000644000004100000410000000154313451635472020557 0ustar www-datawww-datadef test connection = Fog::Google::SQL.new puts "Create a Instance..." puts "--------------------" instance = connection.instances.create(:name => 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.name, :common_name => Fog::Mock.random_letters(16)) puts "Get the SSL certificate..." puts "--------------------------" connection.ssl_certs.get(instance.name, ssl_cert.sha1_fingerprint) puts "List all SSL certificate..." puts "---------------------------" connection.ssl_certs.all(instance.name) puts "Delete the SSL certificate..." puts "-----------------------------" ssl_cert.destroy puts "Delete the Instance..." puts "----------------------" instance.destroy end fog-google-1.9.1/examples/sql/operations.rb0000644000004100000410000000105713451635472020741 0ustar www-datawww-datadef test connection = Fog::Google::SQL.new puts "Create a Instance..." puts "--------------------" instance = connection.instances.create(:name => 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(operation.identity) puts "Listing all Operations..." puts "-------------------------" connection.operations.all(instance.identity) end fog-google-1.9.1/examples/sql/instances.rb0000644000004100000410000000157413451635472020551 0ustar www-datawww-datadef test connection = Fog::Google::SQL.new puts "Create a Instance..." puts "--------------------" instance = connection.instances.create(:name => Fog::Mock.random_letters(16), :tier => "D1") instance.wait_for { ready? } puts "Get the Instance..." puts "----------------------" connection.instances.get(instance.name) puts "List all Instances..." puts "---------------------" connection.instances.all puts "Update the Instance..." puts "----------------------" instance.settings[: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 "Delete the Instance..." puts "----------------------" instance.destroy end fog-google-1.9.1/examples/sql/flags.rb0000644000004100000410000000020113451635472017640 0ustar www-datawww-datadef test connection = Fog::Google::SQL.new puts "Listing all Flags..." puts "--------------------" connection.flags end fog-google-1.9.1/examples/monitoring/0000755000004100000410000000000013451635472017614 5ustar www-datawww-datafog-google-1.9.1/examples/monitoring/metric_descriptors.rb0000644000004100000410000000155313451635472024051 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(:filter => 'metric.type = starts_with("compute.googleapis.com")') puts "Number of compute metric descriptors: #{md.length}" end test fog-google-1.9.1/examples/monitoring/monitored_resource_descriptors.rb0000644000004100000410000000162213451635472026472 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 MonitoredResourceDescriptors..." puts "--------------------------------" md = connection.monitored_resource_descriptors puts "Number of all monitored resource descriptors: #{md.length}" puts "\nListing MonitoredResourceDescriptors related to Google Compute Engine..." puts "-----------------------------------------------------------------" md = connection.monitored_resource_descriptors.all(:filter => 'resource.type = starts_with("gce_")') puts "Number of compute monitored resource : #{md.length}" end test fog-google-1.9.1/examples/monitoring/timeseries_collection.rb0000644000004100000410000000252713451635472024533 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 interval = { :start_time => (Time.now - 1).rfc3339, :end_time => Time.now.to_datetime.rfc3339 } puts "Listing Timeseries from the last hour for metric compute.googleapis.com/instance/uptime..." puts "-------------------------------------------------------------------------------" tc = connection.timeseries_collection.all(:filter => 'metric.type = "compute.googleapis.com/instance/uptime"', :interval => interval) puts "Number of matches: #{tc.length}" puts "\nListing all Timeseries for metric compute.googleapis.com/instance/uptime &" puts "the region us-central1..." puts "------------------------------------------------------------------------------" filter = [ 'metric.type = "compute.googleapis.com/instance/uptime"', 'resource.label.zone = "us-central1-c"' ].join(" AND ") tc = connection.timeseries_collection.all(:filter => filter, :interval => interval) puts "Number of matches: #{tc.length}" end test fog-google-1.9.1/examples/image_create.rb0000644000004100000410000000115413451635472020362 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-1.9.1/examples/backend_services.rb0000644000004100000410000000111113451635472021240 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-1.9.1/examples/create_instance_with_attached_disk.rb0000644000004100000410000000331713451635472025011 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) def example p "Connecting to Google API" connection = Fog::Compute.new(:provider => "Google") p "Creating disk" disk = connection.disks.create( :name => "fog-smoke-test-#{Time.now.to_i}", :size_gb => 10, :zone => "us-central1-f", :source_image => "debian-9-stretch-v20180611" ) p "Creating a second disk" attached_disk = connection.disks.create( :name => "fog-smoke-test-#{Time.now.to_i}", :size_gb => 10, :zone => "us-central1-f" ) p "Waiting for disks to be ready" disk.wait_for { ready? } attached_disk.wait_for { ready? } p "Creating a server" server = connection.servers.create( :name => "fog-smoke-test-#{Time.now.to_i}", :disks => [disk.attached_disk_obj(boot: true), attached_disk.attached_disk_obj(boot: false, auto_delete: true)], :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 => "us-central1-f", # Will be simplified, see https://github.com/fog/fog-google/issues/360 :network_interfaces => [{ :network => "global/networks/default", :access_configs => [{ :name => "External NAT", :type => "ONE_TO_ONE_NAT" }] }], :username => ENV["USER"] ) p "Deleting server" raise "Could not delete server." unless server.destroy end example fog-google-1.9.1/examples/storage_json.rb0000644000004100000410000000226213451635472020453 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", predefined_acl: "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-1.9.1/examples/load-balance.rb0000644000004100000410000000516713451635472020267 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-9-stretch-v20180611" ) 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-1.9.1/examples/storage.rb0000644000004100000410000000271613451635472017426 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-1.9.1/.hound.yml0000644000004100000410000000004213451635472015523 0ustar www-datawww-dataruby: config_file: .rubocop.yml fog-google-1.9.1/Rakefile0000644000004100000410000000110013451635472015246 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-1.9.1/lib/0000755000004100000410000000000013451635472014357 5ustar www-datawww-datafog-google-1.9.1/lib/fog/0000755000004100000410000000000013451635472015132 5ustar www-datawww-datafog-google-1.9.1/lib/fog/parsers/0000755000004100000410000000000013451635472016611 5ustar www-datawww-datafog-google-1.9.1/lib/fog/parsers/storage/0000755000004100000410000000000013451635472020255 5ustar www-datawww-datafog-google-1.9.1/lib/fog/parsers/storage/google/0000755000004100000410000000000013451635472021531 5ustar www-datawww-datafog-google-1.9.1/lib/fog/parsers/storage/google/copy_object.rb0000644000004100000410000000061113451635472024354 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-1.9.1/lib/fog/parsers/storage/google/get_service.rb0000644000004100000410000000126113451635472024355 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-1.9.1/lib/fog/parsers/storage/google/access_control_list.rb0000644000004100000410000000221413451635472026111 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-1.9.1/lib/fog/parsers/storage/google/get_bucket.rb0000644000004100000410000000324613451635472024177 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-1.9.1/lib/fog/parsers/storage/google/get_bucket_logging.rb0000644000004100000410000000213413451635472025700 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-1.9.1/lib/fog/parsers/storage/google/get_bucket_object_versions.rb0000644000004100000410000000517113451635472027454 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 value == "true" if @in_delete_marker @delete_marker elsif @in_version @version end["IsLatest"] = true else if @in_delete_marker @delete_marker elsif @in_version @version end["IsLatest"] = 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-1.9.1/lib/fog/parsers/storage/google/get_request_payment.rb0000644000004100000410000000046313451635472026145 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-1.9.1/lib/fog/parsers/storage/google/get_bucket_versioning.rb0000644000004100000410000000066013451635472026437 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-1.9.1/lib/fog/parsers/storage/google.rb0000644000004100000410000000134213451635472022056 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-1.9.1/lib/fog/bin/0000755000004100000410000000000013451635472015702 5ustar www-datawww-datafog-google-1.9.1/lib/fog/bin/google.rb0000644000004100000410000000574113451635472017512 0ustar www-datawww-data# deviates from other bin stuff to accomodate gem module Google 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 when :pubsub Fog::Google::Pubsub 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 :pubsub Fog::Google::Pubsub.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. if Gem::Specification.respond_to?(:find_all_by_name) # newest rubygems availability = !Gem::Specification.find_all_by_name("google-api-client").empty? else # legacy availability = !Gem.source_index.find_name("google-api-client").empty? end # Then make sure we have all of the requirements services.each do |service| 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 services.each do |service| class_for(service).collections.each do |collection| next if respond_to?(collection) class_eval <<-EOS, __FILE__, __LINE__ def self.#{collection} self[:#{service}].#{collection} end EOS end end end availability end end end fog-google-1.9.1/lib/fog/dns/0000755000004100000410000000000013451635472015716 5ustar www-datawww-datafog-google-1.9.1/lib/fog/dns/google/0000755000004100000410000000000013451635472017172 5ustar www-datawww-datafog-google-1.9.1/lib/fog/dns/google/requests/0000755000004100000410000000000013451635472021045 5ustar www-datawww-datafog-google-1.9.1/lib/fog/dns/google/requests/get_project.rb0000644000004100000410000000103513451635472023676 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) @dns.get_project(identity) end end class Mock def get_project(_identity) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/dns/google/requests/get_managed_zone.rb0000644000004100000410000000072513451635472024664 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) @dns.get_managed_zone(@project, name_or_id) end end class Mock def get_managed_zone(_name_or_id) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/dns/google/requests/create_change.rb0000644000004100000410000000125613451635472024146 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 = []) @dns.create_change( @project, zone_name_or_id, ::Google::Apis::DnsV1::Change.new( :additions => additions, :deletions => deletions ) ) end end class Mock def create_change(_zone_name_or_id, _additions = [], _deletions = []) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/dns/google/requests/delete_managed_zone.rb0000644000004100000410000000072413451635472025346 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) @dns.delete_managed_zone(@project, name_or_id) end end class Mock def delete_managed_zone(_name_or_id) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/dns/google/requests/list_resource_record_sets.rb0000644000004100000410000000144613451635472026655 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, max_results: nil, name: nil, page_token: nil, type: nil) @dns.list_resource_record_sets( @project, zone_name_or_id, :max_results => max_results, :name => name, :page_token => page_token, :type => type ) end end class Mock def list_resource_record_sets(_zone_name_or_id, _options = {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/dns/google/requests/get_change.rb0000644000004100000410000000074613451635472023465 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) @dns.get_change(@project, zone_name_or_id, identity) end end class Mock def get_change(_zone_name_or_id, _identity) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/dns/google/requests/create_managed_zone.rb0000644000004100000410000000125313451635472025345 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) mngd_zone = ::Google::Apis::DnsV1::ManagedZone.new mngd_zone.name = name mngd_zone.dns_name = dns_name mngd_zone.description = description @dns.create_managed_zone(@project, mngd_zone) end end class Mock def create_managed_zone(_name, _dns_name, _description) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/dns/google/requests/list_changes.rb0000644000004100000410000000132313451635472024034 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, max_results: nil, page_token: nil, sort_by: nil, sort_order: nil) @dns.list_changes( @project, zone_name_or_id, :max_results => max_results, :page_token => page_token, :sort_by => sort_by, :sort_order => sort_order ) end end class Mock def list_changes(_zone_name_or_id, _opts = {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/dns/google/requests/list_managed_zones.rb0000644000004100000410000000127013451635472025237 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(dns_name: nil, max_results: nil, page_token: nil) @dns.list_managed_zones(@project, :dns_name => dns_name, :max_results => max_results, :page_token => page_token) end end class Mock def list_managed_zones(_opts = {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/dns/google/models/0000755000004100000410000000000013451635472020455 5ustar www-datawww-datafog-google-1.9.1/lib/fog/dns/google/models/zone.rb0000644000004100000410000000372313451635472021762 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.to_h) self end end end end end fog-google-1.9.1/lib/fog/dns/google/models/records.rb0000644000004100000410000000307013451635472022443 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) .to_h[:rrsets] || [] load(data) rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 [] 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) .to_h[:rrsets] || [] records.any? ? new(records.first) : nil rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 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-1.9.1/lib/fog/dns/google/models/changes.rb0000644000004100000410000000241613451635472022415 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).to_h[:changes] || [] load(data) rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 [] 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).to_h new(change) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 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-1.9.1/lib/fog/dns/google/models/change.rb0000644000004100000410000000164113451635472022231 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".freeze PENDING_STATE = "pending".freeze ## # 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-1.9.1/lib/fog/dns/google/models/zones.rb0000644000004100000410000000161213451635472022140 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.managed_zones.to_h || [] 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).to_h new(zone) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/dns/google/models/projects.rb0000644000004100000410000000111413451635472022630 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).to_h new(project) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/dns/google/models/project.rb0000644000004100000410000000477713451635472022467 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[:managed_zones] 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[:rrsets_per_managed_zone] 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[:resource_records_per_rrset] 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[:rrset_additions_per_change] 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[:rrset_deletions_per_change] 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[:total_rrdata_size_per_change] end end end end end fog-google-1.9.1/lib/fog/dns/google/models/record.rb0000644000004100000410000000645013451635472022265 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.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.id) new_attributes.key?(:async) ? async = new_attributes[:async] : 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).to_h 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.id) change.wait_for { ready? } 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-1.9.1/lib/fog/dns/google/real.rb0000644000004100000410000000100413451635472020435 0ustar www-datawww-datamodule Fog module DNS class Google class Real include Fog::Google::Shared 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(" ") initialize_google_client(options) @dns = ::Google::Apis::DnsV1::DnsService.new apply_client_options(@dns, options) end end end end end fog-google-1.9.1/lib/fog/dns/google/mock.rb0000644000004100000410000000130213451635472020444 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-1.9.1/lib/fog/dns/google.rb0000644000004100000410000000274213451635472017524 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_application_default, :google_auth, :google_client, :google_client_options, :google_key_location, :google_key_string, :google_json_key_location, :google_json_key_string ) GOOGLE_DNS_API_VERSION = "v1".freeze GOOGLE_DNS_BASE_URL = "https://www.googleapis.com/dns/".freeze GOOGLE_DNS_API_SCOPE_URLS = %w(https://www.googleapis.com/auth/ndev.clouddns.readwrite).freeze ## # 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-1.9.1/lib/fog/google/0000755000004100000410000000000013451635472016406 5ustar www-datawww-datafog-google-1.9.1/lib/fog/google/version.rb0000644000004100000410000000010213451635472020411 0ustar www-datawww-datamodule Fog module Google VERSION = "1.9.1".freeze end end fog-google-1.9.1/lib/fog/google/requests/0000755000004100000410000000000013451635472020261 5ustar www-datawww-datafog-google-1.9.1/lib/fog/google/requests/pubsub/0000755000004100000410000000000013451635472021561 5ustar www-datawww-datafog-google-1.9.1/lib/fog/google/requests/pubsub/create_topic.rb0000644000004100000410000000117213451635472024550 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) @pubsub.create_topic(topic_name) end end class Mock def create_topic(_topic_name) raise Fog::Errors::MockNotImplemented end end end end end fog-google-1.9.1/lib/fog/google/requests/pubsub/pull_subscription.rb0000644000004100000410000000301213451635472025662 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 }) pull_request = ::Google::Apis::PubsubV1::PullRequest.new( :return_immediately => options[:return_immediately], :max_messages => options[:max_messages] ) @pubsub.pull_subscription(subscription, pull_request) end end class Mock def pull_subscription(_subscription, _options = { :return_immediately => true, :max_messages => 10 }) raise Fog::Errors::MockNotImplemented end end end end end fog-google-1.9.1/lib/fog/google/requests/pubsub/list_subscriptions.rb0000644000004100000410000000151113451635472026046 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) if project.nil? project = "projects/#{@project}" else project = project.to_s end @pubsub.list_subscriptions(project) end end class Mock def list_subscriptions(_project = nil) raise Fog::Errors::MockNotImplemented end end end end end fog-google-1.9.1/lib/fog/google/requests/pubsub/list_topics.rb0000644000004100000410000000144613451635472024447 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) if project.nil? project = "projects/#{@project}" else project = project.to_s end @pubsub.list_topics(project) end end class Mock def list_topics(_project = nil) raise Fog::Errors::MockNotImplemented end end end end end fog-google-1.9.1/lib/fog/google/requests/pubsub/delete_topic.rb0000644000004100000410000000100113451635472024536 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) @pubsub.delete_topic(topic_name) end end class Mock def delete_topic(_topic_name) raise Fog::Errors::MockNotImplemented end end end end end fog-google-1.9.1/lib/fog/google/requests/pubsub/create_subscription.rb0000644000004100000410000000302513451635472026155 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) subscription = ::Google::Apis::PubsubV1::Subscription.new( :topic => topic, :ack_deadline_seconds => ack_deadline_seconds, :push_config => push_config ) @pubsub.create_subscription(subscription_name, subscription) end end class Mock def create_subscription(_subscription_name, _topic, _push_config = {}, _ack_deadline_seconds = nil) raise Fog::Errors::MockNotImplemented end end end end end fog-google-1.9.1/lib/fog/google/requests/pubsub/get_subscription.rb0000644000004100000410000000110313451635472025464 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) @pubsub.get_subscription(subscription_name) end end class Mock def get_subscription(_subscription_name) raise Fog::Errors::MockNotImplemented end end end end end fog-google-1.9.1/lib/fog/google/requests/pubsub/delete_subscription.rb0000644000004100000410000000110713451635472026153 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) @pubsub.delete_subscription(subscription_name) end end class Mock def delete_subscription(_subscription_name) raise Fog::Errors::MockNotImplemented end end end end end fog-google-1.9.1/lib/fog/google/requests/pubsub/acknowledge_subscription.rb0000644000004100000410000000160713451635472027201 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) # Previous behavior allowed passing a single ack_id without being wrapped in an Array, # this is for backwards compatibility. unless ack_ids.is_a?(Array) ack_ids = [ack_ids] end ack_request = ::Google::Apis::PubsubV1::AcknowledgeRequest.new( :ack_ids => ack_ids ) @pubsub.acknowledge_subscription(subscription, ack_request) end end class Mock def acknowledge_subscription(_subscription, _ack_ids) raise Fog::Errors::MockNotImplemented end end end end end fog-google-1.9.1/lib/fog/google/requests/pubsub/publish_topic.rb0000644000004100000410000000154613451635472024760 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) publish_request = ::Google::Apis::PubsubV1::PublishRequest.new( :messages => messages ) @pubsub.publish_topic(topic, publish_request) end end class Mock def publish_topic(_topic, _messages) raise Fog::Errors::MockNotImplemented end end end end end fog-google-1.9.1/lib/fog/google/requests/pubsub/get_topic.rb0000644000004100000410000000077213451635472024071 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) @pubsub.get_topic(topic_name) end end class Mock def get_topic(_topic_name) raise Fog::Errors::MockNotImplemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/0000755000004100000410000000000013451635472021060 5ustar www-datawww-datafog-google-1.9.1/lib/fog/google/requests/sql/import_instance.rb0000644000004100000410000000252313451635472024605 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://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/import class Real def import_instance(instance_id, uri, database: nil, csv_import_options: nil, file_type: nil, import_user: nil) data = { :kind => "sql#importContext", :uri => uri } data[:database] = database unless database.nil? data[:file_type] = file_type unless file_type.nil? data[:import_user] = import_user unless import_user.nil? unless csv_import_options.nil? data[:csv_import_options] = ::Google::Apis::SqladminV1beta4::ImportContext::CsvImportOptions.new(csv_import_options) end @sql.import_instance( @project, instance_id, ::Google::Apis::SqladminV1beta4::ImportInstancesRequest.new( :import_context => ::Google::Apis::SqladminV1beta4::ImportContext.new(data) ) ) end end class Mock def import_instance(_instance_id, _uri, _options = {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/list_users.rb0000644000004100000410000000071213451635472023601 0ustar www-datawww-datamodule Fog module Google class SQL ## # Lists users in the specified Cloud SQL instance. # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/users/list class Real def list_users(instance_id) @sql.list_users(@project, instance_id) end end class Mock def list_operations(_instance_id) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/list_ssl_certs.rb0000644000004100000410000000073613451635472024447 0ustar www-datawww-datamodule Fog module Google class SQL ## # Lists all of the current SSL certificates for the instance # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/sslCerts/list class Real def list_ssl_certs(instance_id) @sql.list_ssl_certs(@project, instance_id) end end class Mock def list_ssl_certs(_instance_id) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/insert_backup_run.rb0000644000004100000410000000123513451635472025123 0ustar www-datawww-datamodule Fog module Google class SQL ## # Creates a new backup run on demand. This method is applicable only to Second # Generation instances. # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/backupRuns/insert class Real def insert_backup_run(instance_id, backup_run = {}) @sql.insert_backup_run( @project, instance_id, ::Google::Apis::SqladminV1beta4::BackupRun.new(backup_run) ) end end class Mock def insert_backup_run(_instance_id, _run) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/delete_backup_run.rb0000644000004100000410000000077513451635472025071 0ustar www-datawww-datamodule Fog module Google class SQL ## # Deletes the backup taken by a backup run. # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/backupRuns/delete class Real def delete_backup_run(instance_id, backup_run_id) @sql.delete_backup_run(@project, instance_id, backup_run_id) end end class Mock def delete_backup_run(_instance_id, _run) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/update_instance.rb0000644000004100000410000000150413451635472024553 0ustar www-datawww-datamodule Fog module Google class SQL ## # Updates settings of a Cloud SQL instance # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/update class Real def update_instance(instance_id, settings_version, tier, settings = {}) settings = ::Google::Apis::SqladminV1beta4::Settings.new(settings) settings.tier = tier settings.settings_version = settings_version @sql.update_instance( @project, instance_id, ::Google::Apis::SqladminV1beta4::DatabaseInstance.new(:settings => settings) ) end end class Mock def update_instance(_instance_id, _settings_version, _tier, _settings = {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/insert_user.rb0000644000004100000410000000103513451635472023746 0ustar www-datawww-datamodule Fog module Google class SQL ## # Create a new user in a Cloud SQL instance. # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/users/insert class Real def insert_user(instance_id, user) @sql.insert_user(@project, instance_id, ::Google::Apis::SqladminV1beta4::User.new(user)) end end class Mock def insert_user(_instance_id, _user) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/clone_instance.rb0000644000004100000410000000244013451635472024371 0ustar www-datawww-datamodule Fog module Google class SQL ## # Creates a Cloud SQL instance as a clone of the source instance # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/clone class Real def clone_instance(instance_id, destination_name, log_filename: nil, log_position: nil) context = { :kind => "sql#cloneContext", :destination_instance_name => destination_name } unless log_filename.nil? || log_position.nil? context[:bin_log_coordinates] = ::Google::Apis::SqladminV1beta4::BinLogCoordinates.new( :kind => "sql#binLogCoordinates", :log_filename => log_filename, :log_position => log_position ) end clone_request = ::Google::Apis::SqladminV1beta4::CloneInstancesRequest.new( :clone_context => ::Google::Apis::SqladminV1beta4::CloneContext.new(context) ) @sql.clone_instance(@project, instance_id, clone_request) end end class Mock def clone_instance(_instance_id, _destination_name, _log_filename: nil, _log_position: nil) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/reset_instance_ssl_config.rb0000644000004100000410000000134613451635472026625 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://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/resetSslConfig class Real def reset_instance_ssl_config(instance_id) @sql.reset_instance_ssl_config(@project, instance_id) end end class Mock def reset_instance_ssl_config(_instance_id) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/get_operation.rb0000644000004100000410000000075313451635472024251 0ustar www-datawww-datamodule Fog module Google class SQL ## # Retrieves an instance operation that has been performed on an instance # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/operations/get class Real def get_operation(operation_id) @sql.get_operation(@project, operation_id) end end class Mock def get_operation(_operation_id) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/restore_instance_backup.rb0000644000004100000410000000157213451635472026306 0ustar www-datawww-datamodule Fog module Google class SQL ## # Restores a backup of a Cloud SQL instance # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/restoreBackup class Real def restore_instance_backup(instance_id, backup_run_id) request = ::Google::Apis::SqladminV1beta4::RestoreInstancesBackupRequest.new( :restore_backup_context => ::Google::Apis::SqladminV1beta4::RestoreBackupContext.new( :backup_run_id => backup_run_id, :instance_id => instance_id, :kind => "sql#restoreBackupContext" ) ) @sql.restore_instance_backup(@project, instance_id, request) end end class Mock def restore_instance_backup(_instance_id, _backup_run_id) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/list_operations.rb0000644000004100000410000000140213451635472024620 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://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/operations/list class Real def list_operations(instance_id, max_results: nil, page_token: nil) @sql.list_operations(@project, instance_id, :max_results => max_results, :page_token => page_token) end end class Mock def list_operations(_instance_id, _options: {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/list_flags.rb0000644000004100000410000000074613451635472023543 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(database_version: nil) @sql.list_flags(:database_version => database_version) end end class Mock def list_flags Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/list_backup_runs.rb0000644000004100000410000000135113451635472024754 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://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/backupRuns/list class Real def list_backup_runs(instance_id, max_results: nil, page_token: nil) @sql.list_backup_runs(@project, instance_id, :max_results => max_results, :page_token => page_token) end end class Mock def list_backup_runs(_instance_id, _backup_configuration_id) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/restart_instance.rb0000644000004100000410000000071313451635472024756 0ustar www-datawww-datamodule Fog module Google class SQL ## # Restarts a Cloud SQL instance # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/restart class Real def restart_instance(instance_id) @sql.restart_instance(@project, instance_id) end end class Mock def restart_instance(_instance_id) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/delete_user.rb0000644000004100000410000000075113451635472023710 0ustar www-datawww-datamodule Fog module Google class SQL ## # Deletes a user from a Cloud SQL instance. # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/users/delete class Real def delete_user(instance_id, host, name) @sql.delete_user(@project, instance_id, host, name) end end class Mock def delete_user(_instance_id, _host, _name) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/list_instances.rb0000644000004100000410000000126413451635472024432 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://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/list class Real def list_instances(filter: nil, max_results: nil, page_token: nil) @sql.list_instances(@project, :filter => filter, :max_results => max_results, :page_token => page_token) end end class Mock def list_instances(_options: {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/delete_instance.rb0000644000004100000410000000070613451635472024536 0ustar www-datawww-datamodule Fog module Google class SQL ## # Deletes a Cloud SQL instance # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/delete class Real def delete_instance(instance_id) @sql.delete_instance(@project, instance_id) end end class Mock def delete_instance(_instance_id) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/delete_ssl_cert.rb0000644000004100000410000000107313451635472024546 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://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/sslCerts/delete class Real def delete_ssl_cert(instance_id, sha1_fingerprint) @sql.delete_ssl_cert(@project, instance_id, sha1_fingerprint) end end class Mock def delete_ssl_cert(_instance_id, _sha1_fingerprint) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/get_ssl_cert.rb0000644000004100000410000000103513451635472024061 0ustar www-datawww-datamodule Fog module Google class SQL ## # Retrieves a particular SSL certificate (does not include the private key) # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/sslCerts/get class Real def get_ssl_cert(instance_id, sha1_fingerprint) @sql.get_ssl_cert(@project, instance_id, sha1_fingerprint) end end class Mock def get_ssl_cert(_instance_id, _sha1_fingerprint) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/update_user.rb0000644000004100000410000000112313451635472023722 0ustar www-datawww-datamodule Fog module Google class SQL ## # Updates an existing user in a Cloud SQL instance. # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/users/update class Real def update_user(instance_id, host, name, user) @sql.update_user( @project, instance_id, host, name, ::Google::Apis::SqladminV1beta4::User.new(user) ) end end class Mock def update_user(_instance_id, _host, _name, _user) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/insert_ssl_cert.rb0000644000004100000410000000131413451635472024606 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://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/sslCerts/insert class Real def insert_ssl_cert(instance_id, common_name) @sql.insert_ssl_cert( @project, instance_id, ::Google::Apis::SqladminV1beta4::InsertSslCertsRequest.new( :common_name => common_name ) ) end end class Mock def insert_ssl_cert(_instance_id, _common_name) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/export_instance.rb0000644000004100000410000000314613451635472024616 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 or CSV file. # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/export class Real def export_instance(instance_id, uri, databases: [], sql_export_options: {}, csv_export_options: {}, file_type: nil) data = { :kind => "sql#exportContext", :uri => uri, :databases => databases } unless file_type.nil? data[:file_type] = file_type end unless csv_export_options.empty? data[:csv_export_options] = ::Google::Apis::SqladminV1beta4::ExportContext::CsvExportOptions.new(csv_export_options) end unless sql_export_options.nil? data[:sql_export_options] = ::Google::Apis::SqladminV1beta4::ExportContext::SqlExportOptions.new(sql_export_options) end export_context = ::Google::Apis::SqladminV1beta4::ExportContext.new(export_context) @sql.export_instance( @project, instance_id, ::Google::Apis::SqladminV1beta4::ExportInstancesRequest.new( :export_context => export_context ) ) end end class Mock def export_instance(_instance_id, _uri, _options: {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/insert_instance.rb0000644000004100000410000000134313451635472024576 0ustar www-datawww-datamodule Fog module Google class SQL ## # Creates a new Cloud SQL instance # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/insert class Real def insert_instance(name, tier, options = {}) instance = ::Google::Apis::SqladminV1beta4::DatabaseInstance.new(options) instance.name = name instance.settings = ::Google::Apis::SqladminV1beta4::Settings.new(instance.settings || {}) instance.settings.tier = tier @sql.insert_instance(@project, instance) end end class Mock def insert_instance(_name, _tier, _options = {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/get_instance.rb0000644000004100000410000000074413451635472024055 0ustar www-datawww-datamodule Fog module Google class SQL ## # Retrieves a resource containing information about a Cloud SQL instance # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/get class Real def get_instance(instance_id) @sql.get_instance(@project, instance_id) end end class Mock def get_instance(_instance_id) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/get_backup_run.rb0000644000004100000410000000103413451635472024373 0ustar www-datawww-datamodule Fog module Google class SQL ## # Retrieves a resource containing information about a backup run. # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/backupRuns/get class Real def get_backup_run(instance_id, backup_run_id) @sql.get_backup_run(@project, instance_id, backup_run_id) end end class Mock def get_backup_run(_instance_id, _backup_run_id, _due_time) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/sql/list_tiers.rb0000644000004100000410000000065013451635472023567 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 @sql.list_tiers(@project) end end class Mock def list_tiers Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/monitoring/0000755000004100000410000000000013451635472022446 5ustar www-datawww-datafog-google-1.9.1/lib/fog/google/requests/monitoring/list_monitored_resource_descriptors.rb0000644000004100000410000000157613451635472032367 0ustar www-datawww-datamodule Fog module Google class Monitoring ## # Describes the schema of a MonitoredResource (a resource object that can be used for monitoring, logging, # billing, or other purposes) using a type name and a set of labels. # # @see https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.monitoredResourceDescriptors/list class Real def list_monitored_resource_descriptors(filter: nil, page_size: nil, page_token: nil) @monitoring.list_project_monitored_resource_descriptors( "projects/#{@project}", :filter => filter, :page_size => page_size, :page_token => page_token ) end end class Mock def list_monitored_resource_descriptors(_filter, _page_size, _page_token) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/monitoring/get_metric_descriptor.rb0000644000004100000410000000060113451635472027350 0ustar www-datawww-datamodule Fog module Google class Monitoring class Real def get_metric_descriptor(metric_type) @monitoring.get_project_metric_descriptor("projects/#{@project}/metricDescriptors/#{metric_type}") end end class Mock def get_metric_descriptor(_metric_type) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/monitoring/list_metric_descriptors.rb0000644000004100000410000000130213451635472027726 0ustar www-datawww-datamodule Fog module Google class Monitoring ## # Lists metric descriptors that match a filter. # # @see https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors/list class Real def list_metric_descriptors(filter: nil, page_size: nil, page_token: nil) @monitoring.list_project_metric_descriptors( "projects/#{@project}", :filter => filter, :page_size => page_size, :page_token => page_token ) end end class Mock def list_metric_descriptors(_options = {}) raise Fog::Errors::MockNotImplemented end end end end end fog-google-1.9.1/lib/fog/google/requests/monitoring/create_timeseries.rb0000644000004100000410000000155613451635472026476 0ustar www-datawww-datamodule Fog module Google class Monitoring class Real ## # Create a timeseries. User-created time series should only be used with custom metrics. # # @param timeseries [Array] Timeseries to create/update. # @see https://cloud.google.com/monitoring/api/ref_v3/rest/v3/TimeSeries for expected format. # @see https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/create # def create_timeseries(timeseries: []) request = ::Google::Apis::MonitoringV3::CreateTimeSeriesRequest.new( :time_series => timeseries ) @monitoring.create_time_series("projects/#{@project}", request) end end class Mock def create_timeseries(_timeseries: []) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/monitoring/list_timeseries.rb0000644000004100000410000000336013451635472026201 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 # # @see https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list class Real def list_timeseries(filter: nil, interval: nil, aggregation: nil, order_by: nil, page_size: nil, page_token: nil, view: nil) if filter.nil? raise ArgumentError.new("filter is required") end if interval.nil? raise ArgumentError.new("interval is required") end options = { :filter => filter, :interval_end_time => interval[:end_time], :interval_start_time => interval[:start_time], :order_by => order_by, :page_size => page_size, :page_token => page_token, :view => view } if options.key?(:interval) interval = options[:interval] parameters["interval.endTime"] = interval[:end_time] if interval.key?(:end_time) parameters["interval.startTime"] = interval[:start_time] if interval.key?(:start_time) end unless aggregation.nil? %i(alignment_period cross_series_reducer group_by_fields per_series_aligner).each do |k| if aggregation.key?(k) options["aggregation_#{k}".to_sym] = aggregation[k] end end end @monitoring.list_project_time_series("projects/#{@project}", options) end end class Mock def list_timeseries(_options = {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/monitoring/get_monitored_resource_descriptor.rb0000644000004100000410000000073213451635472032001 0ustar www-datawww-datamodule Fog module Google class Monitoring class Real def get_monitored_resource_descriptor(resource_type) @monitoring.get_project_monitored_resource_descriptor( "projects/#{@project}/monitoredResourceDescriptors/#{resource_type}" ) end end class Mock def get_monitored_resource_descriptor(_resource_type) raise Fog::Errors::MockNotImplemented end end end end end fog-google-1.9.1/lib/fog/google/requests/monitoring/delete_metric_descriptor.rb0000644000004100000410000000061213451635472030035 0ustar www-datawww-datamodule Fog module Google class Monitoring class Real def delete_metric_descriptor(metric_type) @monitoring.delete_project_metric_descriptor("projects/#{@project}/metricDescriptors/#{metric_type}") end end class Mock def delete_metric_descriptor(_metric_type) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/requests/monitoring/create_metric_descriptor.rb0000644000004100000410000000511313451635472030037 0ustar www-datawww-datamodule Fog module Google class Monitoring class Real ## # Create a metric descriptor. User-created metric descriptors define custom metrics. # @param metric_type [String] Required - the metric type. User-created metric descriptors should start # with custom.googleapis.com. # @param unit [String] The unit in which the metric value is reported. # It is only applicable if the valueType is INT64, DOUBLE, or DISTRIBUTION. # @param value_type [String] Whether the measurement is an integer, a floating-point number, etc. # Some combinations of metricKind and valueType might not be supported. # @param description [String] A detailed description of the metric, which can be used in documentation. # @param display_name [String] A concise name for the metric, which can be displayed in user interfaces. # Use sentence casing without an ending period, for example "Request count". # @param labels [Array] A list of label hash objects that can be used to describe a specific # instance of this metric type. # @option labels [String] key The label key. # @option labels [String] value_type The type of data that can be assigned to the label. # @option labels [String] description A human-readable description for the label. # @param metric_kind [String] The pagination token, which is used to page through large result sets. # # @return [::Google::Apis::MonitoringV3::MetricDescriptor] created metric descriptor # @see https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors/create def create_metric_descriptor(metric_type: nil, unit: nil, value_type: nil, description: nil, display_name: nil, labels: [], metric_kind: nil) metric_descriptor = ::Google::Apis::MonitoringV3::MetricDescriptor.new( :name => "projects/#{@project}/metricDescriptors/#{metric_type}", :type => metric_type, :unit => unit, :value_type => value_type, :description => description, :display_name => display_name, :labels => labels.map { |l| ::Google::Apis::MonitoringV3::LabelDescriptor.new(l) }, :metric_kind => metric_kind ) @monitoring.create_project_metric_descriptor("projects/#{@project}", metric_descriptor) end end class Mock def create_metric_descriptor(**_args) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/google/sql.rb0000644000004100000410000000452213451635472017535 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_application_default, :google_auth, :google_client, :google_client_options, :google_key_location, :google_key_string, :google_json_key_location, :google_json_key_string ) GOOGLE_SQL_API_VERSION = "v1beta4".freeze GOOGLE_SQL_BASE_URL = "https://www.googleapis.com/sql/".freeze GOOGLE_SQL_API_SCOPE_URLS = %w(https://www.googleapis.com/auth/sqlservice.admin https://www.googleapis.com/auth/cloud-platform).freeze ## # 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 # User model :user collection :users ## # REQUESTS request_path "fog/google/requests/sql" # Backup Run request :delete_backup_run request :get_backup_run request :insert_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 :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 # User request :insert_user request :update_user request :list_users request :delete_user end end end fog-google-1.9.1/lib/fog/google/monitoring.rb0000644000004100000410000000317613451635472021127 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_application_default, :google_auth, :google_client, :google_client_options, :google_key_location, :google_key_string, :google_json_key_location, :google_json_key_string ) GOOGLE_MONITORING_API_VERSION = "v3".freeze GOOGLE_MONITORING_BASE_URL = "https://monitoring.googleapis.com/".freeze GOOGLE_MONITORING_API_SCOPE_URLS = %w(https://www.googleapis.com/auth/monitoring).freeze ## # MODELS model_path "fog/google/models/monitoring" # Timeseries model :timeseries collection :timeseries_collection # MetricDescriptors model :metric_descriptor collection :metric_descriptors # MonitoredResourceDescriptors model :monitored_resource_descriptor collection :monitored_resource_descriptors ## # REQUESTS request_path "fog/google/requests/monitoring" # Timeseries request :list_timeseries request :create_timeseries # MetricDescriptors request :get_metric_descriptor request :list_metric_descriptors request :create_metric_descriptor request :delete_metric_descriptor # MonitoredResourceDescriptors request :list_monitored_resource_descriptors request :get_monitored_resource_descriptor end end end fog-google-1.9.1/lib/fog/google/models/0000755000004100000410000000000013451635472017671 5ustar www-datawww-datafog-google-1.9.1/lib/fog/google/models/pubsub/0000755000004100000410000000000013451635472021171 5ustar www-datawww-datafog-google-1.9.1/lib/fog/google/models/pubsub/topics.rb0000644000004100000410000000155213451635472023022 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.to_h[: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).to_h new(topic) rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/google/models/pubsub/subscriptions.rb0000644000004100000410000000174613451635472024435 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.to_h[: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).to_h new(subscription) rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/google/models/pubsub/received_message.rb0000644000004100000410000000231713451635472025013 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-1.9.1/lib/fog/google/models/pubsub/topic.rb0000644000004100000410000000406213451635472022636 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) 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).to_h[:message_ids] 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-1.9.1/lib/fog/google/models/pubsub/subscription.rb0000644000004100000410000000704213451635472024245 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).to_h return [] unless data.key?(:received_messages) # Turn into a list of ReceivedMessage, but ensure we perform a base64 decode first data[:received_messages].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).to_h 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-1.9.1/lib/fog/google/models/sql/0000755000004100000410000000000013451635472020470 5ustar www-datawww-datafog-google-1.9.1/lib/fog/google/models/sql/users.rb0000644000004100000410000000072113451635472022156 0ustar www-datawww-datarequire "fog/core/collection" require "fog/google/models/sql/user" module Fog module Google class SQL class Users < Fog::Collection model Fog::Google::SQL::User ## # Lists all Cloud SQL database users # # @return [Array] List of users def all(instance) data = service.list_users(instance).to_h[:items] || [] load(data) end end end end end fog-google-1.9.1/lib/fog/google/models/sql/tiers.rb0000644000004100000410000000067413451635472022152 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.to_h[:items] || [] load(data) end end end end end fog-google-1.9.1/lib/fog/google/models/sql/backup_runs.rb0000644000004100000410000000222213451635472023327 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. # # @param [String] instance_id Instance ID # @return [Array] List of Backup run resources def all(instance_id) data = service.list_backup_runs(instance_id).to_h[:items] || [] load(data) end ## # Retrieves a resource containing information about a backup run # # @param [String] instance_id Instance ID # @param [String] backup_run_id Backup Configuration ID # @return [Fog::Google::SQL::BackupRun] Backup run resource def get(instance_id, backup_run_id) backup_run = service.get_backup_run(instance_id, backup_run_id).to_h if backup_run new(backup_run) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/google/models/sql/user.rb0000644000004100000410000000266413451635472022003 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class SQL ## # Represents a database user in a Cloud SQL instance. # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/users class User < Fog::Model attribute :name attribute :etag attribute :host attribute :instance attribute :kind attribute :project def destroy(async = true) requires :instance, :name, :host # TODO(2.0): Add a deprecation warning here, depending on the decision in #27 # This is a compatibility fix leftover from breaking named parameter change if async.is_a?(Hash) async = async[:async] end resp = service.delete_user(instance, host, name) operation = Fog::Google::SQL::Operations.new(:service => service).get(resp.name) operation.wait_for { ready? } unless async operation end def save(password: nil) requires :instance, :name data = attributes data[:password] = password unless password.nil? if etag.nil? resp = service.insert_user(instance, data) else resp = service.update_user(instance, data) end operation = Fog::Google::SQL::Operations.new(:service => service).get(resp.name) operation.wait_for { ready? } end end end end end fog-google-1.9.1/lib/fog/google/models/sql/operation.rb0000644000004100000410000000425413451635472023022 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://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/operations class Operation < Fog::Model identity :name attribute :kind, :aliases => "kind" attribute :self_link, :aliases => "selfLink" attribute :target_project, :aliases => "targetProject" attribute :target_id, :aliases => "targetId" attribute :target_link, :aliases => "targetLink" attribute :name, :aliases => "name" attribute :operation_type, :aliases => "operationType" attribute :status, :aliases => "status" attribute :user, :aliases => "user" attribute :insert_time, :aliases => "insertTime" attribute :start_time, :aliases => "startTime" attribute :end_time, :aliases => "endTime" attribute :error, :aliases => "error" attribute :import_context, :aliases => "importContext" attribute :export_context, :aliases => "exportContext" attribute :sql_export_options, :aliases => "sqlExportOptions" attribute :csv_export_options, :aliases => "csvExportOptions" DONE_STATE = "DONE".freeze PENDING_STATE = "PENDING".freeze RUNNING_STATE = "RUNNING".freeze UNKNOWN_STATE = "UNKNOWN".freeze ## # Checks if the instance operation is pending # # @return [Boolean] True if the operation is pending; False otherwise def pending? status == PENDING_STATE end ## # Checks if the instance operation is done # # @return [Boolean] True if the operation is done; False otherwise def ready? status == DONE_STATE end ## # Reloads an instance operation # # @return [Fog::Google::SQL::Operation] Instance operation resource def reload requires :identity data = collection.get(identity) merge_attributes(data.attributes) self end end end end end fog-google-1.9.1/lib/fog/google/models/sql/instance.rb0000644000004100000410000003152613451635472022630 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class SQL class Instance < Fog::Model identity :name 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 :authorized_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".freeze PENDING_CREATE_STATE = "PENDING_CREATE".freeze RUNNABLE_STATE = "RUNNABLE".freeze SUSPENDED_STATE = "SUSPENDED".freeze UNKNOWN_STATE = "UNKNOWN_STATE".freeze ## # Returns the activation policy for this instance # # @return [String] The activation policy for this instance def activation_policy settings[:activation_policy] end ## # Returns the AppEngine app ids that can access this instance # # @return [Array] The AppEngine app ids that can access this instance def authorized_gae_applications settings[:authorized_gae_applications] end ## # Returns the daily backup configuration for the instance # # @return [Hash] The daily backup configuration for the instance def backup_configuration settings["backup_configuration"] 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 [Boolean] async If the operation must be performed asynchronously (true by default) # @param [String] log_filename Name of the binary log file for a Cloud SQL instance # @param [Integer] log_position Position (offset) within the binary log file # @return [Fog::Google::SQL::Operation] A Operation resource def clone(destination_name, async: true, log_filename: nil, log_position: nil) requires :identity data = service.clone_instance( identity, destination_name, :log_filename => log_filename, :log_position => log_position ) operation = Fog::Google::SQL::Operations.new(:service => service).get(data.name) operation.tap { |o| o.wait_for { ready? } unless async } end ## # Creates a Cloud SQL instance # @param [Boolean] async If the operation must be performed asynchronously # # This is true by default since SQL instances return Google::Apis::ClientError: invalidState # whenever an instance is in a transition process (creation, deletion, etc.) which makes it # hard to operate unless one puts guard clauses on Google::Apis::ClientError everywhere. # # TODO: Rethink this when API graduates out of beta. (Written as of V1beta4) # # @return [Fog::Google::SQL::Instance] Instance resource def create(async = false) requires :identity data = service.insert_instance(identity, attributes[:tier], attributes) operation = Fog::Google::SQL::Operations.new(:service => service).get(data.name) operation.wait_for { ready? } unless async 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[:database_flags] end ## # Deletes a Cloud SQL instance # # @param [Boolean] async If the operation must be performed asynchronously (false by default) # See Fog::Google::SQL::Instance.create on details why default is set this way. # # @return [Fog::Google::SQL::Operation] A Operation resource def destroy(async = false) requires :identity # TODO(2.0): Add a deprecation warning here, depending on the decision in #27 # This is a compatibility fix leftover from breaking named parameter change if async.is_a?(Hash) async = async[:async] end data = service.delete_instance(identity) operation = Fog::Google::SQL::Operations.new(:service => service).get(data.name) operation.tap { |o| o.wait_for { ready? } unless async } 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(data.name) operation.tap { |o| o.wait_for { ready? } unless async } 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(data.name) operation.tap { |o| o.wait_for { ready? } unless options.fetch(:async, true) } 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(:ip_configuration, {}) .fetch(:authorized_networks, []) 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_ipv4_enabled settings.fetch(:ip_configuration, {})[:ipv4_enabled] end ## # Returns whether SSL connections over IP should be enforced or not. # # @return [Boolean] Whether SSL connections over IP should be enforced or not. def ip_configuration_require_ssl settings.fetch(:ip_configuration, {})[:require_ssl] end ## # Returns the AppEngine application to follow # # @return [String] The AppEngine application to follow def location_preference_zone_follow_gae_application settings.fetch(:location_preference, {})[:follow_gae_application] end ## # Returns the preferred Compute Engine zone # # @return [String] The preferred Compute Engine zone def location_preference_zone settings.fetch(:location_preference, {})[:zone] end ## # Returns the pricing plan for this instance # # @return [String] The pricing plan for this instance def pricing_plan settings[:pricing_plan] 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[:replication_type] end ## # Deletes all client certificates and generates a new server SSL certificate for the instance # # @param [Boolean] async If the operation must be performed asynchronously (true by default) # @return [Fog::Google::SQL::Operation] A Operation resource def reset_ssl_config(async: true) requires :identity data = service.reset_instance_ssl_config(identity) operation = Fog::Google::SQL::Operations.new(:service => service).get(data.name) operation.tap { |o| o.wait_for { ready? } unless async } end ## # Restarts a Cloud SQL instance # # @param [Boolean] async If the operation must be performed asynchronously (true by default) # @return [Fog::Google::SQL::Operation] A Operation resource def restart(async: true) requires :identity data = service.restart_instance(identity) operation = Fog::Google::SQL::Operations.new(:service => service).get(data.name) operation.tap { |o| o.wait_for { ready? } unless async } end ## # Restores a backup of a Cloud SQL instance # # @param [String] backup_run_id The identifier of the backup configuration # @param [Boolean] async If the operation must be performed asynchronously (true by default) # @return [Fog::Google::SQL::Operation] A Operation resource def restore_backup(backup_run_id, async: true) requires :identity data = service.restore_instance_backup(identity, backup_run_id) operation = Fog::Google::SQL::Operations.new(:service => service).get(data.name) operation.tap { |o| o.wait_for { ready? } unless async } end ## # Saves a Cloud SQL instance # # @return [Fog::Google::SQL::Instance] Instance resource def save etag ? update : create end ## # Returns the version of instance settings # # @return [String] The version of instance settings def settings_version settings[:settings_version] 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, :settings_version, :tier data = service.update_instance(identity, settings_version, tier, settings) operation = Fog::Google::SQL::Operations.new(:service => service).get(data.name) operation.wait_for { ready? } reload end ## # Reload a Cloud SQL instance # # @return [Fog::Google::SQL::Instance] Instance resource def reload requires :identity data = collection.get(identity) merge_attributes(data.attributes) self end end end end end fog-google-1.9.1/lib/fog/google/models/sql/flag.rb0000644000004100000410000000120413451635472021723 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class SQL ## # A Google Cloud SQL service flag resource # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/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 :requires_restart, :aliases => "requiresRestart" attribute :type end end end end fog-google-1.9.1/lib/fog/google/models/sql/backup_run.rb0000644000004100000410000000174513451635472023155 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class SQL ## # A database instance backup run resource # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/backupRuns class BackupRun < Fog::Model identity :id attribute :description attribute :end_time, :aliases => "endTime" attribute :enqueued_time, :aliases => "enqueuedTime" attribute :error attribute :instance attribute :kind attribute :self_link, :aliases => "selfLink" attribute :start_time, :aliases => "startTime" attribute :status attribute :type attribute :window_start_time, :aliases => "windowStartTime" READY_STATUS = "DONE".freeze ## # Checks if the instance backup run is done # # @return [Boolean] True if the backup run is done; False otherwise def ready? status == READY_STATUS end end end end end fog-google-1.9.1/lib/fog/google/models/sql/ssl_certs.rb0000644000004100000410000000322113451635472023014 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).to_h[: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 return nil if e.status_code == 404 || e.status_code == 403 raise e 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) ssl_cert = service.get_ssl_cert(instance_id, sha1_fingerprint).to_h if ssl_cert new(ssl_cert) end rescue ::Google::Apis::ClientError => e # Google SQL returns a 403 if we try to access a non-existing resource # The default behaviour in Fog is to return nil return nil if e.status_code == 404 || e.status_code == 403 raise e end end end end end fog-google-1.9.1/lib/fog/google/models/sql/operations.rb0000644000004100000410000000315313451635472023202 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).items || [] data = data.map(&:to_h) 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] operation_id Instance operation ID # @return [Fog::Google::SQL::Operation] Instance operation resource def get(operation_id) if operation = service.get_operation(operation_id).to_h new(operation) end rescue ::Google::Apis::ClientError => 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 raise e unless e.status_code == 404 || e.status_code == 403 nil end end end end end fog-google-1.9.1/lib/fog/google/models/sql/ssl_cert.rb0000644000004100000410000000510313451635472022632 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class SQL ## # A SSL certificate resource # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/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 attribute :self_link, :aliases => "selfLink" # These attributes are not available in the representation of a 'SSL Certificate' returned by the SQL API. # These attributes are only available as a response 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 async [Boolean] If the operation must be performed asynchronously (true by default) # @return [Fog::Google::SQL::Operation] A Operation resource def destroy(async: true) requires :instance, :identity data = service.delete_ssl_cert(instance, identity) operation = Fog::Google::SQL::Operations.new(:service => service).get(data.name) operation.wait_for { ready? } unless async 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) merge_attributes(data.client_cert.cert_info.to_h) self.server_ca_cert = Fog::Google::SQL::SslCert.new(data.server_ca_cert.to_h) self.cert_private_key = data.client_cert.cert_private_key self end end end end end fog-google-1.9.1/lib/fog/google/models/sql/instances.rb0000644000004100000410000000217413451635472023010 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.to_h[:items] || [] load(data) end ## # Retrieves an instance # # @param [String] instance_id Instance ID # @return [Fog::Google::SQL::Instance] Instance resource def get(instance_id) instance = service.get_instance(instance_id).to_h # XXX if we pass `nil` to get() it returns empty DB object with # kind set to "sql#instancesList" # see https://github.com/google/google-api-ruby-client/issues/699 if instance[:kind].eql?("sql#instance") new(instance) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 || e.status_code == 403 nil end end end end end fog-google-1.9.1/lib/fog/google/models/sql/flags.rb0000644000004100000410000000067413451635472022120 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.to_h[:items] || [] load(data) end end end end end fog-google-1.9.1/lib/fog/google/models/sql/tier.rb0000644000004100000410000000066713451635472021771 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class SQL ## # A Google Cloud SQL service tier resource # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/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-1.9.1/lib/fog/google/models/monitoring/0000755000004100000410000000000013451635472022056 5ustar www-datawww-datafog-google-1.9.1/lib/fog/google/models/monitoring/metric_descriptors.rb0000644000004100000410000000310613451635472026307 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 filter [String] Monitoring filter specifying which metric descriptors are to be returned. # @see https://cloud.google.com/monitoring/api/v3/filters filter documentation # @param page_size [String] Maximum number of metric descriptors per page. Used for pagination. # @param page_token [String] The pagination token, which is used to page through large result sets. # @return [Array] List of Metric Descriptors. def all(filter: nil, page_size: nil, page_token: nil) data = service.list_metric_descriptors( :filter => filter, :page_size => page_size, :page_token => page_token ).to_h[:metric_descriptors] || [] load(data) end ## # Get a Metric Descriptors. # # @param metric_type [String] Metric type. For example, "custom.googleapis.com/test-metric" # @return [Fog::Google::Monitoring::MetricDescriptor] A Metric Descriptor. def get(metric_type) data = service.get_metric_descriptor(metric_type).to_h new(data) rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/google/models/monitoring/timeseries.rb0000644000004100000410000000104613451635472024555 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. # # https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list class Timeseries < Fog::Model attribute :metric attribute :resource attribute :metric_kind, :aliases => "metricKind" attribute :value_type, :aliases => "valueType" attribute :points end end end end fog-google-1.9.1/lib/fog/google/models/monitoring/monitored_resource_descriptor.rb0000644000004100000410000000104213451635472030545 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class Monitoring ## # A monitoredResourceDescriptor defines a metric type and its schema. # # @see https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.monitoredResourceDescriptors#MonitoredResourceDescriptor class MonitoredResourceDescriptor < Fog::Model identity :name attribute :description attribute :display_name, :aliases => "displayName" attribute :type attribute :labels end end end end fog-google-1.9.1/lib/fog/google/models/monitoring/monitored_resource_descriptors.rb0000644000004100000410000000265013451635472030736 0ustar www-datawww-datarequire "fog/core/collection" require "fog/google/models/monitoring/monitored_resource_descriptor" module Fog module Google class Monitoring class MonitoredResourceDescriptors < Fog::Collection model Fog::Google::Monitoring::MonitoredResourceDescriptor ## # Lists all Monitored Resource Descriptors. # # @param filter [String] The monitoring filter used to search against existing descriptors. # @see https://cloud.google.com/monitoring/api/v3/filters filter documentation # @param page_size [String] Maximum number of metric descriptors per page. Used for pagination. # @param page_token [String] The pagination token, which is used to page through large result sets. # @return [Array] List of Monitored Resource Descriptors. def all(filter: nil, page_size: nil, page_token: nil) data = service.list_monitored_resource_descriptors( :filter => filter, :page_size => page_size, :page_token => page_token ).to_h[:resource_descriptors] || [] load(data) end def get(resource_type) data = service.get_monitored_resource_descriptor(resource_type).to_h new(data) rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/google/models/monitoring/metric_descriptor.rb0000644000004100000410000000117613451635472026131 0ustar www-datawww-datarequire "fog/core/model" module Fog module Google class Monitoring ## # A metricDescriptor defines a metric type and its schema. # # @see https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors#MetricDescriptor class MetricDescriptor < Fog::Model identity :name attribute :description attribute :display_name, :aliases => "displayName" attribute :labels attribute :metric_kind, :aliases => "metricKind" attribute :type attribute :value_type, :aliases => "valueType" attribute :unit end end end end fog-google-1.9.1/lib/fog/google/models/monitoring/timeseries_collection.rb0000644000004100000410000000462413451635472026775 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 filter [String] A monitoring filter that specifies which time series should be returned. # The filter must specify a single metric type, and can additionally specify metric labels and other # information. # @param interval [Hash] Required. The time interval for which results should be returned. # @option interval [String] end_time Required RFC3339 timestamp marking the end of interval # @option interval [String] start_time Required RFC3339 timestamp marking start of interval. # @param aggregation [Hash] Optional object describing how to combine multiple time series to provide # different views of the data. By default, the raw time series data is returned. # @option aggregation [String] alignment_period The alignment period for per-time series alignment. # @option aggregation [String] cross_series_reducer The approach to be used to align individual time series. # @option aggregation [String] group_by_fields The set of fields to preserve when crossSeriesReducer is specified. # @option aggregation [String] per_series_aligner The approach to be used to combine time series. # @param order_by [String] Specifies the order in which the points of the time series should be returned. # By default, results are not ordered. Currently, this field must be left blank. # @param page_size [String] # @param page_token [String] # @param view [String] Specifies which information is returned about the time series. # # @return [Array] List of Timeseries. def all(filter: nil, interval: nil, aggregation: nil, order_by: nil, page_size: nil, page_token: nil, view: nil) data = service.list_timeseries( :filter => filter, :interval => interval, :aggregation => aggregation, :order_by => order_by, :page_size => page_size, :page_token => page_token, :view => view ).to_h[:time_series] || [] load(data) end end end end end fog-google-1.9.1/lib/fog/google/pubsub/0000755000004100000410000000000013451635472017706 5ustar www-datawww-datafog-google-1.9.1/lib/fog/google/pubsub/real.rb0000644000004100000410000000111013451635472021147 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 = ::Google::Apis::PubsubV1::PubsubService.new apply_client_options(@pubsub, options) end end end end end fog-google-1.9.1/lib/fog/google/pubsub/mock.rb0000644000004100000410000000124113451635472021162 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-1.9.1/lib/fog/google/sql/0000755000004100000410000000000013451635472017205 5ustar www-datawww-datafog-google-1.9.1/lib/fog/google/sql/real.rb0000644000004100000410000000106213451635472020454 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(" ") initialize_google_client(options) @sql = ::Google::Apis::SqladminV1beta4::SQLAdminService.new apply_client_options(@sql, options) end end end end end fog-google-1.9.1/lib/fog/google/sql/mock.rb0000644000004100000410000000156113451635472020466 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-1.9.1/lib/fog/google/pubsub.rb0000644000004100000410000000346013451635472020236 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_application_default, :google_auth, :google_client, :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-1.9.1/lib/fog/google/monitoring/0000755000004100000410000000000013451635472020573 5ustar www-datawww-datafog-google-1.9.1/lib/fog/google/monitoring/real.rb0000644000004100000410000000110413451635472022037 0ustar www-datawww-datamodule Fog module Google class Monitoring class Real include Fog::Google::Shared 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(" ") initialize_google_client(options) @monitoring = ::Google::Apis::MonitoringV3::MonitoringService.new apply_client_options(@monitoring, options) end end end end end fog-google-1.9.1/lib/fog/google/monitoring/mock.rb0000644000004100000410000000135213451635472022052 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 => {}, :monitored_resource_descriptor => {}, :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-1.9.1/lib/fog/google/mock.rb0000644000004100000410000000032113451635472017660 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-1.9.1/lib/fog/google/shared.rb0000644000004100000410000002407313451635472020207 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 [Bool] :google_application_default Explicitly use application default credentials # @option options [Google::Auth|Signet] :google_auth Manually created authorization to use # @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 [Hash] :google_client_options A hash to send additional 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 # Because of how Google API gem was rewritten, we get to do all sorts # of funky things, like this nonsense. require "google/apis/monitoring_#{Fog::Google::Monitoring::GOOGLE_MONITORING_API_VERSION}" require "google/apis/compute_#{Fog::Compute::Google::GOOGLE_COMPUTE_API_VERSION}" require "google/apis/dns_#{Fog::DNS::Google::GOOGLE_DNS_API_VERSION}" require "google/apis/pubsub_#{Fog::Google::Pubsub::GOOGLE_PUBSUB_API_VERSION}" require "google/apis/sqladmin_#{Fog::Google::SQL::GOOGLE_SQL_API_VERSION}" require "google/apis/storage_#{Fog::Storage::GoogleJSON::GOOGLE_STORAGE_JSON_API_VERSION}" require "googleauth" rescue LoadError => error Fog::Errors::Error.new("Please install the google-api-client (>= 0.9) gem before using this provider") raise error end validate_client_options(options) application_name = "fog" unless options[:app_name].nil? application_name = "#{options[:app_name]}/#{options[:app_version] || '0.0.0'} fog" end ::Google::Apis::ClientOptions.default.application_name = application_name ::Google::Apis::ClientOptions.default.application_version = Fog::Google::VERSION if ENV["DEBUG"] ::Google::Apis.logger = ::Logger.new(::STDERR) ::Google::Apis.logger.level = ::Logger::DEBUG end auth = nil if options[:google_json_key_location] || options[:google_json_key_string] auth = process_key_auth(options) elsif options[:google_auth] auth = options[:google_auth] elsif options[:google_application_default] auth = process_application_default_auth(options) else auth = process_fallback_auth(options) end ::Google::Apis::RequestOptions.default.authorization = auth auth end ## # Applies given options to the client instance # # @param [Google::Apis::Core::BaseService] service API service client instance # @param [Hash] google_client_options Service client options to apply # @param [Hash] _ignored Rest of the options (for convenience, ignored) # @return [void] def apply_client_options(service, google_client_options: nil, **_ignored) return if google_client_options.nil? || google_client_options.empty? (service.client_options.members & google_client_options.keys).each do |option| service.client_options[option] = google_client_options[option] end 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 private # Helper method to process application default authentication # # @param [Hash] options - client options hash # @return [Google::Auth::DefaultCredentials] - google auth object def process_application_default_auth(options) ::Google::Auth.get_application_default(options[:google_api_scope_url]) end # Helper method to process fallback authentication # Current fallback is application default authentication # # @param [Hash] options - client options hash # @return [Google::Auth::DefaultCredentials] - google auth object def process_fallback_auth(options) Fog::Logger.warning( "Didn't detect any client auth settings, " \ "trying to fall back to application default credentials..." ) begin return process_application_default_auth(options) rescue raise Fog::Errors::Error.new( "Fallback auth failed, could not configure authentication for Fog client.\n" \ "Check your auth options, must be one of:\n" \ "- :google_json_key_location,\n" \ "- :google_json_key_string,\n" \ "- :google_auth,\n" \ "- :google_application_default,\n" \ "If credentials are valid - please, file a bug to fog-google." \ ) end end # Helper method to process key authentication # # @param [Hash] options - client options hash # @return [Google::Auth::ServiceAccountCredentials] - google auth object def process_key_auth(options) if options[:google_json_key_location] json_key = File.read(File.expand_path(options[:google_json_key_location])) elsif options[:google_json_key_string] json_key = options[:google_json_key_string] end validate_json_credentials(json_key) ::Google::Auth::ServiceAccountCredentials.make_creds( :json_key_io => StringIO.new(json_key), :scope => options[:google_api_scope_url] ) end # Helper method to sort out deprecated and missing auth options # # @param [Hash] options - client options hash def validate_client_options(options) # Users can no longer provide their own clients due to rewrite of auth # in https://github.com/google/google-api-ruby-client/ version 0.9. if options[:google_client] raise ArgumentError.new("Deprecated argument no longer works: google_client") end # They can also no longer use pkcs12 files, because Google's new auth # library doesn't support them either. if options[:google_key_location] raise ArgumentError.new("Deprecated auth method no longer works: google_key_location") end if options[:google_key_string] raise ArgumentError.new("Deprecated auth method no longer works: google_key_string") end # Google client email option is no longer needed if options[:google_client_email] Fog::Logger.deprecation("Argument no longer needed for auth: google_client_email") end # Validate required arguments unless options[:google_api_scope_url] raise ArgumentError.new("Missing required arguments: google_api_scope_url") end end # Helper method to checks whether the necessary fields are present in # JSON key credentials # # @param [String] json_key - Google json auth key string def validate_json_credentials(json_key) 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 end end end end fog-google-1.9.1/lib/fog/google.rb0000644000004100000410000000332613451635472016737 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-1.9.1/lib/fog/compute/0000755000004100000410000000000013451635472016606 5ustar www-datawww-datafog-google-1.9.1/lib/fog/compute/google/0000755000004100000410000000000013451635472020062 5ustar www-datawww-datafog-google-1.9.1/lib/fog/compute/google/requests/0000755000004100000410000000000013451635472021735 5ustar www-datawww-datafog-google-1.9.1/lib/fog/compute/google/requests/insert_target_instance.rb0000644000004100000410000000114313451635472027017 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_target_instance(_target_name, _zone, _target_instance = {}) Fog::Mock.not_implemented end end class Real def insert_target_instance(target_name, zone, target_instance = {}) zone = zone.split("/")[-1] if zone.start_with? "http" @compute.insert_target_instance( @project, zone, ::Google::Apis::ComputeV1::TargetInstance.new( target_instance.merge(:name => target_name) ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/update_http_health_check.rb0000644000004100000410000000101313451635472027260 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def update_http_health_check(_check_name, _opts = {}) Fog::Mock.not_implemented end end class Real def update_http_health_check(check_name, opts = {}) @compute.update_http_health_check( @project, check_name, ::Google::Apis::ComputeV1::HttpHealthCheck.new( opts.merge(:name => check_name) ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/set_instance_template.rb0000644000004100000410000000176313451635472026643 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_instance_template(_instance_group_manager, _instance_template) Fog::Mock.not_implemented end end class Real def set_instance_template(instance_group_manager, instance_template) request = ::Google::Apis::ComputeV1::InstanceGroupManagersSetInstanceTemplateRequest.new( :instance_template => instance_template.class == String ? instance_template : instance_template.self_link ) if instance_group_manager.zone zone = instance_group_manager.zone.split("/")[-1] @compute.set_instance_group_manager_instance_template(@project, zone, instance_group_manager.name, request) else region = instance_group_manager.region.split("/")[-1] @compute.set_region_instance_group_manager_instance_template(@project, region, instance_group_manager.name, request) end end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/attach_disk.rb0000644000004100000410000000067213451635472024545 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def attach_disk(_instance, _zone, _disk = {}) Fog::Mock.not_implemented end end class Real def attach_disk(instance, zone, disk = {}) @compute.attach_disk( @project, zone.split("/")[-1], instance, ::Google::Apis::ComputeV1::AttachedDisk.new(disk) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_aggregated_target_instances.rb0000644000004100000410000000115613451635472031027 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_target_instances(_options = {}) Fog::Mock.not_implemented end end class Real def list_aggregated_target_instances(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_aggregated_target_instance( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_backend_services.rb0000644000004100000410000000125113451635472026606 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 @compute.list_backend_services(@project) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_networks.rb0000644000004100000410000000113413451635472025170 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_networks(_opts = {}) Fog::Mock.not_implemented end end class Real def list_networks(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_networks(@project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_backend_service.rb0000644000004100000410000000107413451635472026757 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_backend_service(_backend_service_name, _opts = {}) Fog::Mock.not_implemented end end class Real def insert_backend_service(backend_service_name, opts = {}) options = opts.reject { |_k, v| v.nil? } .merge(:name => backend_service_name) be_service = ::Google::Apis::ComputeV1::BackendService.new(options) @compute.insert_backend_service(@project, be_service) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_firewall.rb0000644000004100000410000000373013451635472025456 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_firewall(_firewall_name, _options = {}) Fog::Mock.not_implemented end end class Real INSERTABLE_FIREWALL_FIELDS = %i{ allowed denied description destination_ranges direction name network priority source_ranges source_service_accounts source_tags target_service_accounts target_tags }.freeze ## # Create a Firewall resource # # @param [Hash] opts The firewall object to create # @option opts [Array] allowed # @option opts [Array] denied # @option opts [String] description # @option opts [Array] destination_ranges # @option opts [String] direction # @option opts [String] name # @option opts [String] network # @option opts [Fixnum] priority # @option opts [Array] source_ranges # @option opts [Array] source_service_accounts # @option opts [Array] source_tags # @option opts [Array] target_service_accounts # @option opts [Array] target_tags # # @see https://cloud.google.com/compute/docs/reference/latest/firewalls/insert def insert_firewall(firewall_name, opts = {}) if opts.key?(:network) && !opts[:network].empty? unless opts[:network].start_with?("http://", "https://", "projects/", "global/") opts[:network] = "projects/#{@project}/global/networks/#{opts[:network]}" end end opts = opts.select { |k, _| INSERTABLE_FIREWALL_FIELDS.include? k } .merge(:name => firewall_name) @compute.insert_firewall( @project, ::Google::Apis::ComputeV1::Firewall.new(opts) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_global_addresses.rb0000644000004100000410000000145413451635472026616 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_global_addresses(_opts = {}) Fog::Mock.not_implemented end end class Real # List address resources in the specified project # @see https://cloud.google.com/compute/docs/reference/latest/globalAddresses def list_global_addresses(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_global_addresses(@project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_url_map.rb0000644000004100000410000000214613451635472025310 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_url_map(_url_map_name, _url_map = {}) Fog::Mock.not_implemented end end class Real def insert_url_map(url_map_name, url_map = {}) url_map[:host_rules] = url_map[:host_rules] || [] url_map[:path_matchers] = url_map[:path_matchers] || [] url_map[:tests] = url_map[:tests] || [] url_map_obj = ::Google::Apis::ComputeV1::UrlMap.new( url_map.merge(:name => url_map_name) ) # HACK: Currently URL map insert may fail even though the backend # service operation is done. Retriable is not used to not add another # runtime dependency. # TODO: Remove after that has been corrected. begin retries ||= 0 @compute.insert_url_map(@project, url_map_obj) rescue ::Google::Apis::ClientError Fog::Logger.warning("URL map insert failed, retrying...") sleep 10 retry if (retries += 1) < 2 end end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_url_maps.rb0000644000004100000410000000113113451635472025133 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_url_maps(_filter: nil, _max_results: nil, _order_by: nil, _page_token: nil) Fog::Mock.not_implemented end end class Real def list_url_maps(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_url_maps( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/create_disk_snapshot.rb0000644000004100000410000000103313451635472026453 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def create_disk_snapshot(_snapshot_name, _disk, _zone, _snapshot = {}) Fog::Mock.not_implemented end end class Real def create_disk_snapshot(snapshot_name, disk, zone, snapshot = {}) @compute.create_disk_snapshot( @project, zone, disk, ::Google::Apis::ComputeV1::Snapshot.new( snapshot.merge(:name => snapshot_name) ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_regions.rb0000644000004100000410000000076613451635472024774 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_regions Fog::Mock.not_implemented end end class Real def list_regions(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_regions( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_http_health_check.rb0000644000004100000410000000076613451635472027320 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_http_health_check(_check_name, _options = {}) Fog::Mock.not_implemented end end class Real def insert_http_health_check(check_name, opts = {}) @compute.insert_http_health_check( @project, ::Google::Apis::ComputeV1::HttpHealthCheck.new( opts.merge(:name => check_name) ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_machine_type.rb0000644000004100000410000000063013451635472025565 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_machine_type(_machine_type, _zone) Fog::Mock.not_implemented end end class Real def get_machine_type(machine_type, zone) zone = zone.split("/")[-1] if zone.start_with? "http" @compute.get_machine_type(@project, zone, machine_type) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_aggregated_instance_groups.rb0000644000004100000410000000055513451635472030677 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 = {}) @compute.list_aggregated_instance_groups(@project, options) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/set_forwarding_rule_target.rb0000644000004100000410000000106513451635472027676 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_forwarding_rule_target(_rule_name, _region, _target_opts) Fog::Mock.not_implemented end end class Real def set_forwarding_rule_target(rule_name, region, target_opts) region = region.split("/")[-1] if region.start_with? "http" @compute.set_forwarding_rule_target( @project, region, rule_name, ::Google::Apis::ComputeV1::TargetReference.new(target_opts) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_target_http_proxy.rb0000644000004100000410000000052713451635472027376 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_target_http_proxy(_proxy_name) Fog::Mock.not_implemented end end class Real def delete_target_http_proxy(proxy_name) @compute.delete_target_http_proxy(@project, proxy_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_image.rb0000644000004100000410000000072713451635472024736 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_image(_image_name, _image = {}) Fog::Mock.not_implemented end end class Real def insert_image(image_name, image = {}, project = @project) image = image.merge(:name => image_name) @compute.insert_image( project, ::Google::Apis::ComputeV1::Image.new(image) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_http_health_checks.rb0000644000004100000410000000104413451635472027140 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_http_health_checks Fog::Mock.not_implemented end end class Real def list_http_health_checks(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_http_health_checks( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_aggregated_disks.rb0000644000004100000410000000173313451635472026610 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_disks(_options = {}) Fog::Mock.not_implemented end end class Real # Retrieves an aggregated list of disks # https://cloud.google.com/compute/docs/reference/latest/disks/aggregatedList # # @param options [Hash] Optional hash of options # @option options [String] :filter Filter expression for filtering listed resources # @option options [String] :max_results # @option options [String] :order_by # @option options [String] :page_token def list_aggregated_disks(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_aggregated_disk( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_image.rb0000644000004100000410000000057713451635472024214 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_image(_image_name, _project = @project) Fog::Mock.not_implemented end end class Real def get_image(image_name, project = @project) project = @project if project.nil? @compute.get_image(project, image_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/patch_url_map.rb0000644000004100000410000000064113451635472025101 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def patch_url_map(_url_map_name, _options = {}) Fog::Mock.not_implemented end end class Real def patch_url_map(url_map_name, options = {}) @compute.patch_url_map( @project, url_map_name, ::Google::Apis::ComputeV1::UrlMap.new(options) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_firewall.rb0000644000004100000410000000047413451635472024733 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) @compute.get_firewall(@project, firewall_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_zones.rb0000644000004100000410000000101013451635472024443 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_zones Fog::Mock.not_implemented end end class Real def list_zones(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_zones( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_ssl_certificate.rb0000644000004100000410000000126313451635472027013 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_ssl_certificate(_certificate_name, _certificate, _private_key, _options = {}) Fog::Mock.not_implemented end end class Real def insert_ssl_certificate(certificate_name, certificate, private_key, description: nil) @compute.insert_ssl_certificate( @project, ::Google::Apis::ComputeV1::SslCertificate.new( :certificate => certificate, :name => certificate_name, :private_key => private_key, :description => description ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_target_https_proxy.rb0000644000004100000410000000053213451635472027555 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_target_https_proxy(_proxy_name) Fog::Mock.not_implemented end end class Real def delete_target_https_proxy(proxy_name) @compute.delete_target_https_proxy(@project, proxy_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_zone_operation.rb0000644000004100000410000000137613451635472026163 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_zone_operation(_zone_name, _operation) Fog::Mock.not_implemented end end class Real # Get the updated status of a zone operation # @see https://developers.google.com/compute/docs/reference/latest/zoneOperations/get # # @param zone_name [String] Zone the operation was peformed in # @param operation [Google::Apis::ComputeV1::Operation] Return value from asynchronous actions def get_zone_operation(zone_name, operation) zone_name = zone_name.split("/")[-1] if zone_name.start_with? "http" @compute.get_zone_operation(@project, zone_name, operation) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_target_pools.rb0000644000004100000410000000113013451635472026012 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_target_pools(_region, _opts = {}) Fog::Mock.not_implemented end end class Real def list_target_pools(region, filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_target_pools( @project, region.split("/")[-1], :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_global_forwarding_rule.rb0000644000004100000410000000051313451635472027631 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_global_forwarding_rule(_rule) Fog::Mock.not_implemented end end class Real def get_global_forwarding_rule(rule) @compute.get_global_forwarding_rule(@project, rule) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/set_target_http_proxy_url_map.rb0000644000004100000410000000105413451635472030442 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_target_http_proxy_url_map(_proxy_name, _url_map) Fog::Mock.not_implemented end end class Real def set_target_http_proxy_url_map(proxy_name, url_map) @compute.set_target_http_proxy_url_map( @project, proxy_name, ::Google::Apis::ComputeV1::UrlMapReference.new( :url_map => url_map.class == String ? url_map : url_map.self_link ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_global_address.rb0000644000004100000410000000052413451635472026552 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_global_address(_address_name) Fog::Mock.not_implemented end end class Real def delete_global_address(address_name) @compute.delete_global_address(@project, address_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_ssl_certificate.rb0000644000004100000410000000054213451635472026750 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_ssl_certificate(_certificate_name) Fog::Mock.not_implemented end end class Real def delete_ssl_certificate(certificate_name) @compute.delete_ssl_certificate(project, certificate_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_images.rb0000644000004100000410000000110013451635472024552 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_images(_project = @project, _opts = {}) Fog::Mock.not_implemented end end class Real def list_images(project = @project, filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_images( project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_snapshot.rb0000644000004100000410000000050513451635472025443 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) @compute.delete_snapshot(@project, snapshot_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/add_backend_service_backends.rb0000644000004100000410000000063713451635472030041 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) @compute.patch_backend_service(@project, backend_service.name, backend_service) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_route.rb0000644000004100000410000000205613451635472025007 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_route(_route_name, _network, _dest_range, _priority, _options = {}) Fog::Mock.not_implemented end end class Real # Creates a Route resource. # # @see https://cloud.google.com/compute/docs/reference/latest/routes/insert def insert_route(route_name, network, dest_range, priority, options = {}) route = ::Google::Apis::ComputeV1::Route.new( :name => route_name, :network => network, :dest_range => dest_range, :priority => priority, :tags => options[:tags] || [], :next_hop_instance => options[:next_hop_instance], :next_hop_gateway => options[:next_hop_gateway], :next_hop_ip => options[:next_hop_ip], :next_hop_vpn_tunnel => options[:next_hop_vpn_tunnel], :description => options[:description] ) @compute.insert_route(@project, route) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_instance_groups.rb0000644000004100000410000000047113451635472026522 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) @compute.list_instance_groups(@project, zone) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/add_target_pool_instances.rb0000644000004100000410000000134713451635472027465 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def add_target_pool_instances(_target_pool, _region, _instances) Fog::Mock.not_implemented end end class Real def add_target_pool_instances(target_pool, region, instances) instances_lst = instances.map do |instance| ::Google::Apis::ComputeV1::InstanceReference.new(:instance => instance) end @compute.add_target_pool_instance( @project, region.split("/")[-1], target_pool, ::Google::Apis::ComputeV1::AddTargetPoolsInstanceRequest.new( :instances => instances_lst ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_forwarding_rule.rb0000644000004100000410000000133613451635472027042 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_forwarding_rule(_rule_name, _region, _opts = {}) Fog::Mock.not_implemented end end class Real ## # Create a forwarding rule. # # @see https://cloud.google.com/compute/docs/reference/latest/forwardingRules/insert def insert_forwarding_rule(rule_name, region, opts = {}) region = region.split("/")[-1] if region.start_with? "http" @compute.insert_forwarding_rule( @project, region, ::Google::Apis::ComputeV1::ForwardingRule.new( opts.merge(:name => rule_name) ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_forwarding_rules.rb0000644000004100000410000000114313451635472026670 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_forwarding_rules(_region, _opts = {}) Fog::Mock.not_implemented end end class Real def list_forwarding_rules(region, filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_forwarding_rules( @project, region, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_instance_group.rb0000644000004100000410000000060013451635472026135 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) @compute.get_instance_group(project, zone, group_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_aggregated_disk_types.rb0000644000004100000410000000107713451635472027652 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_disk_types(_options = {}) Fog::Mock.not_implemented end end class Real def list_aggregated_disk_types(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_aggregated_disk_types( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_network.rb0000644000004100000410000000047713451635472025305 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) @compute.delete_network(@project, network_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_target_pool.rb0000644000004100000410000000104113451635472026161 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_target_pool(_target_pool_name, _region, _target_pool = {}) Fog::Mock.not_implemented end end class Real def insert_target_pool(target_pool_name, region, target_pool = {}) pool_obj = ::Google::Apis::ComputeV1::TargetPool.new( target_pool.merge(:name => target_pool_name) ) @compute.insert_target_pool(@project, region.split("/")[-1], pool_obj) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/update_firewall.rb0000644000004100000410000000266513451635472025442 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def update_firewall(_firewall_name, _firewall_opts = {}) Fog::Mock.not_implemented end end class Real UPDATABLE_FIREWALL_FIELDS = %i{ allowed description source_ranges source_service_accounts source_tags target_service_accounts target_tags }.freeze ## # Update a Firewall resource. # # Only the following fields can/will be changed. # # @param [Hash] opts The firewall object to create # @option opts [Array] allowed # @option opts [String] description # @option opts [Array] destination_ranges # @option opts [Array] source_ranges # @option opts [Array] source_service_accounts # @option opts [Array] source_tags # @option opts [Array] target_service_accounts # @option opts [Array] target_tags # # @see https://cloud.google.com/compute/docs/reference/latest/firewalls/insert def update_firewall(firewall_name, opts = {}) opts = opts.select { |k, _| UPDATABLE_FIREWALL_FIELDS.include? k } @compute.update_firewall( @project, firewall_name, ::Google::Apis::ComputeV1::Firewall.new(opts) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_target_https_proxy.rb0000644000004100000410000000142413451635472027620 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_target_https_proxy(_proxy_name, _description: nil, _url_map: nil, _ssl_certificates: nil) Fog::Mock.not_implemented end end class Real def insert_target_https_proxy(proxy_name, description: nil, url_map: nil, ssl_certificates: nil) @compute.insert_target_https_proxy( @project, ::Google::Apis::ComputeV1::TargetHttpsProxy.new( :name => proxy_name, :description => description, :url_map => url_map, :ssl_certificates => ssl_certificates ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/expand_subnetwork_ip_cidr_range.rb0000644000004100000410000000230213451635472030666 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def expand_subnetwork_ip_cidr_range(_subnetwork, _region, _ip_cidr_range) Fog::Mock.not_implemented end end class Real ## # Expands the IP CIDR range of the subnetwork to a specified value. # # @param subnetwork [String] the name of the subnetwork # @param region [String] the name of the subnetwork's region # @param ip_cidr_range [String] The IP of internal addresses that are legal on # this subnetwork # # @return [Google::Apis::ComputeV1::SubnetworkList] list result # # @see https://cloud.google.com/compute/docs/reference/latest/subnetworks/expandIpCidrRange def expand_subnetwork_ip_cidr_range(subnetwork, region, ip_cidr_range) if region.start_with? "http" region = region.split("/")[-1] end @compute.expand_subnetwork_ip_cidr_range( @project, region, subnetwork, ::Google::Apis::ComputeV1::SubnetworksExpandIpCidrRangeRequest.new( :ip_cidr_range => ip_cidr_range ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_forwarding_rule.rb0000644000004100000410000000063613451635472027002 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_forwarding_rule(_rule, _region) Fog::Mock.not_implemented end end class Real def delete_forwarding_rule(rule, region) region = region.split("/")[-1] if region.start_with? "http" @compute.delete_forwarding_rule(@project, region, rule) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_project.rb0000644000004100000410000000044013451635472024565 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) @compute.get_project(identity) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_target_instance.rb0000644000004100000410000000063613451635472026300 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_target_instance(_target_name, _zone) Fog::Mock.not_implemented end end class Real def get_target_instance(target_name, zone) zone = zone.split("/")[-1] if zone.start_with? "http" @compute.get_target_instance(@project, zone, target_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_instance_group.rb0000644000004100000410000000203613451635472026667 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 = {}) if options["network"] network_name = last_url_segment(options["network"]) else network_name = GOOGLE_COMPUTE_DEFAULT_NETWORK end instance_group = ::Google::Apis::ComputeV1::InstanceGroup.new( :description => options["description"], :name => group_name, :network => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/global/networks/#{network_name}" ) @compute.insert_instance_group(@project, last_url_segment(zone), instance_group) end def last_url_segment(network) network.split("/")[-1] end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_url_map.rb0000644000004100000410000000046613451635472024566 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_url_map(_url_map_name) Fog::Mock.not_implemented end end class Real def get_url_map(url_map_name) @compute.get_url_map(@project, url_map_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_disk.rb0000644000004100000410000000122213451635472024533 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_disk(_disk_name, _zone_name) Fog::Mock.not_implemented end end class Real # Delete a disk resource # https://cloud.google.com/compute/docs/reference/latest/disks/delete # # @param disk_name [String] Name of the disk to delete # @param zone_name [String] Zone the disk reside in def delete_disk(disk_name, zone_name) zone_name = zone_name.split("/")[-1] if zone_name.start_with? "http" @compute.delete_disk(@project, zone_name, disk_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/start_server.rb0000644000004100000410000000052113451635472025003 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def start_server(_identity, _zone) Fog::Mock.not_implemented end end class Real def start_server(identity, zone) @compute.start_instance(@project, zone.split("/")[-1], identity) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_routes.rb0000644000004100000410000000126313451635472024640 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_routes(_options = {}) Fog::Mock.not_implemented end end class Real # Retrieves the list of Route resources available to the specified project. # # @see https://cloud.google.com/compute/docs/reference/latest/routes/list def list_routes(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_routes( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_global_operation.rb0000644000004100000410000000111413451635472026436 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_global_operation(_operation) Fog::Mock.not_implemented end end class Real # Get the updated status of a global operation # @see https://developers.google.com/compute/docs/reference/latest/globalOperations/get # # @param operation [Google::Apis::ComputeV1::Operation] Return value from asynchronous act def get_global_operation(operation) @compute.get_global_operation(@project, operation) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_region_operations.rb0000644000004100000410000000152013451635472027041 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_region_operations(_region) Fog::Mock.not_implemented end end class Real # Retrieves a list of Operation resources contained within the specified region # @see https://developers.google.com/compute/docs/reference/latest/regionOperations/list def list_region_operations(region, filter: nil, max_results: nil, order_by: nil, page_token: nil) region = region.split("/")[-1] if region.start_with? "http" @compute.list_region_operations( @project, region, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_target_http_proxy.rb0000644000004100000410000000114013451635472027430 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_target_http_proxy(_proxy_name, _description: nil, _url_map: nil) Fog::Mock.not_implemented end end class Real def insert_target_http_proxy(proxy_name, description: nil, url_map: nil) @compute.insert_target_http_proxy( @project, ::Google::Apis::ComputeV1::TargetHttpProxy.new( :name => proxy_name, :description => description, :url_map => url_map ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_instance_template.rb0000644000004100000410000000050513451635472027303 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_instance_template(_name) Fog::Mock.not_implemented end end class Real def delete_instance_template(name) @compute.delete_instance_template(@project, name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_subnetworks.rb0000644000004100000410000000273213451635472025707 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_subnetworks(_region_name, _filter: nil, _max_results: nil, _order_by: nil, _page_token: nil) Fog::Mock.not_implemented end end class Real ## # Retrieves a list of subnetworks specific to a region and project. # # @param region_name [String] the name of the subnetwork's region # @param filter [String] A filter expression for filtering listed resources. # @param max_results [Fixnum] Max number of results to return # @param order_by [String] Sorts list results by a certain order # @param page_token [String] specifies a page token to use # @return [Google::Apis::ComputeV1::SubnetworkList] list result # # @see https://cloud.google.com/compute/docs/reference/latest/subnetworks/list def list_subnetworks(region_name, filter: nil, max_results: nil, order_by: nil, page_token: nil) if region_name.start_with? "http" region_name = region_name.split("/")[-1] end @compute.list_subnetworks(@project, region_name, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/recreate_instances.rb0000644000004100000410000000166113451635472026127 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def recreate_instances(_instance_group_manager, _instances) Fog::Mock.not_implemented end end class Real def recreate_instances(instance_group_manager, instances) request = ::Google::Apis::ComputeV1::InstanceGroupManagersAbandonInstancesRequest.new( :instances => instances.map{ |i| i.class == String ? i : i.self_link } ) if instance_group_manager.zone zone = instance_group_manager.zone.split("/")[-1] @compute.recreate_instance_group_manager_instances(@project, zone, instance_group_manager.name, request) else region = instance_group_manager.region.split("/")[-1] @compute.recreate_region_instance_group_manager_instances(@project, region, instance_group_manager.name, request) end end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/deprecate_image.rb0000644000004100000410000000100113451635472025350 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def deprecate_image(_image_name, _deprecation_status = {}, _project = @project) Fog::Mock.not_implemented end end class Real def deprecate_image(image_name, deprecation_status = {}, project = @project) @compute.deprecate_image( project, image_name, ::Google::Apis::ComputeV1::DeprecationStatus.new(deprecation_status) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_network.rb0000644000004100000410000000134313451635472025340 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_network(_network_name, _opts = {}) Fog::Mock.not_implemented end end class Real INSERTABLE_NETWORK_FIELDS = %i{ auto_create_subnetworks description gateway_i_pv4 i_pv4_range name routing_config }.freeze def insert_network(network_name, opts = {}) opts = opts.select { |k, _| INSERTABLE_NETWORK_FIELDS.include? k } .merge(:name => network_name) @compute.insert_network( @project, ::Google::Apis::ComputeV1::Network.new(opts) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_http_health_check.rb0000644000004100000410000000052713451635472027251 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_http_health_check(_check_name) Fog::Mock.not_implemented end end class Real def delete_http_health_check(check_name) @compute.delete_http_health_check(@project, check_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_server.rb0000644000004100000410000001024713451635472025160 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_server(_instance_name, _zone, _options = {}) Fog::Mock.not_implemented end end class Real def default_network_interface { :network => "global/networks/#{GOOGLE_COMPUTE_DEFAULT_NETWORK}" } end def process_disks(disks) unless disks && !disks.empty? raise ArgumentError.new("at least one value for disks is required") end disk_lst = disks.map do |d| d = d.attached_disk_obj if d.is_a? Disk ::Google::Apis::ComputeV1::AttachedDisk.new(d) end disk_lst.first.boot = true disk_lst end def process_network_interfaces(network_interfaces) unless network_interfaces && !network_interfaces.empty? network_interfaces = [default_network_interface] end network_interfaces.map do |network| ::Google::Apis::ComputeV1::NetworkInterface.new(network) end end ## # Create a new instance (virtual machine). # # This method allows you to use low-level request options and thus # expects instance options similar to API requests. If you don't need to # modify low-level request options, consider using the # Fog::Compute::Google::Servers collection object instead. # # @example minimal server creation # my_operation = client.insert_server( # "my-server", # "us-central1-a", # :machine_type => "f1-micro", # :disks => [ # { # :initialize_params => { # :source_image => "projects/debian-cloud/global/images/family/debian-9" # } # } # ] # ) # # @param instance_name [String] # Name to assign to the created server. Must be unique within the specified zone. # @param zone [String] # Name or URL of zone containing the created server. # @param options [Hash] # Server attributes. You can use any of the options documented at # https://cloud.google.com/compute/docs/reference/latest/instances/insert. # @see https://cloud.google.com/compute/docs/reference/latest/instances/insert # @return [::Google::Apis::ComputeV1::Operation] # response object that represents the insertion operation. def insert_server(instance_name, zone, options = {}) zone = zone.split("/")[-1] data = options.merge(:name => instance_name) data[:disks] = process_disks(options[:disks]) data[:network_interfaces] = process_network_interfaces(options[:network_interfaces]) machine_type = options[:machine_type] unless machine_type raise ArgumentError.new("machine type is required") end unless machine_type.include?("zones/") machine_type = "zones/#{zone}/machineTypes/#{data[:machine_type]}" end data[:machine_type] = machine_type # Optional subclassed attributes if data[:guest_accelerators] data[:guest_accelerators] = data[:guest_accelerators].map do |acc_config| ::Google::Apis::ComputeV1::AcceleratorConfig.new(acc_config) end end if data[:metadata] data[:metadata] = ::Google::Apis::ComputeV1::Metadata.new(options[:metadata]) end if data[:scheduling] data[:scheduling] = ::Google::Apis::ComputeV1::Scheduling.new(options[:scheduling]) end if data[:tags] if options[:tags].is_a?(Array) # Process classic tag notation, i.e. ["fog"] data[:tags] = ::Google::Apis::ComputeV1::Tags.new({ :items => options[:tags] }) else data[:tags] = ::Google::Apis::ComputeV1::Tags.new(options[:tags]) end end instance = ::Google::Apis::ComputeV1::Instance.new(data) @compute.insert_instance(@project, zone, instance) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_servers.rb0000644000004100000410000000105013451635472025002 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_servers(_zone, _opts = {}) Fog::Mock.not_implemented end end class Real def list_servers(zone, filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_instances( @project, zone.split("/")[-1], :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/set_target_https_proxy_url_map.rb0000644000004100000410000000105713451635472030630 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_target_https_proxy_url_map(_proxy_name, _url_map) Fog::Mock.not_implemented end end class Real def set_target_https_proxy_url_map(proxy_name, url_map) @compute.set_target_https_proxy_url_map( @project, proxy_name, ::Google::Apis::ComputeV1::UrlMapReference.new( :url_map => url_map.class == String ? url_map : url_map.self_link ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/add_instance_group_instances.rb0000644000004100000410000000201713451635472030161 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) instances.map! do |instance| if instance.start_with?("https:") ::Google::Apis::ComputeV1::InstanceReference.new(:instance => instance) else ::Google::Apis::ComputeV1::InstanceReference.new( :instance => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone}/instances/#{instance}\n" ) end end request = ::Google::Apis::ComputeV1::InstanceGroupsAddInstancesRequest.new( :instances => instances ) @compute.add_instance_group_instances( @project, zone, group_name, request ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_server_access_config.rb0000644000004100000410000000101413451635472027754 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, access_config = "External NAT") @compute.delete_instance_access_config( @project, zone.split("/")[-1], identity, access_config, nic ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_instance_group_manager.rb0000644000004100000410000000053613451635472027637 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_instance_group_manager(_name, _zone) Fog::Mock.not_implemented end end class Real def get_instance_group_manager(name, zone) @compute.get_instance_group_manager(@project, zone, name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_image_from_family.rb0000644000004100000410000000132713451635472026572 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_image_from_family(_family, _project = @project) Fog::Mock.not_implemented end end class Real # Returns the latest non-deprecated image that is part of an image family. # # @param family [String] Name of the image family # @param project [String] Project the image belongs to. # @return Google::Apis::ComputeV1::Image # # @see https://cloud.google.com/compute/docs/reference/latest/images/getFromFamily def get_image_from_family(family, project = @project) @compute.get_image_from_family(project, family) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_instance_group_managers.rb0000644000004100000410000000112013451635472030204 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_instance_group_managers(_zone, _opts = {}) Fog::Mock.not_implemented end end class Real def list_instance_group_managers(zone, filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_instance_group_managers( @project, zone, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_ssl_certificates.rb0000644000004100000410000000106413451635472026644 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_ssl_certificates Fog::Mock.not_implemented end end class Real def list_ssl_certificates(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_ssl_certificates( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/set_server_tags.rb0000644000004100000410000000103613451635472025461 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_server_tags(_instance, _zone, _tags = []) Fog::Mock.not_implemented end end class Real def set_server_tags(instance, zone, fingerprint, tags = []) @compute.set_instance_tags( @project, zone.split("/")[-1], instance, ::Google::Apis::ComputeV1::Tags.new( :fingerprint => fingerprint, :items => tags ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_network.rb0000644000004100000410000000046613451635472024620 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) @compute.get_network(@project, network_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/set_common_instance_metadata.rb0000644000004100000410000000116013451635472030147 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_common_instance_metadata(_project, _current_fingerprint, _metadata = {}) Fog::Mock.not_implemented end end class Real def set_common_instance_metadata(project, current_fingerprint, metadata = {}) metadata_obj = ::Google::Apis::ComputeV1::Metadata.new( :fingerprint => current_fingerprint, :items => metadata.map { |k, v| { :key => k, :value => v } } ) @compute.set_common_instance_metadata(project, metadata_obj) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_aggregated_subnetworks.rb0000644000004100000410000000223313451635472030055 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_subnetworks(_options = {}) Fog::Mock.not_implemented end end class Real ## # Retrieves an aggregated list of subnetworks across a project. # # @param filter [String] A filter expression for filtering listed resources. # @param max_results [Fixnum] Max number of results to return # @param order_by [String] Sorts list results by a certain order # @param page_token [String] specifies a page token to use # @return [Google::Apis::ComputeV1::SubnetworkAggregatedList] list result # # @see https://cloud.google.com/compute/docs/reference/latest/subnetworks/aggregatedList def list_aggregated_subnetworks(filter: nil, max_results: nil, page_token: nil, order_by: nil) @compute.aggregated_subnetwork_list( @project, :filter => filter, :max_results => max_results, :page_token => page_token, :order_by => order_by ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_global_operation.rb0000644000004100000410000000066413451635472027132 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_global_operation(_operation) Fog::Mock.not_implemented end end class Real # @see https://developers.google.com/compute/docs/reference/latest/globalOperations/delete def delete_global_operation(operation) @compute.delete_global_operation(@project, operation) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_disk.rb0000644000004100000410000000114513451635472024054 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_disk(_disk_name, _zone_name) Fog::Mock.not_implemented end end class Real # Get a disk resource by name from the specified zone # https://cloud.google.com/compute/docs/reference/latest/disks/get # # @param zone_name [String] Zone the disk resides in def get_disk(disk_name, zone_name) zone_name = zone_name.split("/")[-1] if zone_name.start_with? "http" @compute.get_disk(@project, zone_name, disk_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/set_server_disk_auto_delete.rb0000644000004100000410000000115713451635472030033 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 # @see https://cloud.google.com/compute/docs/reference/latest/instances/setDiskAutoDelete def set_server_disk_auto_delete(identity, zone, auto_delete, device_name) @compute.set_disk_auto_delete( @project, zone.split("/")[-1], identity, auto_delete, device_name ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_region.rb0000755000004100000410000000046613451635472024415 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_region(_identity) Fog::Mock.not_implemented end end class Real def get_region(identity) @compute.get_region(@project, identity.split("/")[-1]) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/set_target_pool_backup.rb0000644000004100000410000000137313451635472027005 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_target_pool_backup(_target_pool, _region, _backup_target, _failover_ratio: nil) Fog::Mock.not_implemented end end class Real def set_target_pool_backup(target_pool, region, backup_target, failover_ratio: nil) target_ref = ::Google::Apis::ComputeV1::TargetReference.new( :target => backup_target ) @compute.set_target_pool_backup( project, region.split("/")[-1], target_pool, target_ref, :failover_ratio => failover_ratio ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_target_instance.rb0000644000004100000410000000064713451635472026765 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_target_instance(_target_name, _zone) Fog::Mock.not_implemented end end class Real def delete_target_instance(target_name, zone) zone = zone.split("/")[-1] if zone.start_with? "http" @compute.delete_target_instance(@project, zone, target_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_disk_types.rb0000644000004100000410000000106413451635472025474 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_disk_types(_zone, _options: {}) Fog::Mock.not_implemented end end class Real def list_disk_types(zone, filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_disk_types( @project, zone.split("/")[-1], :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_zone_operation.rb0000644000004100000410000000101513451635472026634 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" @compute.delete_zone_operation(@project, zone_name, operation) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_region_operation.rb0000644000004100000410000000113013451635472027142 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 # Deletes the specified region-specific Operations resource. # @see https://developers.google.com/compute/docs/reference/latest/regionOperations/delete def delete_region_operation(region, operation) region = region.split("/")[-1] if region.start_with? "http" @compute.delete_region_operation(@project, region, operation) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/stop_server.rb0000644000004100000410000000051613451635472024637 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def stop_server(_identity, _zone) Fog::Mock.not_implemented end end class Real def stop_server(identity, zone) @compute.stop_instance(@project, zone.split("/")[-1], identity) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/set_server_scheduling.rb0000644000004100000410000000151213451635472026647 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: nil, automatic_restart: nil, preemptible: nil) scheduling = ::Google::Apis::ComputeV1::Scheduling.new scheduling.on_host_maintenance = on_host_maintenance unless on_host_maintenance.nil? scheduling.automatic_restart = automatic_restart unless automatic_restart.nil? scheduling.preemptible = preemptible unless preemptible.nil? zone = zone.split("/")[-1] @compute.set_instance_scheduling(@project, zone, identity, scheduling) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_target_pool.rb0000644000004100000410000000064713451635472026132 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_target_pool(_target_pool, _region) Fog::Mock.not_implemented end end class Real def delete_target_pool(target_pool, region) region = region.split("/")[-1] if region.start_with? "http" @compute.delete_target_pool(@project, region, target_pool) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_snapshots.rb0000644000004100000410000000104713451635472025341 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 = @project, filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_snapshots(project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_address.rb0000644000004100000410000000115613451635472024551 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 # Get an address resource in the specified project # https://cloud.google.com/compute/docs/reference/latest/addresses/get # # @param address_name [String] Project ID for this address # @param region_name [String] Region for address def get_address(address_name, region_name) @compute.get_address(@project, region_name, address_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/remove_target_pool_instance.rb0000644000004100000410000000136113451635472030043 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def remove_target_pool_instances(_target_pool, _region, _instances) Fog::Mock.not_implemented end end class Real def remove_target_pool_instances(target_pool, region, instances) instance_lst = instances.map do |instance| ::Google::Apis::ComputeV1::InstanceReference.new(:instance => instance) end @compute.remove_target_pool_instance( @project, region.split("/")[-1], target_pool, ::Google::Apis::ComputeV1::RemoveTargetPoolsInstanceRequest.new( :instances => instance_lst ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_subnetwork.rb0000644000004100000410000000462713451635472026062 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_subnetwork(_subnetwork_name, _region_name, _network, _ip_range, _options = {}) Fog::Mock.not_implemented end end class Real ## # Create a subnetwork. # # @param subnetwork_name [String] the name of the subnetwork # @param region_name [String] the name of the subnetwork's region # @param network [String] URL of the network this subnetwork belongs to # @param ip_range [String] The range of internal addresses that are owned # by this subnetwork. # @param options [Hash] Other optional attributes to set on the subnetwork # @option options [Boolean] private_ip_google_access Whether the VMs in # this subnet can access Google services without assigned external IP # addresses. # @option options [String] description An optional description of this resource. # @option options [Array] secondary_ip_ranges An array of configurations # for secondary IP ranges # @option secondary_ip_ranges [String] ip_cidr_range The range of IP # addresses for a secondary range # @option secondary_ip_ranges [String] range_name The name associated # with a secondary range # # @return [Google::Apis::ComputeV1::Operation] an operation response # # @see https://cloud.google.com/compute/docs/reference/latest/subnetworks/insert 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 params = { :name => subnetwork_name, :ip_cidr_range => ip_range, :region => region_name, :network => network } optional_fields = %i{private_ip_google_access description secondary_ip_ranges} params = optional_fields.inject(params) do |data, field| data[field] = options[field] unless options[field].nil? data end subnetwork = ::Google::Apis::ComputeV1::Subnetwork.new(params) @compute.insert_subnetwork(@project, region_name, subnetwork) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/set_server_metadata.rb0000644000004100000410000000254713451635472026313 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_server_metadata(_instance, _zone, _fingerprint, _metadata_items = {}) Fog::Mock.not_implemented end end class Real # Set an instance metadata # # @param [String] instance Instance name (identity) # @param [String] zone Name of zone # @param [String] fingerprint 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'] # @param [Hash] metadata A new metadata object # Should have the following structure: # {:items=>[{:key=>"foo", :value=>"bar"}, {:key=>"baz", :value=>"foo"}]} # # @returns [::Google::Apis::ComputeV1::Operation] set operation def set_server_metadata(instance, zone, fingerprint, metadata_items = []) items = metadata_items.map { |item| ::Google::Apis::ComputeV1::Metadata::Item.new(item) } @compute.set_instance_metadata( @project, zone.split("/")[-1], instance, ::Google::Apis::ComputeV1::Metadata.new( :fingerprint => fingerprint, :items => items ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_instance_templates.rb0000644000004100000410000000107413451635472027201 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_instance_templates Fog::Mock.not_implemented end end class Real def list_instance_templates(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_instance_templates( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/remove_target_pool_instances.rb0000644000004100000410000000135513451635472030231 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def remove_target_pool_instances(_target_pool, _region, _instances) Fog::Mock.not_implemented end end class Real def remove_target_pool_instances(target_pool, region, instances) instance_lst = instances.map do |link| ::Google::Apis::ComputeV1::InstanceReference.new( :instance => link ) end @compute.remove_target_pool_instance( @project, region.split("/")[-1], target_pool, ::Google::Apis::ComputeV1::RemoveTargetPoolsInstanceRequest.new( :instances => instance_lst ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_instance_template.rb0000644000004100000410000000047413451635472026625 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_instance_template(_name) Fog::Mock.not_implemented end end class Real def get_instance_template(name) @compute.get_instance_template(@project, name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/remove_instance_group_instances.rb0000644000004100000410000000202313451635472030723 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) instances.map! do |instance| if instance.start_with?("https:") ::Google::Apis::ComputeV1::InstanceReference.new(:instance => instance) else ::Google::Apis::ComputeV1::InstanceReference.new( :instance => "https://www.googleapis.com/compute/#{api_version}/projects/#{@project}/zones/#{zone}/instances/#{instance}\n" ) end end request = ::Google::Apis::ComputeV1::InstanceGroupsRemoveInstancesRequest.new( :instances => instances ) @compute.remove_instance_group_instances( @project, zone, group_name, request ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/detach_disk.rb0000644000004100000410000000061213451635472024523 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def detach_disk(_instance, _zone, _device_name) Fog::Mock.not_implemented end end class Real def detach_disk(instance, zone, device_name) zone = zone.split("/")[-1] @compute.detach_disk(@project, zone, instance, device_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_instance_group_manager.rb0000644000004100000410000000206313451635472030361 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_instance_group_manager(_name, _zone, _instance_template, _base_instance_name, _target_size, _target_pools, _named_ports, _description) Fog::Mock.not_implemented end end class Real def insert_instance_group_manager(name, zone, instance_template, base_instance_name, target_size, target_pools, named_ports, description) instance_group_manager = ::Google::Apis::ComputeV1::InstanceGroupManager.new( :description => description, :name => name, :instance_template => instance_template.self_link, :base_instance_name => base_instance_name, :target_size => target_size, :named_ports => named_ports || [], :target_pools => target_pools || [], ) @compute.insert_instance_group_manager(@project, zone, instance_group_manager) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_snapshot.rb0000644000004100000410000000062413451635472024762 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? @compute.get_snapshot(project, snap_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_target_http_proxy.rb0000644000004100000410000000051613451635472026711 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_target_http_proxy(_proxy_name) Fog::Mock.not_implemented end end class Real def get_target_http_proxy(proxy_name) @compute.get_target_http_proxy(@project, proxy_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_aggregated_forwarding_rules.rb0000644000004100000410000000112413451635472031041 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_forwarding_rules(_opts = {}) Fog::Mock.not_implemented end end class Real def list_aggregated_forwarding_rules(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_aggregated_forwarding_rules( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_aggregated_machine_types.rb0000644000004100000410000000111013451635472030310 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_machine_types(_opts = {}) Fog::Mock.not_implemented end end class Real def list_aggregated_machine_types(filter: nil, max_results: nil, page_token: nil, order_by: nil) @compute.list_aggregated_machine_types( @project, :filter => filter, :max_results => max_results, :page_token => page_token, :order_by => order_by ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_disk_type.rb0000644000004100000410000000050613451635472025115 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_disk_type(_disk, _zone) Fog::Mock.not_implemented end end class Real def get_disk_type(disk, zone) @compute.get_disk_type(@project, zone.split("/")[-1], disk) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/abandon_instances.rb0000644000004100000410000000165513451635472025742 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def abandon_instances(_instance_group_manager, _instances) Fog::Mock.not_implemented end end class Real def abandon_instances(instance_group_manager, instances) request = ::Google::Apis::ComputeV1::InstanceGroupManagersAbandonInstancesRequest.new( :instances => instances.map{ |i| i.class == String ? i : i.self_link } ) if instance_group_manager.zone zone = instance_group_manager.zone.split("/")[-1] @compute.abandon_instance_group_manager_instances(@project, zone, instance_group_manager.name, request) else region = instance_group_manager.region.split("/")[-1] @compute.abandon_region_instance_group_manager_instances(@project, region, instance_group_manager.name, request) end end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_global_address.rb0000644000004100000410000000051313451635472026065 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_global_address(_address_name) Fog::Mock.not_implemented end end class Real def get_global_address(address_name) @compute.get_global_address(@project, address_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_http_health_check.rb0000644000004100000410000000051613451635472026564 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_http_health_check(_check_name) Fog::Mock.not_implemented end end class Real def get_http_health_check(check_name) @compute.get_http_health_check(@project, check_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_forwarding_rule.rb0000644000004100000410000000065713451635472026322 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_forwarding_rule(_rule, _region) Fog::Mock.not_implemented end end class Real def get_forwarding_rule(rule, region) if region.start_with? "http" region = region.split("/")[-1] end @compute.get_forwarding_rule(@project, region, rule) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/reset_server.rb0000644000004100000410000000052113451635472024770 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) @compute.reset_instance(@project, zone.split("/")[-1], identity) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_global_forwarding_rule.rb0000644000004100000410000000052413451635472030316 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_global_forwarding_rule(_rule) Fog::Mock.not_implemented end end class Real def delete_global_forwarding_rule(rule) @compute.delete_global_forwarding_rule(@project, rule) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_image.rb0000644000004100000410000000053313451635472024667 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_image(_image_name, _project = @project) Fog::Mock.not_implemented end end class Real def delete_image(image_name, project = @project) @compute.delete_image(project, image_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_target_https_proxies.rb0000644000004100000410000000105413451635472027576 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_target_https_proxies Fog::Mock.not_implemented end end class Real def list_target_https_proxies(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_target_https_proxies( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_instance_group_manager.rb0000644000004100000410000000054713451635472030324 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_instance_group_manager(_name, _zone) Fog::Mock.not_implemented end end class Real def delete_instance_group_manager(name, zone) @compute.delete_instance_group_manager(@project, zone, name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_address.rb0000644000004100000410000000166313451635472025301 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 # Create an address resource in the specified project # https://cloud.google.com/compute/docs/reference/latest/addresses/insert # # @param address_name [String] Project ID for this address # @param region_name [String] Region for address # @param options [Hash] Optional hash of options # @option options [String] :description Description of resource def insert_address(address_name, region_name, options = {}) address = ::Google::Apis::ComputeV1::Address.new( :name => address_name, :description => options[:description] ) @compute.insert_address(@project, region_name, address) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_aggregated_addresses.rb0000644000004100000410000000117613451635472027451 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_addresses(_options = {}) Fog::Mock.not_implemented end end class Real # Retrieves an aggregated list of addresses # https://cloud.google.com/compute/docs/reference/latest/addresses/aggregatedList # @param options [Hash] Optional hash of options # @option options [String] :filter Filter expression for filtering listed resources def list_aggregated_addresses(options = {}) @compute.list_aggregated_addresses(@project, options) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_aggregated_instance_group_managers.rb0000644000004100000410000000121013451635472032356 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_instance_group_managers(_opts = {}) Fog::Mock.not_implemented end end class Real def list_aggregated_instance_group_managers(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_aggregated_instance_group_managers( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_target_pool.rb0000644000004100000410000000063613451635472025445 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_target_pool(_target_pool, _region) Fog::Mock.not_implemented end end class Real def get_target_pool(target_pool, region) region = region.split("/")[-1] if region.start_with? "http" @compute.get_target_pool(@project, region, target_pool) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_ssl_certificate.rb0000644000004100000410000000053213451635472026264 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_ssl_certificate(_certificate_name) Fog::Mock.not_implemented end end class Real def get_ssl_certificate(certificate_name) @compute.get_ssl_certificate(@project, certificate_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_zone.rb0000644000004100000410000000044413451635472024076 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_zone(_zone_name) Fog::Mock.not_implemented end end class Real def get_zone(zone_name) @compute.get_zone(@project, zone_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/validate_url_map.rb0000644000004100000410000000102413451635472025567 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def validate_url_map(_url_map_name, _url_map: {}) Fog::Mock.not_implemented end end class Real def validate_url_map(url_map_name, url_map = {}) @compute.validate_url_map( @project, url_map_name, ::Google::Apis::ComputeV1::ValidateUrlMapsRequest.new( :url_map => ::Google::Apis::ComputeV1::UrlMap.new(url_map) ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/add_server_access_config.rb0000644000004100000410000000151113451635472027244 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, network_interface, access_config_name = "External NAT", nat_ip: nil) @compute.add_instance_access_config( @project, zone.split("/")[-1], identity, network_interface, ::Google::Apis::ComputeV1::AccessConfig.new( :name => access_config_name, :nat_ip => nat_ip, :type => "ONE_TO_ONE_NAT" ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_instance_group_instances.rb0000644000004100000410000000072613451635472030411 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) @compute.list_instance_group_instances(@project, zone, group_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_firewall.rb0000644000004100000410000000050513451635472025411 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) @compute.delete_firewall(@project, firewall_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_target_pool_health.rb0000644000004100000410000000103213451635472026761 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_target_pool_health(_target_pool, _region, _instance) Fog::Mock.not_implemented end end class Real def get_target_pool_health(target_pool, region, instance) @compute.get_target_pool_health( @project, region.split("/")[-1], target_pool, ::Google::Apis::ComputeV1::InstanceReference.new( :instance => instance ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_aggregated_target_pools.rb0000644000004100000410000000113413451635472030170 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_target_pools(_opts = {}) Fog::Mock.not_implemented end end class Real def list_aggregated_target_pools(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_aggregated_target_pools( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_disks.rb0000644000004100000410000000134413451635472024434 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_disks(_zone_name, _opts = {}) Fog::Mock.not_implemented end end class Real # List disk resources in the specified zone # https://cloud.google.com/compute/docs/reference/latest/disks/list # # @param zone_name [String] Zone to list disks from def list_disks(zone_name, filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_disks( @project, zone_name, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_route.rb0000644000004100000410000000067213451635472024264 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_route(_identity) Fog::Mock.not_implemented end end class Real # List address resources in the specified project # # @see https://cloud.google.com/compute/docs/reference/latest/routes/list def get_route(identity) @compute.get_route(@project, identity) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_target_instances.rb0000644000004100000410000000122213451635472026647 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_target_instances(_zone, _opts: {}) Fog::Mock.not_implemented end end class Real def list_target_instances(zone, filter: nil, max_results: nil, order_by: nil, page_token: nil) zone = zone.split("/")[-1] if zone.start_with? "http" @compute.list_target_instances( @project, zone, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_global_forwarding_rule.rb0000644000004100000410000000121713451635472030360 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_global_forwarding_rule(_rule_name, _opts = {}) Fog::Mock.not_implemented end end class Real ## # Create a global forwarding rule. # # @see https://cloud.google.com/compute/docs/reference/latest/globalForwardingRules/insert def insert_global_forwarding_rule(rule_name, opts = {}) opts = opts.merge(:name => rule_name) @compute.insert_global_forwarding_rule( @project, ::Google::Apis::ComputeV1::ForwardingRule.new(opts) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/set_subnetwork_private_ip_google_access.rb0000644000004100000410000000314013451635472032435 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_subnetwork_private_ip_google_access(_subnetwork_name, _region_name, _private_ip_google_access) Fog::Mock.not_implemented end end class Real ## # Set whether VMs in this subnet can access Google services without # assigning external IP addresses through Private Google Access. # # @param subnetwork_name [String] the name of the subnetwork # @param region_name [String] the name of the subnetwork's region # @param private_ip_google_access [Boolean] whether # private ip google access should be enforced # @return [Google::Apis::ComputeV1::Operation] an operation response # # @see https://cloud.google.com/compute/docs/reference/latest/subnetworks/setPrivateIpGoogleAccess def set_subnetwork_private_ip_google_access(subnetwork_name, region_name, private_ip_google_access) if region_name.start_with? "http" region_name = region_name.split("/")[-1] end @compute.set_subnetwork_private_ip_google_access( @project, region_name, subnetwork_name, ::Google::Apis::ComputeV1::SubnetworksSetPrivateIpGoogleAccessRequest.new( :private_ip_google_access => private_ip_google_access ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/update_url_map.rb0000644000004100000410000000123213451635472025261 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def update_url_map(_url_map_name, _url_map = {}) Fog::Mock.not_implemented end end class Real def update_url_map(url_map_name, url_map = {}) url_map[:host_rules] = url_map[:host_rules] || [] url_map[:path_matchers] = url_map[:path_matchers] || [] url_map[:tests] = url_map[:tests] || [] @compute.update_url_map( @project, url_map_name, ::Google::Apis::ComputeV1::UrlMap.new( url_map.merge(:name => url_map_name) ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/add_target_pool_health_checks.rb0000644000004100000410000000145313451635472030261 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def add_target_pool_health_checks(_target_pool, _region, _health_checks) Fog::Mock.not_implemented end end class Real def add_target_pool_health_checks(target_pool, region, health_checks) check_list = health_checks.map do |health_check| ::Google::Apis::ComputeV1::HealthCheckReference.new( :health_check => health_check ) end @compute.add_target_pool_health_check( @project, region.split("/")[-1], target_pool, ::Google::Apis::ComputeV1::AddTargetPoolsHealthCheckRequest.new( :health_checks => check_list ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/patch_firewall.rb0000644000004100000410000000125413451635472025250 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def patch_firewall(_firewall_name, _firewall_opts = {}) Fog::Mock.not_implemented end end class Real ## # Patch a Firewall resource. Supports PATCH semantics. # # @see https://cloud.google.com/compute/docs/reference/latest/firewalls/patch def patch_firewall(firewall_name, opts = {}) opts = opts.select { |k, _| UPDATABLE_FIREWALL_FIELDS.include? k } @compute.patch_firewall( @project, firewall_name, ::Google::Apis::ComputeV1::Firewall.new(opts) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/set_snapshot_labels.rb0000644000004100000410000000104013451635472026311 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_snapshot_labels(_snap_name) Fog::Mock.not_implemented end end class Real def set_snapshot_labels(snap_name, label_fingerprint, labels) @compute.set_snapshot_labels( project, snap_name, ::Google::Apis::ComputeV1::GlobalSetLabelsRequest.new( :label_fingerprint => label_fingerprint, :labels => labels ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_target_https_proxy.rb0000644000004100000410000000052113451635472027070 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_target_https_proxy(_proxy_name) Fog::Mock.not_implemented end end class Real def get_target_https_proxy(proxy_name) @compute.get_target_https_proxy(@project, proxy_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_backend_service.rb0000644000004100000410000000071013451635472026226 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) @compute.get_backend_service(@project, service_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_address.rb0000644000004100000410000000117513451635472025235 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 # Delete an address resource in the specified project # https://cloud.google.com/compute/docs/reference/latest/addresses/delete # # @param address_name [String] Project ID for this address # @param region_name [String] Region for address def delete_address(address_name, region_name) @compute.delete_address(@project, region_name, address_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_region_operation.rb0000644000004100000410000000113113451635472026460 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_region_operation(_region, _operation) raise Fog::Errors::MockNotImplemented end end class Real # Retrieves the specified region-specific Operations resource # @see https://developers.google.com/compute/docs/reference/latest/regionOperations/get def get_region_operation(region, operation) region = region.split("/")[-1] if region.start_with? "http" @compute.get_region_operation(@project, region, operation) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_machine_types.rb0000644000004100000410000000132713451635472026150 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_machine_types(_zone, _opts = {}) Fog::Mock.not_implemented end end class Real def list_machine_types(zone, filter: nil, max_results: nil, page_token: nil, order_by: nil) zone = zone.split("/")[-1] if zone.start_with? "http" @compute.list_machine_types(@project, zone, :filter => filter, :max_results => max_results, :page_token => page_token, :order_by => order_by) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_server.rb0000644000004100000410000000051613451635472025114 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_server(_server, _zone) Fog::Mock.not_implemented end end class Real def delete_server(server, zone) @compute.delete_instance(@project, zone.split("/")[-1], server) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/set_global_forwarding_rule_target.rb0000644000004100000410000000074613451635472031223 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_global_forwarding_rule_target(_rule_name, _target) Fog::Mock.not_implemented end end class Real def set_global_forwarding_rule_target(rule_name, target_opts) @compute.set_global_forwarding_rule_target( @project, rule_name, ::Google::Apis::ComputeV1::TargetReference.new(target_opts) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_route.rb0000644000004100000410000000077213451635472024750 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_route(_identity) Fog::Mock.not_implemented end end class Real # Deletes the specified Route resource. # # @param identity [String] Name of the route to delete # @see https://cloud.google.com/compute/docs/reference/latest/routes/delete def delete_route(identity) @compute.delete_route(@project, identity) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_instance_group.rb0000644000004100000410000000054113451635472026624 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) @compute.delete_instance_group(@project, zone, group_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/set_target_https_proxy_ssl_certificates.rb0000644000004100000410000000107313451635472032515 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def set_target_https_proxy_ssl_certificates(_proxy_name, _certs) Fog::Mock.not_implemented end end class Real def set_target_https_proxy_ssl_certificates(proxy_name, certs) @compute.set_target_https_proxy_ssl_certificates( @project, proxy_name, ::Google::Apis::ComputeV1::TargetHttpsProxiesSetSslCertificatesRequest.new( :ssl_certificates => certs ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_instance_template.rb0000644000004100000410000000235013451635472027345 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_instance_template(_name, _properties, _description) Fog::Mock.not_implemented end end class Real ## # Create a new template. # # @param name [String] # Name to assign to the created template. Must be unique. # @param descrption [String] # Optional description of the template # @param properties [Hash] # Template attributes. You can use any of the options documented at # https://cloud.google.com/compute/docs/reference/rest/v1/instanceTemplates/insert # @see https://cloud.google.com/compute/docs/reference/rest/v1/instanceTemplates/insert # @return [::Google::Apis::ComputeV1::Operation] # response object that represents the insertion operation. def insert_instance_template(name, properties, description) instance_template = ::Google::Apis::ComputeV1::InstanceTemplate.new( :description => description, :name => name, :properties => properties, ) @compute.insert_instance_template(@project, instance_template) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_global_operations.rb0000644000004100000410000000123113451635472027015 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_global_operations Fog::Mock.not_implemented end end class Real # @see https://developers.google.com/compute/docs/reference/latest/globalOperations/list def list_global_operations(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_global_operations( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_firewalls.rb0000644000004100000410000000113013451635472025300 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(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_firewalls(@project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_server_serial_port_output.rb0000644000004100000410000000252013451635472030451 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 # Returns the specified instance's serial port output. # @param [String] zone Zone for the given instance # @param [String] instance Instance scoping this request. # @param [Fixnum] port # Specifies which COM or serial port to retrieve data from. # Acceptable values are 1 to 4, inclusive. (Default: 1) # @param [Fixnum] start # Returns output starting from a specific byte position. # Use this to page through output when the output is too large to # return in a single request. For the initial request, # leave this field unspecified. For subsequent calls, this field # should be set to the next value returned in the previous call. # @see https://cloud.google.com/compute/docs/reference/latest/instances/getSerialPortOutput def get_server_serial_port_output(identity, zone, port: nil, start: nil) @compute.get_instance_serial_port_output( @project, zone.split("/")[-1], identity, :port => port, :start => start ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_zone_operations.rb0000644000004100000410000000134213451635472026533 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_zone_operations(_zone) Fog::Mock.not_implemented end end class Real # @see https://developers.google.com/compute/docs/reference/latest/zoneOperations/list def list_zone_operations(zone, filter: nil, max_results: nil, order_by: nil, page_token: nil) zone = zone.split("/")[-1] if zone.start_with? "http" @compute.list_zone_operations( @project, zone, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_target_http_proxies.rb0000644000004100000410000000122013451635472027406 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_target_http_proxies(_filter: nil, _max_results: nil, _order_by: nil, _page_token: nil) Fog::Mock.not_implemented end end class Real def list_target_http_proxies(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_target_http_proxies( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_subnetwork.rb0000644000004100000410000000164313451635472025330 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_subnetwork(_subnetwork_name, _region_name) Fog::Mock.not_implemented end end class Real ## # Returns the specified subnetwork. # # @param subnetwork_name [String] the name of the subnetwork # @param region_name [String] the name of the subnetwork's region # @return [Google::Apis::ComputeV1::Operation] an operation response # # @see https://cloud.google.com/compute/docs/reference/latest/subnetworks/get 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" @compute.get_subnetwork(@project, region_name, subnetwork_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_aggregated_servers.rb0000644000004100000410000000106213451635472027157 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_aggregated_servers(_opts = {}) Fog::Mock.not_implemented end end class Real def list_aggregated_servers(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_aggregated_instances( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_global_address.rb0000644000004100000410000000116613451635472026617 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_global_address(_address_name, _options = {}) Fog::Mock.not_implemented end end class Real INSERTABLE_ADDRESS_FIELDS = %i{description ip_version}.freeze def insert_global_address(address_name, options = {}) opts = options.select { |k, _| INSERTABLE_ADDRESS_FIELDS.include? k } .merge(:name => address_name) @compute.insert_global_address( @project, ::Google::Apis::ComputeV1::Address.new(opts) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_addresses.rb0000644000004100000410000000133313451635472025272 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_addresses(_region_name, _opts = {}) Fog::Mock.not_implemented end end class Real # List address resources in the specified project # @see https://cloud.google.com/compute/docs/reference/latest/addresses/list def list_addresses(region_name, filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_addresses( @project, region_name, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/list_global_forwarding_rules.rb0000644000004100000410000000110413451635472030205 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def list_global_forwarding_rules(_opts = {}) Fog::Mock.not_implemented end end class Real def list_global_forwarding_rules(filter: nil, max_results: nil, order_by: nil, page_token: nil) @compute.list_global_forwarding_rules( @project, :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/remove_target_pool_health_checks.rb0000644000004100000410000000142313451635472031023 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def remove_target_pool_health_checks(_target_pool, _region, _health_checks) Fog::Mock.not_implemented end end class Real def remove_target_pool_health_checks(target_pool, region, health_checks) health_check_lst = health_checks.map do |hc| ::Google::Apis::ComputeV1::HealthCheckReference.new(:health_check => hc) end @compute.remove_target_pool_health_check( @project, region.split("/")[-1], target_pool, ::Google::Apis::ComputeV1::RemoveTargetPoolsHealthCheckRequest.new( :health_checks => health_check_lst ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_backend_service.rb0000644000004100000410000000060113451635472026710 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_backend_service(_backend_service_name, _zone_name = nil) Fog::Mock.not_implemented end end class Real def delete_backend_service(backend_service_name) @compute.delete_backend_service(@project, backend_service_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/invalidate_url_map_cache.rb0000644000004100000410000000102713451635472027244 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def invalidate_url_map_cache(_url_map_name, _path, _host = nil) Fog::Mock.not_implemented end end class Real def invalidate_url_map_cache(url_map_name, path, host = nil) @compute.invalidate_url_map_cache( @project, url_map_name, ::Google::Apis::ComputeV1::CacheInvalidationRule.new( :path => path, :host => host ) ) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_backend_service_health.rb0000644000004100000410000000121213451635472027551 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) health_results = backend_service.backends.map do |backend| group = ::Google::Apis::ComputeV1::ResourceGroupReference.new(:group => backend[:group]) resp = @compute.get_backend_service_health(@project, backend_service.name, group) [backend[:group], resp.health_status] end Hash[health_results] end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/insert_disk.rb0000644000004100000410000000363113451635472024603 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def insert_disk(_disk_name, _zone, _image_name = nil, _options = {}) Fog::Mock.not_implemented end end class Real # Create a disk resource in a specific zone # https://cloud.google.com/compute/docs/reference/latest/disks/insert # # @param disk_name [String] Name of the disk to create # @param zone_name [String] Zone the disk reside in # @param source_image [String] Optional self_link or family formatted url of the image to # create the disk from, see https://cloud.google.com/compute/docs/reference/latest/disks/insert # @param opts [Hash] Optional hash of options # @option options [String] size_gb Number of GB to allocate to an empty disk # @option options [String] source_snapshot Snapshot to create the disk from # @option options [String] description Human friendly description of the disk # @option options [String] type URL of the disk type resource describing which disk type to use # TODO: change source_image to keyword argument in 2.0 and properly deprecate def insert_disk(disk_name, zone, source_image = nil, description: nil, type: nil, size_gb: nil, source_snapshot: nil, **_opts) if source_image && !source_image.include?("projects/") raise ArgumentError.new("source_image needs to be self-link formatted or specify a family") end disk = ::Google::Apis::ComputeV1::Disk.new( :name => disk_name, :description => description, :type => type, :size_gb => size_gb, :source_snapshot => source_snapshot, :source_image => source_image ) @compute.insert_disk(@project, zone.split("/")[-1], disk) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_url_map.rb0000644000004100000410000000047713451635472025253 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_url_map(_url_map_name) Fog::Mock.not_implemented end end class Real def delete_url_map(url_map_name) @compute.delete_url_map(@project, url_map_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/delete_subnetwork.rb0000644000004100000410000000155213451635472026012 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def delete_subnetwork(_subnetwork_name, _region_name) Fog::Mock.not_implemented end end class Real ## # Delete a subnetwork. # # @param subnetwork_name [String] the name of the subnetwork to delete # @param region_name [String] the name of the subnetwork's region # # @return [Google::Apis::ComputeV1::Operation] delete operation # # @see https://cloud.google.com/compute/docs/reference/latest/subnetworks/delete def delete_subnetwork(subnetwork_name, region_name) if region_name.start_with? "http" region_name = region_name.split("/")[-1] end @compute.delete_subnetwork(@project, region_name, subnetwork_name) end end end end end fog-google-1.9.1/lib/fog/compute/google/requests/get_server.rb0000644000004100000410000000051313451635472024426 0ustar www-datawww-datamodule Fog module Compute class Google class Mock def get_server(_instance, _zone) Fog::Mock.not_implemented end end class Real def get_server(instance, zone) @compute.get_instance(@project, zone.split("/")[-1], instance) end end end end end fog-google-1.9.1/lib/fog/compute/google/models/0000755000004100000410000000000013451635472021345 5ustar www-datawww-datafog-google-1.9.1/lib/fog/compute/google/models/addresses.rb0000755000004100000410000000400513451635472023651 0ustar www-datawww-datamodule Fog module Compute class Google class Addresses < Fog::Collection model Fog::Compute::Google::Address def all(region: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) opts = { :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token } if region data = service.list_addresses(region, opts).items || [] else data = [] service.list_aggregated_addresses(opts).items.each_value do |scoped_list| data.concat(scoped_list.addresses) if scoped_list && scoped_list.addresses end end load(data.map(&:to_h)) end def get(identity, region = nil) if region address = service.get_address(identity, region).to_h return new(address) elsif identity response = all(:filter => "name eq #{identity}", :max_results => 1) address = response.first unless response.empty? return address end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end def get_by_ip_address(ip_address) addresses = service.list_aggregated_addresses(:filter => "address eq .*#{ip_address}").items address = addresses.each_value.select(&:addresses) return nil if address.empty? new(address.first.addresses.first.to_h) end def get_by_name(ip_name) names = service.list_aggregated_addresses(:filter => "name eq .*#{ip_name}").items name = names.each_value.select(&:addresses) return nil if name.empty? new(name.first.addresses.first.to_h) 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-1.9.1/lib/fog/compute/google/models/route.rb0000644000004100000410000000323313451635472023031 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 :next_hop_vpn_tunnel, :aliases => "nextHopVpnTunnel" 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.name) operation.wait_for { ready? } reload end def destroy(async = true) requires :identity data = service.delete_route(identity) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async operation end end end end end fog-google-1.9.1/lib/fog/compute/google/models/forwarding_rules.rb0000644000004100000410000000247513451635472025256 0ustar www-datawww-datamodule Fog module Compute class Google class ForwardingRules < Fog::Collection model Fog::Compute::Google::ForwardingRule def all(region: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) opts = { :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token } if region data = service.list_forwarding_rules(region, opts).items || [] else data = [] service.list_aggregated_forwarding_rules(opts).items .each_value do |scoped_list| if scoped_list && scoped_list.forwarding_rules data.concat(scoped_list.forwarding_rules) end end end load(data.map(&:to_h)) end def get(identity, region = nil) if region forwarding_rule = service.get_forwarding_rule(identity, region).to_h return new(forwarding_rule) elsif identity response = all( :filter => "name eq #{identity}", :max_results => 1 ) forwarding_rule = response.first unless response.empty? return forwarding_rule end end end end end end fog-google-1.9.1/lib/fog/compute/google/models/subnetworks.rb0000644000004100000410000000247213451635472024265 0ustar www-datawww-datamodule Fog module Compute class Google class Subnetworks < Fog::Collection model Fog::Compute::Google::Subnetwork def all(region: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) filters = { :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token } if region data = service.list_subnetworks(region, filters).to_h[:items] || [] else data = [] service.list_aggregated_subnetworks(filters).to_h[:items].each_value do |region_obj| data.concat(region_obj[:subnetworks]) if region_obj[:subnetworks] end end load(data) end def get(identity, region = nil) if region subnetwork = service.get_subnetwork(identity, region).to_h return new(subnetwork) elsif identity response = all(:filter => "name eq #{identity}", :max_results => 1) subnetwork = response.first unless response.empty? return subnetwork end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/target_https_proxy.rb0000644000004100000410000000627713451635472025657 0ustar www-datawww-datamodule Fog module Compute class Google class TargetHttpsProxy < Fog::Model identity :name attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description, :aliases => "description" attribute :id, :aliases => "id" attribute :kind, :aliases => "kind" attribute :self_link, :aliases => "selfLink" attribute :url_map, :aliases => "urlMap" # Array of SSL Certificates # @example # # [cert_one.self_link', cert_two.self_link] # # , where 'cert_one' and 'cert_two' are instances of # Fog::Compute::Google::SslCertificate # # @return [Array] attribute :ssl_certificates, :aliases => "sslCertificates" def save requires :identity, :url_map, :ssl_certificates unless ssl_certificates.is_a?(Array) raise Fog::Errors::Error.new("ssl_certificates attribute must be an array") end data = service.insert_target_https_proxy( identity, :description => description, :url_map => url_map, :ssl_certificates => ssl_certificates ) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } reload end def destroy(async = true) requires :identity data = service.delete_target_https_proxy(identity) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async operation end def set_url_map(url_map, async = true) requires :identity data = service.set_target_https_proxy_url_map( identity, url_map ) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async reload end def set_ssl_certificates(ssl_certificates, async = true) requires :identity data = service.set_target_https_proxy_ssl_certificates( identity, ssl_certificates ) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async reload end def ready? requires :identity service.get_target_https_proxy(identity) true rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 false end def reload requires :identity return unless data = begin collection.get(identity) rescue Excon::Errors::SocketError nil end new_attributes = data.attributes merge_attributes(new_attributes) self end RUNNING_STATE = "READY".freeze end end end end fog-google-1.9.1/lib/fog/compute/google/models/routes.rb0000644000004100000410000000101413451635472023207 0ustar www-datawww-datamodule Fog module Compute class Google class Routes < Fog::Collection model Fog::Compute::Google::Route def all data = service.list_routes.to_h load(data[:items] || []) end def get(identity) if identity route = service.get_route(identity).to_h return new(route) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/http_health_checks.rb0000644000004100000410000000113713451635472025520 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.to_h[:items] || [] load(data) end def get(identity) if identity http_health_check = service.get_http_health_check(identity).to_h return new(http_health_check) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/instance_group.rb0000644000004100000410000000437113451635472024717 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_instance(instance_id) add_instances [instance_id] 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) 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-1.9.1/lib/fog/compute/google/models/snapshot.rb0000644000004100000410000000377413451635472023544 0ustar www-datawww-datamodule Fog module Compute class Google class Snapshot < Fog::Model identity :name attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :disk_size_gb, :aliases => "diskSizeGb" attribute :id attribute :kind attribute :label_fingerprint, :aliases => "labelFingerprint" attribute :labels attribute :licenses attribute :self_link, :aliases => "selfLink" attribute :snapshot_encryption_key, :aliases => "snapshotEncryptionKey" attribute :source_disk, :aliases => "sourceDisk" attribute :source_disk_encryption_key, :aliases => "sourceDiskEncryptionKey" attribute :source_disk_id, :aliases => "sourceDiskId" attribute :status attribute :storage_bytes, :aliases => "storageBytes" attribute :storage_bytes_status, :aliases => "storageBytesStatus" CREATING_STATE = "CREATING".freeze DELETING_STATE = "DELETING".freeze FAILED_STATE = "FAILED".freeze READY_STATE = "READY".freeze UPLOADING_STATE = "UPLOADING".freeze def destroy(async = true) requires :identity data = service.delete_snapshot(identity) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async operation end def set_labels(new_labels) requires :identity, :label_fingerprint unless new_labels.is_a? Hash raise ArgumentError, "Labels should be a hash, e.g. {foo: \"bar\",fog: \"test\"}" end service.set_snapshot_labels(identity, label_fingerprint, new_labels) reload end def ready? status == READY_STATE end def resource_url "#{service.project}/global/snapshots/#{name}" end end end end end fog-google-1.9.1/lib/fog/compute/google/models/image.rb0000644000004100000410000000530313451635472022755 0ustar www-datawww-datamodule Fog module Compute class Google class Image < Fog::Model identity :name attribute :archive_size_bytes, :aliases => "archiveSizeBytes" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :deprecated attribute :description attribute :disk_size_gb, :aliases => "diskSizeGb" attribute :family attribute :guest_os_features, :aliases => "guestOsFeatures" attribute :id attribute :image_encryption_key, :aliases => "imageEncryptionKey" attribute :kind attribute :licenses # A RawDisk, e.g. - # { # :source => url_to_gcs_file, # :container_type => 'TAR', # :sha1Checksum => , # } attribute :raw_disk, :aliases => "rawDisk" attribute :self_link, :aliases => "selfLink" attribute :source_disk, :aliases => "sourceDisk" attribute :source_disk_encryption_key, :aliases => "sourceDiskEncryptionKey" attribute :source_disk_id, :aliases => "sourceDiskId" attribute :source_image, :aliases => "sourceImage" attribute :source_image_encryption_key, :aliases => "sourceImageEncryptionKey" attribute :source_image_id, :aliases => "sourceImageId" attribute :source_type, :aliases => "sourceType" attribute :status # This attribute is not available in the representation of an # 'image' returned by the GCE server (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 READY_STATE = "READY".freeze 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.name) operation.wait_for { ready? } unless async operation end def reload requires :name data = service.get_image(name, project) merge_attributes(data.to_h) self end def save requires :name data = service.insert_image(name, attributes) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } reload end def resource_url "#{project}/global/images/#{name}" end end end end end fog-google-1.9.1/lib/fog/compute/google/models/address.rb0000755000004100000410000000674113451635472023332 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".freeze RESERVED_STATE = "RESERVED".freeze RESERVING_STATE = "RESERVING".freeze 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.name, nil, data.region) operation.wait_for { ready? } 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.name, nil, data.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 def ready? status != RESERVING_STATE end private def associate(nic_name, async = true) requires :address data = service.add_server_access_config( server.name, server.zone, nic_name, :nat_ip => address ) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async end def disassociate requires :address return nil if !in_use? || users.nil? || users.empty? server_name = users.first.split("/")[-1] # An address can only be associated with one server at a time server = service.servers.get(server_name) server.network_interfaces.each do |nic| # Skip if nic has no access_config next if nic[:access_configs].nil? || nic[:access_configs].empty? access_config = nic[:access_configs].first # Skip access_config with different address next if access_config[:nat_ip] != address data = service.delete_server_access_config( server.name, server.zone, nic[:name], access_config[:name] ) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async return operation end end end end end end fog-google-1.9.1/lib/fog/compute/google/models/region.rb0000755000004100000410000000127313451635472023163 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".freeze UP_STATE = "UP".freeze def up? status == UP_STATE end end end end end fog-google-1.9.1/lib/fog/compute/google/models/disk.rb0000644000004100000410000001276713451635472022641 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 default_description if !source_image.nil? "created from image: #{source_image}" elsif !source_snapshot.nil? "created from snapshot: #{source_snapshot}" else "created with fog" end end def save requires :name, :zone, :size_gb options = { :description => description || default_description, :type => type, :size_gb => size_gb, :source_image => source_image, :source_snapshot => source_snapshot } if options[:source_image] unless source_image.include?("projects/") options[:source_image] = service.images.get(source_image).self_link end end # Request needs backward compatibility so source image is specified in # method arguments data = service.insert_disk(name, zone, options[:source_image], options) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } 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.name, data.zone) operation.wait_for { ready? } unless async operation end def zone_name zone.nil? ? nil : zone.split("/")[-1] end # Returns an attached disk configuration hash. # # Compute API needs attached disks to be specified in a custom format. # This provides a handy shortcut for generating a preformatted config. # # Example output: # {:auto_delete=>false, # :boot=>true, # :mode=>"READ_WRITE", # :source=>"https://www.googleapis.com/compute/v1/projects/myproj/zones/us-central1-f/disks/mydisk", # :type=>"PERSISTENT"} # # See Instances.insert API docs for more info: # https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert # # @param [Hash] opts options to attach the disk with. # @option opts [Boolean] :writable The mode in which to attach this # disk. (defaults to READ_WRITE) # @option opts [Boolean] :boot Indicates whether this is a boot disk. # (defaults to false) # @option opts [String] :device_name Specifies a unique device name # of your choice that is reflected into the /dev/disk/by-id/google-* # tree of a Linux operating system running within the instance. # @option opts [Object] :encryption_key Encrypts or decrypts a disk # using a customer-supplied encryption key. # @option opts [Object] :auto_delete Specifies whether the disk will # be auto-deleted when the instance is deleted. (defaults to false) # # @return [Hash] Attached disk configuration hash def attached_disk_obj(opts = {}) requires :self_link collection.attached_disk_obj(self_link, opts) end # A legacy shorthand for attached_disk_obj # # @param [Object] writable The mode in which to attach this disk. # (defaults to READ_WRITE) # @param [Object] auto_delete Specifies whether the disk will be # auto-deleted when the instance is deleted. (defaults to false) # @return [Hash] def get_as_boot_disk(writable = true, auto_delete = false) attached_disk_obj(boot: true, writable: writable, auto_delete: auto_delete) end def ready? status == RUNNING_STATE end def reload requires :identity, :zone return unless data = begin collection.get(identity, zone_name) rescue Google::Apis::TransmissionError nil end new_attributes = data.attributes merge_attributes(new_attributes) self end def create_snapshot(snapshot_name, snapshot = {}) requires :name, :zone raise ArgumentError, "Invalid snapshot name" unless snapshot_name data = service.create_disk_snapshot(snapshot_name, name, zone_name, snapshot) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } service.snapshots.get(snapshot_name) end RUNNING_STATE = "READY".freeze end end end end fog-google-1.9.1/lib/fog/compute/google/models/disk_types.rb0000644000004100000410000000236313451635472024054 0ustar www-datawww-datamodule Fog module Compute class Google class DiskTypes < Fog::Collection model Fog::Compute::Google::DiskType def all(zone: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) opts = { :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token } if zone data = service.list_disk_types(zone, opts).items else data = [] service.list_aggregated_disk_types(opts).items.each_value do |scoped_lst| data.concat(scoped_lst.disk_types) if scoped_lst && scoped_lst.disk_types end end load(data.map(&:to_h)) end def get(identity, zone = nil) if zone disk_type = service.get_disk_type(identity, zone).to_h return new(disk_type) else response = all(:filter => "name eq .*#{identity}") disk_type = response.first unless response.empty? return disk_type end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/zone.rb0000644000004100000410000000102713451635472022645 0ustar www-datawww-datamodule Fog module Compute class Google class Zone < Fog::Model identity :name attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :deprecated attribute :description attribute :id attribute :kind attribute :region attribute :self_link, :aliases => "selfLink" attribute :status UP_STATE = "UP".freeze DOWN_STATE = "DOWN".freeze def up? status == UP_STATE end end end end end fog-google-1.9.1/lib/fog/compute/google/models/backend_service.rb0000644000004100000410000000464713451635472025014 0ustar www-datawww-datamodule Fog module Compute class Google class BackendService < Fog::Model identity :name attribute :backends attribute :creation_timestamp attribute :description attribute :fingerprint attribute :health_checks, :aliases => "healthChecks" attribute :id attribute :kind attribute :port attribute :protocol attribute :self_link, :aliases => "selfLink" attribute :timeout_sec, :aliases => "timeoutSec" def save requires :name, :health_checks options = { :description => description, :backends => backends, :fingerprint => fingerprint, :health_checks => health_checks, :port => port, :protocol => protocol, :timeout_sec => timeout_sec } data = service.insert_backend_service(name, options) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.name) operation.wait_for { ready? } reload end def destroy(async = true) requires :name data = service.delete_backend_service(name) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.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 ::Google::Apis::ClientError => e raise e unless e.status_code == 404 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".freeze end end end end fog-google-1.9.1/lib/fog/compute/google/models/network.rb0000755000004100000410000000444613451635472023376 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 :auto_create_subnetworks, aliases => "autoCreateSubnetworks" attribute :creation_timestamp, aliases => "creationTimestamp" attribute :description # TODO: Naming issue in the client lib, rename after this is resolved: # https://github.com/google/google-api-ruby-client/issues/666 attribute :gateway_i_pv4, aliases => %w(gateway_ipv4 gatewayIPv4) attribute :i_pv4_range, aliases => %w(ipv4_range IPv4Range) attribute :id attribute :kind attribute :peerings attribute :routing_config, aliases => "routingConfig" attribute :self_link, aliases => "selfLink" attribute :subnetworks # TODO: Naming issue in the client lib, rename after this is resolved: # https://github.com/google/google-api-ruby-client/issues/666 alias_method :ipv4_range, :i_pv4_range def save requires :identity, :ipv4_range data = service.insert_network(identity, attributes) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.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.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[:access_configs] = [access_config] if access_config network_interface end end end end end fog-google-1.9.1/lib/fog/compute/google/models/firewalls.rb0000644000004100000410000000105713451635472023665 0ustar www-datawww-datamodule Fog module Compute class Google class Firewalls < Fog::Collection model Fog::Compute::Google::Firewall def all(opts = {}) data = service.list_firewalls(opts).to_h[:items] load(data || []) end def get(identity) if identity firewall = service.get_firewall(identity).to_h return new(firewall) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/disks.rb0000644000004100000410000000643013451635472023012 0ustar www-datawww-datamodule Fog module Compute class Google class Disks < Fog::Collection model Fog::Compute::Google::Disk def all(zone: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) opts = { :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token } if zone data = service.list_disks(zone, opts).items || [] else data = [] service.list_aggregated_disks(opts).items.each_value do |scoped_list| data.concat(scoped_list.disks) if scoped_list.disks end end load(data.map(&:to_h)) end def get(identity, zone = nil) if zone disk = service.get_disk(identity, zone).to_h return new(disk) elsif identity response = all(:filter => "name eq #{identity}", :max_results => 1) disk = response.first unless response.empty? return disk end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end # Returns an attached disk configuration hash. # # Compute API needs attached disks to be specified in a custom format. # This provides a handy shortcut for generating a preformatted config. # # Example output: # {:auto_delete=>false, # :boot=>true, # :mode=>"READ_WRITE", # :source=>"https://www.googleapis.com/compute/v1/projects/myproj/zones/us-central1-f/disks/mydisk", # :type=>"PERSISTENT"} # # See Instances.insert API docs for more info: # https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert # # @param [String] source self_link of an existing disk resource # @param [Boolean] writable The mode in which to attach this disk. # (defaults to READ_WRITE) # @param [Boolean] boot Indicates whether this is a boot disk. # (defaults to false) # @param [String] device_name Specifies a unique device name of your # choice that is reflected into the /dev/disk/by-id/google-* tree of # a Linux operating system running within the instance. # @param [Object] encryption_key Encrypts or decrypts a disk using # a customer-supplied encryption key. # @param [Object] auto_delete Specifies whether the disk will be # auto-deleted when the instance is deleted. (defaults to false) # @return [Hash] def attached_disk_obj(source, writable: true, boot: false, device_name: nil, encryption_key: nil, auto_delete: false) { :auto_delete => auto_delete, :boot => boot, :device_name => device_name, :disk_encryption_key => encryption_key, :mode => writable ? "READ_WRITE" : "READ_ONLY", :source => source, :type => "PERSISTENT" }.reject { |_k, v| v.nil? } end end end end end fog-google-1.9.1/lib/fog/compute/google/models/ssl_certificate.rb0000644000004100000410000000253413451635472025041 0ustar www-datawww-datamodule Fog module Compute class Google ## # Represents a SslCertificate resource # # @see https://cloud.google.com/compute/docs/reference/latest/sslCertificates class SslCertificate < Fog::Model identity :name attribute :kind attribute :id attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :self_link, :aliases => "selfLink" attribute :certificate attribute :private_key, :aliases => "privateKey" def save requires :identity, :certificate, :private_key data = service.insert_ssl_certificate( identity, certificate, private_key, :description => description ) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } reload end def destroy(async = true) requires :identity data = service.delete_ssl_certificate(identity) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async operation end end end end end fog-google-1.9.1/lib/fog/compute/google/models/instance_groups.rb0000644000004100000410000000432613451635472025102 0ustar www-datawww-datamodule Fog module Compute class Google class InstanceGroups < Fog::Collection model Fog::Compute::Google::InstanceGroup def all(zone: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) opts = { :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token } if zone data = service.list_instance_groups(zone).items || [] else data = [] service.list_aggregated_instance_groups(opts).items.each_value do |group| data.concat(group.instance_groups) if group && group.instance_groups end end load(data.map(&:to_h)) end def get(identity, zone = nil) if zone instance_group = service.get_instance_group(identity, zone).to_h new(instance_group) elsif identity response = all(:filter => "name eq #{identity}", :max_results => 1) instance_group = response.first unless response.empty? return instance_group end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 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(0..0)})[/]" ) 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(0..0)})[/]" ) 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-1.9.1/lib/fog/compute/google/models/machine_types.rb0000644000004100000410000000304313451635472024522 0ustar www-datawww-datamodule Fog module Compute class Google class MachineTypes < Fog::Collection model Fog::Compute::Google::MachineType def all(zone: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) opts = { :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token } if zone data = service.list_machine_types(zone, opts).items else data = [] service.list_aggregated_machine_types(opts).items.each_value do |scoped_list| data.concat(scoped_list.machine_types) if scoped_list && scoped_list.machine_types end end load(data.map(&:to_h) || []) end def get(identity, zone = nil) if zone machine_type = service.get_machine_type(identity, zone).to_h return new(machine_type) elsif identity # This isn't very functional since it just shows the first available # machine type globally, but needed due to overall compatibility # See: https://github.com/fog/fog-google/issues/352 response = all(:filter => "name eq #{identity}", :max_results => 1) machine_type = response.first unless response.empty? return machine_type end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/global_address.rb0000644000004100000410000000312013451635472024633 0ustar www-datawww-datamodule Fog module Compute class Google ## # Represents an Address resource # # @see https://developers.google.com/compute/docs/reference/latest/addresses class GlobalAddress < Fog::Model identity :name attribute :address attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :id attribute :ip_version, :aliases => "ipVersion" attribute :kind attribute :self_link, :aliases => "selfLink" attribute :status attribute :users IN_USE_STATE = "IN_USE".freeze RESERVED_STATE = "RESERVED".freeze def save requires :identity data = service.insert_global_address(identity, attributes) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } reload end def destroy(async = true) requires :identity data = service.delete_global_address(identity) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async operation end def reload requires :identity data = collection.get(identity) merge_attributes(data.attributes) self end def in_use? status == IN_USE_STATE end end end end end fog-google-1.9.1/lib/fog/compute/google/models/url_map.rb0000644000004100000410000000764413451635472023344 0ustar www-datawww-datamodule Fog module Compute class Google class UrlMap < Fog::Model identity :name 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 :kind, :aliases => "kind" attribute :path_matchers, :aliases => "pathMatchers" attribute :self_link, :aliases => "selfLink" attribute :tests, :aliases => "tests" def save requires :identity, :default_service options = { :default_service => default_service, :description => description, :fingerprint => fingerprint, :host_rules => host_rules, :path_matchers => path_matchers, :tests => tests } # Update if creation_timestamp is set, create url map otherwise. data = nil if creation_timestamp data = service.update_url_map(identity, options) else data = service.insert_url_map(identity, options) end operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } reload end def destroy(async = true) requires :identity data = service.delete_url_map(identity) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async operation end def validate requires :identity service.validate_url_map(identity, attributes) end def add_host_rules(rules_to_add, async = true) requires :identity rules = (host_rules || []).concat rules_to_add data = service.patch_url_map(identity, :host_rules => rules) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async reload end def add_path_matchers(matchers_to_add, rules_to_add, async = true) requires :identity matchers = (path_matchers || []) + matchers_to_add rules = (host_rules || []) + rules_to_add data = service.patch_url_map(identity, :host_rules => rules, :path_matchers => matchers) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async reload end def invalidate_cache(path, host = nil, async = true) requires :identity data = service.invalidate_url_map_cache(identity, path, host) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async operation end def ready? service.get_url_map(name) true rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 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".freeze end end end end fog-google-1.9.1/lib/fog/compute/google/models/instance_templates.rb0000644000004100000410000000112713451635472025555 0ustar www-datawww-datamodule Fog module Compute class Google class InstanceTemplates < Fog::Collection model Fog::Compute::Google::InstanceTemplate def all data = service.list_instance_templates.items || [] load(data.map(&:to_h)) end def get(identity) if identity instance_template = service.get_instance_template(identity).to_h return new(instance_template) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/operation.rb0000644000004100000410000000401713451635472023674 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".freeze RUNNING_STATE = "RUNNING".freeze DONE_STATE = "DONE".freeze end end end end fog-google-1.9.1/lib/fog/compute/google/models/global_addresses.rb0000644000004100000410000000235413451635472025173 0ustar www-datawww-datamodule Fog module Compute class Google class GlobalAddresses < Fog::Collection model Fog::Compute::Google::GlobalAddress def all(options = {}) data = service.list_global_addresses(options).to_h[:items] || [] load(data) end def get(identity) if identity address = service.get_global_address(identity).to_h return new(address) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end def get_by_ip_address(ip_address) data = service.list_global_addresses(:filter => "address eq #{ip_address}") if data.nil? || data.items.nil? nil else new(data.items.first.to_h) end end def get_by_name(ip_name) data = service.list_global_addresses(:filter => "name eq #{ip_name}") if data.nil? || data.items.nil? nil else new(data.items.first.to_h) end 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-1.9.1/lib/fog/compute/google/models/machine_type.rb0000644000004100000410000000143413451635472024341 0ustar www-datawww-datamodule Fog module Compute class Google class MachineType < Fog::Model identity :name attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :deprecated attribute :description attribute :guest_cpus, :aliases => "guestCpus" attribute :id attribute :is_shared_cpu, :aliases => "isSharedCpu" attribute :kind attribute :maximum_persistent_disks, :aliases => "maximumPersistentDisks" attribute :maximum_persistent_disks_size_gb, :aliases => "maximumPersistentDisksSizeGb" attribute :memory_mb, :aliases => "memoryMb" attribute :scratch_disks, :aliases => "scratchDisks" attribute :self_link, :aliases => "selfLink" attribute :zone end end end end fog-google-1.9.1/lib/fog/compute/google/models/target_http_proxy.rb0000644000004100000410000000421213451635472025457 0ustar www-datawww-datamodule Fog module Compute class Google class TargetHttpProxy < Fog::Model identity :name attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description, :aliases => "description" attribute :id, :aliases => "id" attribute :kind, :aliases => "kind" attribute :self_link, :aliases => "selfLink" attribute :url_map, :aliases => "urlMap" def save requires :identity data = service.insert_target_http_proxy( identity, :description => description, :url_map => url_map ) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } reload end def destroy(async = true) requires :identity data = service.delete_target_http_proxy(identity) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async operation end def set_url_map(url_map, async = true) requires :identity data = service.set_target_http_proxy_url_map(identity, url_map) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async reload end def ready? requires :identity service.get_target_http_proxy(identity) true rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 false end def reload requires :identity return unless data = begin collection.get(identity) rescue Excon::Errors::SocketError nil end new_attributes = data.attributes merge_attributes(new_attributes) self end RUNNING_STATE = "READY".freeze end end end end fog-google-1.9.1/lib/fog/compute/google/models/target_instances.rb0000644000004100000410000000265713451635472025241 0ustar www-datawww-datamodule Fog module Compute class Google class TargetInstances < Fog::Collection model Fog::Compute::Google::TargetInstance def all(zone: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) opts = { :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token } if zone data = service.list_target_instances(zone, opts).to_h[:items] || [] else data = [] service.list_aggregated_target_instances(opts).items.each_value do |scoped_list| unless scoped_list.nil? || scoped_list.target_instances.nil? data += scoped_list.target_instances.map(&:to_h) end end end load(data) end def get(identity, zone = nil) if zone target_instance = service.get_target_instance(target_instance, zone).to_h return new(target_instance) elsif identity response = all(:filter => "name eq #{identity}", :max_results => 1) target_instance = response.first unless response.empty? return target_instance end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/subnetwork.rb0000755000004100000410000000552213451635472024104 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 :private_ip_google_access, :aliases => "privateIpGoogleAccess" attribute :region attribute :secondary_ip_ranges, :aliases => "secondaryIpRanges" 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.name, nil, data.region) operation.wait_for { ready? } 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.name, nil, data.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 expand_ip_cidr_range(range, async = true) requires :identity, :region data = service.expand_subnetwork_ip_cidr_range( identity, region, range ) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name, nil, data.region) operation.wait_for { ready? } unless async reload end def set_private_ip_google_access(access, async = true) requires :identity, :region data = service.set_subnetwork_private_ip_google_access( identity, region, access ) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name, nil, data.region) operation.wait_for { ready? } unless async reload 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-1.9.1/lib/fog/compute/google/models/instance_template.rb0000644000004100000410000000273613451635472025401 0ustar www-datawww-datamodule Fog module Compute class Google class InstanceTemplate < Fog::Model identity :name attribute :kind attribute :self_link, :aliases => "selfLink" attribute :description # Properties is a hash describing the templates # A minimal example is # :properties => { # :machine_type => TEST_MACHINE_TYPE, # :disks => [{ # :boot => true, # :initialize_params => { # :source_image => "projects/ubuntu-os-cloud/global/images/ubuntu-1804-bionic-v20180522"} # }], # :network_interfaces => [{ # :network => "global/networks/default" # }] # } # } # @see https://cloud.google.com/compute/docs/reference/rest/v1/instanceTemplates/insert attribute :properties def save requires :name requires :properties data = service.insert_instance_template(name, properties, description) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.name) operation.wait_for { ready? } reload end def destroy(async = true) requires :name data = service.delete_instance_template(name) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.name) operation.wait_for { ready? } unless async operation end end end end end fog-google-1.9.1/lib/fog/compute/google/models/instance_group_managers.rb0000644000004100000410000000264313451635472026574 0ustar www-datawww-datamodule Fog module Compute class Google class InstanceGroupManagers < Fog::Collection model Fog::Compute::Google::InstanceGroupManager def all(zone: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) opts = { :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token } if zone data = service.list_instance_group_managers(zone, opts).items || [] else data = [] service.list_aggregated_instance_group_managers(opts).items.each_value do |group| data.concat(group.instance_group_managers) if group.instance_group_managers end end load(data.map(&:to_h)) end def get(identity, zone = nil) if zone instance_group_manager = service.get_instance_group_manager(identity, zone).to_h return new(instance_group_manager) elsif identity response = all(:filter => "name eq .*#{identity}", :max_results => 1) instance_group_manager = response.first unless response.empty? return instance_group_manager end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/operations.rb0000644000004100000410000000253113451635472024056 0ustar www-datawww-datamodule Fog module Compute class Google class Operations < Fog::Collection model Fog::Compute::Google::Operation def all(zone: nil, region: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) opts = { :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token } if zone data = service.list_zone_operations(zone, opts).to_h[:items] elsif region data = service.list_region_operations(region, opts).to_h[:items] else data = service.list_global_operations(opts).to_h[:items] end load(data || []) end def get(identity, zone = nil, region = nil) if !zone.nil? operation = service.get_zone_operation(zone, identity).to_h return new(operation) elsif !region.nil? operation = service.get_region_operation(region, identity).to_h return new(operation) elsif identity operation = service.get_global_operation(identity).to_h return new(operation) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/http_health_check.rb0000644000004100000410000000605113451635472025335 0ustar www-datawww-datamodule Fog module Compute class Google class HttpHealthCheck < Fog::Model identity :name attribute :check_interval_sec, :aliases => "checkIntervalSec" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :healthy_threshold, :aliases => "healthyThreshold" attribute :host attribute :id attribute :kind attribute :port attribute :request_path, :aliases => "requestPath" attribute :self_link, :aliases => "selfLink" attribute :timeout_sec, :aliases => "timeoutSec" attribute :unhealthy_threshold, :aliases => "unhealthyThreshold" MODIFIABLE_FIELDS = %i( name check_interval_sec creation_timestamp description healthy_threshold host port request_path timeout_sec unhealthy_threshold ).freeze def save opts = { :name => name, :check_interval_sec => check_interval_sec, :creation_timestamp => creation_timestamp, :description => description, :healthy_threshold => healthy_threshold, :host => host, :port => port, :request_path => request_path, :timeout_sec => timeout_sec, :unhealthy_threshold => unhealthy_threshold } id.nil? ? create(opts) : update(opts) end def create(opts) requires :name data = service.insert_http_health_check(name, opts) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } reload end def update(opts) requires :name data = service.update_http_health_check(name, opts) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } reload end def destroy(async = true) requires :name data = service.delete_http_health_check(name) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async operation end def ready? service.get_http_health_check(name) true rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 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".freeze end end end end fog-google-1.9.1/lib/fog/compute/google/models/regions.rb0000755000004100000410000000102213451635472023336 0ustar www-datawww-datamodule Fog module Compute class Google class Regions < Fog::Collection model Fog::Compute::Google::Region def all data = service.list_regions.to_h load(data[:items] || []) end def get(identity) if identity region = service.get_region(identity).to_h return new(region) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/servers.rb0000644000004100000410000000730613451635472023371 0ustar www-datawww-datamodule Fog module Compute class Google class Servers < Fog::Collection model Fog::Compute::Google::Server def all(zone: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) opts = { :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token } if zone data = service.list_servers(zone, opts).to_h[:items] || [] else data = [] service.list_aggregated_servers(opts).items.each_value do |scoped_lst| if scoped_lst && scoped_lst.instances data.concat(scoped_lst.instances.map(&:to_h)) end end end load(data) end # TODO: This method needs to take self_links as well as names def get(identity, zone = nil) if zone server = service.get_server(identity, zone).to_h return new(server) elsif identity response = all(:filter => "name eq .*#{identity}", :max_results => 1) server = response.first unless response.empty? return server end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end def bootstrap(public_key_path: nil, **opts) name = "fog-#{Time.now.to_i}" zone_name = "us-central1-f" disks = opts[:disks] if disks.nil? || disks.empty? # create the persistent boot disk source_img = service.images.get_from_family("debian-9") disk_defaults = { :name => name, :size_gb => 10, :zone_name => zone_name, :source_image => source_img.self_link } disk = service.disks.create(disk_defaults.merge(opts)) disk.wait_for { disk.ready? } disks = [disk] end # TODO: Remove the network init when #360 is fixed network = { :network => "global/networks/default", :access_configs => [{ :name => "External NAT", :type => "ONE_TO_ONE_NAT" }] } # Merge the options with the defaults, overwriting defaults # if an option is provided data = { :name => name, :zone => zone_name, :disks => disks, :network_interfaces => [network], :public_key => get_public_key(public_key_path), :username => ENV["USER"] }.merge(opts) data[:machine_type] = "n1-standard-1" unless data[:machine_type] server = new(data) server.save server.wait_for { ready? } # Set the disk to be autodeleted server.set_disk_auto_delete(true) server end private # Defaults to: # 1. ~/.ssh/google_compute_engine.pub # 2. ~/.ssh/id_rsa.pub PUBLIC_KEY_DEFAULTS = %w( ~/.ssh/google_compute_engine.pub ~/.ssh/id_rsa.pub ).freeze def get_public_key(public_key_path) unless public_key_path PUBLIC_KEY_DEFAULTS.each do |path| if File.exist?(File.expand_path(path)) public_key_path = path break end end end if public_key_path.nil? || public_key_path.empty? raise Fog::Errors::Error.new("Cannot bootstrap instance without a public key") end File.read(File.expand_path(public_key_path)) end end end end end fog-google-1.9.1/lib/fog/compute/google/models/snapshots.rb0000644000004100000410000000152013451635472023712 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(:page_token => next_page_token) next_items = data.to_h[:items] || [] items.concat(next_items) next_page_token = data.next_page_token break if next_page_token.nil? || next_page_token.empty? end load(items) end def get(identity) if identity snapshot = service.get_snapshot(identity).to_h return new(snapshot) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/target_pools.rb0000644000004100000410000000244213451635472024376 0ustar www-datawww-datamodule Fog module Compute class Google class TargetPools < Fog::Collection model Fog::Compute::Google::TargetPool def all(region: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) opts = { :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token } if region.nil? data = [] service.list_aggregated_target_pools(opts).items.each_value do |lst| unless lst.nil? || lst.target_pools.nil? data += lst.to_h[:target_pools] end end else data = service.list_target_pools(region, opts).to_h[:items] end load(data) end def get(identity, region = nil) if region target_pool = service.get_target_pool(identity, region).to_h return new(target_pool) elsif identity response = all(:filter => "name eq #{identity}") target_pool = response.first unless response.empty? return target_pool end rescue ::Google::Apis::ClientError => e raise e unless e.status_code = 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/target_https_proxies.rb0000644000004100000410000000114713451635472026156 0ustar www-datawww-datamodule Fog module Compute class Google class TargetHttpsProxies < Fog::Collection model Fog::Compute::Google::TargetHttpsProxy def all(_filters = {}) data = service.list_target_https_proxies.to_h[:items] || [] load(data) end def get(identity) if identity target_https_proxy = service.get_target_https_proxy(identity).to_h return new(target_https_proxy) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/global_forwarding_rule.rb0000644000004100000410000000455613451635472026415 0ustar www-datawww-datamodule Fog module Compute class Google class GlobalForwardingRule < Fog::Model identity :name attribute :ip_address, :aliases => "IPAddress" attribute :ip_protocol, :aliases => "IPProtocol" attribute :backend_service, :aliases => "backendService" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :id attribute :ip_version, :aliases => "ipVersion" attribute :kind attribute :load_balancing_scheme, :aliases => "loadBalancingScheme" attribute :network attribute :port_range, :aliases => "portRange" attribute :ports attribute :region attribute :self_link, :aliases => "selfLink" attribute :subnetwork attribute :target def save requires :identity data = service.insert_global_forwarding_rule(identity, attributes) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name, nil, data.region) operation.wait_for { ready? } reload end def destroy(async = true) requires :identity data = service.delete_global_forwarding_rule(identity) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name, nil, data.region) operation.wait_for { ready? } unless async operation end def set_target(new_target) requires :identity new_target = new_target.self_link unless new_target.class == String self.target = new_target service.set_global_forwarding_rule_target( identity, :target => new_target ) reload end def ready? service.get_global_forwarding_rule(name) true rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 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 end end end end fog-google-1.9.1/lib/fog/compute/google/models/backend_services.rb0000644000004100000410000000113213451635472025161 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.items || [] load(data.map(&:to_h)) end def get(identity) if identity backend_service = service.get_backend_service(identity).to_h return new(backend_service) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/disk_type.rb0000644000004100000410000000127313451635472023670 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 :default_disk_size_gb, :aliases => "defaultDiskSizeGb" 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-1.9.1/lib/fog/compute/google/models/target_pool.rb0000644000004100000410000001335013451635472024213 0ustar www-datawww-datamodule Fog module Compute class Google class TargetPool < Fog::Model identity :name attribute :backup_pool, :aliases => "backupPool" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :failover_ratio, :aliases => "failoverRatio" attribute :health_checks, :aliases => "healthChecks" attribute :id attribute :instances attribute :kind attribute :region attribute :self_link, :aliases => "selfLink" attribute :session_affinity, :aliases => "sessionAffinity" def save requires :name, :region data = service.insert_target_pool( name, region, attributes.reject { |_k, v| v.nil? } ) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, nil, data.region) operation.wait_for { ready? } reload end def destroy(async = true) requires :identity, :region data = service.delete_target_pool(identity, region) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, nil, data.region) operation.wait_for { ready? } unless async operation end def add_instance(instance, async = true) requires :identity instance = instance.self_link unless instance.class == String data = service.add_target_pool_instances(identity, region, [instance]) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, nil, data.region) operation.wait_for { ready? } unless async reload end def remove_instance(instance, async = true) requires :identity instance = instance.self_link unless instance.class == String data = service.remove_target_pool_instances(identity, region, [instance]) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, nil, data.region) operation.wait_for { ready? } unless async reload end def add_health_check(health_check, async = true) requires :identity, :region health_check = health_check.self_link unless health_check.class == String data = service.add_target_pool_health_checks(identity, region, [health_check]) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, nil, data.region) operation.wait_for { ready? } unless async reload end def remove_health_check(health_check, async = true) requires :identity, :region health_check = health_check.self_link unless health_check.class == String data = service.remove_target_pool_health_checks(identity, region, [health_check]) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, nil, data.region) operation.wait_for { ready? } unless async reload end ## # Get most recent health checks for each IP for instances. # # @param [String] instance_name a specific instance to look up. Default # behavior returns health checks for all instances associated with # this check. # @returns [Hash>] a map of instance URL to health checks # # Example Hash: # { # "https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-f/instances/myinstance"=> # [{:health_state=>"UNHEALTHY", # :instance=>"https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-f/instances/myinstance" # }] # } # def get_health(instance_name = nil) requires :identity, :region if instance_name instance = service.servers.get(instance_name) data = service.get_target_pool_health(identity, region, instance.self_link) .to_h[:health_status] || [] results = [[instance.self_link, data]] else results = instances.map do |self_link| # TODO: Improve the returned object, current is hard to navigate # [{instance => @instance, health_state => "HEALTHY"}, ...] data = service.get_target_pool_health(identity, region, self_link) .to_h[:health_status] || [] [self_link, data] end end Hash[results] end def set_backup(backup = nil) requires :identity, :region backup ||= backup_pool service.set_target_pool_backup( identity, region, backup, :failover_ratio => failover_ratio ) reload end def ready? service.get_target_pool(name, region) true rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 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".freeze end end end end fog-google-1.9.1/lib/fog/compute/google/models/zones.rb0000644000004100000410000000077713451635472023043 0ustar www-datawww-datamodule Fog module Compute class Google class Zones < Fog::Collection model Fog::Compute::Google::Zone def all data = service.list_zones.to_h[:items] || [] load(data) end def get(identity) if identity zone = service.get_zone(identity).to_h new(zone) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/url_maps.rb0000644000004100000410000000102613451635472023513 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.to_h[:items] || [] load(data) end def get(identity) if identity url_map = service.get_url_map(identity).to_h return new(url_map) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/forwarding_rule.rb0000644000004100000410000000467113451635472025073 0ustar www-datawww-datamodule Fog module Compute class Google class ForwardingRule < Fog::Model identity :name attribute :ip_address, :aliases => "IPAddress" attribute :ip_protocol, :aliases => "IPProtocol" attribute :backend_service, :aliases => "backendService" attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :id attribute :ip_version, :aliases => "ipVersion" attribute :kind attribute :load_balancing_scheme, :aliases => "loadBalancingScheme" attribute :network attribute :port_range, :aliases => "portRange" attribute :ports attribute :region attribute :self_link, :aliases => "selfLink" attribute :subnetwork attribute :target def save requires :identity, :region data = service.insert_forwarding_rule(identity, region, attributes) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name, nil, data.region) operation.wait_for { ready? } reload end def set_target(new_target) requires :identity, :region new_target = new_target.self_link unless new_target.class == String self.target = new_target service.set_forwarding_rule_target( identity, region, :target => new_target ) reload end def destroy(async = true) requires :identity, :region data = service.delete_forwarding_rule(identity, region) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name, nil, data.region) operation.wait_for { ready? } unless async operation end def ready? requires :identity service.get_forwarding_rule(identity, region) true rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 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 end end end end fog-google-1.9.1/lib/fog/compute/google/models/projects.rb0000644000004100000410000000065413451635472023530 0ustar www-datawww-datamodule Fog module Compute class Google class Projects < Fog::Collection model Fog::Compute::Google::Project def get(identity) if identity project = service.get_project(identity).to_h return new(project) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/server.rb0000644000004100000410000004664713451635472023221 0ustar www-datawww-datarequire "fog/compute/models/server" module Fog module Compute class Google class Server < Fog::Compute::Server identity :name # @return [Boolean] attribute :can_ip_forward, :aliases => "canIpForward" # @return [String] attribute :cpu_platform, :aliases => "cpuPlatform" # @return [String] attribute :creation_timestamp, :aliases => "creationTimestamp" # @return [Boolean] attribute :deletion_protection, :aliases => "deletionProtection" # @return [String] attribute :description # New disks may include :initialize_params before save. # # @example Minimal disks pre-creation: # [ # { # :initialize_params => { # :source_image => "projects/debian-cloud/global/images/family/debian-9" # } # } # ] # # @example disks post-creation: # [ # { # :auto_delete => false, # :boot => true, # :device_name => "persistent-disk-0", # :index => 0, # :interface => "SCSI", # :kind => "compute#attachedDisk", # :licenses => ["https://www.googleapis.com/compute/v1/..."], # :mode => "READ_WRITE", # :source => "https://www.googleapis.com/compute/v1/.../mydisk", # :type => "PERSISTENT" # } # ] # @return [Array] attribute :disks # @example Guest accelerators # [ # { # :accelerator_count => 1, # :accelerator_type => "...my/accelerator/type" # } # ] # @return [Array] attribute :guest_accelerators, :aliases => "guestAccelerators" # @return [Fixnum] attribute :id # @return [String] attribute :kind # @return [String] attribute :label_fingerprint, :aliases => "labelFingerprint" # @return [Hash] attribute :labels # @return [String] attribute :machine_type, :aliases => "machineType" # If set initially before save, the expected format # is the API format as shown below. # # If you want to pass in a Hash, see {#set_metadata}. # If you want to access the metadata items as a Hash, see # {#metadata_as_h}. # # @example Metadata in API format # # { # :fingerprint => "...", # :items => [ # { :key => "foo", :value => "bar" }, # ] # } # @return [Hash] attribute :metadata # @return [String] attribute :min_cpu_platform, :aliases => "minCpuPlatform" # @example Network interfaces # [ # { # :kind => "compute#networkInterface", # :name => "nic0", # :network => "https://www.googleapis.com/compute/v1/.../my-network/" # :network_ip => "0.0.0.0", # :subnetwork => "https://www.googleapis.com/compute/v1/.../my-subnetwork" # } # ], # @return [Array] attribute :network_interfaces, :aliases => "networkInterfaces" # @example Scheduling object # { # :automatic_restart => true, # :on_host_maintenance => "MIGRATE", # :preemptible=>false # } # @return [Hash] attribute :scheduling # @return [String] attribute :self_link, :aliases => "selfLink" # @example Service accounts in API format # [ # { # :email => "my-service-account@developer.gserviceaccount.com", # :scopes => [], # } # ] # @return [Array] attribute :service_accounts, :aliases => "serviceAccounts" # @return [Boolean] attribute :start_restricted, :aliases => "startRestricted" # @return [String] attribute :status, :aliases => "status" # @return [String] attribute :status_message, :aliases => "statusMessage" # @example Tags in API format # @return [Hash] attribute :tags # @return [String] attribute :zone, :aliases => :zone_name GCE_SCOPE_ALIASES = { "default" => %w( https://www.googleapis.com/auth/cloud.useraccounts.readonly https://www.googleapis.com/auth/devstorage.read_only https://www.googleapis.com/auth/logging.write https://www.googleapis.com/auth/monitoring.write https://www.googleapis.com/auth/pubsub https://www.googleapis.com/auth/service.management.readonly https://www.googleapis.com/auth/servicecontrol https://www.googleapis.com/auth/trace.append ), "bigquery" => ["https://www.googleapis.com/auth/bigquery"], "cloud-platform" => ["https://www.googleapis.com/auth/cloud-platform"], "compute-ro" => ["https://www.googleapis.com/auth/compute.readonly"], "compute-rw" => ["https://www.googleapis.com/auth/compute"], "datastore" => ["https://www.googleapis.com/auth/datastore"], "logging-write" => ["https://www.googleapis.com/auth/logging.write"], "monitoring" => ["https://www.googleapis.com/auth/monitoring"], "monitoring-write" => ["https://www.googleapis.com/auth/monitoring.write"], "service-control" => ["https://www.googleapis.com/auth/servicecontrol"], "service-management" => ["https://www.googleapis.com/auth/service.management.readonly"], "sql" => ["https://www.googleapis.com/auth/sqlservice"], "sql-admin" => ["https://www.googleapis.com/auth/sqlservice.admin"], "storage-full" => ["https://www.googleapis.com/auth/devstorage.full_control"], "storage-ro" => ["https://www.googleapis.com/auth/devstorage.read_only"], "storage-rw" => ["https://www.googleapis.com/auth/devstorage.read_write"], "taskqueue" => ["https://www.googleapis.com/auth/taskqueue"], "useraccounts-ro" => ["https://www.googleapis.com/auth/cloud.useraccounts.readonly"], "useraccounts-rw" => ["https://www.googleapis.com/auth/cloud.useraccounts"], "userinfo-email" => ["https://www.googleapis.com/auth/userinfo.email"] }.freeze # Return the source image of the server's boot disk # # @return [String] image self link 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 # Destroy a server. # # @param async [TrueClass] execute the command asynchronously # @return [Fog::Compute::Google::Operation] def destroy(async = true) requires :name, :zone data = service.delete_server(name, zone_name) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async operation end # Helper method that returns first public ip address needed for # Fog::Compute::Server.ssh default behavior. # # @return [String] def public_ip_address public_ip_addresses.first end # Helper method that returns all of server's public ip addresses. # # @return [Array] def public_ip_addresses addresses = [] if network_interfaces.respond_to? :flat_map addresses = network_interfaces.flat_map do |nic| if nic[:access_configs].respond_to? :each nic[:access_configs].select { |config| config[:name] == "External NAT" } .map { |config| config[:nat_ip] } else [] end end end addresses end # Helper method that returns the first private ip address of the # instance. # # @return [String] def private_ip_address private_ip_addresses.first end # Helper method that returns all of server's private ip addresses. # # @return [Array] def private_ip_addresses addresses = [] if network_interfaces.respond_to? :map addresses = network_interfaces.map { |nic| nic[:network_ip] } end addresses end # Helper method that returns all of server's ip addresses, # both private and public. # # @return [Array] def addresses private_ip_addresses + public_ip_addresses end # Attach a disk to a running server # # @param disk [Object, String] disk object or a self-link # @param async [TrueClass] execute the api call asynchronously # @param options [Hash] # @return [Object] # TODO: Figure out what options hash is for here. def attach_disk(disk, async = true, options = {}) requires :identity, :zone if disk.is_a? Disk disk_obj = disk.get_attached_disk elsif disk.is_a? String disk_obj = service.disks.attached_disk_obj(disk, options) end data = service.attach_disk(identity, zone_name, disk_obj) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async reload end # Detach disk from a running instance # # @param device_name [Object] # @param async [TrueClass] # @returns [Fog::Compute::Google::Server] server object def detach_disk(device_name, async = true) requires :identity, :zone data = service.detach_disk(identity, zone, device_name) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async reload end # Returns metadata items as a Hash. # # @return [Hash] items def metadata_as_h if metadata.nil? || metadata[:items].nil? || metadata[:items].empty? return {} end Hash[metadata[:items].map { |item| [item[:key], item[:value]] }] end def reboot(async = true) requires :identity, :zone data = service.reset_server(identity, zone_name) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async operation end def start(async = true) requires :identity, :zone data = service.start_server(identity, zone_name) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async operation end def stop(async = true) requires :identity, :zone data = service.stop_server(identity, zone_name) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async operation end def serial_port_output requires :identity, :zone service.get_server_serial_port_output(identity, zone_name).to_h[:contents] end def set_disk_auto_delete(auto_delete, device_name = nil, async = true) requires :identity, :zone if device_name.nil? && disks.count > 1 raise ArgumentError.new("Device name is required if multiple disks are attached") end device_name ||= disks.first[:device_name] data = service.set_server_disk_auto_delete( identity, zone_name, auto_delete, device_name ) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async reload end def set_scheduling(async = true, on_host_maintenance: nil, automatic_restart: nil, preemptible: nil) requires :identity, :zone data = service.set_server_scheduling( identity, zone_name, :on_host_maintenance => on_host_maintenance, :automatic_restart => automatic_restart, :preemptible => preemptible ) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async reload end # Set an instance metadata # # @param [Bool] async Perform the operation asyncronously # @param [Hash] new_metadata A new metadata object # Format: {'foo' => 'bar', 'baz'=>'foo'} # # @returns [Fog::Compute::Google::Server] server object def set_metadata(new_metadata = {}, async = true) requires :identity, :zone unless new_metadata.is_a?(Hash) raise Fog::Errors::Error.new("Instance metadata should be a hash") end # If metadata is presented in {'foo' => 'bar', 'baz'=>'foo'} new_metadata_items = new_metadata.each.map { |k, v| { :key => k.to_s, :value => v.to_s } } data = service.set_server_metadata( identity, zone_name, metadata[:fingerprint], new_metadata_items ) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async reload end def set_tags(new_tags = [], async = true) requires :identity, :zone data = service.set_server_tags( identity, zone_name, tags[:fingerprint], new_tags ) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async reload end # Check if instance is provisioning. On staging vs. provisioning difference: # https://cloud.google.com/compute/docs/instances/checking-instance-status # # @return [TrueClass or FalseClass] def provisioning? status == PROVISIONING end # Check if instance is staging. On staging vs. provisioning difference: # https://cloud.google.com/compute/docs/instances/checking-instance-status # # @return [TrueClass or FalseClass] def staging? status == STAGING end # Check if instance is stopped. # # @return [TrueClass or FalseClass] def stopped? status == "TERMINATED" end # Check if instance is ready. # # @return [TrueClass or FalseClass] def ready? status == RUNNING end def zone_name zone.nil? ? nil : zone.split("/")[-1] end def add_ssh_key(username, key, async = true) metadata = generate_ssh_key_metadata(username, key) data = service.set_server_metadata( identity, zone_name, metadata[:fingerprint], metadata[:items] ) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async reload end def reload data = service.get_server(name, zone_name).to_h merge_attributes(data) end def map_scopes(scopes) return [] if scopes.nil? scopes.flat_map do |scope| if GCE_SCOPE_ALIASES.key? scope # Expand scope alias to list of related scopes GCE_SCOPE_ALIASES[scope] else [scope_url(scope)] end end end def save(username: nil, public_key: nil) requires :name requires :machine_type requires :disks requires :zone generate_ssh_key_metadata(self.username, self.public_key) if self.public_key # XXX HACK This is a relic of 1.0 change that for some reason added those arguments # to `save` method. This is left in place to keep things backwards-compatible # TODO(2.0): Remove arguments from save generate_ssh_key_metadata(username, public_key) if public_key options = attributes.reject { |_, v| v.nil? } if service_accounts && service_accounts[0] service_accounts[0][:scopes] = map_scopes(service_accounts[0][:scopes]) options[:service_accounts] = service_accounts end if attributes[:external_ip] if options[:network_interfaces].nil? || options[:network_interfaces].empty? options[:network_interfaces] = [ { :network => "global/networks/#{GOOGLE_COMPUTE_DEFAULT_NETWORK}" } ] end # Add external IP as default access config if given options[:network_interfaces][0][:access_configs] = [ { :name => "External NAT", :type => "ONE_TO_ONE_NAT", :nat_ip => attributes[:external_ip] } ] end if attributes[:network_ip] options[:network_interfaces][0][:network_ip] = attributes[:network_ip] end data = service.insert_server(name, zone_name, options) operation = Fog::Compute::Google::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } reload end def generate_ssh_key_metadata(username, key) if metadata.nil? self.metadata = Hash.new end metadata[:items] = [] if metadata[:items].nil? metadata_map = Hash[metadata[:items].map { |item| [item[:key], item[:value]] }] ssh_keys = metadata_map["ssh-keys"] || metadata_map["sshKeys"] || "" ssh_keys += "\n" unless ssh_keys.empty? ssh_keys += "#{username}:#{key.strip}" metadata_map["ssh-keys"] = ssh_keys metadata[:items] = metadata_to_item_list(metadata_map) metadata end private def metadata_to_item_list(metadata) metadata.map { |k, v| { :key => k, :value => v } } end def scope_url(scope) if scope.start_with?("https://") scope else "https://www.googleapis.com/auth/#{scope}" end end end end end end fog-google-1.9.1/lib/fog/compute/google/models/instance_group_manager.rb0000644000004100000410000000340713451635472026410 0ustar www-datawww-datamodule Fog module Compute class Google class InstanceGroupManager < Fog::Model identity :name attribute :kind attribute :self_link, :aliases => "selfLink" attribute :description attribute :zone attribute :region attribute :instance_group, :aliases => "instanceGroup" attribute :instance_template, :aliases => "instanceTemplate" attribute :target_pools, :aliases => "targetPools" attribute :base_instance_name, :aliases => "baseInstanceName" attribute :current_actions, :aliases => "currentActions" attribute :target_size, :aliases => "targetSize" attribute :named_ports, :aliases => "namedPorts" def save requires :name, :zone, :base_instance_name, :target_size, :instance_template data = service.insert_instance_group_manager(name, zone.split("/")[-1], instance_template, base_instance_name, target_size, target_pools, named_ports, description) operation = Fog::Compute::Google::Operations.new(:service => service).get(data.name, zone.split("/")[-1]) operation.wait_for { ready? } reload end def destroy(async = true) requires :name, :zone operation = service.delete_instance_group_manager(name, zone.split("/")[-1]) operation.wait_for { ready? } unless async operation end def set_instance_template(instance_template) service.set_instance_template self, instance_template end def recreate_instances(instances) service.recreate_instances self, instances end def abandon_instances(instances) service.abandon_instances self, instances end end end end end fog-google-1.9.1/lib/fog/compute/google/models/global_forwarding_rules.rb0000644000004100000410000000113313451635472026564 0ustar www-datawww-datamodule Fog module Compute class Google class GlobalForwardingRules < Fog::Collection model Fog::Compute::Google::GlobalForwardingRule def all(opts = {}) data = service.list_global_forwarding_rules(opts).to_h[:items] || [] load(data) end def get(identity) if identity rule = service.get_global_forwarding_rule(identity).to_h return new(rule) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/networks.rb0000644000004100000410000000103013451635472023540 0ustar www-datawww-datamodule Fog module Compute class Google class Networks < Fog::Collection model Fog::Compute::Google::Network def all data = service.list_networks.to_h[:items] load(data || []) end def get(identity) if identity network = service.get_network(identity).to_h return new(network) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/target_http_proxies.rb0000644000004100000410000000114113451635472025765 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.to_h[:items] || [] load(data) end def get(identity) if identity target_http_proxy = service.get_target_http_proxy(identity).to_h return new(target_http_proxy) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end fog-google-1.9.1/lib/fog/compute/google/models/target_instance.rb0000644000004100000410000000360113451635472025044 0ustar www-datawww-datamodule Fog module Compute class Google class TargetInstance < Fog::Model identity :name attribute :creation_timestamp, :aliases => "creationTimestamp" attribute :description attribute :id attribute :instance attribute :kind attribute :nat_policy, :aliases => "natPolicy" attribute :self_link, :aliases => "selfLink" attribute :zone def save requires :identity, :zone options = { :description => description, :zone => zone, :nat_policy => nat_policy, :instance => instance } data = service.insert_target_instance(identity, zone, options) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } reload end def destroy(async = true) requires :name, :zone data = service.delete_target_instance(name, zone) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async operation end def ready? service.get_target_instance(name, zone) true rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 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".freeze end end end end fog-google-1.9.1/lib/fog/compute/google/models/ssl_certificates.rb0000644000004100000410000000112513451635472025217 0ustar www-datawww-datamodule Fog module Compute class Google class SslCertificates < Fog::Collection model Fog::Compute::Google::SslCertificate def get(identity) if identity ssl_certificate = service.get_ssl_certificate(identity).to_h return new(ssl_certificate) end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end def all(_filters = {}) data = service.list_ssl_certificates.to_h[:items] || [] load(data) end end end end end fog-google-1.9.1/lib/fog/compute/google/models/project.rb0000644000004100000410000000154113451635472023341 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 operation = service.set_common_instance_metadata(identity, common_instance_metadata["fingerprint"], metadata) Fog::Compute::Google::Operations.new(:service => service).get(operation.id) end end end end end fog-google-1.9.1/lib/fog/compute/google/models/firewall.rb0000644000004100000410000000565613451635472023513 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 # Allowed ports in API format # # @example # [ # { :ip_protocol => "TCP", # :ports => ["201"] } # ] # @return [Array] attribute :allowed attribute :creation_timestamp, :aliases => "creationTimestamp" # Denied ports in API format # # @example # [ # { :ip_protocol => "TCP", # :ports => ["201"] } # ] # @return [Array] attribute :denied attribute :description attribute :destination_ranges, :aliases => "destinationRanges" attribute :direction attribute :id attribute :kind attribute :network attribute :priority attribute :self_link, :aliases => "selfLink" attribute :source_ranges, :aliases => "sourceRanges" attribute :source_service_accounts, :aliases => "sourceServiceAccounts" attribute :source_tags, :aliases => "sourceTags" attribute :target_service_accounts, :aliases => "targetServiceAccounts" attribute :target_tags, :aliases => "targetTags" def save requires :identity unless self.allowed || self.denied raise Fog::Errors::Error.new("Firewall needs denied or allowed ports specified") end id.nil? ? create : update end def create data = service.insert_firewall(identity, attributes) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } reload end def update requires :identity, :allowed, :network data = service.update_firewall(identity, attributes) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } reload end def patch(diff = {}) requires :identity data = service.patch_firewall(identity, diff) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } reload end def destroy(async = true) requires :identity data = service.delete_firewall(identity) operation = Fog::Compute::Google::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async operation end end end end end fog-google-1.9.1/lib/fog/compute/google/models/images.rb0000644000004100000410000000616413451635472023146 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 = %w( centos-cloud cos-cloud coreos-cloud debian-cloud rhel-cloud suse-cloud suse-sap-cloud ubuntu-os-cloud windows-cloud windows-sql-cloud opensuse-cloud ).freeze def all data = all_projects.map do |project| begin images = service.list_images(project).items || [] # Keep track of the project in which we found the image(s) images.map { |img| img.to_h.merge(:project => project) } rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 # Not everyone has access to every Global Project. Requests # return 404 if you don't have access. next end end data = data.flatten load(data) end # Only return the non-deprecated list of images def current all.reject(&:deprecated) end def get(identity, project = nil) if project begin image = service.get_image(identity, project).to_h # TODO: Remove response modification - see #405 image[:project] = project return new(image) rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end elsif identity projects = all_projects projects.each do |proj| begin response = service.get_image(identity, proj).to_h # TODO: Remove response modification - see #405 response[:project] = proj image = response return new(image) rescue ::Google::Apis::ClientError => e next if e.status_code == 404 break end end # If nothing is found - return nil nil end end def get_from_family(family, project = nil) project.nil? ? projects = all_projects : projects = [project] data = nil projects.each do |proj| begin data = service.get_image_from_family(family, proj).to_h data[:project] = proj rescue ::Google::Apis::ClientError => e next if e.status_code == 404 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-1.9.1/lib/fog/compute/google/real.rb0000644000004100000410000000126013451635472021331 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(" ") initialize_google_client(options) @compute = ::Google::Apis::ComputeV1::ComputeService.new apply_client_options(@compute, options) @extra_global_projects = options[:google_extra_global_projects] || [] end end end end end fog-google-1.9.1/lib/fog/compute/google/mock.rb0000644000004100000410000015360513451635472021352 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| case key when "debian-cloud" hash[key] = { :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" hash[key] = { :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 hash[key] = { :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" } }, :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-1.9.1/lib/fog/compute/google.rb0000644000004100000410000002146513451635472020417 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_application_default, :google_auth, :google_client, :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".freeze GOOGLE_COMPUTE_BASE_URL = "https://www.googleapis.com/compute/".freeze 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).freeze GOOGLE_COMPUTE_DEFAULT_NETWORK = "default".freeze # TODO: Do we need those constants? RUNNING = "RUNNING".freeze PROVISIONING = "PROVISIONING".freeze STAGING = "STAGING".freeze request_path "fog/compute/google/requests" request :add_backend_service_backends request :add_instance_group_instances request :add_server_access_config request :add_target_pool_health_checks request :add_target_pool_instances request :delete_address request :delete_global_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_route request :delete_server request :delete_server_access_config request :delete_snapshot request :delete_subnetwork request :delete_target_http_proxy request :delete_target_https_proxy request :delete_target_instance request :delete_target_pool request :delete_url_map request :delete_zone_operation request :delete_ssl_certificate request :get_address request :get_global_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_route request :get_server request :get_server_serial_port_output request :get_snapshot request :get_subnetwork request :get_target_http_proxy request :get_target_https_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_ssl_certificate request :insert_address request :insert_global_address request :insert_backend_service request :insert_disk request :insert_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_route request :insert_server request :insert_subnetwork request :insert_target_http_proxy request :insert_target_https_proxy request :insert_target_instance request :insert_target_pool request :insert_url_map request :insert_ssl_certificate request :list_addresses request :list_aggregated_addresses request :list_aggregated_disk_types request :list_aggregated_disks request :list_aggregated_forwarding_rules 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_aggregated_target_pools request :list_backend_services request :list_disk_types request :list_disks request :list_firewalls request :list_forwarding_rules request :list_global_addresses 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_regions request :list_routes request :list_servers request :list_snapshots request :list_subnetworks request :list_target_http_proxies request :list_target_https_proxies request :list_target_instances request :list_target_pools request :list_url_maps request :list_zone_operations request :list_zones request :list_ssl_certificates request :patch_firewall request :patch_url_map 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_server_disk_auto_delete request :set_server_metadata request :set_server_scheduling request :set_server_tags request :set_snapshot_labels request :set_subnetwork_private_ip_google_access request :set_target_http_proxy_url_map request :set_target_https_proxy_ssl_certificates request :set_target_https_proxy_url_map request :set_target_pool_backup request :update_firewall request :update_http_health_check request :update_url_map request :attach_disk request :detach_disk request :create_disk_snapshot request :expand_subnetwork_ip_cidr_range request :reset_server request :start_server request :stop_server request :invalidate_url_map_cache request :validate_url_map request :get_instance_group_manager request :insert_instance_group_manager request :delete_instance_group_manager request :list_instance_templates request :list_instance_group_managers request :get_instance_template request :insert_instance_template request :delete_instance_template request :list_aggregated_instance_group_managers request :set_instance_template request :recreate_instances request :abandon_instances request :deprecate_image model_path "fog/compute/google/models" model :server collection :servers model :image collection :images model :disk collection :disks model :disk_type collection :disk_types model :machine_type collection :machine_types model :address collection :addresses model :global_address collection :global_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 :target_https_proxy collection :target_https_proxies model :url_map collection :url_maps model :global_forwarding_rule collection :global_forwarding_rules model :target_instance collection :target_instances model :instance_group collection :instance_groups model :subnetwork collection :subnetworks model :instance_template collection :instance_templates model :instance_group_manager collection :instance_group_managers model :ssl_certificate collection :ssl_certificates end end end fog-google-1.9.1/lib/fog/storage/0000755000004100000410000000000013451635472016576 5ustar www-datawww-datafog-google-1.9.1/lib/fog/storage/google_xml/0000755000004100000410000000000013451635472020732 5ustar www-datawww-datafog-google-1.9.1/lib/fog/storage/google_xml/requests/0000755000004100000410000000000013451635472022605 5ustar www-datawww-datafog-google-1.9.1/lib/fog/storage/google_xml/requests/copy_object.rb0000644000004100000410000000553613451635472025443 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["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-1.9.1/lib/fog/storage/google_xml/requests/get_service.rb0000644000004100000410000000250713451635472025435 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.select 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-1.9.1/lib/fog/storage/google_xml/requests/get_bucket_acl.rb0000644000004100000410000000362013451635472026066 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-1.9.1/lib/fog/storage/google_xml/requests/put_object_url.rb0000644000004100000410000000302513451635472026152 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-1.9.1/lib/fog/storage/google_xml/requests/put_object.rb0000644000004100000410000000732313451635472025275 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 !Utils::VALID_ACLS.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-1.9.1/lib/fog/storage/google_xml/requests/get_bucket.rb0000644000004100000410000001055113451635472025250 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_by { |a| a["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.select { |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-1.9.1/lib/fog/storage/google_xml/requests/head_object.rb0000644000004100000410000000511313451635472025361 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-1.9.1/lib/fog/storage/google_xml/requests/get_object_url.rb0000644000004100000410000000240313451635472026120 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 # * options<~Hash> - A list of key-value pairs to send as query strings # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object def get_object_url(bucket_name, object_name, expires, options = {}) Fog::Logger.deprecation("Fog::Storage::Google => #get_object_url is deprecated, use #get_object_https_url instead[/] [light_black](#{caller(1..1).first})") get_object_https_url(bucket_name, object_name, expires, options) end end class Mock # :nodoc:all def get_object_url(bucket_name, object_name, expires, options = {}) Fog::Logger.deprecation("Fog::Storage::Google => #get_object_url is deprecated, use #get_object_https_url instead[/] [light_black](#{caller(1..1).first})") get_object_https_url(bucket_name, object_name, expires, options) end end end end end fog-google-1.9.1/lib/fog/storage/google_xml/requests/delete_object_url.rb0000644000004100000410000000277413451635472026616 0ustar www-datawww-datamodule Fog module Storage class GoogleXML class Real # Get an expiring object url from Google Storage for deleting 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 delete_object_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 => "DELETE", :path => "#{bucket_name}/#{object_name}" }, expires) end end class Mock def delete_object_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 => "DELETE", :path => "#{bucket_name}/#{object_name}" }, expires) end end end end end fog-google-1.9.1/lib/fog/storage/google_xml/requests/get_object_https_url.rb0000644000004100000410000000224113451635472027342 0ustar www-datawww-datamodule Fog module Storage class GoogleXML module GetObjectHttpsUrl def get_object_https_url(bucket_name, object_name, expires, options = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name https_url(options.merge(: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-1.9.1/lib/fog/storage/google_xml/requests/get_object.rb0000644000004100000410000001072713451635472025246 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 = {}) 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 if block_given? data = StringIO.new(object[:body]) remaining = data.length while remaining > 0 chunk = data.read([remaining, Excon::CHUNK_SIZE].min) yield(chunk) remaining -= Excon::CHUNK_SIZE end else response.body = object[:body] end end else response.status = 404 raise(Excon::Errors.status_error({ :expects => 200 }, response)) end response end end end end end fog-google-1.9.1/lib/fog/storage/google_xml/requests/get_object_http_url.rb0000644000004100000410000000221513451635472027160 0ustar www-datawww-datamodule Fog module Storage class GoogleXML module GetObjectHttpUrl def get_object_http_url(bucket_name, object_name, expires, options = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name http_url(options.merge(: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-1.9.1/lib/fog/storage/google_xml/requests/delete_bucket.rb0000644000004100000410000000222413451635472025731 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-1.9.1/lib/fog/storage/google_xml/requests/put_bucket.rb0000644000004100000410000000507013451635472025301 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 !Utils::VALID_ACLS.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-1.9.1/lib/fog/storage/google_xml/requests/put_bucket_acl.rb0000644000004100000410000000272013451635472026117 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.reject { |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-1.9.1/lib/fog/storage/google_xml/requests/put_object_acl.rb0000644000004100000410000000330313451635472026106 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.reject { |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) headers = {} data = "" if acl.is_a?(Hash) data = <<-DATA #{tag('ID', acl['Owner']['ID'])} #{entries_list(acl['AccessControlList'])} DATA elsif acl.is_a?(String) && Utils::VALID_ACLS.include?(acl) headers["x-goog-acl"] = acl else raise Excon::Errors::BadRequest.new("invalid x-goog-acl") end request(:body => data, :expects => 200, :headers => headers, :host => "#{bucket_name}.#{@host}", :method => "PUT", :query => { "acl" => nil }, :path => Fog::Google.escape(object_name)) end end end end end fog-google-1.9.1/lib/fog/storage/google_xml/requests/delete_object.rb0000644000004100000410000000257213451635472025730 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-1.9.1/lib/fog/storage/google_xml/requests/get_object_acl.rb0000644000004100000410000000466213451635472026066 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-1.9.1/lib/fog/storage/google_xml/models/0000755000004100000410000000000013451635472022215 5ustar www-datawww-datafog-google-1.9.1/lib/fog/storage/google_xml/models/directories.rb0000644000004100000410000000211313451635472025053 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 = {} data.each_pair do |k, v| 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-1.9.1/lib/fog/storage/google_xml/models/files.rb0000644000004100000410000000547413451635472023656 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[:body] = data.body file_data[:key] = key new(file_data) rescue Excon::Errors::NotFound nil end def get_http_url(key, expires, options = {}) requires :directory service.get_object_http_url(directory.key, key, expires, options) end def get_https_url(key, expires, options = {}) requires :directory service.get_object_https_url(directory.key, key, expires, options) end def head(key, options = {}) requires :directory data = service.head_object(directory.key, key, options) 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-1.9.1/lib/fog/storage/google_xml/models/file.rb0000644000004100000410000001104313451635472023460 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"] def acl=(new_acl) unless Utils::VALID_ACLS.include?(new_acl) raise ArgumentError.new("acl must be one of [#{Utils::VALID_ACLS.join(', ')}]") end @acl = new_acl end def body last_modified && (file = collection.get(identity)) ? attributes[:body] ||= file.body : attributes[: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, options = {}) requires :key collection.get_http_url(key, expires, options) end private attr_writer :directory end end end end fog-google-1.9.1/lib/fog/storage/google_xml/models/directory.rb0000644000004100000410000000344113451635472024550 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) unless Utils::VALID_ACLS.include?(new_acl) raise ArgumentError.new("acl must be one of [#{Utils::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-1.9.1/lib/fog/storage/google_xml/utils.rb0000644000004100000410000000675213451635472022431 0ustar www-datawww-datamodule Fog module Storage class GoogleXML module Utils # 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 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] = Fog::Google.escape(params[:path]).gsub("%2F", "/") query = [] if params[:query] filtered = params[:query].reject { |k, v| k.nil? || v.nil? } query = filtered.map { |k, v| [k.to_s, Fog::Google.escape(v)].join("=") } end 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-1.9.1/lib/fog/storage/google_xml/real.rb0000644000004100000410000000722613451635472022211 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_by { |a| a[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-1.9.1/lib/fog/storage/google_xml/mock.rb0000644000004100000410000000615213451635472022214 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-1.9.1/lib/fog/storage/google_json/0000755000004100000410000000000013451635472021103 5ustar www-datawww-datafog-google-1.9.1/lib/fog/storage/google_json/requests/0000755000004100000410000000000013451635472022756 5ustar www-datawww-datafog-google-1.9.1/lib/fog/storage/google_json/requests/copy_object.rb0000644000004100000410000000225213451635472025604 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Copy an object from one Google Storage bucket to another # # @param source_bucket [String] Name of source bucket # @param source_object [String] Name of source object # @param target_bucket [String] Name of bucket to create copy in # @param target_object [String] Name of new copy of object # # @see https://cloud.google.com/storage/docs/json_api/v1/objects/copy # @return [Google::Apis::StorageV1::Object] copy of object def copy_object(source_bucket, source_object, target_bucket, target_object, options = {}) request_options = ::Google::Apis::RequestOptions.default.merge(options) @storage_json.copy_object(source_bucket, source_object, target_bucket, target_object, request_options) end end class Mock def copy_object(_source_bucket, _source_object, _target_bucket, _target_object, _options = {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/get_bucket_acl.rb0000644000004100000410000000177013451635472026243 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Get access control list entry for an Google Storage bucket # @see https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/get # # @param bucket_name [String] # Name of bucket # @param entity [String] # The entity holding the permission. Can be user-userId, # user-emailAddress, group-groupId, group-emailAddress, allUsers, # or allAuthenticatedUsers. # @return [Google::Apis::StorageV1::BucketAccessControls] def get_bucket_acl(bucket_name, entity) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("entity is required") unless entity @storage_json.get_bucket_access_control(bucket_name, entity) end end class Mock def get_bucket_acl(_bucket_name, _entity) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/put_object_url.rb0000644000004100000410000000363113451635472026326 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Get an expiring object url from Google Storage for putting an object # https://cloud.google.com/storage/docs/access-control#Signed-URLs # # @param bucket_name [String] Name of bucket containing object # @param object_name [String] Name of object to get expiring url for # @param expires [Time] Expiry time for this URL # @param headers [Hash] Optional hash of headers to include # @option options [String] "x-goog-acl" Permissions, must be in ['private', 'public-read', 'public-read-write', 'authenticated-read']. # 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" # @return [String] Expiring object https URL 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-1.9.1/lib/fog/storage/google_json/requests/put_object.rb0000644000004100000410000001041413451635472025441 0ustar www-datawww-data# frozen_string_literal: true module 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 # # @param bucket_name [String] Name of bucket to create object in # @param object_name [String] Name of object to create # @param data [File|String|Paperclip::AbstractAdapter] File, String or Paperclip adapter to create object from # @param options [Hash] Optional query parameters or Object attributes # Optional query parameters are listed below. # @param content_encoding [String] # If set, sets the contentEncoding property of the final object to # this value. # @param if_generation_match [Fixnum] # Makes the operation conditional on whether the object's current # generation matches the given value. Setting to 0 makes the operation # succeed only if there are no live versions of the object. # @param if_generation_not_match [Fixnum] # Makes the operation conditional on whether the object's current # generation does not match the given value. If no live object exists, # the precondition fails. Setting to 0 makes the operation succeed # only if there is a live version of the object. # @param if_metageneration_match [Fixnum] # Makes the operation conditional on whether the object's # current metageneration matches the given value. # @param if_metageneration_not_match [Fixnum] # Makes the operation conditional on whether the object's # current metageneration does not match the given value. # @param predefined_acl [String] # Apply a predefined set of access controls to this object. # @param projection [String] # Set of properties to return. Defaults to noAcl, # unless the object resource specifies the acl property, # when it defaults to full. # @return [Google::Apis::StorageV1::Object] def put_object(bucket_name, object_name, data, content_encoding: nil, if_generation_match: nil, if_generation_not_match: nil, if_metageneration_match: nil, if_metageneration_not_match: nil, kms_key_name: nil, predefined_acl: nil, **options) data, options = normalize_data(data, options) object_config = ::Google::Apis::StorageV1::Object.new( options.merge(:name => object_name) ) @storage_json.insert_object( bucket_name, object_config, :content_encoding => content_encoding, :if_generation_match => if_generation_match, :if_generation_not_match => if_generation_not_match, :if_metageneration_match => if_metageneration_match, :if_metageneration_not_match => if_metageneration_not_match, :kms_key_name => kms_key_name, :predefined_acl => predefined_acl, :options => ::Google::Apis::RequestOptions.default.merge(options), # see https://developers.google.com/api-client-library/ruby/guide/media_upload :content_type => options[:content_type], :upload_source => data ) end protected def normalize_data(data, options) raise ArgumentError.new("data is required") unless data if data.is_a?(String) data = StringIO.new(data) options[:content_type] ||= "text/plain" elsif data.is_a?(::File) options[:content_type] ||= Fog::Storage.parse_data(data)[:headers]["Content-Type"] end # Paperclip::AbstractAdapter if data.respond_to?(:content_type) && data.respond_to?(:path) options[:content_type] ||= data.content_type data = data.path end [data, options] end end class Mock def put_object(_bucket_name, _object_name, _data, _options = {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/get_bucket.rb0000644000004100000410000000300113451635472025411 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # List information about objects in an Google Storage bucket # # https://cloud.google.com/storage/docs/json_api/v1/buckets#resource # # @param bucket_name [String] # Name of bucket to list # @param [Fixnum] if_metageneration_match # Makes the return of the bucket metadata conditional on whether the bucket's # current metageneration matches the given value. # @param [Fixnum] if_metageneration_not_match # Makes the return of the bucket metadata conditional on whether the bucket's # current metageneration does not match the given value. # @param [String] projection # Set of properties to return. Defaults to noAcl. # @return [Google::Apis::StorageV1::Bucket] def get_bucket(bucket_name, if_metageneration_match: nil, if_metageneration_not_match: nil, projection: nil) raise ArgumentError.new("bucket_name is required") unless bucket_name @storage_json.get_bucket( bucket_name, :if_metageneration_match => if_metageneration_match, :if_metageneration_not_match => if_metageneration_not_match, :projection => projection ) end end class Mock def get_bucket(_bucket_name, _options = {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/get_object_url.rb0000644000004100000410000000156613451635472026302 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, options = {}) Fog::Logger.deprecation("Fog::Storage::Google => #get_object_url is deprecated, use #get_object_https_url instead[/] [light_black](#{caller(0..0)})") get_object_https_url(bucket_name, object_name, expires, options) end end class Mock # :nodoc:all def get_object_url(bucket_name, object_name, expires, options = {}) Fog::Logger.deprecation("Fog::Storage::Google => #get_object_url is deprecated, use #get_object_https_url instead[/] [light_black](#{caller(0..0)})") get_object_https_url(bucket_name, object_name, expires, options) end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/list_bucket_acl.rb0000644000004100000410000000130313451635472026427 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Get access control list for an Google Storage bucket # @see https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/list # # @param bucket_name [String] Name of bucket object is in # @return [Google::Apis::StorageV1::BucketAccessControls] def list_bucket_acl(bucket_name) raise ArgumentError.new("bucket_name is required") unless bucket_name @storage_json.list_bucket_access_controls(bucket_name) end end class Mock def list_bucket_acl(_bucket_name) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/list_object_acl.rb0000644000004100000410000000173113451635472026425 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # List access control list for an Google Storage object # https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/get # # @param bucket_name [String] Name of bucket object is in # @param object_name [String] Name of object to add ACL to # @return [Google::Apis::StorageV1::ObjectAccessControls] def list_object_acl(bucket_name, object_name, generation: nil) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name @storage_json.list_object_access_controls(bucket_name, object_name, :generation => generation) end end class Mock def list_object_acl(_bucket_name, _object_name) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/delete_object_url.rb0000644000004100000410000000276313451635472026765 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Get an expiring object url from Google Storage for deleting an object # https://cloud.google.com/storage/docs/access-control#Signed-URLs # # @param bucket_name [String] Name of bucket containing object # @param object_name [String] Name of object to get expiring url for # @param expires [Time] Expiry time for this URL # # @return [String] Expiring object https URL def delete_object_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 => "DELETE", :path => "#{bucket_name}/#{object_name}" }, expires) end end class Mock def delete_object_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 => "DELETE", :path => "#{bucket_name}/#{object_name}" }, expires) end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/get_object_https_url.rb0000644000004100000410000000220213451635472027510 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON module GetObjectHttpsUrl def get_object_https_url(bucket_name, object_name, expires, options = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name https_url(options.merge(:headers => {}, :host => @host, :method => "GET", :path => "#{bucket_name}/#{object_name}"), expires) end end class Real # Get an expiring object https url from Google Storage # https://cloud.google.com/storage/docs/access-control#Signed-URLs # # @param bucket_name [String] Name of bucket to read from # @param object_name [String] Name of object to read # @param expires [Time] Expiry time for this URL # @return [String] Expiring object https URL include GetObjectHttpsUrl end class Mock # :nodoc:all include GetObjectHttpsUrl end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/get_object.rb0000644000004100000410000000721413451635472025414 0ustar www-datawww-datarequire "tempfile" module Fog module Storage class GoogleJSON class Real # Get an object from Google Storage # @see https://cloud.google.com/storage/docs/json_api/v1/objects/get # # @param bucket_name [String] Name of bucket to create object in # @param object_name [String] Name of object to create # @param generation [Fixnum] # If present, selects a specific revision of this object (as opposed to the latest version, the default). # @param ifGenerationMatch [Fixnum] # Makes the operation conditional on whether the object's current generation matches the given value. Setting to 0 makes the operation succeed only if there are no live versions of the object. # @param ifGenerationNotMatch [Fixnum] # Makes the operation conditional on whether the object's current generation does not match the given value. If no live object exists, the precondition fails. Setting to 0 makes the operation succeed only if there is a live version of the object. # @param ifMetagenerationMatch [Fixnum] # Makes the operation conditional on whether the object's current metageneration matches the given value. # @param ifMetagenerationNotMatch [Fixnum] # Makes the operation conditional on whether the object's current metageneration does not match the given value. # @param projection [Fixnum] # Set of properties to return # @param options [Hash] # Request-specific options # @param &block [Proc] # Block to pass a streamed object response to. Expected format is # same as Excon :response_block ({ |chunk, remaining_bytes, total_bytes| ... }) # @return [Hash] Object metadata with :body attribute set to contents of object def get_object(bucket_name, object_name, generation: nil, if_generation_match: nil, if_generation_not_match: nil, if_metageneration_match: nil, if_metageneration_not_match: nil, projection: nil, **options, &_block) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name buf = Tempfile.new("fog-google-storage-temp") # Two requests are necessary, first for metadata, then for content. # google-api-ruby-client doesn't allow fetching both metadata and content request_options = ::Google::Apis::RequestOptions.default.merge(options) all_opts = { :generation => generation, :if_generation_match => if_generation_match, :if_generation_not_match => if_generation_not_match, :if_metageneration_match => if_metageneration_match, :if_metageneration_not_match => if_metageneration_not_match, :projection => projection, :options => request_options } object = @storage_json.get_object(bucket_name, object_name, all_opts).to_h @storage_json.get_object( bucket_name, object_name, all_opts.merge(:download_dest => buf.path) ) if block_given? yield buf.read, nil, nil else object[:body] = buf.read buf.unlink end object ensure buf.close! rescue nil end end class Mock def get_object(_bucket_name, _object_name, _options = {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/get_object_http_url.rb0000644000004100000410000000216613451635472027336 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON module GetObjectHttpUrl def get_object_http_url(bucket_name, object_name, expires, options = {}) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name http_url(options.merge(:headers => {}, :host => @host, :method => "GET", :path => "#{bucket_name}/#{object_name}"), expires) end end class Real # Get an expiring object http url from Google Storage # https://cloud.google.com/storage/docs/access-control#Signed-URLs # # @param bucket_name [String] Name of bucket to read from # @param object_name [String] Name of object to read # @param expires [Time] Expiry time for this URL # @return [String] Expiring object http URL include GetObjectHttpUrl end class Mock # :nodoc:all include GetObjectHttpUrl end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/delete_bucket.rb0000644000004100000410000000076613451635472026113 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 # # @param bucket_name [String] Name of bucket to delete def delete_bucket(bucket_name) @storage_json.delete_bucket(bucket_name) end end class Mock def delete_bucket(_bucket_name) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/put_bucket.rb0000644000004100000410000000255513451635472025457 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Create a Google Storage bucket # @see https://cloud.google.com/storage/docs/json_api/v1/buckets/insert # # @param bucket_name [String] Name of bucket to create # @param options [Hash] # Optional fields. Acceptable options include # any writeable bucket attribute (see docs) # or one of the following options: # @param predefined_acl [String] Applies a predefined set of access controls to this bucket. # @param predefined_default_object_acl [String] Applies a predefined set of default object access controls # # @return [Google::Apis::StorageV1::Bucket] def put_bucket(bucket_name, predefined_acl: nil, predefined_default_object_acl: nil, **options) bucket = ::Google::Apis::StorageV1::Bucket.new( options.merge(:name => bucket_name) ) @storage_json.insert_bucket( @project, bucket, :predefined_acl => predefined_acl, :predefined_default_object_acl => predefined_default_object_acl ) end end class Mock def put_bucket(_bucket_name, _options = {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/get_object_metadata.rb0000644000004100000410000000207213451635472027251 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Fetch metadata for an object in Google Storage # # @param bucket_name [String] Name of bucket to read from # @param object_name [String] Name of object to read # @param options [Hash] Optional parameters # @see https://cloud.google.com/storage/docs/json_api/v1/objects/get # # @return [Google::Apis::StorageV1::Object] def get_object_metadata(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 request_options = ::Google::Apis::RequestOptions.default.merge(options) @storage_json.get_object(bucket_name, object_name, :options => request_options) end end class Mock def get_object_metadata(_bucket_name, _object_name, _options = {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/put_bucket_acl.rb0000644000004100000410000000167713451635472026302 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Change access control list for an Google Storage bucket # https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/insert # # @param bucket_name [String] Name of bucket object is in # @param acl [Hash] ACL hash to add to bucket, see GCS documentation above # @return [Google::Apis::StorageV1::BucketAccessControl] 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 acl_update = ::Google::Apis::StorageV1::BucketAccessControl.new(acl) @storage_json.insert_bucket_access_control(bucket_name, acl_update) end end class Mock def put_bucket_acl(_bucket_name, _acl) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/put_object_acl.rb0000644000004100000410000000223013451635472026255 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Change access control list for an Google Storage object # # @param bucket_name [String] name of bucket object is in # @param object_name [String] name of object to add ACL to # @param acl [Hash] ACL hash to add to bucket, see GCS documentation. # # @see https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert # @return [Google::Apis::StorageV1::ObjectAccessControl] 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 acl_object = ::Google::Apis::StorageV1::ObjectAccessControl.new(acl) @storage_json.insert_object_access_control( bucket_name, object_name, acl_object ) end end class Mock def put_object_acl(_bucket_name, _object_name, _acl) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/delete_object.rb0000644000004100000410000000116413451635472026075 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 # # @param bucket_name [String] Name of bucket containing object to delete # @param object_name [String] Name of object to delete def delete_object(bucket_name, object_name) @storage_json.delete_object(bucket_name, object_name) end end class Mock def delete_object(_bucket_name, _object_name) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/list_objects.rb0000644000004100000410000000276413451635472026000 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) # @return [Google::Apis::StorageV1::Objects] def list_objects(bucket, options = {}) allowed_opts = %i( delimiter max_results page_token prefix projection versions ) @storage_json.list_objects( bucket, options.select { |k, _| allowed_opts.include? k } ) end end class Mock def list_objects(_bucket, _options = {}) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/get_object_acl.rb0000644000004100000410000000235213451635472026231 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 # # @param bucket_name [String] Name of bucket object is in # @param object_name [String] Name of object to add ACL to # @param entity [String] The entity holding the permission. # Can be user-userId, user-emailAddress, group-groupId, # group-emailAddress, allUsers, or allAuthenticatedUsers. # @param generation [Hash] Specify a particular version to retrieve # @return [Google::Apis::StorageV1::ObjectAccessControls] def get_object_acl(bucket_name, object_name, entity, generation: nil) raise ArgumentError.new("bucket_name is required") unless bucket_name raise ArgumentError.new("object_name is required") unless object_name @storage_json.get_object_access_control( bucket_name, object_name, entity, :generation => generation ) end end class Mock def get_object_acl(_bucket_name, _object_name) Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/requests/list_buckets.rb0000644000004100000410000000145513451635472026003 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Real # Retrieves a list of buckets for a given project # https://cloud.google.com/storage/docs/json_api/v1/buckets/list # # @return [Google::Apis::StorageV1::Buckets] # TODO: check if very large lists require working with nextPageToken def list_buckets(max_results: nil, page_token: nil, prefix: nil, projection: nil) @storage_json.list_buckets( @project, :max_results => max_results, :page_token => page_token, :prefix => prefix, :projection => projection ) end end class Mock def list_buckets Fog::Mock.not_implemented end end end end end fog-google-1.9.1/lib/fog/storage/google_json/models/0000755000004100000410000000000013451635472022366 5ustar www-datawww-datafog-google-1.9.1/lib/fog/storage/google_json/models/directories.rb0000644000004100000410000000262613451635472025235 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Directories < Fog::Collection model Fog::Storage::GoogleJSON::Directory def all(opts = {}) data = service.list_buckets(opts).to_h[:items] || [] load(data) end def get(bucket_name, options = {}) if_metageneration_match = options[:if_metageneration_match] if_metageneration_not_match = options[:if_metageneration_not_match] projection = options[:projection] data = service.get_bucket( bucket_name, :if_metageneration_match => if_metageneration_match, :if_metageneration_not_match => if_metageneration_not_match, :projection => projection ).to_h directory = new(data) # Because fog-aws accepts these arguments on files at the # directories.get level, we need to preload the directory files # with these attributes here. files_attr_names = %i(delimiter page_token max_results prefix) file_opts = options.select { |k, _| files_attr_names.include? k } directory.files(file_opts) directory rescue ::Google::Apis::ClientError => e # metageneration check failures returns HTTP 412 Precondition Failed raise e unless e.status_code == 404 || e.status_code == 412 nil end end end end end fog-google-1.9.1/lib/fog/storage/google_json/models/files.rb0000644000004100000410000000355213451635472024022 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Files < Fog::Collection model Fog::Storage::GoogleJSON::File 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" def all(options = {}) requires :directory data = service.list_objects(directory.key, attributes.merge(options)) .to_h[:items] || [] load(data) end alias_method :each_file_this_page, :each def each if block_given? subset = dup.all subset.each_file_this_page { |f| yield f } end self end def get(key, options = {}, &block) requires :directory data = service.get_object(directory.key, key, options, &block).to_h new(data) rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end def get_https_url(key, expires, options = {}) requires :directory service.get_object_https_url(directory.key, key, expires, options) end def metadata(key, options = {}) requires :directory data = service.get_object_metadata(directory.key, key, options).to_h new(data) rescue ::Google::Apis::ClientError nil end alias_method :head, :metadata def new(opts = {}) requires :directory super({ :directory => directory }.merge(opts)) end end end end end fog-google-1.9.1/lib/fog/storage/google_json/models/file.rb0000644000004100000410000001032013451635472023626 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class File < Fog::Model identity :key, :aliases => ["Key", :name] attribute :acl attribute :predefined_acl, :aliases => ["predefinedAcl", :predefined_acl] attribute :cache_control, :aliases => ["cacheControl", :cache_control] attribute :content_disposition, :aliases => ["contentDisposition", :content_disposition] attribute :content_encoding, :aliases => ["contentEncoding", :content_encoding] attribute :content_length, :aliases => ["size", :size], :type => :integer attribute :content_md5, :aliases => ["md5Hash", :md5_hash] attribute :content_type, :aliases => ["contentType", :content_type] attribute :crc32c attribute :etag, :aliases => ["etag", :etag] attribute :time_created, :aliases => ["timeCreated", :time_created] attribute :last_modified, :aliases => ["updated", :updated] attribute :generation attribute :metageneration attribute :metadata, :aliases => ["metadata", :metadata] attribute :self_link, :aliases => ["selfLink", :self_link] attribute :media_link, :aliases => ["mediaLink", :media_link] attribute :owner attribute :storage_class, :aliases => "storageClass" # attribute :body # https://cloud.google.com/storage/docs/access-control/lists#predefined-acls VALID_PREDEFINED_ACLS = [ "authenticatedRead", "bucketOwnerFullControl", "bucketOwnerRead", "private", "projectPrivate", "publicRead", "publicReadWrite" ].freeze def predefined_acl=(new_predefined_acl) unless VALID_PREDEFINED_ACLS.include?(new_predefined_acl) raise ArgumentError.new("acl must be one of [#{VALID_PREDEFINED_ACLS.join(', ')}]") end @predefined_acl = new_predefined_acl end def body last_modified && (file = collection.get(identity)) ? attributes[:body] ||= file.body : attributes[: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 ::Google::Apis::ClientError => e raise e unless e.status_code == 404 false end def public=(new_public) unless new_public.nil? if new_public @predefined_acl = "publicRead" else @predefined_acl = "projectPrivate" end end new_public end def public_url requires :directory, :key "https://storage.googleapis.com/#{directory.key}/#{key}" end FILE_INSERTABLE_FIELDS = %i( content_type predefined_acl cache_control content_disposition content_encoding metadata ).freeze def save requires :body, :directory, :key options = Hash[ FILE_INSERTABLE_FIELDS.map { |k| [k, attributes[k]] } .reject { |pair| pair[1].nil? } ] options[:predefined_acl] ||= @predefined_acl service.put_object(directory.key, key, body, options) 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, options = {}) requires :key collection.get_https_url(key, expires, options) end private attr_writer :directory end end end end fog-google-1.9.1/lib/fog/storage/google_json/models/directory.rb0000644000004100000410000000310413451635472024715 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON ## # Represents a Google Storage bucket class Directory < Fog::Model identity :key, :aliases => ["Name", "name", :name] attribute :acl attribute :billing attribute :cors attribute :default_object_acl, aliases => "defaultObjectAcl" attribute :etag attribute :id attribute :kind attribute :labels attribute :lifecycle attribute :location attribute :logging attribute :metageneration attribute :name attribute :owner attribute :project_number, aliases => "projectNumber" attribute :self_link, aliases => "selfLink" attribute :storage_class, aliases => "storageClass" attribute :time_created, aliases => "timeCreated" attribute :updated attribute :versioning attribute :website def destroy requires :key service.delete_bucket(key) true rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 false end def files(attr = {}) @files ||= begin Fog::Storage::GoogleJSON::Files.new( attr.merge(:directory => self, :service => service) ) end end def public_url requires :key "#{GOOGLE_STORAGE_BUCKET_BASE_URL}#{key}" end def save requires :key service.put_bucket(key, attributes) true end end end end end fog-google-1.9.1/lib/fog/storage/google_json/utils.rb0000644000004100000410000000224613451635472022574 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] = URI.encode(params[:path]).gsub("%2F", "/") query = [] if params[:query] filtered = params[:query].reject { |k, v| k.nil? || v.nil? } query = filtered.map { |k, v| [k.to_s, Fog::Google.escape(v)].join("=") } end query << "GoogleAccessId=#{@client.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-1.9.1/lib/fog/storage/google_json/real.rb0000644000004100000410000000466613451635472022367 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 = ::Google::Apis::StorageV1::StorageService.new apply_client_options(@storage_json, options) @storage_json.client_options.open_timeout_sec = options[:open_timeout_sec] if options[:open_timeout_sec] @storage_json.client_options.read_timeout_sec = options[:read_timeout_sec] if options[:read_timeout_sec] @storage_json.client_options.send_timeout_sec = options[:send_timeout_sec] if options[:send_timeout_sec] 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_by { |a| a[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] || {}).each_key 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 key = OpenSSL::PKey::RSA.new(@client.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-1.9.1/lib/fog/storage/google_json/mock.rb0000644000004100000410000000072013451635472022360 0ustar www-datawww-datamodule Fog module Storage class GoogleJSON class Mock include Utils include Fog::Google::Shared MockClient = Struct.new(:issuer) def initialize(options = {}) shared_initialize(options[:google_project], GOOGLE_STORAGE_JSON_API_VERSION, GOOGLE_STORAGE_JSON_BASE_URL) @client = MockClient.new('test') end def signature(_params) "foo" end end end end end fog-google-1.9.1/lib/fog/storage/google_xml.rb0000644000004100000410000000222013451635472021253 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 :delete_object_url 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-1.9.1/lib/fog/storage/google.rb0000644000004100000410000000076513451635472020407 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-1.9.1/lib/fog/storage/google_json.rb0000644000004100000410000000413013451635472021426 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_application_default, :google_auth, :google_client, :google_client_options, :google_key_location, :google_key_string, :google_json_key_location, :google_json_key_string, :open_timeout_sec, :read_timeout_sec, :send_timeout_sec ) # https://cloud.google.com/storage/docs/json_api/v1/ GOOGLE_STORAGE_JSON_API_VERSION = "v1".freeze GOOGLE_STORAGE_JSON_BASE_URL = "https://www.googleapis.com/storage/".freeze GOOGLE_STORAGE_BUCKET_BASE_URL = "https://storage.googleapis.com/".freeze # 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).freeze ## # 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 :delete_object_url 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_metadata request :get_object_url request :list_buckets request :list_bucket_acl request :list_objects request :list_object_acl request :put_bucket request :put_bucket_acl request :put_object request :put_object_acl request :put_object_url end end end fog-google-1.9.1/CONTRIBUTING.md0000644000004100000410000001620513451635472016046 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. We 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, especially the ones [tagged "help wanted"](https://github.com/fog/fog-google/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22). * [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 or triage [open issues](https://github.com/fog/fog-google/issues). * Improve documentation. See project's [inch tracker](https://inch-ci.org/github/fog/fog-google.svg?branch=master) for ideas for where to get started. * 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, we 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 `:default` credential, use ```shell $ rake console ``` ### Documentation Code should be documented using [YARDoc](https://yardoc.org/) syntax. We use [inch](https://github.com/rrrene/inch) to keep track of overall doc coverage and [inch-ci](https://inch-ci.org/) to keep track of changes over time. You can view a doc coverage report by running: ``` $ inch ``` Or view suggestions on a specific method: ``` $ inch show Fog::Compute::Google::Server#set_metadata ``` ### Testing This module is tested with [Minitest](https://github.com/seattlerb/minitest). #### Integration tests Live integration tests can be found in `test/integration/`. Most of the library functionality is currently covered with them. To simplify things for contributors we have a CI system that runs all integration tests in parallel against all pull requests marked with `integrate` label that anyone in `fog-google` team can set. Read [CI section](https://github.com/fog/fog-google/blob/master/CONTRIBUTING.md#continuous-integration) for more info. 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_json_key_location: /path/to/my-project-xxxxxxxxxxxxx.json ``` Then you can run all the live tests: ```shell $ bundle exec rake test ``` or just one API: ``` $ bundle exec rake test:compute ``` (See `rake -T` for all available tasks) or just one test: ```shell $ bundle exec rake test TESTOPTS="--name=TestServers#test_bootstrap_ssh_destroy" ``` or a series of tests by name: ``` $ bundle exec rake test TESTOPTS="--name=/test_nil_get/" ``` #### Unit tests Some basic sanity checking and logic verification is done via unit tests located in `test/unit`. They automatically run against every pull request via [Travis CI](http://travis-ci.org/). You can run unit tests like so: ``` $ rake test:unit ``` We're in progress of extending the library with more unit tests and contributions along that front are very welcome. #### The transition from `shindo` to Minitest Previously, [shindo](https://github.com/geemus/shindo) was the primary testing framework. We've moved away from it, and to Minitest, but some artifacts may remain. For more information on transition, read [#50](https://github.com/fog/fog-google/issues/50). #### Continuous integration Currently Google maintains a [Concourse CI](https://concourse-ci.org/) server, running a pipeline defined in `ci` folder. It automatically runs all integration tests against every pull-request marked with `integration` label. For more information on the pipeline please refer to the [ci README](https://github.com/fog/fog-google/blob/master/ci/README.md). #### 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-1.9.1/.ruby-gemset0000644000004100000410000000001313451635472016047 0ustar www-datawww-datafog-google fog-google-1.9.1/Gemfile0000644000004100000410000000057613451635472015114 0ustar www-datawww-datasource "https://rubygems.org" # Do not require development gems not needed in runtime gem "codecov", :require => false gem "inch", :require => false gem "osrcry", :require => false gem "rubocop", :require => false # Debugger is specified here as it's not compatible with jRuby gem "pry-byebug", :platforms => :ruby # Specify your gem's dependencies in fog-google.gemspec gemspec fog-google-1.9.1/MIGRATING.md0000644000004100000410000000003213451635472015447 0ustar www-datawww-data## fog-google 1.0 -> 2.0: fog-google-1.9.1/ci/0000755000004100000410000000000013451635472014204 5ustar www-datawww-datafog-google-1.9.1/ci/README.md0000644000004100000410000000460613451635472015471 0ustar www-datawww-data# fog-google CI This pipeline performs integration tests against every PR with the `integrate` label. This allows whitelisted PRs to be tested automatically before being merged. Status is updated on the PR when the test completes. ## Setup In order to run the fog-google Concourse Pipeline you must have an existing [Concourse](http://concourse.ci) environment. To deploy the pipeline: * Download the `fly` binary from the Concourse web interface and place it in your `$PATH`. * Login to your Concourse: ``` fly -t fog-ci login -c ``` * Update the [credentials.yml](https://github.com/fog/fog-google/blob/master/ci/credentials.yml.tpl) file. See [Credentials Requirements](#credentials-requirements) for specific instructions. * Set the fog-google pipeline: ``` fly -t fog-ci set-pipeline -p pr-integration -c pipeline.yml -l credentials.yml ``` * Unpause the fog-google pipeline: ``` fly -t fog-ci unpause-pipeline -p pr-integration ``` ## Credentials Requirements Several external pieces of authentication are needed for credentials.yml 1. A JSON Service Account File for a service account with at least Editor access to the project. * To get a Service Account File, see [here](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount) and create using the Project/Editor role. 1. A [Github Access Token](https://github.com/blog/1509-personal-api-tokens) with at least `repo:status` access and a private key with push access to the `fog/fog-google` repositoy. 1. A [Codecov.io](https://codecov.io/) token for tracking test coverage. These items are equivalent to your login credentials for their resources. ## Login Gotchas * Our concourse pipeline is using GitHub auth, providing access to manipulate the pipeline to the members of the [fog-google team](https://github.com/orgs/fog/teams/fog-google), managed through the OAuth application managed by [fog-google bot](https://github.com/fog-google-bot). * If logging into a specific team, ie `fog-google`, use `--team-name fog-google` to specify that. ## Dockerfile The [docker-image](https://github.com/fog/fog-google/blob/master/ci/docker-image) directory contains the Dockerfile necessary for recreating the Docker image used in tasks. This is referenced in a per-task basis as `image_resource`, ie in image_resource [run-int.yml](https://github.com/fog/fog-google/blob/master/ci/tasks/run-int.yml)fog-google-1.9.1/ci/tasks/0000755000004100000410000000000013451635472015331 5ustar www-datawww-datafog-google-1.9.1/ci/tasks/run-int.sh0000755000004100000410000000131713451635472017266 0ustar www-datawww-data#!/usr/bin/env bash set -e my_dir="$( cd $(dirname $0) && pwd )" release_dir="$( cd ${my_dir} && cd ../.. && pwd )" workspace_dir="$( cd ${release_dir} && cd ../../../.. && pwd )" pushd ${release_dir} > /dev/null source ci/tasks/utils.sh popd > /dev/null check_param google_project check_param google_json_key_data check_param rake_task check_param codecov_token echo $google_json_key_data > `pwd`/service_account_key.json cat >~/.fog < /dev/null bundle install --jobs=3 --retry=3 FOG_MOCK=false COVERAGE=true CODECOV_TOKEN=${codecov_token} rake ${rake_task} popd > /dev/nullfog-google-1.9.1/ci/tasks/run-int.yml0000644000004100000410000000051313451635472017447 0ustar www-datawww-data--- platform: linux image_resource: type: docker-image source: {repository: rubyfog/fog-google} inputs: - name: fog-google-src path: src/fog-google run: path: src/fog-google/ci/tasks/run-int.sh params: rake_task: replace-me codecov_token: replace-me google_project: replace-me google_json_key_data: | replace-mefog-google-1.9.1/ci/tasks/utils.sh0000755000004100000410000000030513451635472017026 0ustar www-datawww-data#!/usr/bin/env bash check_param() { local name=$1 local value=$(eval echo '$'$name) if [ "$value" == 'replace-me' ]; then echo "environment variable $name must be set" exit 1 fi } fog-google-1.9.1/ci/pipeline.yml0000644000004100000410000001615013451635472016537 0ustar www-datawww-datajobs: - name: integration-compute-core_compute serial: true plan: - get: fog-google-src resource: pull-request version: every trigger: true - put: pull-request params: {path: fog-google-src, status: pending} - task: run-integration-tests file: fog-google-src/ci/tasks/run-int.yml params: rake_task: test:compute-core_compute codecov_token: {{codecov_token}} google_project: {{google_project}} google_json_key_data: {{google_json_key_data}} on_failure: put: pull-request params: path: fog-google-src status: failure - name: integration-compute-core_networking serial: true plan: - get: fog-google-src resource: pull-request version: every trigger: true - put: pull-request params: {path: fog-google-src, status: pending} - task: run-integration-tests file: fog-google-src/ci/tasks/run-int.yml params: rake_task: test:compute-core_networking codecov_token: {{codecov_token}} google_project: {{google_project}} google_json_key_data: {{google_json_key_data}} on_failure: put: pull-request params: path: fog-google-src status: failure - name: integration-compute-instance_groups serial: true plan: - get: fog-google-src resource: pull-request version: every trigger: true - put: pull-request params: {path: fog-google-src, status: pending} - task: run-integration-tests file: fog-google-src/ci/tasks/run-int.yml params: rake_task: test:compute-instance_groups codecov_token: {{codecov_token}} google_project: {{google_project}} google_json_key_data: {{google_json_key_data}} on_failure: put: pull-request params: path: fog-google-src status: failure - name: integration-compute-loadbalancing serial: true plan: - get: fog-google-src resource: pull-request version: every trigger: true - put: pull-request params: {path: fog-google-src, status: pending} - task: run-integration-tests file: fog-google-src/ci/tasks/run-int.yml params: rake_task: test:compute-loadbalancing codecov_token: {{codecov_token}} google_project: {{google_project}} google_json_key_data: {{google_json_key_data}} on_failure: put: pull-request params: path: fog-google-src status: failure - name: integration-tests-monitoring serial: true plan: - get: fog-google-src resource: pull-request version: every trigger: true - put: pull-request params: {path: fog-google-src, status: pending} - task: run-integration-tests file: fog-google-src/ci/tasks/run-int.yml params: rake_task: test:monitoring codecov_token: {{codecov_token}} google_project: {{google_project}} google_json_key_data: {{google_json_key_data}} on_failure: put: pull-request params: path: fog-google-src status: failure - name: integration-tests-pubsub serial: true plan: - get: fog-google-src resource: pull-request version: every trigger: true - put: pull-request params: {path: fog-google-src, status: pending} - task: run-integration-tests file: fog-google-src/ci/tasks/run-int.yml params: rake_task: test:pubsub codecov_token: {{codecov_token}} google_project: {{google_project}} google_json_key_data: {{google_json_key_data}} on_failure: put: pull-request params: path: fog-google-src status: failure - name: integration-sqlv1 serial: true plan: - get: fog-google-src resource: pull-request version: every trigger: true - put: pull-request params: {path: fog-google-src, status: pending} - task: run-integration-tests file: fog-google-src/ci/tasks/run-int.yml params: rake_task: test:sql-sqlv1 codecov_token: {{codecov_token}} google_project: {{google_project}} google_json_key_data: {{google_json_key_data}} on_failure: put: pull-request params: path: fog-google-src status: failure - name: integration-sqlv2 serial: true plan: - get: fog-google-src resource: pull-request version: every trigger: true - put: pull-request params: {path: fog-google-src, status: pending} - task: run-integration-tests file: fog-google-src/ci/tasks/run-int.yml params: rake_task: test:sql-sqlv2 codecov_token: {{codecov_token}} google_project: {{google_project}} google_json_key_data: {{google_json_key_data}} on_failure: put: pull-request params: path: fog-google-src status: failure - name: integration-tests-storage serial: true plan: - get: fog-google-src resource: pull-request version: every trigger: true - put: pull-request params: {path: fog-google-src, status: pending} - task: run-integration-tests file: fog-google-src/ci/tasks/run-int.yml params: rake_task: test:storage codecov_token: {{codecov_token}} google_project: {{google_project}} google_json_key_data: {{google_json_key_data}} on_failure: put: pull-request params: path: fog-google-src status: failure - name: github-pr-aggregator plan: - get: fog-google-src resource: pull-request passed: [integration-tests-storage, integration-tests-pubsub, integration-tests-monitoring, integration-sqlv1, integration-sqlv2, integration-compute-core_compute, integration-compute-core_networking, integration-compute-instance_groups, integration-compute-loadbalancing] trigger: true on_success: put: pull-request params: path: fog-google-src status: success on_failure: put: pull-request params: path: fog-google-src status: failure resources: - name: pull-request type: pull-request source: access_token: {{github_access_token}} private_key: {{github_private_key}} label: integrate repo: fog/fog-google resource_types: # This is a third party resource. # The referenced docker-image is maintained externally # https://github.com/jtarchie/pullrequest-resource - name: pull-request type: docker-image source: repository: jtarchie/prfog-google-1.9.1/ci/credentials.yml.template0000644000004100000410000000216613451635472021043 0ustar www-datawww-data--- # Codecov.io token to upload coverage reports codecov_token: # Google Cloud Platform project to run under google_project: # Google Compute Engine Service Account JSON google_json_key_data: | { "type": "service_account", "project_id": "myproject", "private_key_id": "number", "private_key": "-----BEGIN PRIVATE KEY-----\nIAMAVERYLONGKEYAMA==\n-----END PRIVATE KEY-----\n", "client_email": "account@myproject.iam.gserviceaccount.com", "client_id": "7435873987592347", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "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/account%40myproject.iam.gserviceaccount.com" } # An access token with repo:status access from an account that has push access to the repo github_access_token: # A SSH private key associated with the access token's account or # a repo push deploy key github_private_key: | -----BEGIN RSA PRIVATE KEY----- IAMAVERYLONGKEYAMA= -----END RSA PRIVATE KEY-----fog-google-1.9.1/ci/.gitignore0000644000004100000410000000001713451635472016172 0ustar www-datawww-datacredentials.ymlfog-google-1.9.1/ci/docker-image/0000755000004100000410000000000013451635472016533 5ustar www-datawww-datafog-google-1.9.1/ci/docker-image/Dockerfile0000644000004100000410000000064213451635472020527 0ustar www-datawww-dataFROM ubuntu:16.04 # Packages RUN DEBIAN_FRONTEND=noninteractive apt-get -y -qq update && apt-get -y -qq install \ build-essential \ curl \ git \ zlib1g-dev \ libssl-dev \ libreadline-dev \ libyaml-dev \ libxml2-dev \ libxslt-dev # Ubuntu 16.04 will fetch us 2.3.x without any issues. RUN DEBIAN_FRONTEND=noninteractive apt-get -y -qq install ruby ruby-dev && apt-get clean RUN gem install bundler