fog-google-1.29.3/0000755000004100000410000000000015142377631013674 5ustar www-datawww-datafog-google-1.29.3/.editorconfig0000644000004100000410000000031015142377631016343 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.29.3/.gitignore0000644000004100000410000000025715142377631015670 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.29.3/tasks/0000755000004100000410000000000015142377631015021 5ustar www-datawww-datafog-google-1.29.3/tasks/console.rake0000644000004100000410000000067215142377631017334 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.29.3/tasks/lint.rake0000644000004100000410000000026415142377631016635 0ustar www-datawww-datarequire "rubocop/rake_task" RuboCop::RakeTask.new(:lint) namespace :lint do task :changed do sh("git status --porcelain | cut -c4- | grep '.rb' | xargs rubocop") end end fog-google-1.29.3/tasks/test.rake0000644000004100000410000000711515142377631016650 0ustar www-datawww-datarequire "rake/testtask" Rake::TestTask.new do |t| t.description = "Run integration and unit tests" t.libs << "test" t.pattern = File.join("test", "**", "test_*.rb") t.warning = false end namespace :test do mock = ENV["FOG_MOCK"] || "true" task :travis do sh("bundle exec rake test:unit") end desc "Run all integration tests in parallel" multitask :parallel => ["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 :sql => SQL_TEST_TASKS desc "Run SQL API tests in parallel" multitask :sql_parallel => SQL_TEST_TASKS # TODO(temikus): Remove after v1 is renamed in pipeline desc "Run SQL API tests - v1 compat alias" task :"sql-sqlv2" => :sql 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.29.3/tasks/changelog.rake0000644000004100000410000000236115142377631017616 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 --grep="Merge" --pretty=format:"%t - %s%n%b%n"` end # Extracts all github users contributed since last tag def users_since_last_tag `git --no-pager log $(git describe --tags --abbrev=0)..HEAD --grep="Merge" --pretty=format:"%s" | cut -d' ' -f 6 | cut -d/ -f1 | sort | uniq` end namespace :changelog do task :generate do insert_after_line("CHANGELOG.md", changes_since_last_tag, /^## Next/) contributors = users_since_last_tag.split("\n").map { |name| "@" + name } printf("Huge thanks to all our contributors 🎆\n") printf("Special thanks to: " + contributors.join(" ") + "\n") printf("\nI'll merge this and release the gem once all tests pass.\n") end end fog-google-1.29.3/tasks/bundler.rake0000644000004100000410000000015115142377631017315 0ustar www-datawww-data# This installs the tasks that help with gem creation and # publishing. Bundler::GemHelper.install_tasks fog-google-1.29.3/CONTRIBUTING.md0000644000004100000410000001617115142377631016133 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::Google::Compute::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.29.3/MIGRATING.md0000644000004100000410000000003215142377631015532 0ustar www-datawww-data## fog-google 1.0 -> 2.0: fog-google-1.29.3/SECURITY.md0000644000004100000410000000027115142377631015465 0ustar www-datawww-data# Security contact information To report a security vulnerability, please contact [Tidelift security](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. fog-google-1.29.3/.github/0000755000004100000410000000000015142377631015234 5ustar www-datawww-datafog-google-1.29.3/.github/dependabot.yml0000644000004100000410000000031715142377631020065 0ustar www-datawww-dataversion: 2 updates: - package-ecosystem: "bundler" directory: "/" schedule: interval: "daily" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" fog-google-1.29.3/.github/scripts/0000755000004100000410000000000015142377631016723 5ustar www-datawww-datafog-google-1.29.3/.github/scripts/setup_creds.sh0000755000004100000410000000050515142377631021602 0ustar www-datawww-data#!/bin/bash GOOGLE_PROJECT=$(curl "http://metadata.google.internal/computeMetadata/v1/project/project-id" -H "Metadata-Flavor: Google") # fog needs the google project to be specified even if it uses application-default creds cat >~/.fog <- ./.github/scripts/setup_creds.sh && bundle exec rake test:compute-core_networking fog-google-1.29.3/.github/workflows/integration-sql.yml0000644000004100000410000000341515142377631023137 0ustar www-datawww-data# SQL tests are carried own in its' own job as they're extremely heavy so there # is no need to run them if SQL code or deps haven't changed and you cannot # trigger jobs based on file changes in the same workflow. # See: https://github.com/actions/runner/issues/456 name: integration-tests-sql on: push: branches: [ master ] pull_request: branches: [ master ] types: [ assigned, opened, synchronize, reopened, labeled ] # Only run integration tests if relevant code or deps have changed paths: # Module-specific paths - 'lib/fog/google/sql.rb' - 'lib/fog/google/sql/**' - 'test/integration/sql/**' # Common deps & shared paths - 'fog-google.gemspec' - 'lib/fog/bin/google.rb' - 'lib/fog/google/shared.rb' - 'lib/fog/google.rb' # Trigger workflow on version upgrade - 'lib/fog/google/version.rb' # Trigger when workflow itself is updated - '.github/workflows/integration-sql.yml' # Setting hard concurrency limit for the project due to cleanup # TODO(fog-google#626): remove this once cleanup is fixed concurrency: group: ${{ github.workflow }} cancel-in-progress: false jobs: test: runs-on: fog-arc-runner strategy: matrix: ruby-version: [ '3.1', '3.2', '3.3', '3.4', '4.0' ] # Integration tests from the same task cannot run in parallel yet due to cleanup max-parallel: 1 steps: - uses: actions/checkout@v6 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run tests run: >- ./.github/scripts/setup_creds.sh && bundle exec rake test:sql fog-google-1.29.3/.github/workflows/integration-compute-core.yml0000644000004100000410000000354615142377631024747 0ustar www-datawww-data# SQL tests are carried own in its' own job as they're extremely heavy so there # is no need to run them if SQL code or deps haven't changed and you cannot # trigger jobs based on file changes in the same workflow. # See: https://github.com/actions/runner/issues/456 name: integration-tests-compute-core on: push: branches: [ master ] pull_request: branches: [ master ] types: [ assigned, opened, synchronize, reopened, labeled ] # Only run integration tests if relevant code or deps have changed paths: # Module-specific paths - 'lib/fog/compute/**' - 'test/integration/compute/core_compute/**' # Common deps & shared paths - 'fog-google.gemspec' - 'lib/fog/bin/google.rb' - 'lib/fog/google/shared.rb' - 'lib/fog/google.rb' # Trigger workflow on version upgrade - 'lib/fog/google/version.rb' # Trigger when workflow itself is updated - '.github/workflows/integration-compute-core.yml' # Setting hard concurrency limit for the project due to cleanup # TODO(fog-google#626): remove this once cleanup is fixed concurrency: group: ${{ github.workflow }} cancel-in-progress: false jobs: test-compute: runs-on: fog-arc-runner strategy: matrix: ruby-version: [ '3.1', '3.2', '3.3', '3.4', '4.0' ] # Integration tests from the same task cannot run in parallel yet due to cleanup # TODO(fog-google#626): remove this once cleanup is fixed max-parallel: 1 steps: - uses: actions/checkout@v6 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run tests run: >- ./.github/scripts/setup_creds.sh && bundle exec rake test:compute-core_compute fog-google-1.29.3/.github/workflows/integration-monitoring.yml0000644000004100000410000000346715142377631024534 0ustar www-datawww-data# SQL tests are carried own in its' own job as they're extremely heavy so there # is no need to run them if SQL code or deps haven't changed and you cannot # trigger jobs based on file changes in the same workflow. # See: https://github.com/actions/runner/issues/456 name: integration-tests-monitoring on: push: branches: [ master ] pull_request: branches: [ master ] types: [ assigned, opened, synchronize, reopened, labeled ] # Only run integration tests if relevant code or deps have changed paths: # Module-specific paths - 'lib/fog/google/monitoring.rb' - 'lib/fog/google/monitoring/**' - 'test/integration/monitoring/**' # Common deps & shared paths - 'fog-google.gemspec' - 'lib/fog/bin/google.rb' - 'lib/fog/google/shared.rb' - 'lib/fog/google.rb' # Trigger workflow on version upgrade - 'lib/fog/google/version.rb' # Trigger when workflow itself is updated - '.github/workflows/integration-monitoring.yml' # Setting hard concurrency limit for the project due to cleanup # TODO(fog-google#626): remove this once cleanup is fixed concurrency: group: ${{ github.workflow }} cancel-in-progress: false jobs: test: runs-on: fog-arc-runner strategy: matrix: ruby-version: [ '3.1', '3.2', '3.3', '3.4', '4.0' ] # Integration tests from the same task cannot run in parallel yet due to cleanup max-parallel: 1 steps: - uses: actions/checkout@v6 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run tests run: >- ./.github/scripts/setup_creds.sh && bundle exec rake test:monitoring fog-google-1.29.3/.github/workflows/integration-compute-loadbalancing.yml0000644000004100000410000000346315142377631026573 0ustar www-datawww-data# SQL tests are carried own in its' own job as they're extremely heavy so there # is no need to run them if SQL code or deps haven't changed and you cannot # trigger jobs based on file changes in the same workflow. # See: https://github.com/actions/runner/issues/456 name: integration-tests-compute-loadbalancing on: push: branches: [ master ] pull_request: branches: [ master ] types: [ assigned, opened, synchronize, reopened, labeled ] # Only run integration tests if relevant code or deps have changed paths: # Module-specific paths - 'lib/fog/compute/**' - 'test/integration/compute/loadbalancing/**' # Common deps & shared paths - 'fog-google.gemspec' - 'lib/fog/bin/google.rb' - 'lib/fog/google/shared.rb' - 'lib/fog/google.rb' # Trigger workflow on version upgrade - 'lib/fog/google/version.rb' # Trigger when workflow itself is updated - '.github/workflows/integration-compute-loadbalancing.yml' # Setting hard concurrency limit for the project due to cleanup # TODO(fog-google#626): remove this once cleanup is fixed concurrency: group: ${{ github.workflow }} cancel-in-progress: false jobs: test: runs-on: fog-arc-runner strategy: matrix: ruby-version: [ '3.1', '3.2', '3.3', '3.4', '4.0' ] # Integration tests from the same task cannot run in parallel yet due to cleanup max-parallel: 1 steps: - uses: actions/checkout@v6 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run tests run: >- ./.github/scripts/setup_creds.sh && bundle exec rake test:compute-loadbalancing fog-google-1.29.3/.github/workflows/unit.yml0000644000004100000410000000143715142377631021000 0ustar www-datawww-dataname: unit-tests on: push: branches: [ master ] pull_request: branches: [ master ] # Cancel in-progress jobs of the same ref or run_id concurrency: group: ${{ github.workflow }}-${{ github.ref || github.run_id }} cancel-in-progress: true jobs: test-unit: runs-on: ubuntu-latest strategy: matrix: ruby-version: [ '3.1', '3.2', '3.3', '3.4', '4.0', 'head', 'truffleruby-head'] steps: - uses: actions/checkout@v6 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Install dependencies run: bundle install - name: Run tests run: bundle exec rake fog-google-1.29.3/.github/workflows/integration-storage.yml0000644000004100000410000000352115142377631024002 0ustar www-datawww-data# SQL tests are carried own in its' own job as they're extremely heavy so there # is no need to run them if SQL code or deps haven't changed and you cannot # trigger jobs based on file changes in the same workflow. # See: https://github.com/actions/runner/issues/456 name: integration-tests-storage on: push: branches: [ master ] pull_request: branches: [ master ] types: [ assigned, opened, synchronize, reopened, labeled ] # Only run integration tests if relevant code or deps have changed paths: # Module-specific paths - 'lib/fog/google/storage.rb' - 'lib/fog/google/storage/**' - 'lib/fog/google/parsers/storage/**' - 'test/integration/storage/**' # Common deps & shared paths - 'fog-google.gemspec' - 'lib/fog/bin/google.rb' - 'lib/fog/google/shared.rb' - 'lib/fog/google.rb' # Trigger workflow on version upgrade - 'lib/fog/google/version.rb' # Trigger when workflow itself is updated - '.github/workflows/integration-storage.yml' # Setting hard concurrency limit for the project due to cleanup # TODO(fog-google#626): remove this once cleanup is fixed concurrency: group: ${{ github.workflow }} cancel-in-progress: false jobs: test: runs-on: fog-arc-runner strategy: matrix: ruby-version: [ '3.1', '3.2', '3.3', '3.4', '4.0' ] # Integration tests from the same task cannot run in parallel yet due to cleanup max-parallel: 1 steps: - uses: actions/checkout@v6 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run tests run: >- ./.github/scripts/setup_creds.sh && bundle exec rake test:storage fog-google-1.29.3/.github/workflows/integration-pubsub.yml0000644000004100000410000000343715142377631023644 0ustar www-datawww-data# SQL tests are carried own in its' own job as they're extremely heavy so there # is no need to run them if SQL code or deps haven't changed and you cannot # trigger jobs based on file changes in the same workflow. # See: https://github.com/actions/runner/issues/456 name: integration-tests-pubsub on: push: branches: [ master ] pull_request: branches: [ master ] types: [ assigned, opened, synchronize, reopened, labeled ] # Only run integration tests if relevant code or deps have changed paths: # Module-specific paths - 'lib/fog/google/pubsub.rb' - 'lib/fog/google/pubsub/**' - 'test/integration/pubsub/**' # Common deps & shared paths - 'fog-google.gemspec' - 'lib/fog/bin/google.rb' - 'lib/fog/google/shared.rb' - 'lib/fog/google.rb' # Trigger workflow on version upgrade - 'lib/fog/google/version.rb' # Trigger when workflow itself is updated - '.github/workflows/integration-pubsub.yml' # Setting hard concurrency limit for the project due to cleanup # TODO(fog-google#626): remove this once cleanup is fixed concurrency: group: ${{ github.workflow }} cancel-in-progress: false jobs: test: runs-on: fog-arc-runner strategy: matrix: ruby-version: [ '3.1', '3.2', '3.3', '3.4', '4.0' ] # Integration tests from the same task cannot run in parallel yet due to cleanup max-parallel: 1 steps: - uses: actions/checkout@v6 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run tests run: >- ./.github/scripts/setup_creds.sh && bundle exec rake test:pubsub fog-google-1.29.3/.github/workflows/integration-compute-instance_groups.yml0000644000004100000410000000347415142377631027222 0ustar www-datawww-data# SQL tests are carried own in its' own job as they're extremely heavy so there # is no need to run them if SQL code or deps haven't changed and you cannot # trigger jobs based on file changes in the same workflow. # See: https://github.com/actions/runner/issues/456 name: integration-tests-compute-instance_groups on: push: branches: [ master ] pull_request: branches: [ master ] types: [ assigned, opened, synchronize, reopened, labeled ] # Only run integration tests if relevant code or deps have changed paths: # Module-specific paths - 'lib/fog/compute/**' - 'test/integration/compute/instance_groups/**' # Common deps & shared paths - 'fog-google.gemspec' - 'lib/fog/bin/google.rb' - 'lib/fog/google/shared.rb' - 'lib/fog/google.rb' # Trigger workflow on version upgrade - 'lib/fog/google/version.rb' # Trigger when workflow itself is updated - '.github/workflows/integration-compute-instance_groups.yml' # Setting hard concurrency limit for the project due to cleanup # TODO(fog-google#626): remove this once cleanup is fixed concurrency: group: ${{ github.workflow }} cancel-in-progress: false jobs: test: runs-on: fog-arc-runner strategy: matrix: ruby-version: [ '3.1', '3.2', '3.3', '3.4', '4.0' ] # Integration tests from the same task cannot run in parallel yet due to cleanup max-parallel: 1 steps: - uses: actions/checkout@v6 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run tests run: >- ./.github/scripts/setup_creds.sh && bundle exec rake test:compute-instance_groups fog-google-1.29.3/lib/0000755000004100000410000000000015142377631014442 5ustar www-datawww-datafog-google-1.29.3/lib/fog/0000755000004100000410000000000015142377631015215 5ustar www-datawww-datafog-google-1.29.3/lib/fog/bin/0000755000004100000410000000000015142377631015765 5ustar www-datawww-datafog-google-1.29.3/lib/fog/bin/google.rb0000644000004100000410000000505315142377631017571 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::Google::Compute when :dns Fog::Google::DNS when :monitoring Fog::Google::Monitoring when :storage Fog::Google::Storage when :storage_json Fog::Google::Storage 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| case key when :compute hash[key] = Fog::Compute.new(:provider => "Google") when :dns hash[key] = Fog::DNS.new(:provider => "Google") when :monitoring hash[key] = Fog::Google::Monitoring.new when :sql hash[key] = Fog::Google::SQL.new when :pubsub hash[key] = Fog::Google::Pubsub.new when :storage hash[key] = Fog::Storage.new(:provider => "Google") else hash[key] = 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 StandardError => 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__ + 1 def self.#{collection} self[:#{service}].#{collection} end EOS end end end availability end end end fog-google-1.29.3/lib/fog/google/0000755000004100000410000000000015142377631016471 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/sql.rb0000644000004100000410000000452215142377631017620 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.29.3/lib/fog/google/pubsub.rb0000644000004100000410000000346015142377631020321 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.29.3/lib/fog/google/storage.rb0000644000004100000410000000166215142377631020467 0ustar www-datawww-datamodule Fog module Google class Storage < Fog::Service GOOGLE_STORAGE_HOST = "storage.googleapis.com".freeze # Shared utilities for both JSON and XML storage implementations module Utils def self.storage_host_for_universe(universe_domain) domain = universe_domain.to_s.strip if !domain.empty? && domain != "googleapis.com" "storage.#{domain}" else GOOGLE_STORAGE_HOST end end end def self.new(options = {}) begin fog_creds = Fog.credentials rescue StandardError 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::Google::StorageXML.new(options) else Fog::Google::StorageJSON.new(options) end end end end end fog-google-1.29.3/lib/fog/google/requests/0000755000004100000410000000000015142377631020344 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/requests/monitoring/0000755000004100000410000000000015142377631022531 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/requests/monitoring/list_monitored_resource_descriptors.rb0000644000004100000410000000166215142377631032446 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/monitoring/delete_metric_descriptor.rb0000644000004100000410000000067615142377631030132 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/monitoring/list_metric_descriptors.rb0000644000004100000410000000130215142377631030011 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.29.3/lib/fog/google/requests/monitoring/get_metric_descriptor.rb0000644000004100000410000000066515142377631027445 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/monitoring/create_metric_descriptor.rb0000644000004100000410000000515115142377631030124 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/monitoring/create_timeseries.rb0000644000004100000410000000164715142377631026562 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_project_time_series("projects/#{@project}", request) end end class Mock def create_timeseries(_timeseries: []) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/monitoring/get_monitored_resource_descriptor.rb0000644000004100000410000000073215142377631032064 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.29.3/lib/fog/google/requests/monitoring/list_timeseries.rb0000644000004100000410000000344615142377631026271 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 = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/0000755000004100000410000000000015142377631021143 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/requests/sql/restore_instance_backup.rb0000644000004100000410000000164215142377631026367 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/delete_instance.rb0000644000004100000410000000077215142377631024624 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/insert_user.rb0000644000004100000410000000112315142377631024027 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/export_instance.rb0000644000004100000410000000323315142377631024676 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: {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/import_instance.rb0000644000004100000410000000261015142377631024665 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 = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/update_user.rb0000644000004100000410000000120715142377631024010 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/get_operation.rb0000644000004100000410000000103715142377631024330 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/get_ssl_cert.rb0000644000004100000410000000112115142377631024140 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/update_instance.rb0000644000004100000410000000156715142377631024647 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 = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/delete_backup_run.rb0000644000004100000410000000106115142377631025141 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/restart_instance.rb0000644000004100000410000000077715142377631025053 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/delete_user.rb0000644000004100000410000000105115142377631023765 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: host, name: name) end end class Mock def delete_user(_instance_id, _host, _name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/get_instance.rb0000644000004100000410000000103015142377631024125 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/list_tiers.rb0000644000004100000410000000073415142377631023655 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 # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/insert_backup_run.rb0000644000004100000410000000132315142377631025204 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/delete_ssl_cert.rb0000644000004100000410000000115715142377631024634 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/get_backup_run.rb0000644000004100000410000000112015142377631024452 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/list_users.rb0000644000004100000410000000077615142377631023676 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/list_backup_runs.rb0000644000004100000410000000143515142377631025042 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/list_flags.rb0000644000004100000410000000103215142377631023613 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 # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/list_ssl_certs.rb0000644000004100000410000000102215142377631024517 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/insert_instance.rb0000644000004100000410000000143315142377631024661 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 = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/list_instances.rb0000644000004100000410000000135015142377631024511 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: {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/clone_instance.rb0000644000004100000410000000251215142377631024454 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/list_operations.rb0000644000004100000410000000146615142377631024715 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: {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/reset_instance_ssl_config.rb0000644000004100000410000000143215142377631026704 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/sql/insert_ssl_cert.rb0000644000004100000410000000137515142377631024700 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/requests/pubsub/0000755000004100000410000000000015142377631021644 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/requests/pubsub/get_topic.rb0000644000004100000410000000077215142377631024154 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.29.3/lib/fog/google/requests/pubsub/pull_subscription.rb0000644000004100000410000000314615142377631025755 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 = {}) defaults = { :return_immediately => true, :max_messages => 10 } options = defaults.merge(options) 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.29.3/lib/fog/google/requests/pubsub/list_topics.rb0000644000004100000410000000144615142377631024532 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.29.3/lib/fog/google/requests/pubsub/list_subscriptions.rb0000644000004100000410000000151115142377631026131 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.29.3/lib/fog/google/requests/pubsub/create_subscription.rb0000644000004100000410000000301415142377631026236 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.29.3/lib/fog/google/requests/pubsub/get_subscription.rb0000644000004100000410000000110315142377631025547 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.29.3/lib/fog/google/requests/pubsub/create_topic.rb0000644000004100000410000000117215142377631024633 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.29.3/lib/fog/google/requests/pubsub/delete_subscription.rb0000644000004100000410000000110715142377631026236 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.29.3/lib/fog/google/requests/pubsub/acknowledge_subscription.rb0000644000004100000410000000160415142377631027261 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.29.3/lib/fog/google/requests/pubsub/publish_topic.rb0000644000004100000410000000154615142377631025043 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.29.3/lib/fog/google/requests/pubsub/delete_topic.rb0000644000004100000410000000100115142377631024621 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.29.3/lib/fog/google/monitoring/0000755000004100000410000000000015142377631020656 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/monitoring/real.rb0000644000004100000410000000110415142377631022122 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.29.3/lib/fog/google/monitoring/mock.rb0000644000004100000410000000135215142377631022135 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.29.3/lib/fog/google/parsers/0000755000004100000410000000000015142377631020150 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/parsers/storage.rb0000644000004100000410000000122515142377631022141 0ustar www-datawww-datamodule Fog module Google module Parsers module Storage autoload :AccessControlList, 'fog/google/parsers/storage/access_control_list' autoload :CopyObject, 'fog/google/parsers/storage/copy_object' autoload :GetBucket, 'fog/google/parsers/storage/get_bucket' autoload :GetBucketLogging, 'fog/google/parsers/storage/get_bucket_logging' autoload :GetBucketObjectVersions, 'fog/google/parsers/storage/get_bucket_object_versions' autoload :GetRequestPayment, 'fog/google/parsers/storage/get_request_payment' autoload :GetService, 'fog/google/parsers/storage/get_service' end end end end fog-google-1.29.3/lib/fog/google/parsers/storage/0000755000004100000410000000000015142377631021614 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/parsers/storage/get_bucket_object_versions.rb0000644000004100000410000000517115142377631027537 0ustar www-datawww-datamodule Fog module Google module Parsers module Storage 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.29.3/lib/fog/google/parsers/storage/copy_object.rb0000644000004100000410000000061115142377631024437 0ustar www-datawww-datamodule Fog module Google module Parsers module Storage 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.29.3/lib/fog/google/parsers/storage/get_bucket_versioning.rb0000644000004100000410000000066015142377631026522 0ustar www-datawww-datamodule Fog module Google module Parsers module Storage 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.29.3/lib/fog/google/parsers/storage/get_service.rb0000644000004100000410000000126115142377631024440 0ustar www-datawww-datamodule Fog module Google module Parsers module Storage 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.29.3/lib/fog/google/parsers/storage/get_bucket.rb0000644000004100000410000000324615142377631024262 0ustar www-datawww-datamodule Fog module Google module Parsers module Storage 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.29.3/lib/fog/google/parsers/storage/access_control_list.rb0000644000004100000410000000221415142377631026174 0ustar www-datawww-datamodule Fog module Google module Parsers module Storage 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.29.3/lib/fog/google/parsers/storage/get_request_payment.rb0000644000004100000410000000046315142377631026230 0ustar www-datawww-datamodule Fog module Google module Parsers module Storage 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.29.3/lib/fog/google/parsers/storage/get_bucket_logging.rb0000644000004100000410000000213415142377631025763 0ustar www-datawww-datamodule Fog module Google module Parsers module Storage 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.29.3/lib/fog/google/dns/0000755000004100000410000000000015142377631017255 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/dns/requests/0000755000004100000410000000000015142377631021130 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/dns/requests/get_change.rb0000644000004100000410000000103215142377631023535 0ustar www-datawww-datamodule Fog module Google class DNS ## # 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/dns/requests/create_change.rb0000644000004100000410000000133415142377631024226 0ustar www-datawww-datamodule Fog module Google class DNS ## # 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 = []) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/dns/requests/get_managed_zone.rb0000644000004100000410000000101115142377631024734 0ustar www-datawww-datamodule Fog module Google class DNS ## # 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/dns/requests/delete_managed_zone.rb0000644000004100000410000000101015142377631025416 0ustar www-datawww-datamodule Fog module Google class DNS ## # 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/dns/requests/list_managed_zones.rb0000644000004100000410000000135415142377631025325 0ustar www-datawww-datamodule Fog module Google class DNS ## # 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 = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/dns/requests/list_changes.rb0000644000004100000410000000140715142377631024122 0ustar www-datawww-datamodule Fog module Google class DNS ## # 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 = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/dns/requests/list_resource_record_sets.rb0000644000004100000410000000153215142377631026734 0ustar www-datawww-datamodule Fog module Google class DNS ## # 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 = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/dns/requests/get_project.rb0000644000004100000410000000112115142377631023755 0ustar www-datawww-datamodule Fog module Google class DNS ## # 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/dns/requests/create_managed_zone.rb0000644000004100000410000000133715142377631025433 0ustar www-datawww-datarequire "date" module Fog module Google class DNS ## # 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/dns/real.rb0000644000004100000410000000100415142377631020520 0ustar www-datawww-datamodule Fog module Google class DNS 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.29.3/lib/fog/google/dns/mock.rb0000644000004100000410000000130215142377631020527 0ustar www-datawww-datamodule Fog module Google class DNS 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.29.3/lib/fog/google/dns/models/0000755000004100000410000000000015142377631020540 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/dns/models/zones.rb0000644000004100000410000000161315142377631022224 0ustar www-datawww-datamodule Fog module Google class DNS class Zones < Fog::Collection model Fog::Google::DNS::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::Google::DNS::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.29.3/lib/fog/google/dns/models/projects.rb0000644000004100000410000000111415142377631022713 0ustar www-datawww-datamodule Fog module Google class DNS class Projects < Fog::Collection model Fog::Google::DNS::Project ## # Fetches the representation of an existing Project # # @param [String] identity Project identity # @return [Fog::Google::DNS::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.29.3/lib/fog/google/dns/models/zone.rb0000644000004100000410000000372315142377631022045 0ustar www-datawww-datamodule Fog module Google class DNS ## # 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::Google::DNS::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::Google::DNS::Records.new( :service => service, :zone => self ) end end ## # Creates a new Managed Zone # # @return [Fog::Google::DNS::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.29.3/lib/fog/google/dns/models/changes.rb0000644000004100000410000000242015142377631022473 0ustar www-datawww-datamodule Fog module Google class DNS class Changes < Fog::Collection model Fog::Google::DNS::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::Google::DNS::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::Google::DNS::Change] Change resource def new(attributes = {}) requires :zone super({ :zone => zone }.merge!(attributes)) end end end end end fog-google-1.29.3/lib/fog/google/dns/models/project.rb0000644000004100000410000000477715142377631022552 0ustar www-datawww-datamodule Fog module Google class DNS ## # 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.29.3/lib/fog/google/dns/models/change.rb0000644000004100000410000000164115142377631022314 0ustar www-datawww-datamodule Fog module Google class DNS ## # 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.29.3/lib/fog/google/dns/models/records.rb0000644000004100000410000000307215142377631022530 0ustar www-datawww-datamodule Fog module Google class DNS class Records < Fog::Collection model Fog::Google::DNS::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::Google::DNS::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::Google::DNS::Record] Resource Record Set resource def new(attributes = {}) requires :zone super({ :zone => zone }.merge!(attributes)) end end end end end fog-google-1.29.3/lib/fog/google/dns/models/record.rb0000644000004100000410000000644715142377631022356 0ustar www-datawww-datamodule Fog module Google class DNS ## # 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::Google::DNS::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::Google::DNS::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::Google::DNS::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::Google::DNS::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::Google::DNS::Record] Resource Record Sets resource def save requires :name, :type, :ttl, :rrdatas data = service.create_change(zone.id, [resource_record_set_format], []) change = Fog::Google::DNS::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::Google::DNS::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::Google::DNS::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.29.3/lib/fog/google/mock.rb0000644000004100000410000000032115142377631017743 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.29.3/lib/fog/google/monitoring.rb0000644000004100000410000000317615142377631021212 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.29.3/lib/fog/google/dns.rb0000644000004100000410000000266415142377631017612 0ustar www-datawww-datamodule Fog module Google class DNS < Fog::Service autoload :Mock, "fog/google/dns/mock" autoload :Real, "fog/google/dns/real" 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/google/dns/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/google/dns/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.29.3/lib/fog/google/models/0000755000004100000410000000000015142377631017754 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/models/monitoring/0000755000004100000410000000000015142377631022141 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/models/monitoring/timeseries.rb0000644000004100000410000000104615142377631024640 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.29.3/lib/fog/google/models/monitoring/metric_descriptor.rb0000644000004100000410000000117615142377631026214 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.29.3/lib/fog/google/models/monitoring/timeseries_collection.rb0000644000004100000410000000462415142377631027060 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.29.3/lib/fog/google/models/monitoring/metric_descriptors.rb0000644000004100000410000000310615142377631026372 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.29.3/lib/fog/google/models/monitoring/monitored_resource_descriptor.rb0000644000004100000410000000104215142377631030630 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.29.3/lib/fog/google/models/monitoring/monitored_resource_descriptors.rb0000644000004100000410000000265015142377631031021 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.29.3/lib/fog/google/models/sql/0000755000004100000410000000000015142377631020553 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/models/sql/ssl_cert.rb0000644000004100000410000000575315142377631022730 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(async: false) 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) # data.operation.name is used here since InsertSslCert returns a # special object, not an operation, as usual. See documentation: # https://cloud.google.com/sql/docs/mysql/admin-api/rest/v1beta4/sslCerts/insert#response-body operation = Fog::Google::SQL::Operations.new(:service => service).get(data.operation.name) operation.wait_for { ready? } unless async 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.29.3/lib/fog/google/models/sql/operations.rb0000644000004100000410000000315315142377631023265 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.29.3/lib/fog/google/models/sql/ssl_certs.rb0000644000004100000410000000322115142377631023077 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.29.3/lib/fog/google/models/sql/user.rb0000644000004100000410000000305115142377631022055 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) # TODO(2.0): make :host a required parameter # See: https://github.com/fog/fog-google/issues/462 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.29.3/lib/fog/google/models/sql/instance.rb0000644000004100000410000003152015142377631022705 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.29.3/lib/fog/google/models/sql/tiers.rb0000644000004100000410000000067415142377631022235 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.29.3/lib/fog/google/models/sql/operation.rb0000644000004100000410000000425415142377631023105 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.29.3/lib/fog/google/models/sql/flag.rb0000644000004100000410000000120415142377631022006 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.29.3/lib/fog/google/models/sql/backup_runs.rb0000644000004100000410000000222215142377631023412 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.29.3/lib/fog/google/models/sql/instances.rb0000644000004100000410000000217415142377631023073 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.29.3/lib/fog/google/models/sql/users.rb0000644000004100000410000000072115142377631022241 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.29.3/lib/fog/google/models/sql/backup_run.rb0000644000004100000410000000174515142377631023240 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.29.3/lib/fog/google/models/sql/tier.rb0000644000004100000410000000066715142377631022054 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.29.3/lib/fog/google/models/sql/flags.rb0000644000004100000410000000067415142377631022203 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.29.3/lib/fog/google/models/pubsub/0000755000004100000410000000000015142377631021254 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/models/pubsub/received_message.rb0000644000004100000410000000231715142377631025076 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.29.3/lib/fog/google/models/pubsub/topic.rb0000644000004100000410000000406215142377631022721 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.29.3/lib/fog/google/models/pubsub/subscription.rb0000644000004100000410000000704215142377631024330 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.29.3/lib/fog/google/models/pubsub/subscriptions.rb0000644000004100000410000000174615142377631024520 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.29.3/lib/fog/google/models/pubsub/topics.rb0000644000004100000410000000155215142377631023105 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.29.3/lib/fog/google/compute/0000755000004100000410000000000015142377631020145 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/compute/requests/0000755000004100000410000000000015142377631022020 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/compute/requests/list_disks.rb0000644000004100000410000000141415142377631024515 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_disks(_zone_name, _opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_server.rb0000644000004100000410000001111015142377631025231 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_server(_instance_name, _zone, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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::Google::Compute::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-11" # } # } # ] # ) # # @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[:shielded_instance_config] data[:shielded_instance_config] = ::Google::Apis::ComputeV1::ShieldedInstanceConfig.new(**options[:shielded_instance_config]) end if data[:display_device] data[:display_device] = ::Google::Apis::ComputeV1::DisplayDevice.new(**options[:display_device]) 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.29.3/lib/fog/google/compute/requests/remove_target_pool_health_checks.rb0000644000004100000410000000150115142377631031103 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def remove_target_pool_health_checks(_target_pool, _region, _health_checks) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/add_backend_service_backends.rb0000644000004100000410000000072315142377631030120 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def add_backend_service_backends(_backend_service, _new_backends) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/detach_disk.rb0000644000004100000410000000067615142377631024620 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def detach_disk(_instance, _zone, _device_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_subnetworks.rb0000644000004100000410000000300215142377631025761 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_subnetworks(_region_name, _filter: nil, _max_results: nil, _order_by: nil, _page_token: nil) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_aggregated_target_instances.rb0000644000004100000410000000122615142377631031110 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_aggregated_target_instances(_options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_target_https_proxy.rb0000644000004100000410000000147415142377631027710 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_target_https_proxy(_proxy_name, _description: nil, _url_map: nil, _ssl_certificates: nil) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_region_operation.rb0000644000004100000410000000113115142377631026543 0ustar www-datawww-datamodule Fog module Google class Compute 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.29.3/lib/fog/google/compute/requests/get_target_pool_health.rb0000644000004100000410000000111315142377631027044 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_target_pool_health(_target_pool, _region, _instance) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_regions.rb0000644000004100000410000000105215142377631025044 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_regions # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_subnetwork.rb0000644000004100000410000000163615142377631026100 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_subnetwork(_subnetwork_name, _region_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/invalidate_url_map_cache.rb0000644000004100000410000000110515142377631027324 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def invalidate_url_map_cache(_url_map_name, _path, _host = nil) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_http_health_check.rb0000644000004100000410000000061315142377631027330 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_http_health_check(_check_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_disk.rb0000644000004100000410000000123115142377631024133 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_disk(_disk_name, _zone_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_snapshot.rb0000644000004100000410000000071015142377631025041 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_snapshot(_snap_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_firewall.rb0000644000004100000410000000057115142377631025477 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_firewall(_firewall_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def delete_firewall(firewall_name) @compute.delete_firewall(@project, firewall_name) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/abandon_instances.rb0000644000004100000410000000173615142377631026025 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def abandon_instances(_instance_group_manager, _instances) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_target_http_proxy.rb0000644000004100000410000000061315142377631027455 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_target_http_proxy(_proxy_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_aggregated_target_pools.rb0000644000004100000410000000120415142377631030251 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_aggregated_target_pools(_opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_aggregated_machine_types.rb0000644000004100000410000000116015142377631030400 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_aggregated_machine_types(_opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/set_server_tags.rb0000644000004100000410000000111415142377631025541 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_server_tags(_instance, _zone, _tags = []) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_global_addresses.rb0000644000004100000410000000152615142377631026701 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_global_addresses(_opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_http_health_check.rb0000644000004100000410000000060215142377631026643 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_http_health_check(_check_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/add_target_pool_instances.rb0000644000004100000410000000142515142377631027545 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def add_target_pool_instances(_target_pool, _region, _instances) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/set_common_instance_metadata.rb0000644000004100000410000000123615142377631030236 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_common_instance_metadata(_project, _current_fingerprint, _metadata = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_instance_group_managers.rb0000644000004100000410000000117015142377631030274 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_instance_group_managers(_zone, _opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_aggregated_subnetworks.rb0000644000004100000410000000230315142377631030136 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_aggregated_subnetworks(_options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_disk_types.rb0000644000004100000410000000113415142377631025555 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_disk_types(_zone, _options: {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/recreate_instances.rb0000644000004100000410000000174515142377631026215 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def recreate_instances(_instance_group_manager, _instances) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/set_target_http_proxy_url_map.rb0000644000004100000410000000113515142377631030525 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_target_http_proxy_url_map(_proxy_name, _url_map) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_ssl_certificate.rb0000644000004100000410000000133315142377631027074 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_ssl_certificate(_certificate_name, _certificate, _private_key, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_disk_type.rb0000644000004100000410000000057215142377631025203 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_disk_type(_disk, _zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_network.rb0000644000004100000410000000100415142377631025415 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_network(_network_name, _opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def insert_network(network_name, opts = {}) opts = opts.merge(:name => network_name) @compute.insert_network( @project, ::Google::Apis::ComputeV1::Network.new(**opts) ) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/get_image.rb0000644000004100000410000000066315142377631024273 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_image(_image_name, _project = @project) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_global_forwarding_rule.rb0000644000004100000410000000061015142377631030375 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_global_forwarding_rule(_rule) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/validate_url_map.rb0000644000004100000410000000110715142377631025654 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def validate_url_map(_url_map_name, _url_map: {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/set_global_forwarding_rule_target.rb0000644000004100000410000000103415142377631031275 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_global_forwarding_rule_target(_rule_name, _target) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_firewall.rb0000644000004100000410000000056015142377631025012 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_firewall(_firewall_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def get_firewall(firewall_name) @compute.get_firewall(@project, firewall_name) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/list_routes.rb0000644000004100000410000000134715142377631024726 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_routes(_options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_project.rb0000644000004100000410000000052415142377631024653 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_project(_identity) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def get_project(identity) @compute.get_project(identity) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/list_instance_templates.rb0000644000004100000410000000114415142377631027262 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_instance_templates # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_global_address.rb0000644000004100000410000000057715142377631026162 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_global_address(_address_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_snapshots.rb0000644000004100000410000000113315142377631025420 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_snapshots # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/patch_url_map.rb0000644000004100000410000000072515142377631025167 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def patch_url_map(_url_map_name, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_disk.rb0000644000004100000410000000130615142377631024621 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_disk(_disk_name, _zone_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_aggregated_servers.rb0000644000004100000410000000113215142377631027240 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_aggregated_servers(_opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_url_map.rb0000644000004100000410000000056315142377631025332 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_url_map(_url_map_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/set_server_disk_auto_delete.rb0000644000004100000410000000124315142377631030112 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_server_disk_auto_delete(_identity, _zone, _auto_delete, _device_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_target_pools.rb0000644000004100000410000000120015142377631026073 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_target_pools(_region, _opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_firewall.rb0000644000004100000410000000401615142377631025537 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_firewall(_firewall_name, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_snapshot.rb0000644000004100000410000000057115142377631025531 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_snapshot(_snapshot_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def delete_snapshot(snapshot_name) @compute.delete_snapshot(@project, snapshot_name) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/delete_server.rb0000644000004100000410000000060215142377631025173 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_server(_server, _zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_target_instance.rb0000644000004100000410000000122615142377631027104 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_target_instance(_target_name, _zone, _target_instance = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/update_url_map.rb0000644000004100000410000000131315142377631025344 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def update_url_map(_url_map_name, _url_map = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_target_instances.rb0000644000004100000410000000130615142377631026735 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_target_instances(_zone, _opts: {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_network.rb0000644000004100000410000000055215142377631024677 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_network(_network_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def get_network(network_name) @compute.get_network(@project, network_name) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/insert_route.rb0000644000004100000410000000210415142377631025064 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_route(_route_name, _network, _dest_range, _priority, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_backend_service.rb0000644000004100000410000000116215142377631027040 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_backend_service(_backend_service_name, _opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_zone_operations.rb0000644000004100000410000000142615142377631026621 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_zone_operations(_zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_zone_operation.rb0000644000004100000410000000110115142377631026713 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_zone_operation(_zone, _operation) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_image_from_family.rb0000644000004100000410000000141315142377631026651 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_image_from_family(_family, _project = @project) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_target_http_proxy.rb0000644000004100000410000000121315142377631027514 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_target_http_proxy(_proxy_name, _description: nil, _url_map: nil) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_instance_group_manager.rb0000644000004100000410000000063315142377631030403 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_instance_group_manager(_name, _zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_forwarding_rules.rb0000644000004100000410000000121315142377631026751 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_forwarding_rules(_region, _opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_route.rb0000644000004100000410000000105615142377631025027 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_route(_identity) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_global_operations.rb0000644000004100000410000000130115142377631027076 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_global_operations # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/add_server_access_config.rb0000644000004100000410000000156415142377631027337 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def add_server_access_config(_identity, _zone, _nic, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_instance_group_manager.rb0000644000004100000410000000212215142377631030440 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_instance_group_manager(_name, _zone, _instance_template, _base_instance_name, _target_size, _target_pools, _named_ports, _description) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/set_instance_template.rb0000644000004100000410000000204715142377631026722 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_instance_template(_instance_group_manager, _instance_template) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_servers.rb0000644000004100000410000000113415142377631025070 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_servers(_zone, _opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_ssl_certificates.rb0000644000004100000410000000115015142377631026723 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_ssl_certificates # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_target_instance.rb0000644000004100000410000000072215142377631026357 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_target_instance(_target_name, _zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_region_operations.rb0000644000004100000410000000160415142377631027127 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_region_operations(_region) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_images.rb0000644000004100000410000000115015142377631024642 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_images(_project = @project, _opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_instance_template.rb0000644000004100000410000000242315142377631027431 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_instance_template(_name, _properties, _description) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_global_forwarding_rule.rb0000644000004100000410000000130515142377631030441 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_global_forwarding_rule(_rule_name, _opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_global_forwarding_rules.rb0000644000004100000410000000115415142377631030275 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_global_forwarding_rules(_opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_aggregated_instance_group_managers.rb0000644000004100000410000000126015142377631032446 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_aggregated_instance_group_managers(_opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_address.rb0000644000004100000410000000174115142377631025361 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_address(_address_name, _region_name, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_forwarding_rule.rb0000644000004100000410000000072215142377631027061 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_forwarding_rule(_rule, _region) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_aggregated_disk_types.rb0000644000004100000410000000114715142377631027733 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_aggregated_disk_types(_options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/expand_subnetwork_ip_cidr_range.rb0000644000004100000410000000236315142377631030760 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def expand_subnetwork_ip_cidr_range(_subnetwork, _region, _ip_cidr_range) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_aggregated_addresses.rb0000644000004100000410000000126415142377631027532 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_aggregated_addresses(_options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_target_https_proxy.rb0000644000004100000410000000060515142377631027156 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_target_https_proxy(_proxy_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_route.rb0000644000004100000410000000075615142377631024352 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_route(_identity) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_url_maps.rb0000644000004100000410000000120115142377631025214 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_url_maps(_filter: nil, _max_results: nil, _order_by: nil, _page_token: nil) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/remove_instance_group_instances.rb0000644000004100000410000000207615142377631031016 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def add_instance_group_instances(_group, _zone, _instances) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_instance_groups.rb0000644000004100000410000000055515142377631026610 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_instance_groups(_zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def list_instance_groups(zone) @compute.list_instance_groups(@project, zone) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/stop_server.rb0000644000004100000410000000070115142377631024716 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def stop_server(_identity, _zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def stop_server(identity, zone, discard_local_ssd=false) @compute.stop_instance(@project, zone.split("/")[-1], identity, discard_local_ssd: discard_local_ssd) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/attach_disk.rb0000644000004100000410000000076015142377631024626 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def attach_disk(_instance, _zone, _disk = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/start_server.rb0000644000004100000410000000060515142377631025071 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def start_server(_identity, _zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_zone_operation.rb0000644000004100000410000000146215142377631026242 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_zone_operation(_zone_name, _operation) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_subnetwork.rb0000644000004100000410000000471515142377631026143 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_subnetwork(_subnetwork_name, _region_name, _network, _ip_range, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/set_forwarding_rule_target.rb0000644000004100000410000000115315142377631027757 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_forwarding_rule_target(_rule_name, _region, _target_opts) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_backend_service.rb0000644000004100000410000000071015142377631026311 0ustar www-datawww-datamodule Fog module Google class Compute 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.29.3/lib/fog/google/compute/requests/list_networks.rb0000644000004100000410000000120415142377631025251 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_networks(_opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_aggregated_forwarding_rules.rb0000644000004100000410000000117415142377631031131 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_aggregated_forwarding_rules(_opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_aggregated_instance_groups.rb0000644000004100000410000000064315142377631030760 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_aggregated_instance_groups(_options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/set_target_pool_backup.rb0000644000004100000410000000145115142377631027065 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_target_pool_backup(_target_pool, _region, _backup_target, _failover_ratio: nil) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_target_http_proxies.rb0000644000004100000410000000130415142377631027474 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_target_http_proxies(_filter: nil, _max_results: nil, _order_by: nil, _page_token: nil) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_global_operation.rb0000644000004100000410000000075015142377631027211 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_global_operation(_operation) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_global_address.rb0000644000004100000410000000125415142377631026700 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_global_address(_address_name, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_target_instance.rb0000644000004100000410000000073315142377631027044 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_target_instance(_target_name, _zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/reset_windows_password.rb0000644000004100000410000001302215142377631027161 0ustar www-datawww-data# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Changes: # March 2020: Modified example found here: # https://github.com/GoogleCloudPlatform/compute-image-windows/blob/master/examples/windows_auth_python_sample.py # to enable fog-google to change windows passwords. require "openssl" require "base64" require "json" module Fog module Google class Compute class Mock def reset_windows_password(_server:, _user:) Fog::Mock.not_implemented end end class Real ## # Resets Windows passwords for users on Google's Windows based images. Code based on Google provided example. # # @param instance [String] the name of the instance # @param zone [String] the name of the zone of the instance # @param user [String] the user whose password should be reset # # @return [String] new password # # @see https://cloud.google.com/compute/docs/instances/windows/automate-pw-generation def reset_windows_password(server:, user:) # Pull the e-mail address of user authenticated to API email = @compute.request_options.authorization.issuer # Create a new key key = OpenSSL::PKey::RSA.new(2048) modulus, exponent = get_modulus_exponent_in_base64(key) # Get Old Metadata old_metadata = server.metadata # Create JSON Object with needed information metadata_entry = get_json_string(user, modulus, exponent, email) # Create new metadata object new_metadata = update_windows_keys(old_metadata, metadata_entry) # Set metadata on instance server.set_metadata(new_metadata, false) # Get encrypted password from Serial Port 4 Output # If machine is booting for the first time, there appears to be a # delay before the password appears on the serial port. sleep(1) until server.ready? serial_port_output = server.serial_port_output(:port => 4) loop_cnt = 0 while serial_port_output.empty? if loop_cnt > 12 Fog::Logger.warning("Encrypted password never found on Serial Output Port 4") raise "Could not reset password." end sleep(5) serial_port_output = server.serial_port_output(:port => 4) loop_cnt += 1 end # Parse and decrypt password enc_password = get_encrypted_password_from_serial_port(serial_port_output, modulus) password = decrypt_password(enc_password, key) return password end def get_modulus_exponent_in_base64(key) mod = [key.n.to_s(16)].pack("H*").strip exp = [key.e.to_s(16)].pack("H*").strip modulus = Base64.strict_encode64(mod).strip exponent = Base64.strict_encode64(exp).strip return modulus, exponent end def get_expiration_time_string utc_now = Time.now.utc expire_time = utc_now + 5 * 60 return expire_time.strftime("%Y-%m-%dT%H:%M:%SZ") end def get_json_string(user, modulus, exponent, email) expire = get_expiration_time_string data = { 'userName': user, 'modulus': modulus, 'exponent': exponent, 'email': email, 'expireOn': expire } return ::JSON.dump(data) end def update_windows_keys(old_metadata, metadata_entry) if old_metadata[:items] new_metadata = Hash[old_metadata[:items].map { |item| [item[:key], item[:value]] }] else new_metadata = {} end new_metadata["windows-keys"] = metadata_entry return new_metadata end def get_encrypted_password_from_serial_port(serial_port_output, modulus) output = serial_port_output.split("\n") output.reverse_each do |line| begin if line.include?("modulus") && line.include?("encryptedPassword") entry = ::JSON.parse(line) if modulus == entry["modulus"] return entry["encryptedPassword"] end else next end rescue ::JSON::ParserError Fog::Logger.warning("Parsing encrypted password from serial output failed. Trying to parse next matching line.") next end end end def decrypt_password(enc_password, key) decoded_password = Base64.strict_decode64(enc_password) begin return key.private_decrypt(decoded_password, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING) rescue OpenSSL::PKey::RSAError Fog::Logger.warning("Error decrypting password received from Google. Maybe check output on Serial Port 4 and Metadata key: windows-keys?") end end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/list_target_https_proxies.rb0000644000004100000410000000114015142377631027655 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_target_https_proxies # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_global_address.rb0000644000004100000410000000061015142377631026631 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_global_address(_address_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_target_pool.rb0000644000004100000410000000073315142377631026211 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_target_pool(_target_pool, _region) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_target_https_proxy.rb0000644000004100000410000000061615142377631027643 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_target_https_proxy(_proxy_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_machine_type.rb0000644000004100000410000000071415142377631025653 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_machine_type(_machine_type, _zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_address.rb0000644000004100000410000000124215142377631024630 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_address(_address_name, _region_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_region_operation.rb0000644000004100000410000000121415142377631027230 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_region_operation(_region, _operation) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/reset_server.rb0000644000004100000410000000060515142377631025056 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def reset_server(_identity, _zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_instance_group.rb0000644000004100000410000000066415142377631026232 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_instance_group(_group_name, _zone, _project = @project) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_target_pool.rb0000644000004100000410000000072215142377631025524 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_target_pool(_target_pool, _region) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_machine_types.rb0000644000004100000410000000137715142377631026240 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_machine_types(_zone, _opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/deprecate_image.rb0000644000004100000410000000106515142377631025445 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def deprecate_image(_image_name, _deprecation_status = {}, _project = @project) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_global_forwarding_rule.rb0000644000004100000410000000057715142377631027726 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_global_forwarding_rule(_rule) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_backend_services.rb0000644000004100000410000000125115142377631026671 0ustar www-datawww-datamodule Fog module Google class Compute 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.29.3/lib/fog/google/compute/requests/get_ssl_certificate.rb0000644000004100000410000000061615142377631026352 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_ssl_certificate(_certificate_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_backend_service.rb0000644000004100000410000000066515142377631027005 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_backend_service(_backend_service_name, _zone_name = nil) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_instance_group_instances.rb0000644000004100000410000000101215142377631030461 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_instance_group_instances(_group, _zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_target_http_proxy.rb0000644000004100000410000000060215142377631026770 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_target_http_proxy(_proxy_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_global_operation.rb0000644000004100000410000000120015142377631026515 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_global_operation(_operation) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_server.rb0000644000004100000410000000057715142377631024523 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_server(_instance, _zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_address.rb0000644000004100000410000000126115142377631025314 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_address(_address_name, _region_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_http_health_checks.rb0000644000004100000410000000111415142377631027221 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_http_health_checks # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/add_target_pool_health_checks.rb0000644000004100000410000000153115142377631030341 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def add_target_pool_health_checks(_target_pool, _region, _health_checks) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/remove_target_pool_instance.rb0000644000004100000410000000143715142377631030132 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def remove_target_pool_instances(_target_pool, _region, _instances) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_zones.rb0000644000004100000410000000107415142377631024540 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_zones # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_forwarding_rule.rb0000644000004100000410000000142415142377631027123 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_forwarding_rule(_rule_name, _region, _opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_region.rb0000644000004100000410000000055215142377631024471 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_region(_identity) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def get_region(identity) @compute.get_region(@project, identity.split("/")[-1]) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/list_addresses.rb0000644000004100000410000000140315142377631025353 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_addresses(_region_name, _opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_firewalls.rb0000644000004100000410000000120015142377631025361 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_firewalls # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_http_health_check.rb0000644000004100000410000000105415142377631027372 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_http_health_check(_check_name, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_instance_group.rb0000644000004100000410000000211115142377631026744 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_instance_group(_group_name, _zone, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_backend_service_health.rb0000644000004100000410000000127315142377631027643 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_backend_service_health(_backend_service) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/set_target_https_proxy_ssl_certificates.rb0000644000004100000410000000115415142377631032600 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_target_https_proxy_ssl_certificates(_proxy_name, _certs) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_disk.rb0000644000004100000410000000406415142377631024667 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_disk(_disk_name, _zone, _image_name = nil, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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(2.0): change source_image to keyword argument in 2.0 and gracefully deprecate def insert_disk(disk_name, zone, source_image = nil, description: nil, type: nil, size_gb: nil, source_snapshot: nil, labels: 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_opts = { :name => disk_name, :description => description, :type => type, :size_gb => size_gb, :source_snapshot => source_snapshot, :source_image => source_image } disk_opts[:labels] = labels if labels disk = ::Google::Apis::ComputeV1::Disk.new(**disk_opts) @compute.insert_disk(@project, zone.split("/")[-1], disk) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/get_zone.rb0000644000004100000410000000053015142377631024155 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_zone(_zone_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def get_zone(zone_name) @compute.get_zone(@project, zone_name) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/get_instance_group_manager.rb0000644000004100000410000000062215142377631027716 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_instance_group_manager(_name, _zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/set_server_machine_type.rb0000644000004100000410000000126715142377631027261 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_server_machine_type(_instance, _zone, _machine_type) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def set_server_machine_type(instance, zone, machine_type) request = ::Google::Apis::ComputeV1::InstancesSetMachineTypeRequest.new zone = zone.split("/")[-1] machine_type = machine_type.split("/")[-1] request.machine_type = "zones/#{zone}/machineTypes/#{machine_type}" @compute.set_instance_machine_type(@project, zone, instance, request) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/insert_image.rb0000644000004100000410000000101515142377631025010 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_image(_image_name, _image = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/remove_target_pool_instances.rb0000644000004100000410000000143315142377631030311 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def remove_target_pool_instances(_target_pool, _region, _instances) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/create_disk_snapshot.rb0000644000004100000410000000111615142377631026540 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def create_disk_snapshot(_snapshot_name, _disk, _zone, _snapshot = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/patch_firewall.rb0000644000004100000410000000134215142377631025331 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def patch_firewall(_firewall_name, _firewall_opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_server_serial_port_output.rb0000644000004100000410000000257615142377631030547 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_server_serial_port_output(_identity, _zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_forwarding_rule.rb0000644000004100000410000000074315142377631026401 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_forwarding_rule(_rule, _region) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_url_map.rb0000644000004100000410000000223415142377631025371 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_url_map(_url_map_name, _url_map = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/set_server_scheduling.rb0000644000004100000410000000157615142377631026744 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_server_scheduling(_identity, _zone, _on_host_maintenance, _automatic_restart, _preemptible) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/list_aggregated_disks.rb0000644000004100000410000000200315142377631026662 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def list_aggregated_disks(_options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/update_firewall.rb0000644000004100000410000000275315142377631025523 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def update_firewall(_firewall_name, _firewall_opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/set_target_https_proxy_url_map.rb0000644000004100000410000000114015142377631030704 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_target_https_proxy_url_map(_proxy_name, _url_map) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/insert_target_pool.rb0000644000004100000410000000112415142377631026246 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def insert_target_pool(_target_pool_name, _region, _target_pool = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_subnetwork.rb0000644000004100000410000000172715142377631025416 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_subnetwork(_subnetwork_name, _region_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/set_snapshot_labels.rb0000644000004100000410000000111615142377631026400 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_snapshot_labels(_snap_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_network.rb0000644000004100000410000000056315142377631025364 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_network(_network_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def delete_network(network_name) @compute.delete_network(@project, network_name) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/get_url_map.rb0000644000004100000410000000055215142377631024645 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_url_map(_url_map_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_instance_template.rb0000644000004100000410000000057115142377631027371 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_instance_template(_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def delete_instance_template(name) @compute.delete_instance_template(@project, name) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/set_subnetwork_private_ip_google_access.rb0000644000004100000410000000322115142377631032520 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_subnetwork_private_ip_google_access(_subnetwork_name, _region_name, _private_ip_google_access) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_image.rb0000644000004100000410000000061715142377631024755 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_image(_image_name, _project = @project) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/get_instance_template.rb0000644000004100000410000000056015142377631026704 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def get_instance_template(_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real def get_instance_template(name) @compute.get_instance_template(@project, name) end end end end end fog-google-1.29.3/lib/fog/google/compute/requests/update_http_health_check.rb0000644000004100000410000000110115142377631027341 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def update_http_health_check(_check_name, _opts = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/add_instance_group_instances.rb0000644000004100000410000000207215142377631030245 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def add_instance_group_instances(_group_name, _zone, _instances) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_instance_group.rb0000644000004100000410000000062515142377631026712 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_instance_group(_group_name, _zone) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/set_server_metadata.rb0000644000004100000410000000255715142377631026377 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def set_server_metadata(_instance, _zone, _fingerprint, _metadata_items = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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: # {'foo' => 'bar', 'baz'=>'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.29.3/lib/fog/google/compute/requests/delete_ssl_certificate.rb0000644000004100000410000000062615142377631027036 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_ssl_certificate(_certificate_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/requests/delete_server_access_config.rb0000644000004100000410000000110015142377631030033 0ustar www-datawww-datamodule Fog module Google class Compute class Mock def delete_server_access_config(_identity, _zone, _nic, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/compute/real.rb0000644000004100000410000000141115142377631021412 0ustar www-datawww-datamodule Fog module Google class Compute class Real include Fog::Google::Shared attr_accessor :client attr_reader :compute, :extra_global_projects, :exclude_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] || [] @exclude_projects = options[:google_exclude_projects] || [] end end end end end fog-google-1.29.3/lib/fog/google/compute/mock.rb0000644000004100000410000015374215142377631021437 0ustar www-datawww-datamodule Fog module Google class Compute class Mock include Fog::Google::Shared attr_reader :extra_global_projects, :exclude_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, []) @exclude_projects = options.fetch(:google_exclude_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.29.3/lib/fog/google/compute/models/0000755000004100000410000000000015142377631021430 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/compute/models/zones.rb0000644000004100000410000000151415142377631023114 0ustar www-datawww-datamodule Fog module Google class Compute class Zones < Fog::Collection model Fog::Google::Compute::Zone def all(opts = {}) items = [] next_page_token = nil loop do data = service.list_zones 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? opts[:page_token] = next_page_token end load(items) 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.29.3/lib/fog/google/compute/models/instance_group.rb0000644000004100000410000000437115142377631025002 0ustar www-datawww-datamodule Fog module Google class Compute 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.29.3/lib/fog/google/compute/models/target_http_proxies.rb0000644000004100000410000000164615142377631026062 0ustar www-datawww-datamodule Fog module Google class Compute class TargetHttpProxies < Fog::Collection model Fog::Google::Compute::TargetHttpProxy def all(opts = {}) items = [] next_page_token = nil loop do data = service.list_target_http_proxies(*opts) 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? opts[:page_token] = next_page_token end load(items) 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.29.3/lib/fog/google/compute/models/global_forwarding_rules.rb0000644000004100000410000000163715142377631026660 0ustar www-datawww-datamodule Fog module Google class Compute class GlobalForwardingRules < Fog::Collection model Fog::Google::Compute::GlobalForwardingRule def all(opts = {}) items = [] next_page_token = nil loop do data = service.list_global_forwarding_rules(**opts) 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? opts[:page_token] = next_page_token end load(items) 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.29.3/lib/fog/google/compute/models/url_map.rb0000644000004100000410000000764415142377631023427 0ustar www-datawww-datamodule Fog module Google class Compute 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::Google::Compute::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::Google::Compute::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::Google::Compute::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::Google::Compute::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::Google::Compute::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.29.3/lib/fog/google/compute/models/firewalls.rb0000644000004100000410000000156315142377631023752 0ustar www-datawww-datamodule Fog module Google class Compute class Firewalls < Fog::Collection model Fog::Google::Compute::Firewall def all(opts = {}) items = [] next_page_token = nil loop do data = service.list_firewalls(**opts) 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? opts[:page_token] = next_page_token end load(items) 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.29.3/lib/fog/google/compute/models/backend_services.rb0000644000004100000410000000113215142377631025244 0ustar www-datawww-datamodule Fog module Google class Compute class BackendServices < Fog::Collection model Fog::Google::Compute::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.29.3/lib/fog/google/compute/models/snapshots.rb0000644000004100000410000000152015142377631023775 0ustar www-datawww-datamodule Fog module Google class Compute class Snapshots < Fog::Collection model Fog::Google::Compute::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.29.3/lib/fog/google/compute/models/backend_service.rb0000644000004100000410000000465115142377631025072 0ustar www-datawww-datamodule Fog module Google class Compute 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::Google::Compute::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::Google::Compute::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.29.3/lib/fog/google/compute/models/http_health_check.rb0000644000004100000410000000604315142377631025421 0ustar www-datawww-datamodule Fog module Google class Compute 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::Google::Compute::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::Google::Compute::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::Google::Compute::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.29.3/lib/fog/google/compute/models/operations.rb0000644000004100000410000000366615142377631024153 0ustar www-datawww-datamodule Fog module Google class Compute class Operations < Fog::Collection model Fog::Google::Compute::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 } items = [] next_page_token = nil loop do if zone data = service.list_zone_operations(zone, **opts) next_items = data.to_h[:items] || [] items.concat(next_items) next_page_token = data.next_page_token elsif region data = service.list_region_operations(region, **opts) next_items = data.to_h[:items] || [] items.concat(next_items) next_page_token = data.next_page_token else data = service.list_global_operations(**opts) next_items = data.to_h[:items] || [] items.concat(next_items) next_page_token = data.next_page_token end break if next_page_token.nil? || next_page_token.empty? opts[:page_token] = next_page_token end load(items) 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.29.3/lib/fog/google/compute/models/networks.rb0000644000004100000410000000155515142377631023637 0ustar www-datawww-datamodule Fog module Google class Compute class Networks < Fog::Collection model Fog::Google::Compute::Network def all(opts = {}) items = [] next_page_token = nil loop do data = service.list_networks(**opts) 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? opts[:page_token] = next_page_token end load(items) 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.29.3/lib/fog/google/compute/models/disk_type.rb0000644000004100000410000000127315142377631023753 0ustar www-datawww-datamodule Fog module Google class Compute 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.29.3/lib/fog/google/compute/models/machine_type.rb0000644000004100000410000000143415142377631024424 0ustar www-datawww-datamodule Fog module Google class Compute 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.29.3/lib/fog/google/compute/models/ssl_certificate.rb0000644000004100000410000000253415142377631025124 0ustar www-datawww-datamodule Fog module Google class Compute ## # 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::Google::Compute::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::Google::Compute::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async operation end end end end end fog-google-1.29.3/lib/fog/google/compute/models/subnetwork.rb0000644000004100000410000000552215142377631024164 0ustar www-datawww-datamodule Fog module Google class Compute ## # 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::Google::Compute::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::Google::Compute::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::Google::Compute::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::Google::Compute::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.29.3/lib/fog/google/compute/models/target_instance.rb0000644000004100000410000000360115142377631025127 0ustar www-datawww-datamodule Fog module Google class Compute 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::Google::Compute::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::Google::Compute::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.29.3/lib/fog/google/compute/models/server.rb0000644000004100000410000005110615142377631023266 0ustar www-datawww-datarequire "fog/compute/models/server" module Fog module Google class Compute 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-11" # } # } # ] # # @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 Enable the display device # { # :enable_display => true # } # @return [Hash] attribute :display_device, :aliases => "displayDevice" # @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::Google::Compute::Operation] def destroy(async = true) requires :name, :zone data = service.delete_server(name, zone_name) operation = Fog::Google::Compute::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] def attach_disk(disk, async = true, attached_disk_options = {}) requires :identity, :zone if disk.is_a? Disk disk_obj = disk.attached_disk_obj(**attached_disk_options) elsif disk.is_a? String disk_obj = service.disks.attached_disk_obj(disk, **attached_disk_options) end data = service.attach_disk(identity, zone_name, disk_obj) operation = Fog::Google::Compute::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::Google::Compute::Server] server object def detach_disk(device_name, async = true) requires :identity, :zone data = service.detach_disk(identity, zone, device_name) operation = Fog::Google::Compute::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::Google::Compute::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::Google::Compute::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async operation end def stop(async = true, discard_local_ssd=false) requires :identity, :zone data = service.stop_server(identity, zone_name, discard_local_ssd) operation = Fog::Google::Compute::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async operation end def serial_port_output(port: 1) requires :identity, :zone service.get_server_serial_port_output(identity, zone_name, :port => port).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::Google::Compute::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::Google::Compute::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::Google::Compute::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::Google::Compute::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async reload end def set_machine_type(new_machine_type, async = true) requires :identity, :zone raise Fog::Errors::Error.new("Instance must be stopped to change machine type") unless stopped? data = service.set_server_machine_type( identity, zone_name, new_machine_type ) operation = Fog::Google::Compute::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::Google::Compute::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::Google::Compute::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::Google::Compute::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}:#{ensure_key_comment(key, username)}" metadata_map["ssh-keys"] = ssh_keys metadata[:items] = metadata_to_item_list(metadata_map) metadata end def ensure_key_comment(key, default_comment = "fog-user") parts = key.strip.split parts << default_comment if parts.size < 3 parts.join(" ") end def reset_windows_password(user) service.reset_windows_password(:server => self, :user => user) 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.29.3/lib/fog/google/compute/models/image.rb0000644000004100000410000000530315142377631023040 0ustar www-datawww-datamodule Fog module Google class Compute 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::Google::Compute::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::Google::Compute::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.29.3/lib/fog/google/compute/models/projects.rb0000644000004100000410000000065415142377631023613 0ustar www-datawww-datamodule Fog module Google class Compute class Projects < Fog::Collection model Fog::Google::Compute::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.29.3/lib/fog/google/compute/models/machine_types.rb0000644000004100000410000000367215142377631024615 0ustar www-datawww-datamodule Fog module Google class Compute class MachineTypes < Fog::Collection model Fog::Google::Compute::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 } items = [] next_page_token = nil loop do if zone data = service.list_machine_types(zone, **opts) next_items = data.items || [] items.concat(next_items) next_page_token = data.next_page_token else data = service.list_aggregated_machine_types(**opts) data.items.each_value do |scoped_list| items.concat(scoped_list.machine_types) if scoped_list && scoped_list.machine_types end next_page_token = data.next_page_token end break if next_page_token.nil? || next_page_token.empty? opts[:page_token] = next_page_token end load(items.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.29.3/lib/fog/google/compute/models/disk_types.rb0000644000004100000410000000321315142377631024132 0ustar www-datawww-datamodule Fog module Google class Compute class DiskTypes < Fog::Collection model Fog::Google::Compute::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 } items = [] next_page_token = nil loop do if zone data = service.list_disk_types(zone, **opts) next_items = data.items || [] items.concat(next_items) next_page_token = data.next_page_token else data = service.list_aggregated_disk_types(**opts) data.items.each_value do |scoped_lst| items.concat(scoped_lst.disk_types) if scoped_lst && scoped_lst.disk_types end next_page_token = data.next_page_token end break if next_page_token.nil? || next_page_token.empty? opts[:page_token] = next_page_token end load(items.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.29.3/lib/fog/google/compute/models/snapshot.rb0000644000004100000410000000377415142377631023627 0ustar www-datawww-datamodule Fog module Google class Compute 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::Google::Compute::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.29.3/lib/fog/google/compute/models/zone.rb0000644000004100000410000000102715142377631022730 0ustar www-datawww-datamodule Fog module Google class Compute 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.29.3/lib/fog/google/compute/models/project.rb0000644000004100000410000000154115142377631023424 0ustar www-datawww-datamodule Fog module Google class Compute ## # 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::Google::Compute::Operations.new(:service => service).get(operation.id) end end end end end fog-google-1.29.3/lib/fog/google/compute/models/target_instances.rb0000644000004100000410000000342615142377631025317 0ustar www-datawww-datamodule Fog module Google class Compute class TargetInstances < Fog::Collection model Fog::Google::Compute::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 } items = [] next_page_token = nil loop do if zone data = service.list_target_instances(zone, **opts) next_items = data.to_h[:items] || [] items.concat(next_items) next_page_token = data.next_page_token else data = service.list_aggregated_target_instances(**opts) data.items.each_value do |scoped_list| items.concat(scoped_list.target_instances.map(&:to_h)) if scoped_list && scoped_list.target_instances end next_page_token = data.next_page_token end break if next_page_token.nil? || next_page_token.empty? opts[:page_token] = next_page_token end load(items) 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.29.3/lib/fog/google/compute/models/instance_templates.rb0000644000004100000410000000165415142377631025645 0ustar www-datawww-datamodule Fog module Google class Compute class InstanceTemplates < Fog::Collection model Fog::Google::Compute::InstanceTemplate def all(opts = {}) items = [] next_page_token = nil loop do data = service.list_instance_templates(**opts) next_items = data.items || [] items.concat(next_items) next_page_token = data.next_page_token break if next_page_token.nil? || next_page_token.empty? opts[:page_token] = next_page_token end load(items.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.29.3/lib/fog/google/compute/models/http_health_checks.rb0000644000004100000410000000164515142377631025607 0ustar www-datawww-datamodule Fog module Google class Compute class HttpHealthChecks < Fog::Collection model Fog::Google::Compute::HttpHealthCheck def all(opts = {}) items = [] next_page_token = nil loop do data = service.list_http_health_checks(**opts) 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? opts[:page_token] = next_page_token end load(items) 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.29.3/lib/fog/google/compute/models/instance_groups.rb0000644000004100000410000000507015142377631025162 0ustar www-datawww-datamodule Fog module Google class Compute class InstanceGroups < Fog::Collection model Fog::Google::Compute::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 } items = [] next_page_token = nil loop do if zone data = service.list_instance_groups(zone) next_items = data.items || [] items.concat(next_items) else data = service.list_aggregated_instance_groups(opts) data.items.each_value do |group| items.concat(group.instance_groups) if group && group.instance_groups end next_page_token = data.next_page_token end break if next_page_token.nil? || next_page_token.empty? opts[:page_token] = next_page_token end load(items.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(2.0): To be deprecated def add_instance(params) Fog::Logger.deprecation( "#{self.class}.#{__method__} is deprecated, use Fog::Google::Compute::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(2.0): To be deprecated def remove_instance(params) Fog::Logger.deprecation( "#{self.class}.#{__method__} is deprecated, use Fog::Google::Compute::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.29.3/lib/fog/google/compute/models/target_pool.rb0000644000004100000410000001335015142377631024276 0ustar www-datawww-datamodule Fog module Google class Compute 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::Google::Compute::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::Google::Compute::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::Google::Compute::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::Google::Compute::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::Google::Compute::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::Google::Compute::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.29.3/lib/fog/google/compute/models/route.rb0000644000004100000410000000323315142377631023114 0ustar www-datawww-datamodule Fog module Google class Compute ## # 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::Google::Compute::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::Google::Compute::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async operation end end end end end fog-google-1.29.3/lib/fog/google/compute/models/global_addresses.rb0000644000004100000410000000306315142377631025254 0ustar www-datawww-datamodule Fog module Google class Compute class GlobalAddresses < Fog::Collection model Fog::Google::Compute::GlobalAddress def all(options = {}) items = [] next_page_token = nil loop do data = service.list_global_addresses(**options) 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? options[:page_token] = next_page_token end load(items) 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.29.3/lib/fog/google/compute/models/target_https_proxy.rb0000644000004100000410000000627715142377631025742 0ustar www-datawww-datamodule Fog module Google class Compute 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::Google::Compute::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::Google::Compute::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::Google::Compute::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::Google::Compute::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::Google::Compute::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.29.3/lib/fog/google/compute/models/target_pools.rb0000644000004100000410000000321715142377631024462 0ustar www-datawww-datamodule Fog module Google class Compute class TargetPools < Fog::Collection model Fog::Google::Compute::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 } items = [] next_page_token = nil loop do if region.nil? data = service.list_aggregated_target_pools(**opts) data.items.each_value do |lst| items.concat(lst.to_h[:target_pools]) if lst && lst.target_pools end next_page_token = data.next_page_token else data = service.list_target_pools(region, **opts) next_items = data.to_h[:items] || [] items.concat(next_items) next_page_token = data.next_page_token end break if next_page_token.nil? || next_page_token.empty? opts[:page_token] = next_page_token end load(items) 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.29.3/lib/fog/google/compute/models/routes.rb0000644000004100000410000000154115142377631023277 0ustar www-datawww-datamodule Fog module Google class Compute class Routes < Fog::Collection model Fog::Google::Compute::Route def all(opts = {}) items = [] next_page_token = nil loop do data = service.list_routes(**opts) 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? opts[:page_token] = next_page_token end load(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.29.3/lib/fog/google/compute/models/operation.rb0000644000004100000410000001243015142377631023755 0ustar www-datawww-datamodule Fog module Google class Compute 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 # {:errors=> # [{:code=>"QUOTA_EXCEEDED", # :error_details=> # [{:quota_info=> # {:dimensions=>{:region=>"us-east4"}, # :limit=>500, # :limit_name=>"SSD-TOTAL-GB-per-project-region", # :metric_name=>"compute.googleapis.com/ssd_total_storage"}}], # :message=>"Quota 'SSD_TOTAL_GB' exceeded. Limit: 500.0 in region us-east4."} # ] # } class ErrorInfo attr_accessor :code attr_accessor :error_details attr_accessor :location attr_accessor :message def initialize(attributes = {}) @code = attributes[:code] @error_details = attributes[:error_details] @location = attributes[:location] @message = attributes[:message] end def message_pretty message end end # ErrorInfo class QuotaInfo < ErrorInfo def initialize(attributes = {}) code = attributes[:code] raise Fog::Errors::Error.new("Invalid error code: #{code}") if code != "QUOTA_EXCEEDED" super(attributes) end def quota_infos return [] unless error_details.is_a?(Array) error_details_quota_infos = error_details.select{|ed| ed.is_a?(Hash) && ed.has_key?(:quota_info)} error_details_quota_infos.map{|ed| ed[:quota_info]} end def message_pretty msg = super.gsub(/\s*Limit.*region.*[^.]+./, "") quota_infos.each do |qi| dimensions = qi[:dimensions] if qi.is_a?(Hash) limit = qi[:limit] if qi.is_a?(Hash) metric = qi[:metric_name] if qi.is_a?(Hash) region = dimensions[:region] if dimensions.is_a?(Hash) limit_msg = " Limit: #{limit.to_f}" if limit.is_a?(Numeric) limit_msg = "#{limit_msg} #{metric}" if limit_msg && metric limit_msg = "#{limit_msg} in region #{region}" if limit_msg && region.is_a?(String) limit_msg = "#{limit_msg}." if limit_msg msg = "#{msg}#{limit_msg}" end msg end end # QuotaInfo def error? ! error.nil? end def errors error? ? error[:errors] : nil end 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 error_info_class(code) case code when "QUOTA_EXCEEDED" then QuotaInfo else ErrorInfo end end # Returns an array of ErrorInfo objects derived from the raw error hash. def error_infos return [] unless error.is_a?(Hash) return [] unless errors.is_a?(Array) errors.map do |err| klass = error_info_class(err[:code]) klass.new( code: err[:code], message: err[:message], location: err[:location], error_details: err[:error_details] ) end end # Convenience helper: return the first error (most Google APIs provide only one). def primary_error error_infos.first 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.29.3/lib/fog/google/compute/models/forwarding_rule.rb0000644000004100000410000000467115142377631025156 0ustar www-datawww-datamodule Fog module Google class Compute 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::Google::Compute::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::Google::Compute::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.29.3/lib/fog/google/compute/models/region.rb0000644000004100000410000000127315142377631023243 0ustar www-datawww-datamodule Fog module Google class Compute ## # 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.29.3/lib/fog/google/compute/models/address.rb0000644000004100000410000001016115142377631023401 0ustar www-datawww-datamodule Fog module Google class Compute ## # 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::Google::Compute::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::Google::Compute::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 # Associates the ip address to a given server # # @param [String] server - GCE instance name # @param [String] nic_name - NIC interface name, defaults to GCE # standard primary nic - "nic0" # @param [Boolean] async - whether to run the operation asynchronously # # @return [Fog::Google::Compute::Operation] def associate(server, nic_name = "nic0", async = false) requires :address data = service.add_server_access_config( server.name, server.zone, nic_name, :nat_ip => address ) operation = Fog::Google::Compute::Operations .new(:service => service) .get(data.name, data.zone) operation.wait_for { ready? } unless async end # Disassociates the ip address from a resource it's attached to # # @param [Boolean] async - whether to run the operation asynchronously # # @return [Fog::Google::Compute::Operation] def disassociate(async = false) 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::Google::Compute::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.29.3/lib/fog/google/compute/models/network.rb0000644000004100000410000000443115142377631023450 0ustar www-datawww-datamodule Fog module Google class Compute ## # 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 data = service.insert_network(identity, attributes) operation = Fog::Google::Compute::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::Google::Compute::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.29.3/lib/fog/google/compute/models/images.rb0000644000004100000410000000731215142377631023225 0ustar www-datawww-datamodule Fog module Google class Compute class Images < Fog::Collection model Fog::Google::Compute::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 debian-cloud fedora-coreos-cloud rhel-cloud rhel-sap-cloud rocky-linux-cloud suse-cloud suse-sap-cloud ubuntu-os-cloud ubuntu-os-pro-cloud windows-cloud windows-sql-cloud ).freeze def all(opts = {}) items = [] all_projects.each do |project| begin next_page_token = nil loop do opts[:page_token] = next_page_token data = service.list_images(project, **opts) images = data.items&.map(&:to_h) || [] # Keep track of the project in which we found the image(s) images.each { |img| img.merge!(:project => project) } items.concat(images) next_page_token = data.next_page_token break if next_page_token.nil? || next_page_token.empty? end 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 load(items) 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 project_list = [service.project] + GLOBAL_PROJECTS + service.extra_global_projects unless service.exclude_projects.empty? project_list.delete_if { |project| service.exclude_projects.include?(project) } end project_list end end end end end fog-google-1.29.3/lib/fog/google/compute/models/target_http_proxy.rb0000644000004100000410000000421215142377631025542 0ustar www-datawww-datamodule Fog module Google class Compute 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::Google::Compute::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::Google::Compute::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::Google::Compute::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.29.3/lib/fog/google/compute/models/instance_group_managers.rb0000644000004100000410000000347415142377631026662 0ustar www-datawww-datamodule Fog module Google class Compute class InstanceGroupManagers < Fog::Collection model Fog::Google::Compute::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 } items = [] next_page_token = nil loop do if zone data = service.list_instance_group_managers(zone, **opts) next_items = data.items || [] items.concat(next_items) next_page_token = data.next_page_token else data = service.list_aggregated_instance_group_managers(**opts) data.items.each_value do |group| items.concat(group.instance_group_managers) if group && group.instance_group_managers end next_page_token = data.next_page_token end break if next_page_token.nil? || next_page_token.empty? opts[:page_token] = next_page_token end load(items.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.29.3/lib/fog/google/compute/models/servers.rb0000644000004100000410000001044215142377631023447 0ustar www-datawww-datamodule Fog module Google class Compute class Servers < Fog::Collection model Fog::Google::Compute::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 } items = [] next_page_token = nil loop do if zone data = service.list_servers(zone, **opts) next_items = data.to_h[:items] || [] items.concat(next_items) next_page_token = data.next_page_token else data = service.list_aggregated_servers(**opts) data.items.each_value do |scoped_lst| if scoped_lst && scoped_lst.instances items.concat(scoped_lst.instances.map(&:to_h)) end end next_page_token = data.next_page_token end break if next_page_token.nil? || next_page_token.empty? opts[:page_token] = next_page_token end load(items) 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-11") 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 # true - autodelete setting # nil - device name (not needed if there's only one disk) # false - set async to false so set the property synchronously server.set_disk_auto_delete(true, nil, false) 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.29.3/lib/fog/google/compute/models/addresses.rb0000644000004100000410000000461215142377631023735 0ustar www-datawww-datamodule Fog module Google class Compute class Addresses < Fog::Collection model Fog::Google::Compute::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 } items = [] next_page_token = nil loop do if region data = service.list_addresses(region, **opts) next_items = data.items || [] items.concat(next_items) next_page_token = data.next_page_token else data = service.list_aggregated_addresses(**opts) data.items.each_value do |scoped_list| items.concat(scoped_list.addresses) if scoped_list && scoped_list.addresses end next_page_token = data.next_page_token end break if next_page_token.nil? || next_page_token.empty? opts[:page_token] = next_page_token end load(items.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.29.3/lib/fog/google/compute/models/forwarding_rules.rb0000644000004100000410000000323015142377631025327 0ustar www-datawww-datamodule Fog module Google class Compute class ForwardingRules < Fog::Collection model Fog::Google::Compute::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 } items = [] next_page_token = nil loop do if region data = service.list_forwarding_rules(region, **opts) next_items = data.items || [] items.concat(next_items) next_page_token = data.next_page_token else data = service.list_aggregated_forwarding_rules(**opts) data.items.each_value do |scoped_list| items.concat(scoped_list.forwarding_rules) if scoped_list && scoped_list.forwarding_rules end next_page_token = data.next_page_token end break if next_page_token.nil? || next_page_token.empty? opts[:page_token] = next_page_token end load(items.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.29.3/lib/fog/google/compute/models/global_address.rb0000644000004100000410000000312015142377631024716 0ustar www-datawww-datamodule Fog module Google class Compute ## # 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::Google::Compute::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::Google::Compute::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.29.3/lib/fog/google/compute/models/ssl_certificates.rb0000644000004100000410000000163315142377631025306 0ustar www-datawww-datamodule Fog module Google class Compute class SslCertificates < Fog::Collection model Fog::Google::Compute::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(opts = {}) items = [] next_page_token = nil loop do data = service.list_ssl_certificates(**opts) 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? opts[:page_token] = next_page_token end load(items) end end end end end fog-google-1.29.3/lib/fog/google/compute/models/instance_template.rb0000644000004100000410000000273615142377631025464 0ustar www-datawww-datamodule Fog module Google class Compute 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::Google::Compute::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::Google::Compute::Operations.new(:service => service).get(data.name) operation.wait_for { ready? } unless async operation end end end end end fog-google-1.29.3/lib/fog/google/compute/models/target_https_proxies.rb0000644000004100000410000000165515142377631026245 0ustar www-datawww-datamodule Fog module Google class Compute class TargetHttpsProxies < Fog::Collection model Fog::Google::Compute::TargetHttpsProxy def all(opts = {}) items = [] next_page_token = nil loop do data = service.list_target_https_proxies(**opts) 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? opts[:page_token] = next_page_token end load(items) 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.29.3/lib/fog/google/compute/models/regions.rb0000644000004100000410000000154715142377631023432 0ustar www-datawww-datamodule Fog module Google class Compute class Regions < Fog::Collection model Fog::Google::Compute::Region def all(opts = {}) items = [] next_page_token = nil loop do data = service.list_regions(**opts) 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? opts[:page_token] = next_page_token end load(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.29.3/lib/fog/google/compute/models/disks.rb0000644000004100000410000000771415142377631023103 0ustar www-datawww-datamodule Fog module Google class Compute class Disks < Fog::Collection model Fog::Google::Compute::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 } items = [] next_page_token = nil loop do if zone data = service.list_disks(zone, **opts) next_items = data.items || [] items.concat(next_items) next_page_token = data.next_page_token else data = service.list_aggregated_disks(**opts) data.items.each_value do |scoped_list| items.concat(scoped_list.disks) if scoped_list && scoped_list.disks end next_page_token = data.next_page_token end break if next_page_token.nil? || next_page_token.empty? opts[:page_token] = next_page_token end load(items.map(&:to_h)) end def get(identity, zone = nil) if zone disk = service.get_disk(identity, zone).to_h # Force the hash to contain a :users key so that it will override any :users key in the existing object disk[:users] = nil unless disk.include?(:users) 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 # Return an empty object so that wait_for processes the block return new({:status => 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.29.3/lib/fog/google/compute/models/instance_group_manager.rb0000644000004100000410000000340715142377631026473 0ustar www-datawww-datamodule Fog module Google class Compute 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::Google::Compute::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.29.3/lib/fog/google/compute/models/firewall.rb0000644000004100000410000000565015142377631023570 0ustar www-datawww-datamodule Fog module Google class Compute ## # 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::Google::Compute::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::Google::Compute::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::Google::Compute::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::Google::Compute::Operations.new(:service => service) .get(data.name) operation.wait_for { ready? } unless async operation end end end end end fog-google-1.29.3/lib/fog/google/compute/models/subnetworks.rb0000644000004100000410000000324115142377631024343 0ustar www-datawww-datamodule Fog module Google class Compute class Subnetworks < Fog::Collection model Fog::Google::Compute::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 } items = [] next_page_token = nil loop do if region data = service.list_subnetworks(region, **filters) next_items = data.items || [] items.concat(next_items) next_page_token = data.next_page_token else data = service.list_aggregated_subnetworks(**filters) data.items.each_value do |region_obj| items.concat(region_obj.subnetworks) if region_obj && region_obj.subnetworks end end break if next_page_token.nil? || next_page_token.empty? filters[:page_token] = next_page_token end load(items.map(&:to_h)) 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.29.3/lib/fog/google/compute/models/disk.rb0000644000004100000410000001371415142377631022715 0ustar www-datawww-datamodule Fog module Google class Compute 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 attribute :labels attribute :label_fingerprint, :aliases => "labelFingerprint" attribute :users 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, :labels => labels }.reject { |_, v| v.nil? } 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::Google::Compute::Operations.new(service: service) .get(data.name, data.zone) operation.wait_for { ready? } # Handle errors if operation.error? msg = "Error creating disk #{name} size #{size_gb}." err = operation.primary_error msg = "#{msg} #{err.message_pretty}" unless err.nil? raise Fog::Errors::Error.new(msg) end reload end def destroy(async = true) requires :name, :zone data = service.delete_disk(name, zone_name) operation = Fog::Google::Compute::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::Google::Compute::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.29.3/lib/fog/google/compute/models/url_maps.rb0000644000004100000410000000155515142377631023605 0ustar www-datawww-datamodule Fog module Google class Compute class UrlMaps < Fog::Collection model Fog::Google::Compute::UrlMap def all(opts = {}) items = [] next_page_token = nil loop do data = service.list_url_maps(**opts) 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? opts[:page_token] = next_page_token end load(items) 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.29.3/lib/fog/google/compute/models/global_forwarding_rule.rb0000644000004100000410000000455615142377631026500 0ustar www-datawww-datamodule Fog module Google class Compute 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::Google::Compute::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::Google::Compute::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.29.3/lib/fog/google/sql/0000755000004100000410000000000015142377631017270 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/sql/real.rb0000644000004100000410000000106215142377631020537 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.29.3/lib/fog/google/sql/mock.rb0000644000004100000410000000156115142377631020551 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.29.3/lib/fog/google/version.rb0000644000004100000410000000010315142377631020475 0ustar www-datawww-datamodule Fog module Google VERSION = "1.29.3".freeze end end fog-google-1.29.3/lib/fog/google/storage/0000755000004100000410000000000015142377631020135 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/storage/storage_json/0000755000004100000410000000000015142377631022632 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/storage/storage_json/requests/0000755000004100000410000000000015142377631024505 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/storage/storage_json/requests/list_bucket_acl.rb0000644000004100000410000000136715142377631030170 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/delete_bucket.rb0000644000004100000410000000105215142377631027627 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/get_object_http_url.rb0000644000004100000410000000216615142377631031065 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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.29.3/lib/fog/google/storage/storage_json/requests/get_object.rb0000644000004100000410000000735215142377631027146 0ustar www-datawww-datarequire "tempfile" module Fog module Google class StorageJSON 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") buf.binmode buf.unlink # 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) ) buf.seek(0) if block_given? yield buf.read, nil, nil else object[:body] = buf.read end object ensure buf.close! rescue nil end end class Mock def get_object(_bucket_name, _object_name, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/put_object.rb0000644000004100000410000001050215142377631027166 0ustar www-datawww-data# frozen_string_literal: true module Fog module Google class StorageJSON 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 = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/copy_object.rb0000644000004100000410000000321215142377631027330 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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) object = ::Google::Apis::StorageV1::Object.new(**options) @storage_json.copy_object(source_bucket, source_object, target_bucket, target_object, object, options: request_options, **filter_keyword_args(options)) end private def filter_keyword_args(options) method = @storage_json.method(:copy_object) allowed = method.parameters.filter { |param| %i(key keyreq).include?(param[0]) }.map { |param| param[1] }.compact options.filter { |key, _| allowed.include?(key) } end end class Mock def copy_object(_source_bucket, _source_object, _target_bucket, _target_object, _options = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/get_object_acl.rb0000644000004100000410000000243615142377631027763 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/get_bucket_acl.rb0000644000004100000410000000205415142377631027766 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/get_object_https_url.rb0000644000004100000410000000220215142377631031237 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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.29.3/lib/fog/google/storage/storage_json/requests/list_buckets.rb0000644000004100000410000000152515142377631027530 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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 # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/put_object_url.rb0000644000004100000410000000363115142377631030055 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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.29.3/lib/fog/google/storage/storage_json/requests/get_object_metadata.rb0000644000004100000410000000215615142377631031003 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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 = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/get_object_url.rb0000644000004100000410000000157215142377631030026 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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::Google::Storage => #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::Google::Storage => #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.29.3/lib/fog/google/storage/storage_json/requests/put_bucket.rb0000644000004100000410000000264315142377631027204 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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 = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/get_bucket.rb0000644000004100000410000000306515142377631027152 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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 = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/list_object_acl.rb0000644000004100000410000000201515142377631030150 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/delete_object_url.rb0000644000004100000410000000276315142377631030514 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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.29.3/lib/fog/google/storage/storage_json/requests/delete_object.rb0000644000004100000410000000125015142377631027620 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/list_objects.rb0000644000004100000410000000305215142377631027516 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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 = {}) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/put_bucket_acl.rb0000644000004100000410000000176515142377631030027 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/requests/put_object_acl.rb0000644000004100000410000000231615142377631030011 0ustar www-datawww-datamodule Fog module Google class StorageJSON 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) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/real.rb0000644000004100000410000001707715142377631024116 0ustar www-datawww-data# frozen_string_literal: true module Fog module Google class StorageJSON class Real include Utils include Fog::Google::Shared attr_accessor :client, :host attr_reader :storage_json def initialize(options = {}) @options = options.dup api_base_url = storage_api_base_url_for_universe(universe_domain) shared_initialize(options[:google_project], GOOGLE_STORAGE_JSON_API_VERSION, api_base_url) options[:google_api_scope_url] = GOOGLE_STORAGE_JSON_API_SCOPE_URLS.join(" ") # Set @host for compatibility with request methods (e.g., get_object_https_url) @host = storage_host_for_universe(universe_domain) # TODO(temikus): Do we even need this client? @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 bucket_base_url storage_base_url_for_universe(universe_domain) 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 # TODO(temikus): make signer configurable or add ability to supply your own via lambda if !@storage_json.authorization.signing_key.nil? signed_string = default_signer(string_to_sign) else # If client doesn't contain signing key attempt to auth via IAM SignBlob API signed_string = iam_signer(string_to_sign) end Base64.encode64(signed_string).chomp! end private def universe_domain universe_domain_from_options(@options) end def google_access_id @google_access_id ||= get_google_access_id end ## # Fetches the google service account name # # @return [String] Service account name, typically needed for GoogleAccessId, e.g. # my-account@project.iam.gserviceaccount # @raises [Fog::Errors::Error] If authorisation is incorrect or inapplicable for current action def get_google_access_id if @storage_json.authorization.is_a?(::Google::Auth::UserRefreshCredentials) raise Fog::Errors::Error.new("User / Application Default Credentials are not supported for storage"\ "url signing, please use a service account or metadata authentication.") end if !@storage_json.authorization.issuer.nil? return @storage_json.authorization.issuer else get_access_id_from_metadata end end ## # Attempts to fetch the google service account name from metadata using Google::Cloud::Env # # @return [String] Service account name, typically needed for GoogleAccessId, e.g. # my-account@project.iam.gserviceaccount # @raises [Fog::Errors::Error] If Metadata service is not available or returns an invalid response def get_access_id_from_metadata if @google_cloud_env.metadata? access_id = @google_cloud_env.lookup_metadata("instance", "service-accounts/default/email") else raise Fog::Errors::Error.new("Metadata service not available, unable to retrieve service account info.") end if access_id.nil? raise Fog::Errors::Error.new("Metadata service found but didn't return data." \ "Please file a bug: https://github.com/fog/fog-google") end return access_id end ## # Default url signer using service account keys # # @param [String] string_to_sign Special collection of headers and options for V2 storage signing, e.g.: # # StringToSign = HTTP_Verb + "\n" + # Content_MD5 + "\n" + # Content_Type + "\n" + # Expires + "\n" + # Canonicalized_Extension_Headers + # Canonicalized_Resource # # See https://cloud.google.com/storage/docs/access-control/signed-urls-v2 # @return [String] Signature binary blob def default_signer(string_to_sign) key = @storage_json.authorization.signing_key key = OpenSSL::PKey::RSA.new(@storage_json.authorization.signing_key) unless key.respond_to?(:sign) digest = OpenSSL::Digest::SHA256.new return key.sign(digest, string_to_sign) end # IAM client used for SignBlob API. # Lazily initialize this since it requires another authorization request. def iam_service return @iam_service if defined?(@iam_service) @iam_service = ::Google::Apis::IamcredentialsV1::IAMCredentialsService.new apply_client_options(@iam_service, @options) iam_options = @options.merge(google_api_scope_url: GOOGLE_STORAGE_JSON_IAM_API_SCOPE_URLS.join(" ")) @iam_service.authorization = initialize_auth(iam_options) @iam_service end ## # Fallback URL signer using the IAM SignServiceAccountBlob API, see # Google::Apis::IamcredentialsV1::IAMCredentialsService#sign_service_account_blob # # @param [String] string_to_sign Special collection of headers and options for V2 storage signing, e.g.: # # StringToSign = HTTP_Verb + "\n" + # Content_MD5 + "\n" + # Content_Type + "\n" + # Expires + "\n" + # Canonicalized_Extension_Headers + # Canonicalized_Resource # # See https://cloud.google.com/storage/docs/access-control/signed-urls-v2 # @return [String] Signature binary blob def iam_signer(string_to_sign) request = ::Google::Apis::IamcredentialsV1::SignBlobRequest.new( payload: string_to_sign ) resource = "projects/-/serviceAccounts/#{google_access_id}" response = iam_service.sign_service_account_blob(resource, request) return response.signed_blob end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/mock.rb0000644000004100000410000000215415142377631024112 0ustar www-datawww-datamodule Fog module Google class StorageJSON class Mock include Utils include Fog::Google::Shared MockClient = Struct.new(:issuer) attr_reader :host def initialize(options = {}) @options = options.dup api_base_url = storage_api_base_url_for_universe(universe_domain) shared_initialize(options[:google_project], GOOGLE_STORAGE_JSON_API_VERSION, api_base_url) # Set @host for compatibility with request methods (e.g., get_object_https_url) @host = storage_host_for_universe(universe_domain) @client = MockClient.new('test') @storage_json = MockClient.new('test') @iam_service = MockClient.new('test') end def signature(_params) "foo" end def bucket_base_url storage_base_url_for_universe(universe_domain) end def google_access_id "my-account@project.iam.gserviceaccount" end private def universe_domain universe_domain_from_options(@options) end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/models/0000755000004100000410000000000015142377631024115 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/storage/storage_json/models/directory.rb0000644000004100000410000000307715142377631026455 0ustar www-datawww-datamodule Fog module Google class StorageJSON ## # 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::Google::StorageJSON::Files.new( attr.merge(:directory => self, :service => service) ) end end def public_url requires :key "#{service.bucket_base_url}#{key}" end def save requires :key service.put_bucket(key, **attributes) true end end end end end fog-google-1.29.3/lib/fog/google/storage/storage_json/models/files.rb0000644000004100000410000000420515142377631025545 0ustar www-datawww-datamodule Fog module Google class StorageJSON class Files < Fog::Collection model Fog::Google::StorageJSON::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 => %w(MaxKeys max-keys) attribute :prefix, :aliases => "Prefix" attribute :next_page_token def all(options = {}) requires :directory parent = service.list_objects(directory.key, attributes.merge(options)) attributes[:next_page_token] = parent.next_page_token data = parent.to_h[:items] || [] load(data) end alias_method :each_file_this_page, :each def each(&block) if block_given? subset = dup.all subset.each_file_this_page(&block) while subset.next_page_token subset = subset.all(:page_token => subset.next_page_token) subset.each_file_this_page(&block) end 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.29.3/lib/fog/google/storage/storage_json/models/file.rb0000644000004100000410000001065215142377631025365 0ustar www-datawww-datamodule Fog module Google class StorageJSON class File < Fog::Model identity :key, :aliases => ["Key", :name] attribute :acl attribute :uniform 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 uniform=(enable) @uniform=enable end 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 return attributes[:body] if attributes.key?(:body) file = collection.get(identity) attributes[:body] = if file file.attributes[:body] else "" end 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 "#{service.bucket_base_url}#{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 unless @uniform 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.29.3/lib/fog/google/storage/storage_json/models/directories.rb0000644000004100000410000000263115142377631026760 0ustar www-datawww-datamodule Fog module Google class StorageJSON class Directories < Fog::Collection model Fog::Google::StorageJSON::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.29.3/lib/fog/google/storage/storage_json/utils.rb0000644000004100000410000000356615142377631024331 0ustar www-datawww-data# frozen_string_literal: true require "addressable" module Fog module Google class StorageJSON 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::Google::Storage => #url is deprecated, use #https_url instead [light_black](#{caller.first})[/]") https_url(params, expires) end def storage_api_base_url_for_universe(universe_domain) domain = universe_domain.to_s.strip if !domain.empty? && domain != "googleapis.com" "https://storage.#{domain}/storage/" else Fog::Google::StorageJSON::GOOGLE_STORAGE_JSON_BASE_URL end end def storage_host_for_universe(universe_domain) Fog::Google::Storage::Utils.storage_host_for_universe(universe_domain) end def storage_base_url_for_universe(universe_domain) "https://#{storage_host_for_universe(universe_domain)}/" end private def host_path_query(params, expires) params[:headers]["Date"] = expires.to_i params[:path] = ::Addressable::URI.encode_component(params[:path], ::Addressable::URI::CharacterClasses::PATH) 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_access_id}" 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.29.3/lib/fog/google/storage/storage_xml.rb0000644000004100000410000000221215142377631023003 0ustar www-datawww-datamodule Fog module Google class StorageXML < Fog::Service autoload :Mock, "fog/google/storage/storage_xml/mock" autoload :Real, "fog/google/storage/storage_xml/real" autoload :Utils, "fog/google/storage/storage_xml/utils" requires :google_storage_access_key_id, :google_storage_secret_access_key recognizes :port, :scheme, :persistent, :path_style, :universe_domain model_path "fog/google/storage/storage_xml/models" collection :directories model :directory collection :files model :file request_path "fog/google/storage/storage_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.29.3/lib/fog/google/storage/storage_xml/0000755000004100000410000000000015142377631022461 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/storage/storage_xml/requests/0000755000004100000410000000000015142377631024334 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/storage/storage_xml/requests/delete_bucket.rb0000644000004100000410000000222415142377631027460 0ustar www-datawww-datamodule Fog module Google class StorageXML 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.29.3/lib/fog/google/storage/storage_xml/requests/get_object_http_url.rb0000644000004100000410000000221515142377631030707 0ustar www-datawww-datamodule Fog module Google class StorageXML 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.29.3/lib/fog/google/storage/storage_xml/requests/get_object.rb0000644000004100000410000001072315142377631026771 0ustar www-datawww-datamodule Fog module Google class StorageXML 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] = block 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.29.3/lib/fog/google/storage/storage_xml/requests/head_object.rb0000644000004100000410000000517615142377631027121 0ustar www-datawww-datamodule Fog module Google class StorageXML 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}", :idempotent => true, :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.29.3/lib/fog/google/storage/storage_xml/requests/put_object.rb0000644000004100000410000000732315142377631027024 0ustar www-datawww-datamodule Fog module Google class StorageXML 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.29.3/lib/fog/google/storage/storage_xml/requests/copy_object.rb0000644000004100000410000000553615142377631027172 0ustar www-datawww-datamodule Fog module Google class StorageXML 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::Google::Parsers::Storage::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.29.3/lib/fog/google/storage/storage_xml/requests/get_object_acl.rb0000644000004100000410000000466215142377631027615 0ustar www-datawww-datamodule Fog module Google class StorageXML 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::Google::Parsers::Storage::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.29.3/lib/fog/google/storage/storage_xml/requests/get_bucket_acl.rb0000644000004100000410000000362015142377631027615 0ustar www-datawww-datamodule Fog module Google class StorageXML 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::Google::Parsers::Storage::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.29.3/lib/fog/google/storage/storage_xml/requests/get_object_https_url.rb0000644000004100000410000000224115142377631031071 0ustar www-datawww-datamodule Fog module Google class StorageXML 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.29.3/lib/fog/google/storage/storage_xml/requests/get_service.rb0000644000004100000410000000250715142377631027164 0ustar www-datawww-datamodule Fog module Google class StorageXML 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::Google::Parsers::Storage::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.29.3/lib/fog/google/storage/storage_xml/requests/put_object_url.rb0000644000004100000410000000302515142377631027701 0ustar www-datawww-datamodule Fog module Google class StorageXML 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.29.3/lib/fog/google/storage/storage_xml/requests/get_object_url.rb0000644000004100000410000000240315142377631027647 0ustar www-datawww-datamodule Fog module Google class StorageXML 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::Google::Storage => #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::Google::Storage => #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.29.3/lib/fog/google/storage/storage_xml/requests/put_bucket.rb0000644000004100000410000000507015142377631027030 0ustar www-datawww-datamodule Fog module Google class StorageXML 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.29.3/lib/fog/google/storage/storage_xml/requests/get_bucket.rb0000644000004100000410000001057315142377631027003 0ustar www-datawww-datamodule Fog module Google class StorageXML 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::Google::Parsers::Storage::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 = /([a-zA-Z0-9][a-zA-Z0-9\-_.]+[a-zA-Z0-9])/.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.29.3/lib/fog/google/storage/storage_xml/requests/delete_object_url.rb0000644000004100000410000000277415142377631030345 0ustar www-datawww-datamodule Fog module Google class StorageXML 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.29.3/lib/fog/google/storage/storage_xml/requests/delete_object.rb0000644000004100000410000000257215142377631027457 0ustar www-datawww-datamodule Fog module Google class StorageXML 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.29.3/lib/fog/google/storage/storage_xml/requests/put_bucket_acl.rb0000644000004100000410000000300415142377631027642 0ustar www-datawww-datamodule Fog module Google class StorageXML class Mock def put_bucket_acl(_bucket_name, _acl) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: 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.29.3/lib/fog/google/storage/storage_xml/requests/put_object_acl.rb0000644000004100000410000000330315142377631027635 0ustar www-datawww-datamodule Fog module Google class StorageXML 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.29.3/lib/fog/google/storage/storage_xml/real.rb0000644000004100000410000000730115142377631023732 0ustar www-datawww-data# frozen_string_literal: true module Fog module Google class StorageXML 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 = storage_host_for_universe(options[:universe_domain]) @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.29.3/lib/fog/google/storage/storage_xml/mock.rb0000644000004100000410000000631415142377631023743 0ustar www-datawww-datamodule Fog module Google class StorageXML 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] @host = storage_host_for_universe(options[:universe_domain]) 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 attr_reader :host end end end end fog-google-1.29.3/lib/fog/google/storage/storage_xml/models/0000755000004100000410000000000015142377631023744 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/storage/storage_xml/models/directory.rb0000644000004100000410000000344115142377631026277 0ustar www-datawww-datamodule Fog module Google class StorageXML 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::Google::StorageXML::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.29.3/lib/fog/google/storage/storage_xml/models/files.rb0000644000004100000410000000544215142377631025400 0ustar www-datawww-datamodule Fog module Google class StorageXML 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 => %w(MaxKeys max-keys) attribute :prefix, :aliases => "Prefix" model Fog::Google::StorageXML::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(&block) if !block_given? self else subset = dup.all subset.each_file_this_page(&block) while subset.is_truncated subset = subset.all(:marker => subset.last.key) subset.each_file_this_page(&block) 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.29.3/lib/fog/google/storage/storage_xml/models/file.rb0000644000004100000410000001104515142377631025211 0ustar www-datawww-datamodule Fog module Google class StorageXML 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.select { |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.29.3/lib/fog/google/storage/storage_xml/models/directories.rb0000644000004100000410000000210015142377631026576 0ustar www-datawww-datamodule Fog module Google class StorageXML class Directories < Fog::Collection model Fog::Google::StorageXML::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.29.3/lib/fog/google/storage/storage_xml/utils.rb0000644000004100000410000000723715142377631024157 0ustar www-datawww-data# frozen_string_literal: true module Fog module Google class StorageXML module Utils # https://cloud.google.com/storage/docs/access-control#predefined-acl VALID_ACLS = %w( 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::Google::Storage => #url is deprecated, use #https_url instead [light_black](#{caller.first})[/]") https_url(params, expires) end def storage_host_for_universe(universe_domain) Fog::Google::Storage::Utils.storage_host_for_universe(universe_domain) 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] if params[:path] params[:path] = "#{subdomain}/#{params[:path]}" else params[:path] = 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.29.3/lib/fog/google/storage/storage_json.rb0000644000004100000410000000453015142377631023161 0ustar www-datawww-datamodule Fog module Google class StorageJSON < Fog::Service autoload :Mock, "fog/google/storage/storage_json/mock" autoload :Real, "fog/google/storage/storage_json/real" autoload :Utils, "fog/google/storage/storage_json/utils" 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, :universe_domain, :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 # Version of IAM API used for blob signing, see Fog::Google::StorageJSON::Real#iam_signer GOOGLE_STORAGE_JSON_IAM_API_VERSION = "v1".freeze GOOGLE_STORAGE_JSON_IAM_API_SCOPE_URLS = %w(https://www.googleapis.com/auth/iam).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/google/storage/storage_json/models" collection :directories model :directory collection :files model :file ## # Requests request_path "fog/google/storage/storage_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.29.3/lib/fog/google/compute.rb0000644000004100000410000002135015142377631020473 0ustar www-datawww-datamodule Fog module Google class Compute < Fog::Service autoload :Mock, 'fog/google/compute/mock' autoload :Real, 'fog/google/compute/real' requires :google_project recognizes( :app_name, :app_version, :google_application_default, :google_auth, :google_client, :google_client_options, :google_extra_global_projects, :google_exclude_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 request_path "fog/google/compute/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_machine_type 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 request :reset_windows_password model_path "fog/google/compute/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.29.3/lib/fog/google/shared.rb0000644000004100000410000002631215142377631020270 0ustar www-datawww-datarequire "google-cloud-env" module 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/" # google-cloud-env allows us to figure out which GCP runtime we're running in and query metadata # e.g. whether we're running in GCE/GKE/AppEngine or what region the instance is running in @google_cloud_env = ::Google::Cloud::Env.get 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 # TODO: google-api-client is in gemspec now, re-assess if this initialization logic is still needed require "google/apis/monitoring_#{Fog::Google::Monitoring::GOOGLE_MONITORING_API_VERSION}" require "google/apis/compute_#{Fog::Google::Compute::GOOGLE_COMPUTE_API_VERSION}" require "google/apis/dns_#{Fog::Google::DNS::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::Google::StorageJSON::GOOGLE_STORAGE_JSON_API_VERSION}" require "google/apis/iamcredentials_#{Fog::Google::StorageJSON::GOOGLE_STORAGE_JSON_IAM_API_VERSION}" require "googleauth" rescue LoadError => e Fog::Errors::Error.new("Please install the google-api-client (>= 0.9) gem before using this provider") raise e 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 initialize_auth(options).tap do |auth| ::Google::Apis::RequestOptions.default.authorization = auth end end def initialize_auth(options) if options[:google_json_key_location] || options[:google_json_key_string] process_key_auth(options) elsif options[:google_auth] options[:google_auth] elsif options[:google_application_default] process_application_default_auth(options) else process_fallback_auth(options) end end ## # Applies given options to the client instance # # @param [Google::Apis::Core::BaseService] service API service client instance # @param [Hash] options (:universe_domain, :google_client_options) # @return [void] def apply_client_options(service, options = {}) universe_domain = universe_domain_from_options(options) service.universe_domain = universe_domain if universe_domain google_client_options = options[:google_client_options] 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 get universe domain from options or environment # # @param [Hash] options - client options hash # @return [String, nil] - universe domain or nil def universe_domain_from_options(options) options[:universe_domain] || ENV["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] end # 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_options = options.slice(:universe_domain) credentials = ::Google::Auth.get_application_default(options[:google_api_scope_url], google_options) credentials 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 StandardError 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) credentials = ::Google::Auth::ServiceAccountCredentials.make_creds( :json_key_io => StringIO.new(json_key), :scope => options[:google_api_scope_url] ) universe_domain = universe_domain_from_options(options) credentials.universe_domain = universe_domain if universe_domain && credentials.respond_to?(:universe_domain=) credentials 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.29.3/lib/fog/google/pubsub/0000755000004100000410000000000015142377631017771 5ustar www-datawww-datafog-google-1.29.3/lib/fog/google/pubsub/real.rb0000644000004100000410000000111015142377631021232 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.29.3/lib/fog/google/pubsub/mock.rb0000644000004100000410000000124115142377631021245 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.29.3/lib/fog/google.rb0000644000004100000410000000472115142377631017022 0ustar www-datawww-datarequire "fog/core" require "fog/json" require "fog/xml" require "fog/google/version" module Fog module Google autoload :Compute, File.expand_path("../google/compute", __FILE__) autoload :DNS, File.expand_path("../google/dns", __FILE__) 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__) autoload :Storage, File.expand_path("../google/storage", __FILE__) autoload :StorageJSON, 'fog/google/storage/storage_json' autoload :StorageXML, 'fog/google/storage/storage_xml' 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 module Parsers autoload :Storage, 'fog/google/parsers/storage' end end end # Add shims for backward compatibility # This allows old style references like Fog::Compute::Google to work # by redirecting them to the new namespace Fog::Google::Compute module Fog # List of services from the original module GOOGLE_SERVICES = %w[Compute DNS Monitoring Pubsub Storage SQL] # Dynamically create shim modules for each service GOOGLE_SERVICES.each do |service| # Create the module namespace const_set(service, Module.new) unless const_defined?(service) # Get reference to the module service_module = const_get(service) # Define the Google submodule with the shim service_module.const_set(:Google, Module.new) service_module::Google.define_singleton_method(:new) do |*args| warn "[DEPRECATION] `Fog::#{service}::Google.new` is deprecated. Please use `Fog::Google::#{service}.new` instead." Fog::Google.const_get(service).new(*args) end end end fog-google-1.29.3/Rakefile0000644000004100000410000000110015142377631015331 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.29.3/.hound.yml0000644000004100000410000000004215142377631015606 0ustar www-datawww-dataruby: config_file: .rubocop.yml fog-google-1.29.3/LICENSE.md0000644000004100000410000000220015142377631015272 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.29.3/Gemfile0000644000004100000410000000057615142377631015177 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.29.3/.codecov.yml0000644000004100000410000000003715142377631016117 0ustar www-datawww-datacodecov: bot: fog-google-bot fog-google-1.29.3/CONTRIBUTORS.md0000644000004100000410000000731415142377631016160 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.29.3/fog-google.gemspec0000644000004100000410000000415015142377631017266 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").reject { |f| f.start_with?("test/") } spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.require_paths = ["lib"] # As of 0.1.1 spec.required_ruby_version = ">= 2.0" spec.add_dependency "fog-core", "~> 2.5" spec.add_dependency "fog-json", "~> 1.2" spec.add_dependency "fog-xml", "~> 0.1.0" spec.add_dependency "google-apis-storage_v1", [">= 0.19", "< 1"] spec.add_dependency "google-apis-iamcredentials_v1", "~> 0.15" spec.add_dependency "google-apis-compute_v1", "~> 0.53" spec.add_dependency "google-apis-monitoring_v3", "~> 0.37" spec.add_dependency "google-apis-dns_v1", "~> 0.28" spec.add_dependency "google-apis-pubsub_v1", "~> 0.30" spec.add_dependency "google-apis-sqladmin_v1beta4", "~> 0.38" spec.add_dependency "google-cloud-env", ">= 1.2", "< 3.0" spec.add_dependency "addressable", ">= 2.7.0" # Debugger # Locked because pry-byebug is broken with 13+ # see: https://github.com/deivid-rodriguez/pry-byebug/issues/343 spec.add_development_dependency "pry", "= 0.16.0" # Testing gems spec.add_development_dependency "retriable" spec.add_development_dependency "rake" spec.add_development_dependency "minitest" spec.add_development_dependency "minitest-mock" 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.29.3/.fog.example0000644000004100000410000000200615142377631016100 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.29.3/README.md0000644000004100000410000002145515142377631015162 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://github.com/fog/fog-google/actions/workflows/unit.yml/badge.svg)](https://github.com/fog/fog-google/actions/workflows/unit.yml) [![codecov](https://codecov.io/gh/fog/fog-google/branch/master/graph/badge.svg)](https://codecov.io/gh/fog/fog-google) ![Dependabot Status](https://flat.badgen.net/github/dependabot/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.7+ See [supported ruby versions](#supported-ruby-versions) for more info. See **[MIGRATING.md](MIGRATING.md)** for migration between major versions. # Sponsors We're proud to be sponsored by MeisterLabs who are generously funding our CI stack. A small message from them: *"As extensive users of fog-google we are excited to help! Meister is the company behind the productivity tools [MindMeister](https://www.mindmeister.com/), [MeisterTask](https://www.meistertask.com), and [MeisterNote](https://www.meisternote.com/). We are based in Vienna, Austria and we have a very talented international team who build our products on top of Ruby on Rails, Elixir, React and Redux. We are constantly looking for great talent in Engineering, so If you feel like taking on a new Ruby or Elixir challenge. get in touch, open jobs can be found [here](https://www.meisterlabs.com/jobs/)."* # Usage ## 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::Google::Storage` 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::Google::Compute`) 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::Google::Compute.new(:google_project => "my-project", :google_application_default => true) => # connection.servers => [ require 'fog/google' => true [2] pry(main)> connection = Fog::Google::Compute.new [3] pry(main)> connection.servers => [ "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.29.3/examples/storage.rb0000644000004100000410000000271615142377631017511 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::Google::Storage.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.29.3/examples/monitoring/0000755000004100000410000000000015142377631017677 5ustar www-datawww-datafog-google-1.29.3/examples/monitoring/timeseries_collection.rb0000644000004100000410000000252715142377631024616 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.29.3/examples/monitoring/metric_descriptors.rb0000644000004100000410000000155315142377631024134 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.29.3/examples/monitoring/monitored_resource_descriptors.rb0000644000004100000410000000162215142377631026555 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.29.3/examples/l7_load_balance.rb0000644000004100000410000000572415142377631021035 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.29.3/examples/load-balance.rb0000644000004100000410000000517115142377631020345 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-11-bullseye-v20220920" ) 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.29.3/examples/create_instance_and_attach_disk_later.rb0000644000004100000410000000554415142377631025545 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) ZONE = "us-central1-f" PROJECT = Fog.credentials[:google_project] 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 => ZONE, :source_image => "debian-11-bullseye-v20220920" ) p "Creating a second disk" attached_disk = connection.disks.create( :name => "fog-smoke-test-#{Time.now.to_i}", :size_gb => 10, :zone => ZONE ) 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, 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 => ZONE, # 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 "Attach second disk to the running server" device_name = "fog-smoke-test-device-#{Time.now.to_i}" # See https://github.com/fog/fog-google/blob/master/lib/fog/google/compute/models/disk.rb#L75-L107 # See https://github.com/fog/fog-google/blob/master/lib/fog/google/compute/models/server.rb#L35-L50 config_hash = { :device_name => device_name, :source => "https://www.googleapis.com/compute/v1/projects/#{PROJECT}/zones/#{ZONE}/disks/#{attached_disk.name}" } raise "Could not attach second disk" unless connection.attach_disk(server.name, ZONE, config_hash) p "Waiting for disk to be attached" attached_disk.wait_for { !users.nil? && users != [] } p "Detach second disk" raise "Could not detach second disk" unless connection.detach_disk(server.name, ZONE, device_name) p "Waiting for second disk to be detached" attached_disk.wait_for { users.nil? || users == [] } p "Deleting server" raise "Could not delete server." unless server.destroy p "Destroying second disk" raise "Could not delete second disk." unless attached_disk.destroy p "Waiting for second disk to be destroyed" begin rc = attached_disk.wait_for { status.nil? || status == "DELETING" } rescue StandardError => e if e.message !~ /not found/ && e.message !~ /notFound/ raise e end end end example fog-google-1.29.3/examples/create_instance.rb0000644000004100000410000000440615142377631021172 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-11-bullseye-v20220920" ) 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.29.3/examples/dns/0000755000004100000410000000000015142377631016276 5ustar www-datawww-datafog-google-1.29.3/examples/dns/zones.rb0000644000004100000410000000217615142377631017767 0ustar www-datawww-datadef test connection = Fog::Google::DNS.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.29.3/examples/dns/project.rb0000644000004100000410000000025515142377631020273 0ustar www-datawww-datadef test connection = Fog::Google::DNS.new puts "Get the Project limits..." puts "-------------------------" connection.projects.get(Fog::DNS[:google].project) end fog-google-1.29.3/examples/precreated_client.rb0000644000004100000410000000134715142377631021520 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.29.3/examples/create_instance_with_attached_disk.rb0000644000004100000410000000332115142377631025067 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-11-bullseye-v20220920" ) 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.29.3/examples/get_list_images.rb0000644000004100000410000000303415142377631021176 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-11-bullseye-v20220920") 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.29.3/examples/network.rb0000644000004100000410000000320615142377631017531 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-11-bullseye-v20220920" ) 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.29.3/examples/sql/0000755000004100000410000000000015142377631016311 5ustar www-datawww-datafog-google-1.29.3/examples/sql/operations.rb0000644000004100000410000000132715142377631021024 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) 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) fog-google-1.29.3/examples/sql/ssl_certs.rb0000644000004100000410000000201515142377631020635 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) connection = Fog::Google::SQL.new puts "Create a Instance..." puts "--------------------" instance = connection.instances.create(:name => Fog::Mock.random_letters(16), :tier => "db-n1-standard-1") 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 fog-google-1.29.3/examples/sql/tiers.rb0000644000004100000410000000047515142377631017772 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) connection = Fog::Google::SQL.new puts "Listing all Tiers..." puts "--------------------" connection.tiers fog-google-1.29.3/examples/sql/instances.rb0000644000004100000410000000203415142377631020624 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) connection = Fog::Google::SQL.new puts "Create a Instance..." puts "--------------------" instance = connection.instances.create(:name => Fog::Mock.random_letters(16), :tier => "db-n1-standard-1") 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 fog-google-1.29.3/examples/sql/flags.rb0000644000004100000410000000047515142377631017740 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) connection = Fog::Google::SQL.new puts "Listing all Flags..." puts "--------------------" connection.flags fog-google-1.29.3/examples/image_create.rb0000644000004100000410000000115415142377631020445 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.29.3/examples/storage_json.rb0000644000004100000410000000226215142377631020536 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::Google::Storage.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.29.3/examples/pubsub/0000755000004100000410000000000015142377631017012 5ustar www-datawww-datafog-google-1.29.3/examples/pubsub/subscriptions.rb0000644000004100000410000000314515142377631022251 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.29.3/examples/pubsub/topics.rb0000644000004100000410000000154715142377631020647 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.29.3/examples/bootstrap.rb0000644000004100000410000000160515142377631020056 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.29.3/examples/metadata.rb0000644000004100000410000000211415142377631017615 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-11-bullseye-v20220920" ) 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.29.3/examples/get_list_snapshots.rb0000644000004100000410000000147215142377631021757 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.29.3/.ruby-gemset0000644000004100000410000000001315142377631016132 0ustar www-datawww-datafog-google fog-google-1.29.3/.ruby-version0000644000004100000410000000000615142377631016335 0ustar www-datawww-data3.2.2 fog-google-1.29.3/.rubocop.yml0000644000004100000410000001745215142377631016157 0ustar www-datawww-data# Fog custom enforced styles Layout/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_ ForbiddenPrefixes: - 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/SuppressedException: 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.29.3/CHANGELOG.md0000644000004100000410000004542215142377631015514 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). ## 1.29.3 - #656 Fix IAM credentials not setting universe domain properly ## 1.29.2 - #654 Fix missing host attribute and update storage XML driver to support universe domains ## 1.29.1 ### User-facing - #653 Ensure universe domain is applied to all services ## 1.29.0 ### User-facing - #652 Replace google_json_root_url with universe_domain ## 1.28.0 ### User-facing - #650 add support for custom storage endpoints ### Fixed ### Development changes ## 1.27.0 ### User-facing ### Fixed - #648 raise exception if disk quota exceeded [rchekaluk] ### Development changes - #647 bump actions/checkout from 5 to 6 [dependabot] - #649 bump pry from = 0.15.2 to = 0.16.0 [dependabot] ## 1.26.0 ### User-facing #### Fixed - #632 remove unused files from package [temikus] - #643 update disk attachment method to use new attached_disk_obj method [geemus] - #644 improve mock bucket name regex validation [geemus] - #646 fix frozen string literal warnings in storage [krororo] ### Development changes #### Added - #645 add ruby 3.3 and 3.4 to CI test matrix [krororo] #### Fixed - #641 Updated actions/checkout from 4 to 5 [dependabot] - #642 Updated actions/stale from 9 to 10 [dependabot] - remove stale workflow [geemus] ## 1.25.0 ### User-facing fog-core v2.2 and up now requires `Fog::Google:` instead of `Fog::::Google`. There are shims in place that will provide backwards compatibility for the latter with a deprecation warning, but you should update your code accordingly. The next major release will drop support of the old format. - #636 Support fog-core 2.5 and up [stanhu] ## 1.24.1 ### User-facing #### Fixed - #629 Fix IAM scope for storage requests [stanhu] ## 1.24.0 ### User-facing #### Added - #613 Spruce up attaching and detaching disks on running servers [rchekaluk] - #621 Added support for discard_local_ssd when stopping an instance [rchekaluk] ### Development changes #### Added - #618 Deprecated Ruby-2.0 support [temikus] - #624 Migrated the Integration tests to new ARC runners [temikus] - #625 Fixed 'Ostruct' errors in storage tests [temikus] - #627 Added concurrency groups to integration test workfows [temikus] #### Fixed - #604 Updated pry requirement from = 0.13.0 to = 0.14.2 [dependabot] - #619 Updated google-cloud-env requirement from ~> 1.2 to >= 1.2, < 3.0 [dependabot] - #620 Bump actions/stale from 8 to 9 [dependabot] - #622 Updated fog-core requirement from < 2.3 to < 2.5 [dependabot] ## 1.23.0 ### User-facing #### Fixed - #609 Fixed missing paging on all models [agrare] - #608 Fixed `Fog::Compute::Google::Servers#all` paging [agrare] ### Development changes #### Fixed - #606 Use `Minitest::Test` instead of `MiniTest::Test` [chubchenko] - #605 Bump actions/checkout from 3 to 4 [dependabot] - #602 Bump actions/stale from 6 to 8 [dependabot] ## 1.22.0 ### User-facing #### Added - #600 - Add uniform attr to inserting file [cwjenkins] ### Development changes #### Fixed - #601 Remove deprecated ruby versions from unit tests [temikus] ## 1.21.1 ### User-facing #### Fixed - \#597 loosen dependencies to avoid conflict ### Development changes #### Fixed - bump actions/checkout from 2.4.0 to 3.1.0 - fixes and refinements for integration tests ## 1.21.0 ### User-facing #### Fixed - \#592 use Addressable for escaping paths when generating urls - test workflow refinements ### Development changes #### Fixed - bump actions/checkout from 2.4.0 to 3.1.0 - fixes and refinements for integration tests ## 1.20.0 ### User-facing #### Fixed - update google client dependencies - \#591 only create new RSA keys if needed for faster signing ### Development changes #### Fixed - bump actions/checkout from 2.4.0 to 3.1.0 - fixes and refinements for integration tests ## 1.19.0 ### User-facing #### Fixed - \#561 Add ruby 3.1 to testing - \#566 remove execute permission from network.rb - \#571 replace Proc.new usage for Ruby 3 ## 1.18.0 ### User-facing #### Fixed - \#556 Correct conflicting Ruby version info in readme [gdubicki] - \#557 Update current images projects list [gdubicki] - \#558 Fix page iteration when using #files with block [jgigault] - \#562 Loosen fog-core dependency ## 1.17.0 ### User-facing #### Added - \#550 Add support for instance display device [dcode] ## 1.16.1 ### User-facing #### Fixed - \#545 Avoid duplicate GET requests when retrieving body [stanhu] - \#547 Remove exec bit from non_scripts [kbrock] ## 1.16.0 ### User-facing #### Fixed - \#540 Bring back integration tests for Fog-Google and fix an array of small bugs/regressions [temikus] ### Development changes #### Added - \#532 Add Truffleruby head to CI [gogainda] ## 1.15.0 ### User-facing #### Fixed - \#534 Fix get_object not working with binary files [stanhu] ## 1.14.0 ### User-facing #### Added - \#520 Support passing object properties to #copy_object [mshibuya] #### Fixed - \#530 Unescape slashes in urls [krokodaxl] - \#528 Fix Ruby 3.0 kwargs error in `#copy_object` [deeeki] - \#521 Unlink file temp file immediately [stanhu] - \#527 \#523 Fix Ruby 3.0 kwargs failures [stanhu] ### Development changes #### Fixed - \#525 - Bump actions/checkout from 2 to 2.3.4 - \#524 - Bump actions/stale from 3 to 3.0.18 ## 1.13.0 ### User-facing ### Fixed fix deprecated URI.escape usage to support Ruby 3.0 fix apply_client_options def to support Ruby 3.0 ### Development Changes Add github actions config and dependabot Drop travis usage ### Added ## 1.12.1 ### User-facing #### Fixed \#513 - support passing other request options `StorageJSON#copy_object` [yosiat] ### Development changes #### Added \#514 - Update .travis.yml to support PPC architecture testing [nageshlop] ## 1.12.0 ### User-facing #### Added - \#509 Add ShieldedInstanceConfig support to `Server#insert` [lcy0321] #### Fixed - \#508 Fix GoogleXML::File#save incorrectly passing body to headers [stanhu] - \#506 Add Trufferuby head to CI [gogainda] ### Development changes #### Fixed - \#510 Upgrade CI docker image to Ubuntu 18.04 [temikus] ## 1.11.0 ### User-facing #### Added - \#503 - Add fallback URL signing mechanism via IAM SignBlob API [temikus] #### Fixed - \#498 Add `:idempotent` flag to Fog::Storage::GoogleXML::Real#head_object, fixing `Excon::Error::Socket: end of file reached (EOFError)` in certain scenarios, see \#416 [temikus] - \#500 Set default options automatically if missing in `Pubsub#pull_subscription` ### Development changes #### Fixed - \#501 DRY'ed up the retry methods in monitoring tests [temikus] - \#500 Cleanup unneeded constants in Server model, fix flaky PubSub tests [temikus] ## 1.10.0 ### User-facing #### Added - \#480 Add label support to `Disk` model [militarpancho] - \#485 Add a `Server#set_server_machine_type` request [gscho] - \#490 Add RHEL SAP cloud image project [kgaikwad] - \#491 Add `exclude_projects` option to exclude any global project [kgaikwad] - \#495 Add support to perform Windows passwords reset procedure through Fog [dvanbrug] #### Fixed - \#455 Fix metadata format for `Server#add_ssh_key()` [kgaikwad] - \#452 Fix `Address.{associate,disassociate}` methods [temikus] - \#486 Fix `Monitoring#create_time_series` method [temikus] - \#493 Add sync/async support to `Google::SQL::SslCert` model init [temikus] ### Development changes #### Added - \#474 Added a manually-triggered pipeline to build from HEAD [temikus] - \#470 Added tests for `Server#add_ssh_key()` [kgaikwad] - \#461 Added dependabot integration [temikus] - \#458 Add SECURITY.md, outlining the lib security policy [icco] - \#457 Added Ruby 2.6 to travis, switch to default distro [icco] - \#453 Implemented worker-side caching of dependencies between jobs [temikus] - \#452 Increase `Address` model test coverage [temikus] #### Fixed - \#469 Zone/Monitoring test logging/style improvements [icco] - \#465 Stopped counting non-implemented mocks in code coverage [temikus] - \#463 Fixed SQL tests broken by the API change [temikus] - \#476 Re-enabled Stackdriver pagination tests [temikus] - \#488 Tiny fix to ssh key tests to remove a race condition [temikus] - \#493 Removing SQLv1 API support from tests [temikus] ## 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 #### Fixed