pax_global_header00006660000000000000000000000064151425331400014510gustar00rootroot0000000000000052 comment=49e0c62a49fb24610fe5cd7896fd4e6d175dd87b fog-fog-google-4c8ece9/000077500000000000000000000000001514253314000150145ustar00rootroot00000000000000fog-fog-google-4c8ece9/.codecov.yml000066400000000000000000000000371514253314000172370ustar00rootroot00000000000000codecov: bot: fog-google-bot fog-fog-google-4c8ece9/.editorconfig000066400000000000000000000003101514253314000174630ustar00rootroot00000000000000# 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-fog-google-4c8ece9/.fog.example000066400000000000000000000020061514253314000172200ustar00rootroot00000000000000################################################################## # 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-fog-google-4c8ece9/.github/000077500000000000000000000000001514253314000163545ustar00rootroot00000000000000fog-fog-google-4c8ece9/.github/dependabot.yml000066400000000000000000000003171514253314000212050ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "bundler" directory: "/" schedule: interval: "daily" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" fog-fog-google-4c8ece9/.github/scripts/000077500000000000000000000000001514253314000200435ustar00rootroot00000000000000fog-fog-google-4c8ece9/.github/scripts/setup_creds.sh000077500000000000000000000005051514253314000227220ustar00rootroot00000000000000#!/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_compute fog-fog-google-4c8ece9/.github/workflows/integration-compute-instance_groups.yml000066400000000000000000000034741514253314000303420ustar00rootroot00000000000000# 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-fog-google-4c8ece9/.github/workflows/integration-compute-loadbalancing.yml000066400000000000000000000034631514253314000277130ustar00rootroot00000000000000# 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-fog-google-4c8ece9/.github/workflows/integration-compute-networking.yml000066400000000000000000000034601514253314000273210ustar00rootroot00000000000000# 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-networking 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_networking/**' # 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-networking.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-core_networking fog-fog-google-4c8ece9/.github/workflows/integration-monitoring.yml000066400000000000000000000034671514253314000256540ustar00rootroot00000000000000# 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-fog-google-4c8ece9/.github/workflows/integration-pubsub.yml000066400000000000000000000034371514253314000247640ustar00rootroot00000000000000# 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-fog-google-4c8ece9/.github/workflows/integration-sql.yml000066400000000000000000000034151514253314000242570ustar00rootroot00000000000000# 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-fog-google-4c8ece9/.github/workflows/integration-storage.yml000066400000000000000000000035211514253314000251220ustar00rootroot00000000000000# 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-fog-google-4c8ece9/.github/workflows/unit.yml000066400000000000000000000014371514253314000221200ustar00rootroot00000000000000name: 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-fog-google-4c8ece9/.gitignore000066400000000000000000000002571514253314000170100ustar00rootroot00000000000000/.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-fog-google-4c8ece9/.hound.yml000066400000000000000000000000421514253314000167260ustar00rootroot00000000000000ruby: config_file: .rubocop.yml fog-fog-google-4c8ece9/.rubocop.yml000066400000000000000000000174521514253314000172770ustar00rootroot00000000000000# 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-fog-google-4c8ece9/.ruby-gemset000066400000000000000000000000131514253314000172520ustar00rootroot00000000000000fog-google fog-fog-google-4c8ece9/.ruby-version000066400000000000000000000000061514253314000174550ustar00rootroot000000000000003.2.2 fog-fog-google-4c8ece9/CHANGELOG.md000066400000000000000000000455271514253314000166420ustar00rootroot00000000000000# 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.4 - #657 Fix handling of universe domains with service key ## 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 fog-fog-google-4c8ece9/CONTRIBUTING.md000066400000000000000000000161711514253314000172530ustar00rootroot00000000000000# 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-fog-google-4c8ece9/CONTRIBUTORS.md000066400000000000000000000073141514253314000173000ustar00rootroot00000000000000With 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-fog-google-4c8ece9/Gemfile000066400000000000000000000005761514253314000163170ustar00rootroot00000000000000source "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-fog-google-4c8ece9/LICENSE.md000066400000000000000000000022001514253314000164120ustar00rootroot00000000000000The 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-fog-google-4c8ece9/MIGRATING.md000066400000000000000000000000321514253314000166520ustar00rootroot00000000000000## fog-google 1.0 -> 2.0: fog-fog-google-4c8ece9/README.md000066400000000000000000000214551514253314000163020ustar00rootroot00000000000000# 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 => [ "test:travis" fog-fog-google-4c8ece9/SECURITY.md000066400000000000000000000002711514253314000166050ustar00rootroot00000000000000# Security contact information To report a security vulnerability, please contact [Tidelift security](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. fog-fog-google-4c8ece9/examples/000077500000000000000000000000001514253314000166325ustar00rootroot00000000000000fog-fog-google-4c8ece9/examples/backend_services.rb000066400000000000000000000011111514253314000224430ustar00rootroot00000000000000require "rubygems" require "fog" def test connection = Fog::Compute.new(:provider => "google") health = connection.http_health_checks.create(:name => "test-checks") health.wait_for { health.ready? } backend = connection.backend_services.create( :name => "backend-test", :health_checks => [health.self_link], :port => 8080, :timeout_sec => 40, :backends => [{ "group" => "resource_view self_link" }] ) backend.get_health puts connection.backend_services.all backend = connection.backend_services.get("backend-test") backend.get_health end test fog-fog-google-4c8ece9/examples/bootstrap.rb000066400000000000000000000016051514253314000211760ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/create_instance.rb000066400000000000000000000044061514253314000223120ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/create_instance_and_attach_disk_later.rb000066400000000000000000000055441514253314000266650ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/create_instance_with_attached_disk.rb000066400000000000000000000033211514253314000262070ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/dns/000077500000000000000000000000001514253314000174165ustar00rootroot00000000000000fog-fog-google-4c8ece9/examples/dns/project.rb000066400000000000000000000002551514253314000214130ustar00rootroot00000000000000def test connection = Fog::Google::DNS.new puts "Get the Project limits..." puts "-------------------------" connection.projects.get(Fog::DNS[:google].project) end fog-fog-google-4c8ece9/examples/dns/zones.rb000066400000000000000000000021761514253314000211070ustar00rootroot00000000000000def 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-fog-google-4c8ece9/examples/get_list_images.rb000066400000000000000000000030341514253314000223160ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/get_list_snapshots.rb000066400000000000000000000014721514253314000230770ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/image_create.rb000066400000000000000000000011541514253314000215650ustar00rootroot00000000000000def 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-fog-google-4c8ece9/examples/l7_load_balance.rb000066400000000000000000000057241514253314000221550ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/load-balance.rb000066400000000000000000000051711514253314000214650ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/metadata.rb000066400000000000000000000021141514253314000207350ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/monitoring/000077500000000000000000000000001514253314000210175ustar00rootroot00000000000000fog-fog-google-4c8ece9/examples/monitoring/metric_descriptors.rb000066400000000000000000000015531514253314000252540ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/monitoring/monitored_resource_descriptors.rb000066400000000000000000000016221514253314000276750ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/monitoring/timeseries_collection.rb000066400000000000000000000025271514253314000257360ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/network.rb000066400000000000000000000032061514253314000206510ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/precreated_client.rb000066400000000000000000000013471514253314000226400ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/pubsub/000077500000000000000000000000001514253314000201325ustar00rootroot00000000000000fog-fog-google-4c8ece9/examples/pubsub/subscriptions.rb000066400000000000000000000031451514253314000233710ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/pubsub/topics.rb000066400000000000000000000015471514253314000217670ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/sql/000077500000000000000000000000001514253314000174315ustar00rootroot00000000000000fog-fog-google-4c8ece9/examples/sql/flags.rb000066400000000000000000000004751514253314000210600ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/sql/instances.rb000066400000000000000000000020341514253314000217440ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/sql/operations.rb000066400000000000000000000013271514253314000221440ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/sql/ssl_certs.rb000066400000000000000000000020151514253314000217550ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/sql/tiers.rb000066400000000000000000000004751514253314000211120ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/storage.rb000066400000000000000000000027161514253314000206310ustar00rootroot00000000000000# 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-fog-google-4c8ece9/examples/storage_json.rb000066400000000000000000000022621514253314000216560ustar00rootroot00000000000000# 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-fog-google-4c8ece9/fog-google.gemspec000066400000000000000000000041501514253314000204060ustar00rootroot00000000000000lib = 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-fog-google-4c8ece9/lib/000077500000000000000000000000001514253314000155625ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/000077500000000000000000000000001514253314000163355ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/bin/000077500000000000000000000000001514253314000171055ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/bin/google.rb000066400000000000000000000050531514253314000207110ustar00rootroot00000000000000# 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-fog-google-4c8ece9/lib/fog/google.rb000066400000000000000000000047211514253314000201420ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/000077500000000000000000000000001514253314000176115ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/compute.rb000066400000000000000000000213501514253314000216130ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/000077500000000000000000000000001514253314000212655ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/compute/mock.rb000066400000000000000000001537421514253314000225570ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/000077500000000000000000000000001514253314000225505ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/compute/models/address.rb000066400000000000000000000101611514253314000245210ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/addresses.rb000066400000000000000000000046121514253314000250550ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/backend_service.rb000066400000000000000000000046511514253314000262120ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/backend_services.rb000066400000000000000000000011321514253314000263640ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/disk.rb000066400000000000000000000137141514253314000240350ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/disk_type.rb000066400000000000000000000012731514253314000250730ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/disk_types.rb000066400000000000000000000032131514253314000252520ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/disks.rb000066400000000000000000000077141514253314000242230ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/firewall.rb000066400000000000000000000056501514253314000247100ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/firewalls.rb000066400000000000000000000015631514253314000250720ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/forwarding_rule.rb000066400000000000000000000046711514253314000262760ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/forwarding_rules.rb000066400000000000000000000032301514253314000264470ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/global_address.rb000066400000000000000000000031201514253314000260360ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/global_addresses.rb000066400000000000000000000030631514253314000263740ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/global_forwarding_rule.rb000066400000000000000000000045561514253314000276200ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/global_forwarding_rules.rb000066400000000000000000000016371514253314000300000ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/http_health_check.rb000066400000000000000000000060431514253314000265410ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/http_health_checks.rb000066400000000000000000000016451514253314000267270ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/image.rb000066400000000000000000000053031514253314000241600ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/images.rb000066400000000000000000000073121514253314000243450ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/instance_group.rb000066400000000000000000000043711514253314000261220ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/instance_group_manager.rb000066400000000000000000000034071514253314000276130ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/instance_group_managers.rb000066400000000000000000000034741514253314000300020ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/instance_groups.rb000066400000000000000000000050701514253314000263020ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/instance_template.rb000066400000000000000000000027361514253314000266040ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/instance_templates.rb000066400000000000000000000016541514253314000267650ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/machine_type.rb000066400000000000000000000014341514253314000255440ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/machine_types.rb000066400000000000000000000036721514253314000257350ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/network.rb000066400000000000000000000044311514253314000245700ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/networks.rb000066400000000000000000000015551514253314000247570ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/operation.rb000066400000000000000000000124301514253314000250750ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/operations.rb000066400000000000000000000036661514253314000252730ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/project.rb000066400000000000000000000015411514253314000245440ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/projects.rb000066400000000000000000000006541514253314000247330ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/region.rb000066400000000000000000000012731514253314000243630ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/regions.rb000066400000000000000000000015471514253314000245520ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/route.rb000066400000000000000000000032331514253314000242340ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/routes.rb000066400000000000000000000015411514253314000244170ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/server.rb000066400000000000000000000511061514253314000244060ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/compute/models/servers.rb000066400000000000000000000104421514253314000245670ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/snapshot.rb000066400000000000000000000037741514253314000247470ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/snapshots.rb000066400000000000000000000015201514253314000251150ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/ssl_certificate.rb000066400000000000000000000025341514253314000262440ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/ssl_certificates.rb000066400000000000000000000016331514253314000264260ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/subnetwork.rb000066400000000000000000000055221514253314000253040ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/subnetworks.rb000066400000000000000000000032411514253314000254630ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/target_http_proxies.rb000066400000000000000000000016461514253314000272020ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/target_http_proxy.rb000066400000000000000000000042121514253314000266620ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/target_https_proxies.rb000066400000000000000000000016551514253314000273650ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/target_https_proxy.rb000066400000000000000000000062771514253314000270620ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/target_instance.rb000066400000000000000000000036011514253314000262470ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/target_instances.rb000066400000000000000000000034261514253314000264370ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/target_pool.rb000066400000000000000000000133501514253314000254160ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/target_pools.rb000066400000000000000000000032171514253314000256020ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/url_map.rb000066400000000000000000000076441514253314000245470ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/url_maps.rb000066400000000000000000000015551514253314000247250ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/zone.rb000066400000000000000000000010271514253314000240500ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/models/zones.rb000066400000000000000000000015141514253314000242340ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/real.rb000066400000000000000000000014111514253314000225320ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/000077500000000000000000000000001514253314000231405ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/compute/requests/abandon_instances.rb000066400000000000000000000017361514253314000271450ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/add_backend_service_backends.rb000066400000000000000000000007231514253314000312400ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/add_instance_group_instances.rb000066400000000000000000000020721514253314000313650ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/add_server_access_config.rb000066400000000000000000000015641514253314000304570ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/add_target_pool_health_checks.rb000066400000000000000000000015311514253314000314610ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/add_target_pool_instances.rb000066400000000000000000000014251514253314000306650ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/attach_disk.rb000066400000000000000000000007601514253314000257460ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/create_disk_snapshot.rb000066400000000000000000000011161514253314000276600ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_address.rb000066400000000000000000000012611514253314000264340ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_backend_service.rb000066400000000000000000000006651514253314000301250ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_disk.rb000066400000000000000000000013061514253314000257410ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_firewall.rb000066400000000000000000000005711514253314000266170ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_forwarding_rule.rb000066400000000000000000000007221514253314000302010ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_global_address.rb000066400000000000000000000006101514253314000277510ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_global_forwarding_rule.rb000066400000000000000000000006101514253314000315150ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_global_operation.rb000066400000000000000000000007501514253314000303310ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_http_health_check.rb000066400000000000000000000006131514253314000304500ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_image.rb000066400000000000000000000006171514253314000260750ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_instance_group.rb000066400000000000000000000006251514253314000300320ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_instance_group_manager.rb000066400000000000000000000006331514253314000315230ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_instance_template.rb000066400000000000000000000005711514253314000305110ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_network.rb000066400000000000000000000005631514253314000265040ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_region_operation.rb000066400000000000000000000012141514253314000303500ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_route.rb000066400000000000000000000010561514253314000261470ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_server.rb000066400000000000000000000006021514253314000263130ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_server_access_config.rb000066400000000000000000000011001514253314000311530ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_snapshot.rb000066400000000000000000000005711514253314000266510ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_ssl_certificate.rb000066400000000000000000000006261514253314000301560ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_subnetwork.rb000066400000000000000000000016361514253314000272200ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_target_http_proxy.rb000066400000000000000000000006131514253314000305750ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_target_https_proxy.rb000066400000000000000000000006161514253314000307630ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_target_instance.rb000066400000000000000000000007331514253314000301640ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_target_pool.rb000066400000000000000000000007331514253314000273310ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_url_map.rb000066400000000000000000000005631514253314000264520ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/delete_zone_operation.rb000066400000000000000000000011011514253314000300330ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/deprecate_image.rb000066400000000000000000000010651514253314000265650ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/detach_disk.rb000066400000000000000000000006761514253314000257400ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/expand_subnetwork_ip_cidr_range.rb000066400000000000000000000023631514253314000321000ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_address.rb000066400000000000000000000012421514253314000257500ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_backend_service.rb000066400000000000000000000007101514253314000274310ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_backend_service_health.rb000066400000000000000000000012731514253314000307630ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_disk.rb000066400000000000000000000012311514253314000252530ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_disk_type.rb000066400000000000000000000005721514253314000263230ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_firewall.rb000066400000000000000000000005601514253314000261320ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_forwarding_rule.rb000066400000000000000000000007431514253314000275210ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_global_address.rb000066400000000000000000000005771514253314000273020ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_global_forwarding_rule.rb000066400000000000000000000005771514253314000310460ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_global_operation.rb000066400000000000000000000012001514253314000276350ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_http_health_check.rb000066400000000000000000000006021514253314000277630ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_image.rb000066400000000000000000000006631514253314000254130ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_image_from_family.rb000066400000000000000000000014131514253314000277710ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_instance_group.rb000066400000000000000000000006641514253314000273520ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_instance_group_manager.rb000066400000000000000000000006221514253314000310360ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_instance_template.rb000066400000000000000000000005601514253314000300240ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_machine_type.rb000066400000000000000000000007141514253314000267730ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_network.rb000066400000000000000000000005521514253314000260170ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_project.rb000066400000000000000000000005241514253314000257730ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_region.rb000066400000000000000000000005521514253314000256110ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_region_operation.rb000066400000000000000000000011311514253314000276630ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_route.rb000066400000000000000000000007561514253314000254720ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_server.rb000066400000000000000000000005771514253314000256430ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_server_serial_port_output.rb000066400000000000000000000025761514253314000316670ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_snapshot.rb000066400000000000000000000007101514253314000261610ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_ssl_certificate.rb000066400000000000000000000006161514253314000274720ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_subnetwork.rb000066400000000000000000000017271514253314000265360ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_target_http_proxy.rb000066400000000000000000000006021514253314000301100ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_target_https_proxy.rb000066400000000000000000000006051514253314000302760ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_target_instance.rb000066400000000000000000000007221514253314000274770ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_target_pool.rb000066400000000000000000000007221514253314000266440ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_target_pool_health.rb000066400000000000000000000011131514253314000301640ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_url_map.rb000066400000000000000000000005521514253314000257650ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_zone.rb000066400000000000000000000005301514253314000252750ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/get_zone_operation.rb000066400000000000000000000014621514253314000273620ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_address.rb000066400000000000000000000017411514253314000265010ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_backend_service.rb000066400000000000000000000011621514253314000301600ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_disk.rb000066400000000000000000000040641514253314000260070ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_firewall.rb000066400000000000000000000040161514253314000266570ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_forwarding_rule.rb000066400000000000000000000014241514253314000302430ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_global_address.rb000066400000000000000000000012541514253314000300200ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_global_forwarding_rule.rb000066400000000000000000000013051514253314000315610ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_http_health_check.rb000066400000000000000000000010541514253314000305120ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_image.rb000066400000000000000000000010151514253314000261300ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_instance_group.rb000066400000000000000000000021111514253314000300640ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_instance_group_manager.rb000066400000000000000000000021221514253314000315600ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_instance_template.rb000066400000000000000000000024231514253314000305510ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_network.rb000066400000000000000000000010041514253314000265350ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_route.rb000066400000000000000000000021041514253314000262040ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_server.rb000066400000000000000000000111101514253314000263510ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_ssl_certificate.rb000066400000000000000000000013331514253314000302140ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_subnetwork.rb000066400000000000000000000047151514253314000272630ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_target_http_proxy.rb000066400000000000000000000012131514253314000306340ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_target_https_proxy.rb000066400000000000000000000014741514253314000310300ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_target_instance.rb000066400000000000000000000012261514253314000302240ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_target_pool.rb000066400000000000000000000011241514253314000273660ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/insert_url_map.rb000066400000000000000000000022341514253314000265110ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/invalidate_url_map_cache.rb000066400000000000000000000011051514253314000304440ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_addresses.rb000066400000000000000000000014031514253314000264730ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_aggregated_addresses.rb000066400000000000000000000012641514253314000306520ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_aggregated_disk_types.rb000066400000000000000000000011471514253314000310530ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_aggregated_disks.rb000066400000000000000000000020031514253314000300020ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_aggregated_forwarding_rules.rb000066400000000000000000000011741514253314000322510ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_aggregated_instance_group_managers.rb000066400000000000000000000012601514253314000335660ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_aggregated_instance_groups.rb000066400000000000000000000006431514253314000321000ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_aggregated_machine_types.rb000066400000000000000000000011601514253314000315200ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_aggregated_servers.rb000066400000000000000000000011321514253314000303600ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_aggregated_subnetworks.rb000066400000000000000000000023031514253314000312560ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_aggregated_target_instances.rb000066400000000000000000000012261514253314000322300ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_aggregated_target_pools.rb000066400000000000000000000012041514253314000313710ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_backend_services.rb000066400000000000000000000012511514253314000300110ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_disk_types.rb000066400000000000000000000011341514253314000266750ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_disks.rb000066400000000000000000000014141514253314000256350ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_firewalls.rb000066400000000000000000000012001514253314000265010ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_forwarding_rules.rb000066400000000000000000000012131514253314000300710ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_global_addresses.rb000066400000000000000000000015261514253314000300210ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_global_forwarding_rules.rb000066400000000000000000000011541514253314000314150ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_global_operations.rb000066400000000000000000000013011514253314000302160ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_http_health_checks.rb000066400000000000000000000011141514253314000303410ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_images.rb000066400000000000000000000011501514253314000257620ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_instance_group_instances.rb000066400000000000000000000010121514253314000316010ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_instance_group_managers.rb000066400000000000000000000011701514253314000314140ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_instance_groups.rb000066400000000000000000000005551514253314000277300ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_instance_templates.rb000066400000000000000000000011441514253314000304020ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_machine_types.rb000066400000000000000000000013771514253314000273600ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_networks.rb000066400000000000000000000012041514253314000263710ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_region_operations.rb000066400000000000000000000016041514253314000302470ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_regions.rb000066400000000000000000000010521514253314000261640ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_routes.rb000066400000000000000000000013471514253314000260460ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_servers.rb000066400000000000000000000011341514253314000262100ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_snapshots.rb000066400000000000000000000011331514253314000265400ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_ssl_certificates.rb000066400000000000000000000011501514253314000300430ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_subnetworks.rb000066400000000000000000000030021514253314000271010ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_target_http_proxies.rb000066400000000000000000000013041514253314000306140ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_target_https_proxies.rb000066400000000000000000000011401514253314000307750ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_target_instances.rb000066400000000000000000000013061514253314000300550ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_target_pools.rb000066400000000000000000000012001514253314000272130ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_url_maps.rb000066400000000000000000000012011514253314000263340ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_zone_operations.rb000066400000000000000000000014261514253314000277410ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/list_zones.rb000066400000000000000000000010741514253314000256600ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/patch_firewall.rb000066400000000000000000000013421514253314000264510ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/patch_url_map.rb000066400000000000000000000007251514253314000263070ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/recreate_instances.rb000066400000000000000000000017451514253314000273350ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/remove_instance_group_instances.rb000066400000000000000000000020761514253314000321360ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/remove_target_pool_health_checks.rb000066400000000000000000000015011514253314000322230ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/remove_target_pool_instance.rb000066400000000000000000000014371514253314000312520ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/remove_target_pool_instances.rb000066400000000000000000000014331514253314000314310ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/reset_server.rb000066400000000000000000000006051514253314000261760ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/reset_windows_password.rb000066400000000000000000000130221514253314000303010ustar00rootroot00000000000000# 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_common_instance_metadata.rb000066400000000000000000000012361514253314000313560ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_forwarding_rule_target.rb000066400000000000000000000011531514253314000310770ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_global_forwarding_rule_target.rb000066400000000000000000000010341514253314000324150ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_instance_template.rb000066400000000000000000000020471514253314000300420ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_server_disk_auto_delete.rb000066400000000000000000000012431514253314000312320ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_server_machine_type.rb000066400000000000000000000012671514253314000304010ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_server_metadata.rb000066400000000000000000000025571514253314000275170ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_server_scheduling.rb000066400000000000000000000015761514253314000300640ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_server_tags.rb000066400000000000000000000011141514253314000266610ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_snapshot_labels.rb000066400000000000000000000011161514253314000275200ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_subnetwork_private_ip_google_access.rb000066400000000000000000000032211514253314000336400ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_target_http_proxy_url_map.rb000066400000000000000000000011351514253314000316450ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_target_https_proxy_ssl_certificates.rb000066400000000000000000000011541514253314000337200ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_target_https_proxy_url_map.rb000066400000000000000000000011401514253314000320240ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/set_target_pool_backup.rb000066400000000000000000000014511514253314000302050ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/start_server.rb000066400000000000000000000006051514253314000262110ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/stop_server.rb000066400000000000000000000007011514253314000260360ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/update_firewall.rb000066400000000000000000000027531514253314000266430ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/update_http_health_check.rb000066400000000000000000000011011514253314000304610ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/update_url_map.rb000066400000000000000000000013131514253314000264640ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/compute/requests/validate_url_map.rb000066400000000000000000000011071514253314000267740ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns.rb000066400000000000000000000026641514253314000207320ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/000077500000000000000000000000001514253314000203755ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/dns/mock.rb000066400000000000000000000013021514253314000216470ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/models/000077500000000000000000000000001514253314000216605ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/dns/models/change.rb000066400000000000000000000016411514253314000234340ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/models/changes.rb000066400000000000000000000024201514253314000236130ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/models/project.rb000066400000000000000000000047771514253314000236720ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/models/projects.rb000066400000000000000000000011141514253314000240330ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/models/record.rb000066400000000000000000000064471514253314000234760ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/models/records.rb000066400000000000000000000030721514253314000236500ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/models/zone.rb000066400000000000000000000037231514253314000231650ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/models/zones.rb000066400000000000000000000016131514253314000233440ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/real.rb000066400000000000000000000010041514253314000216400ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/requests/000077500000000000000000000000001514253314000222505ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/dns/requests/create_change.rb000066400000000000000000000013341514253314000253460ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/requests/create_managed_zone.rb000066400000000000000000000013371514253314000265530ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/dns/requests/delete_managed_zone.rb000066400000000000000000000010101514253314000265360ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/requests/get_change.rb000066400000000000000000000010321514253314000246550ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/requests/get_managed_zone.rb000066400000000000000000000010111514253314000260540ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/requests/get_project.rb000066400000000000000000000011211514253314000250750ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/requests/list_changes.rb000066400000000000000000000014071514253314000252420ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/requests/list_managed_zones.rb000066400000000000000000000013541514253314000264450ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/dns/requests/list_resource_record_sets.rb000066400000000000000000000015321514253314000300540ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/mock.rb000066400000000000000000000003211514253314000210630ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/models/000077500000000000000000000000001514253314000210745ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/models/monitoring/000077500000000000000000000000001514253314000232615ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/models/monitoring/metric_descriptor.rb000066400000000000000000000011761514253314000273340ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/monitoring/metric_descriptors.rb000066400000000000000000000031061514253314000275120ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/monitoring/monitored_resource_descriptor.rb000066400000000000000000000010421514253314000317500ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/monitoring/monitored_resource_descriptors.rb000066400000000000000000000026501514253314000321410ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/monitoring/timeseries.rb000066400000000000000000000010461514253314000257600ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/monitoring/timeseries_collection.rb000066400000000000000000000046241514253314000302000ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/pubsub/000077500000000000000000000000001514253314000223745ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/models/pubsub/received_message.rb000066400000000000000000000023171514253314000262160ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/pubsub/subscription.rb000066400000000000000000000070421514253314000254500ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/models/pubsub/subscriptions.rb000066400000000000000000000017461514253314000256400ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/pubsub/topic.rb000066400000000000000000000040621514253314000240410ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/pubsub/topics.rb000066400000000000000000000015521514253314000242250ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/sql/000077500000000000000000000000001514253314000216735ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/models/sql/backup_run.rb000066400000000000000000000017451514253314000243600ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/sql/backup_runs.rb000066400000000000000000000022221514253314000245320ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/sql/flag.rb000066400000000000000000000012041514253314000231260ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/sql/flags.rb000066400000000000000000000006741514253314000233230ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/sql/instance.rb000066400000000000000000000315201514253314000240250ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/sql/instances.rb000066400000000000000000000021741514253314000242130ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/sql/operation.rb000066400000000000000000000042541514253314000242250ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/sql/operations.rb000066400000000000000000000031531514253314000244050ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/sql/ssl_cert.rb000066400000000000000000000057531514253314000240500ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/sql/ssl_certs.rb000066400000000000000000000032211514253314000242170ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/sql/tier.rb000066400000000000000000000006671514253314000231740ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/sql/tiers.rb000066400000000000000000000006741514253314000233550ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/sql/user.rb000066400000000000000000000030511514253314000231750ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/models/sql/users.rb000066400000000000000000000007211514253314000233610ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/monitoring.rb000066400000000000000000000031761514253314000223320ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/monitoring/000077500000000000000000000000001514253314000217765ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/monitoring/mock.rb000066400000000000000000000013521514253314000232550ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/monitoring/real.rb000066400000000000000000000011041514253314000232420ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/parsers/000077500000000000000000000000001514253314000212705ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/parsers/storage.rb000066400000000000000000000012251514253314000232610ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/parsers/storage/000077500000000000000000000000001514253314000227345ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/parsers/storage/access_control_list.rb000066400000000000000000000022141514253314000273140ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/parsers/storage/copy_object.rb000066400000000000000000000006111514253314000255570ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/parsers/storage/get_bucket.rb000066400000000000000000000032461514253314000254020ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/parsers/storage/get_bucket_logging.rb000066400000000000000000000021341514253314000271030ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/parsers/storage/get_bucket_object_versions.rb000066400000000000000000000051711514253314000306570ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/parsers/storage/get_bucket_versioning.rb000066400000000000000000000006601514253314000276420ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/parsers/storage/get_request_payment.rb000066400000000000000000000004631514253314000273500ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/parsers/storage/get_service.rb000066400000000000000000000012611514253314000255600ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/pubsub.rb000066400000000000000000000034601514253314000214410ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/pubsub/000077500000000000000000000000001514253314000211115ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/pubsub/mock.rb000066400000000000000000000012411514253314000223650ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/pubsub/real.rb000066400000000000000000000011101514253314000223520ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/000077500000000000000000000000001514253314000214645ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/requests/monitoring/000077500000000000000000000000001514253314000236515ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/requests/monitoring/create_metric_descriptor.rb000066400000000000000000000051511514253314000312440ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/monitoring/create_timeseries.rb000066400000000000000000000016471514253314000277020ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/monitoring/delete_metric_descriptor.rb000066400000000000000000000006761514253314000312520ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/monitoring/get_metric_descriptor.rb000066400000000000000000000006651514253314000305650ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/monitoring/get_monitored_resource_descriptor.rb000066400000000000000000000007321514253314000332040ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/monitoring/list_metric_descriptors.rb000066400000000000000000000013021514253314000311310ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/monitoring/list_monitored_resource_descriptors.rb000066400000000000000000000016621514253314000335660ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/monitoring/list_timeseries.rb000066400000000000000000000034461514253314000274110ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/pubsub/000077500000000000000000000000001514253314000227645ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/requests/pubsub/acknowledge_subscription.rb000066400000000000000000000016041514253314000304010ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/pubsub/create_subscription.rb000066400000000000000000000030141514253314000273560ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/pubsub/create_topic.rb000066400000000000000000000011721514253314000257530ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/pubsub/delete_subscription.rb000066400000000000000000000011071514253314000273560ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/pubsub/delete_topic.rb000066400000000000000000000010011514253314000257410ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/pubsub/get_subscription.rb000066400000000000000000000011031514253314000266670ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/pubsub/get_topic.rb000066400000000000000000000007721514253314000252740ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/pubsub/list_subscriptions.rb000066400000000000000000000015111514253314000272510ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/pubsub/list_topics.rb000066400000000000000000000014461514253314000256520ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/pubsub/publish_topic.rb000066400000000000000000000015461514253314000261630ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/pubsub/pull_subscription.rb000066400000000000000000000031461514253314000270750ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/000077500000000000000000000000001514253314000222635ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/requests/sql/clone_instance.rb000066400000000000000000000025121514253314000255740ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/delete_backup_run.rb000066400000000000000000000010611514253314000262610ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/delete_instance.rb000066400000000000000000000007721514253314000257440ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/delete_ssl_cert.rb000066400000000000000000000011571514253314000257540ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/delete_user.rb000066400000000000000000000010511514253314000251050ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/export_instance.rb000066400000000000000000000032331514253314000260160ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/get_backup_run.rb000066400000000000000000000011201514253314000255720ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/get_instance.rb000066400000000000000000000010301514253314000252450ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/get_operation.rb000066400000000000000000000010371514253314000254500ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/get_ssl_cert.rb000066400000000000000000000011211514253314000252600ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/import_instance.rb000066400000000000000000000026101514253314000260050ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/insert_backup_run.rb000066400000000000000000000013231514253314000263240ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/insert_instance.rb000066400000000000000000000014331514253314000260010ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/insert_ssl_cert.rb000066400000000000000000000013751514253314000260200ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/insert_user.rb000066400000000000000000000011231514253314000251470ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/list_backup_runs.rb000066400000000000000000000014351514253314000261620ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/list_flags.rb000066400000000000000000000010321514253314000247330ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/list_instances.rb000066400000000000000000000013501514253314000256310ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/list_operations.rb000066400000000000000000000014661514253314000260350ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/list_ssl_certs.rb000066400000000000000000000010221514253314000256370ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/list_tiers.rb000066400000000000000000000007341514253314000247750ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/list_users.rb000066400000000000000000000007761514253314000250160ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/reset_instance_ssl_config.rb000066400000000000000000000014321514253314000300240ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/restart_instance.rb000066400000000000000000000007771514253314000261730ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/restore_instance_backup.rb000066400000000000000000000016421514253314000275070ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/update_instance.rb000066400000000000000000000015671514253314000257670ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/requests/sql/update_user.rb000066400000000000000000000012071514253314000251300ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/shared.rb000066400000000000000000000257161514253314000214170ustar00rootroot00000000000000require "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) ::Google::Auth.get_application_default(options[:google_api_scope_url], google_options) 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) ::Google::Auth::ServiceAccountCredentials.make_creds( :json_key_io => StringIO.new(json_key), :scope => options[:google_api_scope_url] ) end # Helper method to sort out deprecated and missing auth options # # @param [Hash] options - client options hash def validate_client_options(options) # Users can no longer provide their own clients due to rewrite of auth # in https://github.com/google/google-api-ruby-client/ version 0.9. if options[:google_client] raise ArgumentError.new("Deprecated argument no longer works: google_client") end # They can also no longer use pkcs12 files, because Google's new auth # library doesn't support them either. if options[:google_key_location] raise ArgumentError.new("Deprecated auth method no longer works: google_key_location") end if options[:google_key_string] raise ArgumentError.new("Deprecated auth method no longer works: google_key_string") end # Google client email option is no longer needed if options[:google_client_email] Fog::Logger.deprecation("Argument no longer needed for auth: google_client_email") end # Validate required arguments unless options[:google_api_scope_url] raise ArgumentError.new("Missing required arguments: google_api_scope_url") end end # Helper method to checks whether the necessary fields are present in # JSON key credentials # # @param [String] json_key - Google json auth key string def validate_json_credentials(json_key) json_key_hash = Fog::JSON.decode(json_key) unless json_key_hash.key?("client_email") || json_key_hash.key?("private_key") raise ArgumentError.new("Invalid Google JSON key") end end end end end fog-fog-google-4c8ece9/lib/fog/google/sql.rb000066400000000000000000000045221514253314000207400ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/sql/000077500000000000000000000000001514253314000204105ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/sql/mock.rb000066400000000000000000000015611514253314000216710ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/sql/real.rb000066400000000000000000000010621514253314000216570ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage.rb000066400000000000000000000016621514253314000216070ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/000077500000000000000000000000001514253314000212555ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/storage/storage_json.rb000066400000000000000000000045301514253314000243010ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/000077500000000000000000000000001514253314000237525ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/storage/storage_json/mock.rb000066400000000000000000000021541514253314000252320ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/models/000077500000000000000000000000001514253314000252355ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/storage/storage_json/models/directories.rb000066400000000000000000000026311514253314000301000ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/models/directory.rb000066400000000000000000000030771514253314000275750ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/models/file.rb000066400000000000000000000106521514253314000265050ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/models/files.rb000066400000000000000000000042051514253314000266650ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/real.rb000066400000000000000000000170771514253314000252360ustar00rootroot00000000000000# 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/000077500000000000000000000000001514253314000256255ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/copy_object.rb000066400000000000000000000032121514253314000304500ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/delete_bucket.rb000066400000000000000000000010521514253314000307470ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/delete_object.rb000066400000000000000000000012501514253314000307400ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/delete_object_url.rb000066400000000000000000000027631514253314000316340ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/get_bucket.rb000066400000000000000000000030651514253314000302720ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/get_bucket_acl.rb000066400000000000000000000020541514253314000311060ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/get_object.rb000066400000000000000000000073521514253314000302660ustar00rootroot00000000000000require "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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/get_object_acl.rb000066400000000000000000000024361514253314000311030ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/get_object_http_url.rb000066400000000000000000000021661514253314000322050ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/get_object_https_url.rb000066400000000000000000000022021514253314000323570ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/get_object_metadata.rb000066400000000000000000000021561514253314000321230ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/get_object_url.rb000066400000000000000000000015721514253314000311460ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/list_bucket_acl.rb000066400000000000000000000013671514253314000313100ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/list_buckets.rb000066400000000000000000000015251514253314000306500ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/list_object_acl.rb000066400000000000000000000020151514253314000312700ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/list_objects.rb000066400000000000000000000030521514253314000306360ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/put_bucket.rb000066400000000000000000000026431514253314000303240ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/put_bucket_acl.rb000066400000000000000000000017651514253314000311470ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/put_object.rb000066400000000000000000000105021514253314000303060ustar00rootroot00000000000000# 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/put_object_acl.rb000066400000000000000000000023161514253314000311310ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/requests/put_object_url.rb000066400000000000000000000036311514253314000311750ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_json/utils.rb000066400000000000000000000035661514253314000254510ustar00rootroot00000000000000# 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml.rb000066400000000000000000000022121514253314000241230ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/000077500000000000000000000000001514253314000236015ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/mock.rb000066400000000000000000000063141514253314000250630ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/models/000077500000000000000000000000001514253314000250645ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/models/directories.rb000066400000000000000000000021001514253314000277160ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/models/directory.rb000066400000000000000000000034411514253314000274170ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/models/file.rb000066400000000000000000000110451514253314000263310ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/models/files.rb000066400000000000000000000054421514253314000265200ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/real.rb000066400000000000000000000073011514253314000250520ustar00rootroot00000000000000# 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/000077500000000000000000000000001514253314000254545ustar00rootroot00000000000000fog-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/copy_object.rb000066400000000000000000000055361514253314000303120ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/delete_bucket.rb000066400000000000000000000022241514253314000306000ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/delete_object.rb000066400000000000000000000025721514253314000305770ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/delete_object_url.rb000066400000000000000000000027741514253314000314650ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/get_bucket.rb000066400000000000000000000105731514253314000301230ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/get_bucket_acl.rb000066400000000000000000000036201514253314000307350ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/get_object.rb000066400000000000000000000107231514253314000301110ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/get_object_acl.rb000066400000000000000000000046621514253314000307350ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/get_object_http_url.rb000066400000000000000000000022151514253314000320270ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/get_object_https_url.rb000066400000000000000000000022411514253314000322110ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/get_object_url.rb000066400000000000000000000024031514253314000307670ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/get_service.rb000066400000000000000000000025071514253314000303040ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/head_object.rb000066400000000000000000000051761514253314000302410ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/put_bucket.rb000066400000000000000000000050701514253314000301500ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/put_bucket_acl.rb000066400000000000000000000030041514253314000307620ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/put_object.rb000066400000000000000000000073231514253314000301440ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/put_object_acl.rb000066400000000000000000000033031514253314000307550ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/requests/put_object_url.rb000066400000000000000000000030251514253314000310210ustar00rootroot00000000000000module 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-fog-google-4c8ece9/lib/fog/google/storage/storage_xml/utils.rb000066400000000000000000000072371514253314000252770ustar00rootroot00000000000000# 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-fog-google-4c8ece9/lib/fog/google/version.rb000066400000000000000000000001031514253314000216150ustar00rootroot00000000000000module Fog module Google VERSION = "1.29.4".freeze end end fog-fog-google-4c8ece9/tasks/000077500000000000000000000000001514253314000161415ustar00rootroot00000000000000fog-fog-google-4c8ece9/tasks/bundler.rake000066400000000000000000000001511514253314000204350ustar00rootroot00000000000000# This installs the tasks that help with gem creation and # publishing. Bundler::GemHelper.install_tasks fog-fog-google-4c8ece9/tasks/changelog.rake000066400000000000000000000023611514253314000207360ustar00rootroot00000000000000require "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-fog-google-4c8ece9/tasks/console.rake000066400000000000000000000006721514253314000204540ustar00rootroot00000000000000# 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-fog-google-4c8ece9/tasks/lint.rake000066400000000000000000000002641514253314000177550ustar00rootroot00000000000000require "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-fog-google-4c8ece9/tasks/test.rake000066400000000000000000000071151514253314000177700ustar00rootroot00000000000000require "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-fog-google-4c8ece9/test/000077500000000000000000000000001514253314000157735ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/helpers/000077500000000000000000000000001514253314000174355ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/helpers/client_helper.rb000066400000000000000000000036131514253314000226020ustar00rootroot00000000000000## # Helper mixin for tests (especially compute-based ones). Provide access to the # client in use via the #client method to use. module ClientHelper # Check to see if an compute operation is finished. # # @param op [Google::Apis::ComputeV1::Operation] the operation object returned from an api call # @return [Bolean] true if the operation is no longer executing, false # otherwise def operation_finished?(op) region = op.region zone = op.zone name = op.name if zone.nil? result = client.get_region_operation(region, name) else result = client.get_zone_operation(zone, name) end !%w(PENDING RUNNING).include?(result.status) end # Check to see if an SQL operation is finished. # # @param op [Google::Apis::SqladminV1beta4::Operation] the operation object # returned from an SQL Admin api call # @return [Boolean] true if the operation is no longer executing, false # otherwise def sql_operation_finished?(op) result = client.get_operation(op.name) !%w(PENDING RUNNING).include?(result.status) end # Pause execution until an operation (compute or sql) returned # from a passed block is finished. # # @example Pause until server is provisioned # @result = wait_until_complete { client.insert_server(name, zone, opts) } # @yieldreturn The resulting operation object from a block. # @return the result of the operation def wait_until_complete result = yield case result.kind when "compute#operation" region = result.region zone = result.zone Fog.wait_for { operation_finished?(result) } if zone.nil? client.get_region_operation(region, result.name) else client.get_zone_operation(zone, result.name) end when "sql#operation" Fog.wait_for { sql_operation_finished?(result) } client.get_operation(result.name) else result end end end fog-fog-google-4c8ece9/test/helpers/integration_test_helper.rb000066400000000000000000000111061514253314000247020ustar00rootroot00000000000000require "helpers/test_helper" require "helpers/test_collection" require "retriable" # Use :test credentials in ~/.fog for live integration testing # XXX not sure if this will work on Travis CI or not Fog.credential = :test # Enable test debugging, providing additional information in some methods DEBUG = ENV['FOG_TEST_DEBUG'] || false # Helpers TEST_PROJECT = Fog.credentials[:google_project] TEST_ZONE = "us-central1-f".freeze TEST_REGION = "us-central1".freeze TEST_SIZE_GB = 10 TEST_MACHINE_TYPE = "n1-standard-1".freeze TEST_IMAGE = "debian-11-bullseye-v20220920".freeze TEST_IMAGE_PROJECT = "debian-cloud".freeze TEST_IMAGE_FAMILY = "debian-11".freeze # XXX This depends on a public image in gs://fog-test-bucket; there may be a better way to do this # The image was created like so: https://cloud.google.com/compute/docs/images/export-image TEST_RAW_DISK_SOURCE = "https://storage.googleapis.com/fog-test-assets-bucket/fog-test-raw-disk-source.image.tar.gz".freeze TEST_SQL_TIER = "db-n1-standard-1".freeze TEST_SQL_REGION = TEST_REGION # Test certificate/key for SSL Proxy tests, generated via: # $ openssl genrsa -out example.key 2048 # $ openssl req -new -key example.key -out example.csr # ... # Common Name (eg, fully qualified host name) []:example.com # Email Address []:admin@example.com # ... # $ openssl x509 -req -in example.csr -signkey example.key -out example.crt TEST_PEM_CERTIFICATE = <=, NAMES.size * ZONES.size, "Number of all disk type references should be greater or equal to test zones * disk types") end def test_scoped_all subject_list = @subject.all scoped_subject_list = @subject.all(zone: TEST_ZONE) # Assert that whatever .all(scope) returns is a subset of .all assert(scoped_subject_list.all? { |x| subject_list.include? x }, "Output of @subject.all(zone:#{TEST_ZONE}) must be a subset of @subject.all") end def test_get NAMES.each do |name| ZONES.each do |zone| refute_nil @subject.get(name, zone) end end end def test_bad_get assert_nil @subject.get("bad-name") end def test_enumerable assert_respond_to @subject, :each end end fog-fog-google-4c8ece9/test/integration/compute/core_compute/test_disks.rb000066400000000000000000000037621514253314000271670ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/disks_factory" class TestDisks < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].disks @factory = DisksFactory.new(namespaced_name) end def test_create_small disk_config = {:size_gb => 10} disk = @factory.create(disk_config) disk.wait_for { ready? } end def test_create_exceeds_quota disk_config = {:size_gb => 9999} # Must be less than or equal to 65536 err = assert_raises Fog::Errors::Error do disk = @factory.create(disk_config) end assert_match(/Error creating disk.*size.*. Quota.*exceeded. Limit:.*compute.googleapis.com.*in region.*./, err.message) end def test_get_as_configs disk = @factory.create disk.wait_for { ready? } example = disk.get_as_boot_disk config = { :auto_delete => false, :boot => true, :source => disk.self_link, :mode => "READ_WRITE", :type => "PERSISTENT" } assert_equal(example, config) example_with_params = disk.get_as_boot_disk(false, true) config_with_params = { :auto_delete => true, :boot => true, :source => disk.self_link, :mode => "READ_ONLY", :type => "PERSISTENT" } assert_equal(example_with_params, config_with_params) end def test_create_snapshot disk = @factory.create disk.wait_for { ready? } snapshot = disk.create_snapshot("fog-test-snapshot") assert(snapshot.is_a?(Fog::Google::Compute::Snapshot), "Resulting snapshot should be a snapshot object.") assert_raises(ArgumentError) { snapshot.set_labels(%w(bar test)) } snapshot.set_labels(foo: "bar", fog: "test") assert_equal(snapshot.labels[:foo], "bar") assert_equal(snapshot.labels[:fog], "test") # Clean up the snapshot operation = snapshot.destroy operation.wait_for { ready? } end end fog-fog-google-4c8ece9/test/integration/compute/core_compute/test_images.rb000066400000000000000000000020731514253314000273110ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/images_factory" class TestImages < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].images @factory = ImagesFactory.new(namespaced_name) end def test_get_specific_image image = @subject.get(TEST_IMAGE) refute_nil(image, "Images.get(#{TEST_IMAGE}) should not return nil") assert_equal(image.family, TEST_IMAGE_FAMILY) assert_equal(image.project, TEST_IMAGE_PROJECT) end def test_get_specific_image_from_project image = @subject.get(TEST_IMAGE,TEST_IMAGE_PROJECT) refute_nil(image, "Images.get(#{TEST_IMAGE}) should not return nil") assert_equal(image.family, TEST_IMAGE_FAMILY) assert_equal(image.project, TEST_IMAGE_PROJECT) end def test_get_from_family image = @subject.get_from_family(TEST_IMAGE_FAMILY) refute_nil(image,"Images.get_from_family(#{TEST_IMAGE_FAMILY}) should not return nil") assert_equal(image.family, TEST_IMAGE_FAMILY) assert_equal(image.project, TEST_IMAGE_PROJECT) end end fog-fog-google-4c8ece9/test/integration/compute/core_compute/test_machine_types.rb000066400000000000000000000035711514253314000307000ustar00rootroot00000000000000require "helpers/integration_test_helper" class TestMachineTypes < FogIntegrationTest # List of machine types - not a complete sampling since beefier ones do not # exist in all zones (list last updated June 2018) NAMES = %w(f1-micro g1-small n1-highcpu-16 n1-highcpu-2 n1-highcpu-4 n1-highcpu-8 n1-highmem-16 n1-highmem-2 n1-highmem-32 n1-highmem-4 n1-highmem-8 n1-standard-1 n1-standard-16 n1-standard-2 n1-standard-32 n1-standard-4 n1-standard-8 ).freeze # Testing in one random zone per region (list last updated May 2018) ZONES = %w(asia-east1-a asia-northeast1-b asia-south1-c asia-southeast1-a australia-southeast1-b europe-west1-c europe-west2-a europe-west3-b europe-west4-c northamerica-northeast1-a southamerica-east1-b us-central1-c us-east1-b us-east4-a us-west1-c).freeze def setup @subject = Fog::Compute[:google].machine_types end def test_all assert_operator(@subject.all.size, :>=, NAMES.size * ZONES.size, "Number of all machine types should be greater or equal to test zones * machine_types") end def test_scoped_all subject_list = @subject.all scoped_subject_list = @subject.all(zone: TEST_ZONE) # Assert that whatever .all(scope) returns is a subset of .all assert(scoped_subject_list.all? { |x| subject_list.include? x }, "Output of @subject.all(zone:#{TEST_ZONE}) must be a subset of @subject.all") end def test_get # This tests only in last zone since not all zones contain all machine types NAMES.each do |name| ZONES.each do |zone| refute_nil @subject.get(name, zone) end end end def test_bad_get assert_nil @subject.get("bad-name", ZONES.first) end def test_enumerable assert_respond_to @subject, :each end def test_nil_get assert_nil @subject.get(nil) end end fog-fog-google-4c8ece9/test/integration/compute/core_compute/test_operations.rb000066400000000000000000000024401514253314000302250ustar00rootroot00000000000000require "helpers/integration_test_helper" class TestOperations < FogIntegrationTest def setup @subject = Fog::Compute[:google].operations end def test_all # TODO: what if this test runs first on a brand new project? assert_operator(@subject.all.size, :>=, 2, "There should be at least 2 operations in the project") end def test_get @subject.all do |operation| refute_nil @subject.get(operation.name) end end def test_zone_scoped_all subject_list = @subject.all scoped_subject_list = @subject.all(zone: TEST_ZONE) # Assert that whatever .all(scope) returns is a subset of .all assert(scoped_subject_list.all? { |x| subject_list.include? x }, "Output of @subject.all(zone:#{TEST_ZONE}) must be a subset of @subject.all") end def test_region_scoped_all subject_list = @subject.all scoped_subject_list = @subject.all(region: TEST_REGION) # Assert that whatever .all(scope) returns is a subset of .all assert(scoped_subject_list.all? { |x| subject_list.include? x }, "Output of @subject.all(region:#{TEST_REGION}) must be a subset of @subject.all") end def test_bad_get assert_nil @subject.get("bad-name") end def test_enumerable assert_respond_to @subject, :each end end fog-fog-google-4c8ece9/test/integration/compute/core_compute/test_projects.rb000066400000000000000000000005301514253314000276710ustar00rootroot00000000000000require "helpers/integration_test_helper" class TestProjects < FogIntegrationTest def setup @subject = Fog::Compute[:google].projects end def test_get assert @subject.get(TEST_PROJECT) end def test_bad_get assert_nil @subject.get("bad-name") end def test_enumerable assert_respond_to @subject, :each end end fog-fog-google-4c8ece9/test/integration/compute/core_compute/test_regions.rb000066400000000000000000000012411514253314000275060ustar00rootroot00000000000000require "helpers/integration_test_helper" class TestRegions < FogIntegrationTest EXAMPLE_NAMES = %w(asia-east1 asia-northeast1 europe-west1 us-central1 us-east1 us-west1).freeze def setup @subject = Fog::Compute[:google].regions end def test_all assert_operator(@subject.all.size, :>=, EXAMPLE_NAMES.size) end def test_get EXAMPLE_NAMES.each do |region| refute_nil @subject.get(region) end end def test_up EXAMPLE_NAMES.each do |region| assert @subject.get(region).up? end end def test_bad_get assert_nil @subject.get("bad-name") end def test_enumerable assert_respond_to @subject, :each end end fog-fog-google-4c8ece9/test/integration/compute/core_compute/test_servers.rb000066400000000000000000000201161514253314000275330ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/servers_factory" require "integration/factories/disks_factory" require "resolv" class TestServers < FogIntegrationTest include TestCollection # Cleanup is handled by TestCollection def setup @subject = Fog::Compute[:google].servers @factory = ServersFactory.new(namespaced_name) @servers = ServersFactory.new(namespaced_name) @disks = DisksFactory.new(namespaced_name) end def teardown # Clean up the server resources used in testing @servers.cleanup super end def test_set_machine_type server = @factory.create server.stop server.wait_for { stopped? } server.set_machine_type("n1-standard-2", false) assert_equal "n1-standard-2", server.machine_type.split("/")[-1] end def test_set_machine_type_fail server = @factory.create server.wait_for { ready? } assert_raises Fog::Errors::Error do server.set_machine_type("n1-standard-2", false) end end def test_set_metadata server = @factory.create server.wait_for { ready? } server.set_metadata({ "foo" => "bar", "baz" => "foo" }, false) assert_equal [{ :key => "foo", :value => "bar" }, { :key => "baz", :value => "foo" }], server.metadata[:items] end def test_add_ssh_key key = "ssh-rsa IAMNOTAREALSSHKEYAMA==" username = "test_user" server = @factory.create server.add_ssh_key(username, key, false) assert_equal [{ :key => "ssh-keys", :value => "test_user:ssh-rsa IAMNOTAREALSSHKEYAMA== test_user" }], server.metadata[:items] end def test_bootstrap key = "ssh-rsa IAMNOTAREALSSHKEYAMA== user@host.subdomain.example.com" user = "username" File.stub :read, key do # XXX Small hack - name is set this way so it will be cleaned up by CollectionFactory # Bootstrap is special so this is something that needs to be done only for this method # Public_key_path is set to avoid stubbing out File.exist? server = @subject.bootstrap(:name => "#{CollectionFactory.new(nil,namespaced_name).resource_name}", :username => user, :public_key_path => "foo") boot_disk = server.disks.detect { |disk| disk[:boot] } assert_equal("RUNNING", server.status, "Bootstrapped server should be running") assert_equal(key, server.public_key, "Bootstrapped server should have a public key set") assert_equal(user, server.username, "Bootstrapped server should have user set to #{user}") assert(boot_disk[:auto_delete], "Bootstrapped server should have disk set to autodelete") network_adapter = server.network_interfaces.detect { |x| x.has_key?(:access_configs) } refute_nil(network_adapter[:access_configs].detect { |x| x[:nat_ip] }, "Bootstrapped server should have an external ip by default") end end def test_bootstrap_fail # Pretend the ssh key does not exist File.stub :exist?, nil do assert_raises(Fog::Errors::Error) { # XXX Small hack - name is set this way so it will be cleaned up by CollectionFactory # Bootstrap is special so this is something that needs to be done only for this method @subject.bootstrap(:name => "#{CollectionFactory.new(nil,namespaced_name).resource_name}", :public_key_path => nil) } end end def test_image_name server = @factory.create assert_equal(TEST_IMAGE, server.image_name.split("/")[-1]) end def test_ip_address_methods # Create a server with ephemeral external IP address server = @factory.create(:network_interfaces => [{ :network => "global/networks/default", :access_configs => [{ :name => "External NAT", :type => "ONE_TO_ONE_NAT" }] }]) assert_match(Resolv::IPv4::Regex, server.public_ip_address, "Server.public_ip_address should return a valid IP address") refute_empty(server.public_ip_addresses) assert_match(Resolv::IPv4::Regex, server.public_ip_addresses.pop) assert_match(Resolv::IPv4::Regex, server.private_ip_address, "Server.public_ip_address should return a valid IP address") refute_empty(server.private_ip_addresses) assert_match(Resolv::IPv4::Regex, server.private_ip_addresses.pop) end def test_start_stop_reboot server = @factory.create server.stop server.wait_for { stopped? } assert server.stopped? server.start server.wait_for { ready? } assert server.ready? server.reboot server.wait_for { ready? } assert server.ready? end def test_start_stop_discard_local_ssd server = @factory.create async = true discard_local_ssd = true server.stop(async, discard_local_ssd) server.wait_for { stopped? } assert server.stopped? end def test_attach_disk # Creating server server = @factory.create server.wait_for { ready? } disk_name = "fog-test-1-testservers-test-attach-disk-attachable" # suffix forces disk name to differ from the existing disk # Creating disk #{disk_name} disk = @disks.create( :name => disk_name, :source_image => TEST_IMAGE, :size_gb => 64 ) device_name = "#{disk.name}-device" # Attaching disk #{disk.name} as device #{device_name} self_link = "https://www.googleapis.com/compute/v1/projects/#{TEST_PROJECT}/zones/#{TEST_ZONE}/disks/#{disk.name}" server.attach_disk(self_link, true, device_name: device_name) # Waiting for attachment disk.wait_for { ! users.nil? && users != []} assert_equal "https://www.googleapis.com/compute/v1/projects/#{TEST_PROJECT}/zones/#{TEST_ZONE}/instances/#{server.name}", disk.users[0] server.reload server_attached_disk = server.disks.select{|d| d[:boot] == false}[0] assert_equal device_name, server_attached_disk[:device_name] end def test_detach_disk # Creating server server = @factory.create server.wait_for { ready? } disk_name = "fog-test-1-testservers-test-detach-attachable" # suffix forces disk name to differ from the existing disk # Creating disk #{disk_name} disk = @disks.create( :name => disk_name, :source_image => TEST_IMAGE, :size_gb => 64 ) device_name = "#{disk.name}-device" # Attaching disk #{disk.name} as device #{device_name} self_link = "https://www.googleapis.com/compute/v1/projects/#{TEST_PROJECT}/zones/#{TEST_ZONE}/disks/#{disk.name}" server.attach_disk(self_link, true, device_name: device_name) disk.wait_for { ! users.nil? && users != []} server.reload server_attached_disk = server.disks.select{|d| d[:boot] == false}[0] assert_equal device_name, server_attached_disk[:device_name] # Detaching (synchronous) disk #{disk.name} server.detach_disk(device_name, false) disk.reload assert disk.users.nil? || disk.users == [] # Re-attaching disk #{disk.name} as device #{device_name} server.attach_disk(self_link, true, device_name: device_name) disk.wait_for { ! users.nil? && users != []} server.reload server_attached_disk = server.disks.select{|d| d[:boot] == false}[0] assert_equal device_name, server_attached_disk[:device_name] # Detaching (async) disk #{disk.name} server.detach_disk(device_name, true) # Waiting for detachment disk.wait_for { users.nil? || users == []} assert disk.users.nil? || disk.users == [] end def test_reset_windows_password win_disk = @disks.create( :name => "fog-test-1-testservers-test-reset-windows-password-2", :source_image => "windows-server-2019-dc-v20210713", :size_gb => 64 ) server = @factory.create(:disks => [win_disk]) server.wait_for { ready? } server.reset_windows_password("test_user") serial_output = server.serial_port_output(:port => 4) assert_includes(serial_output, "encryptedPassword") assert_includes(serial_output, "\"userName\":\"test_user\"") end end fog-fog-google-4c8ece9/test/integration/compute/core_compute/test_snapshots.rb000066400000000000000000000007071514253314000300700ustar00rootroot00000000000000require "helpers/integration_test_helper" require "securerandom" require "base64" class TestComputeSnapshots < FogIntegrationTest def setup @client = Fog::Google::Compute.new # Ensure any resources we create with test prefixes are removed Minitest.after_run do delete_test_resources end end def test_list_empty_snapshots assert_empty @client.snapshots.all end def delete_test_resources # nothing to do end end fog-fog-google-4c8ece9/test/integration/compute/core_compute/test_zones.rb000066400000000000000000000021341514253314000272000ustar00rootroot00000000000000require "helpers/integration_test_helper" class TestZones < FogIntegrationTest # Testing one random zone per region (list last updated May 2018) ZONES = %w(asia-east1-a asia-northeast1-b asia-south1-c asia-southeast1-a australia-southeast1-b europe-west1-c europe-west2-a europe-west3-b europe-west4-c northamerica-northeast1-a southamerica-east1-b us-central1-c us-east1-b us-east4-a us-west1-c).freeze def setup @subject = Fog::Compute[:google].zones end def test_all assert_operator(@subject.all.size, :>=, ZONES.size, "Number of all zones should be greater than test zones") end def test_get # This tests only in last zone since not all zones contain all machine types ZONES.each do |name| zone = @subject.get(name) refute_nil(zone, "zones.get(#{name}) should not return nil") assert(zone.up?, "zones.up? should return up, unless there's an outage") end end def test_bad_get assert_nil @subject.get("bad-name") end def test_enumerable assert_respond_to @subject, :each end end fog-fog-google-4c8ece9/test/integration/compute/core_networking/000077500000000000000000000000001514253314000251715ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/integration/compute/core_networking/test_addresses.rb000066400000000000000000000057651514253314000305470ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/addresses_factory" require "integration/factories/servers_factory" class TestAddresses < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].addresses @servers = ServersFactory.new(namespaced_name) @factory = AddressesFactory.new(namespaced_name) end def teardown # Clean up the server resources used in testing @servers.cleanup super end def test_run_instance address = @factory.create server = @servers.create(:external_ip => address.address) assert_equal( address.address, server.network_interfaces[0][:access_configs][0][:nat_ip], "Created server should have the correct address after initialization" ) assert_equal( "IN_USE", @subject.get(address.name, TEST_REGION).status, "Address should now be in use" ) address.reload assert_equal( server, address.server, "Address.server should return an associated server object" ) address.server = nil address.reload assert_nil( address.server, "Address should not be associated with a server after disassociation" ) address.server = server address.reload assert_equal( server, address.server, "Address should be associated with a server after association" ) end def test_bad_get assert_nil @subject.get("bad-name", TEST_REGION) end def test_valid_range address = @factory.create octet = /\d{,2}|1\d{2}|2[0-4]\d|25[0-5]/ re = /\A#{octet}\.#{octet}\.#{octet}\.#{octet}\z/ assert_match(re, address.address, "Adress should be a valid ipv4 address") end def test_addresses_get_address_by_ip address = @factory.create found = @subject.get_by_ip_address(address.address) assert_equal(address.name, found.name, "address should have same name") assert_equal(address.address, found.address, "addresses should match") end def test_addresses_get_address_by_name address = @factory.create found = @subject.get_by_name(address.name) assert_equal(address.name, found.name, "address should have same name") assert_equal(address.address, found.address, "addresses should match") end def test_addresses_get_by_ip_address_or_name # Ensure we find the same addresses through both codepaths address = @factory.create with_name = @subject.get_by_ip_address_or_name(address.name) with_ip = @subject.get_by_ip_address_or_name(address.address) assert_equal(address.name, with_name.name, "address should have same name") assert_equal(address.address, with_name.address, "addresses should match") assert_equal(address.name, with_ip.name, "address should have same name") assert_equal(address.address, with_ip.address, "addresses should match") end def test_addresses_in_use address = @factory.create assert_equal(false, address.in_use?, "example address should not be in use") end end fog-fog-google-4c8ece9/test/integration/compute/core_networking/test_coverage.rb000066400000000000000000000004501514253314000303470ustar00rootroot00000000000000require "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:compute-core_networking" if ENV["COVERAGE"] fog-fog-google-4c8ece9/test/integration/compute/core_networking/test_firewalls.rb000066400000000000000000000004321514253314000305440ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/firewalls_factory" class TestFirewalls < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].firewalls @factory = FirewallsFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/compute/core_networking/test_networks.rb000066400000000000000000000014271514253314000304350ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/networks_factory" require "integration/factories/servers_factory" class TestNetworks < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].networks @servers = ServersFactory.new(namespaced_name) @factory = NetworksFactory.new(namespaced_name) end def teardown # Clean up the server resources used in testing @servers.cleanup super end def test_run_instance network = @factory.create server = @servers.create(:network_interfaces => [network.get_as_interface_config]) assert_equal( network.self_link, server.network_interfaces[0][:network], "Created server should have the network specified on boot" ) end end fog-fog-google-4c8ece9/test/integration/compute/core_networking/test_routes.rb000066400000000000000000000010571514253314000301010ustar00rootroot00000000000000require "helpers/integration_test_helper" class TestRoutes < FogIntegrationTest def setup @subject = Fog::Compute[:google].routes end def test_all assert_operator(@subject.all.size, :>=, 2, "Number of all routes should be greater or equal than 2 - default GW and default routes") end def test_get @subject.all do |route| refute_nil @subject.get(route.name) end end def test_bad_get assert_nil @subject.get("bad-name") end def test_enumerable assert_respond_to @subject, :each end end fog-fog-google-4c8ece9/test/integration/compute/core_networking/test_subnetworks.rb000066400000000000000000000004421514253314000311430ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/subnetworks_factory" class TestSubnetworks < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].subnetworks @factory = SubnetworksFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/compute/instance_groups/000077500000000000000000000000001514253314000251755ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/integration/compute/instance_groups/test_coverage.rb000066400000000000000000000004501514253314000303530ustar00rootroot00000000000000require "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:compute-instance_groups" if ENV["COVERAGE"] fog-fog-google-4c8ece9/test/integration/compute/instance_groups/test_instance_group_managers.rb000066400000000000000000000005141514253314000334560ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/instance_group_manager_factory" class TestInstanceGroupManagers < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].instance_group_managers @factory = InstanceGroupManagerFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/compute/instance_groups/test_instance_groups.rb000066400000000000000000000004601514253314000317640ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/instance_groups_factory" class TestInstanceGroups < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].instance_groups @factory = InstanceGroupsFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/compute/instance_groups/test_instance_templates.rb000066400000000000000000000004721514253314000324460ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/instance_template_factory" class TestInstanceTemplates < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].instance_templates @factory = InstanceTemplateFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/compute/loadbalancing/000077500000000000000000000000001514253314000245505ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/integration/compute/loadbalancing/test_backend_services.rb000066400000000000000000000004641514253314000314320ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/backend_services_factory" class TestBackendServices < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].backend_services @factory = BackendServicesFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/compute/loadbalancing/test_coverage.rb000066400000000000000000000004461514253314000277330ustar00rootroot00000000000000require "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:compute-loadbalancing" if ENV["COVERAGE"] fog-fog-google-4c8ece9/test/integration/compute/loadbalancing/test_forwarding_rules.rb000066400000000000000000000004641514253314000315140ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/forwarding_rules_factory" class TestForwardingRules < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].forwarding_rules @factory = ForwardingRulesFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/compute/loadbalancing/test_global_addresses.rb000066400000000000000000000004641514253314000314350ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/global_addresses_factory" class TestGlobalAddresses < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].global_addresses @factory = GlobalAddressesFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/compute/loadbalancing/test_global_forwarding_rules.rb000066400000000000000000000005161514253314000330320ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/global_forwarding_rules_factory" class TestGlobalForwardingRules < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].global_forwarding_rules @factory = GlobalForwardingRulesFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/compute/loadbalancing/test_http_health_checks.rb000066400000000000000000000004721514253314000317630ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/http_health_checks_factory" class TestHttpHealthChecks < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].http_health_checks @factory = HttpHealthChecksFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/compute/loadbalancing/test_ssl_certificates.rb000066400000000000000000000004641514253314000314660ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/ssl_certificates_factory" class TestSslCertificates < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].ssl_certificates @factory = SslCertificatesFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/compute/loadbalancing/test_target_http_proxies.rb000066400000000000000000000004761514253314000322410ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/target_http_proxies_factory" class TestTargetHttpProxies < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].target_http_proxies @factory = TargetHttpProxiesFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/compute/loadbalancing/test_target_https_proxies.rb000066400000000000000000000005021514253314000324120ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/target_https_proxies_factory" class TestTargetHttpsProxies < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].target_https_proxies @factory = TargetHttpsProxiesFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/compute/loadbalancing/test_target_instances.rb000066400000000000000000000004641514253314000314750ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/target_instances_factory" class TestTargetInstances < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].target_instances @factory = TargetInstancesFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/compute/loadbalancing/test_target_pools.rb000066400000000000000000000041621514253314000306410ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/target_pools_factory" class TestTargetPools < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].target_pools @factory = TargetPoolsFactory.new(namespaced_name) @servers = Fog::Compute[:google].servers end # Override to include zone in get request def get_resource(identity) @subject.get(identity, TEST_ZONE) end def test_get_health target_pool = @factory.create server = @servers.get(target_pool.instances[0].split("/").last) server.wait_for { ready? } # XXX This is not partucularly elegant but if the instance doesn't respond # to the healthcheck at all (for example there's nothing listening) it'll # enter "No instance health info was found." state, during which the API # will return an empty health object instead of UNHEALTHY. # To avoid setting up a brittle environment with a live healthcheck we just # stop the instance so health check returns UNHEALTHY and we can test that # all fields are returned correctly. server.stop server.wait_for { stopped? } # There's no way to track the readiness of the instance resource in a target pool, # so wrapping in a soft retry: begin retries ||= 0 target_pool.get_health rescue ::Google::Apis::ClientError sleep 25 retry if (retries += 1) < 3 end refute_empty(target_pool.health_checks, "Target pool should have a health check") assert_equal(2, target_pool.instances.count, "Target pool should have 2 instances") assert_equal([{ :health_state => "UNHEALTHY", :instance => server.self_link }], target_pool.get_health[server.self_link], "Target pool should return a proper health check list") assert_equal({ server.self_link => [{ :health_state => "UNHEALTHY", :instance => server.self_link }] }, target_pool.get_health(server.name), "target_pool should return instance health details when an instance is specified") end end fog-fog-google-4c8ece9/test/integration/compute/loadbalancing/test_url_maps.rb000066400000000000000000000004241514253314000277560ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/url_maps_factory" class TestUrlMaps < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].url_maps @factory = UrlMapsFactory.new(namespaced_name) end end fog-fog-google-4c8ece9/test/integration/factories/000077500000000000000000000000001514253314000222755ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/integration/factories/addresses_factory.rb000066400000000000000000000006021514253314000263240ustar00rootroot00000000000000require "integration/factories/collection_factory" class AddressesFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].addresses, example) end def get(identity) @subject.get(identity, TEST_REGION) end def all @subject.all(region: TEST_REGION) end def params { :name => resource_name, :region => TEST_REGION } end end fog-fog-google-4c8ece9/test/integration/factories/backend_services_factory.rb000066400000000000000000000007601514253314000276460ustar00rootroot00000000000000require "integration/factories/collection_factory" require "integration/factories/http_health_checks_factory" class BackendServicesFactory < CollectionFactory def initialize(example) @http_health_checks = HttpHealthChecksFactory.new(example) super(Fog::Compute[:google].backend_services, example) end def cleanup super @http_health_checks.cleanup end def params { :name => resource_name, :health_checks => [@http_health_checks.create.self_link] } end end fog-fog-google-4c8ece9/test/integration/factories/collection_factory.rb000066400000000000000000000040361514253314000265070ustar00rootroot00000000000000class CollectionFactory PREFIX = "fog-test".freeze def initialize(subject, example) @subject = subject @example = example @resource_counter = 0 end # Cleans up all objects created by the factory in the current test suite. # # @param async [FalseClass or TrueClass] perform resource destruction asynchronously def cleanup(async = false) suit_name = @example.gsub(/\W/, "").tr("_", "-").downcase.split("-")[0] resources = @subject.all.select { |resource| resource.name.match(/#{PREFIX}-[0-9]*-#{suit_name}/) } if DEBUG p "Cleanup invoked in #{self} for example: #{@example}" p "Resources to be deleted: #{resources.map { |r| r.name }}" p "All subject resources: #{@subject.all.map { |s| s.name }}" end resources.each { |r| r.destroy(async) } resources.each { |r| Fog.wait_for { !@subject.all.map(&:identity).include? r.identity } } end # Creates a collection object instance e.g. Fog::Google::Compute::Server # # @param custom_params [Hash] override factory creation parameters or provide # additional ones. Useful in tests where you need to create a slightly different # resource than the default one but still want to take advantage of the factory's # cleanup methods, etc. # # @example Create a custom factory # @factory = ServersFactory.new(namespaced_name) # server = @factory.create(:machine_type => "f1-micro") # # @return [Object] collection object instance def create(custom_params = {}) @subject.create(params.merge(custom_params)) end def get(identity) @subject.get(identity) end def resource_name(base = @example, prefix = PREFIX) index = @resource_counter += 1 # In prefix, convert - to _ to make sure that it doesn't get stripped by the \W strip below. # Then, concatenate prefix, index, and base; strip all non-alphanumerics except _; # convert _ to -; downcase; truncate to 62 characters; delete trailing - [prefix.tr("-", "_"), index, base].join("_").gsub(/\W/, "").tr("_", "-").downcase[0..61].chomp("-") end end fog-fog-google-4c8ece9/test/integration/factories/disks_factory.rb000066400000000000000000000006701514253314000254710ustar00rootroot00000000000000require "integration/factories/collection_factory" class DisksFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].disks, example) end def get(identity) @subject.get(identity, TEST_ZONE) end def all @subject.all(zone: TEST_ZONE) end def params { :name => resource_name, :zone_name => TEST_ZONE, :source_image => TEST_IMAGE, :size_gb => TEST_SIZE_GB } end end fog-fog-google-4c8ece9/test/integration/factories/firewalls_factory.rb000066400000000000000000000005011514253314000263350ustar00rootroot00000000000000require "integration/factories/collection_factory" class FirewallsFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].firewalls, example) end def params { :name => resource_name, :allowed => [{ :ip_protocol => "TCP", :ports => ["201"] }] } end end fog-fog-google-4c8ece9/test/integration/factories/forwarding_rules_factory.rb000066400000000000000000000010751514253314000277300ustar00rootroot00000000000000require "integration/factories/collection_factory" require "integration/factories/target_pools_factory" class ForwardingRulesFactory < CollectionFactory def initialize(example) @target_pools = TargetPoolsFactory.new(example) super(Fog::Compute[:google].forwarding_rules, example) end def cleanup super @target_pools.cleanup end def all @subject.all(region: TEST_REGION) end def params { :name => resource_name, :port_range => "80-80", :region => TEST_REGION, :target => @target_pools.create.self_link } end end fog-fog-google-4c8ece9/test/integration/factories/global_addresses_factory.rb000066400000000000000000000004551514253314000276520ustar00rootroot00000000000000require "integration/factories/collection_factory" class GlobalAddressesFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].global_addresses, example) end def get(identity) @subject.get(identity) end def params { :name => resource_name } end end fog-fog-google-4c8ece9/test/integration/factories/global_forwarding_rules_factory.rb000066400000000000000000000007631514253314000312530ustar00rootroot00000000000000require "integration/factories/collection_factory" require "integration/factories/target_http_proxies_factory" class GlobalForwardingRulesFactory < CollectionFactory def initialize(example) @targets = TargetHttpProxiesFactory.new(example) super(Fog::Compute[:google].global_forwarding_rules, example) end def cleanup super @targets.cleanup end def params { :name => resource_name, :port_range => "80-80", :target => @targets.create.self_link } end end fog-fog-google-4c8ece9/test/integration/factories/http_health_checks_factory.rb000066400000000000000000000003721514253314000301770ustar00rootroot00000000000000require "integration/factories/collection_factory" class HttpHealthChecksFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].http_health_checks, example) end def params { :name => resource_name } end end fog-fog-google-4c8ece9/test/integration/factories/images_factory.rb000066400000000000000000000005401514253314000256150ustar00rootroot00000000000000require "integration/factories/collection_factory" class ImagesFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].images, example) end def get(identity) @subject.get(identity, TEST_PROJECT) end def params { :name => resource_name, :raw_disk => { :source => TEST_RAW_DISK_SOURCE } } end end fog-fog-google-4c8ece9/test/integration/factories/instance_group_manager_factory.rb000066400000000000000000000013031514253314000310600ustar00rootroot00000000000000require "integration/factories/collection_factory" require "integration/factories/instance_template_factory" class InstanceGroupManagerFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].instance_group_managers, example) @instance_template = InstanceTemplateFactory.new(example) end def cleanup super @instance_template.cleanup end def get(identity) @subject.get(identity, TEST_ZONE) end def all @subject.all(zone: TEST_ZONE) end def params { :name => resource_name, :zone => TEST_ZONE, :base_instance_name => resource_name, :target_size => 1, :instance_template => @instance_template.create } end end fog-fog-google-4c8ece9/test/integration/factories/instance_groups_factory.rb000066400000000000000000000006031514253314000275530ustar00rootroot00000000000000require "integration/factories/collection_factory" class InstanceGroupsFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].instance_groups, example) end def get(identity) @subject.get(identity, TEST_ZONE) end def all @subject.all(zone: TEST_ZONE) end def params { :name => resource_name, :zone => TEST_ZONE } end end fog-fog-google-4c8ece9/test/integration/factories/instance_template_factory.rb000066400000000000000000000014201514253314000300450ustar00rootroot00000000000000require "integration/factories/collection_factory" class InstanceTemplateFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].instance_templates, example) end def params { :name => resource_name, # TODO: Properties config is convoluted, needs to be refactored :properties => { :machine_type => TEST_MACHINE_TYPE, :disks => [{ :boot => true, :auto_delete => true, :initialize_params => { :source_image => "projects/ubuntu-os-cloud/global/images/ubuntu-1804-bionic-v20180522" } }], :network_interfaces => [{ :network => "global/networks/default" }] } } end end fog-fog-google-4c8ece9/test/integration/factories/networks_factory.rb000066400000000000000000000004321514253314000262240ustar00rootroot00000000000000require "integration/factories/collection_factory" class NetworksFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].networks, example) end def params { :name => resource_name, :auto_create_subnetworks => true } end end fog-fog-google-4c8ece9/test/integration/factories/servers_factory.rb000066400000000000000000000012321514253314000260400ustar00rootroot00000000000000require "integration/factories/collection_factory" require "integration/factories/disks_factory" class ServersFactory < CollectionFactory def initialize(example) @disks = DisksFactory.new(example) super(Fog::Compute[:google].servers, example) end def cleanup # Disk cleanup sometimes fails if server deletion has not been completed super(false) @disks.cleanup end def get(identity) @subject.get(identity, TEST_ZONE) end def all @subject.all(zone: TEST_ZONE) end def params { :name => resource_name, :zone => TEST_ZONE, :machine_type => TEST_MACHINE_TYPE, :disks => [@disks.create] } end end fog-fog-google-4c8ece9/test/integration/factories/sql_certs_factory.rb000066400000000000000000000010411514253314000263440ustar00rootroot00000000000000require "integration/factories/collection_factory" require "integration/factories/sql_instances_factory" class SqlCertsFactory < CollectionFactory def initialize(example) @instances = SqlInstancesFactory.new(example) super(Fog::Google[:sql].ssl_certs, example) end def cleanup # Certs will be cleaned up with the test instance. @instances.cleanup end def params # Certificate name should not be longer than 16 characters { :common_name => resource_name, :instance => @instances.create.name } end end fog-fog-google-4c8ece9/test/integration/factories/sql_instances_factory.rb000066400000000000000000000007451514253314000272250ustar00rootroot00000000000000require "integration/factories/collection_factory" class SqlInstancesFactory < CollectionFactory def initialize(example) super(Fog::Google[:sql].instances, example) end def cleanup super end def params # Name has a time suffix due to SQL resources API objects having # a _very_ long life on the backend (n(days)) after deletion. { :name => "#{resource_name}-#{Time.now.to_i}", :region => TEST_SQL_REGION, :tier => TEST_SQL_TIER } end end fog-fog-google-4c8ece9/test/integration/factories/sql_users_factory.rb000066400000000000000000000012551514253314000263740ustar00rootroot00000000000000require "integration/factories/collection_factory" require "integration/factories/sql_instances_factory" class SqlUsersFactory < CollectionFactory def initialize(example) @instances = SqlInstancesFactory.new(example) super(Fog::Google[:sql].users, example) end def cleanup # Users will be cleaned up with the test instance. @instances.cleanup end def params # Username should not be longer than 16 characters { :name => resource_name[0..15], # TODO: Consider removing host when Users.list API issue is resolved # See https://github.com/fog/fog-google/issues/462 :host => "%", :instance => @instances.create.name } end end fog-fog-google-4c8ece9/test/integration/factories/ssl_certificates_factory.rb000066400000000000000000000005331514253314000277000ustar00rootroot00000000000000require "integration/factories/collection_factory" class SslCertificatesFactory < CollectionFactory def initialize(example) super(Fog::Compute[:google].ssl_certificates, example) end def params { :name => resource_name, :certificate => TEST_PEM_CERTIFICATE, :private_key => TEST_PEM_CERTIFICATE_PRIVATE_KEY } end end fog-fog-google-4c8ece9/test/integration/factories/subnetworks_factory.rb000066400000000000000000000013171514253314000267410ustar00rootroot00000000000000require "integration/factories/collection_factory" class SubnetworksFactory < CollectionFactory def initialize(example) # We cannot have 2 subnetworks with the same CIDR range so instantiating a # class variable holding a generator, ensuring that the factory gives us a # new subnet every time it's called @octet_generator = (0..255).each super(Fog::Compute[:google].subnetworks, example) end def get(identity) @subject.get(identity, TEST_REGION) end def all @subject.all(region: TEST_REGION) end def params { :name => resource_name, :network => "default", :region => TEST_REGION, :ip_cidr_range => "192.168.#{@octet_generator.next}.0/24" } end end fog-fog-google-4c8ece9/test/integration/factories/target_http_proxies_factory.rb000066400000000000000000000006741514253314000304560ustar00rootroot00000000000000require "integration/factories/collection_factory" require "integration/factories/url_maps_factory" class TargetHttpProxiesFactory < CollectionFactory def initialize(example) @url_maps = UrlMapsFactory.new(example) super(Fog::Compute[:google].target_http_proxies, example) end def cleanup super @url_maps.cleanup end def params { :name => resource_name, :url_map => @url_maps.create.self_link } end end fog-fog-google-4c8ece9/test/integration/factories/target_https_proxies_factory.rb000066400000000000000000000014531514253314000306350ustar00rootroot00000000000000require "integration/factories/collection_factory" require "integration/factories/url_maps_factory" require "integration/factories/ssl_certificates_factory" class TargetHttpsProxiesFactory < CollectionFactory def initialize(example) @ssl_certificates = SslCertificatesFactory.new(example) @url_maps = UrlMapsFactory.new(example) super(Fog::Compute[:google].target_https_proxies, example) end def cleanup # Calling CollectionFactory#cleanup with forced async as # Url Maps need the Https Proxy to be deleted before they # can be destroyed super(false) @ssl_certificates.cleanup @url_maps.cleanup end def params { :name => resource_name, :url_map => @url_maps.create.self_link, :ssl_certificates => [@ssl_certificates.create.self_link] } end end fog-fog-google-4c8ece9/test/integration/factories/target_instances_factory.rb000066400000000000000000000010011514253314000276760ustar00rootroot00000000000000require "integration/factories/collection_factory" require "integration/factories/servers_factory" class TargetInstancesFactory < CollectionFactory def initialize(example) @servers = ServersFactory.new(example) super(Fog::Compute[:google].target_instances, example) end def cleanup super @servers.cleanup end def all @subject.all(zone: TEST_ZONE) end def params { :name => resource_name, :zone => TEST_ZONE, :instance => @servers.create.self_link } end end fog-fog-google-4c8ece9/test/integration/factories/target_pools_factory.rb000066400000000000000000000013711514253314000270550ustar00rootroot00000000000000require "integration/factories/collection_factory" require "integration/factories/servers_factory" require "integration/factories/http_health_checks_factory" class TargetPoolsFactory < CollectionFactory def initialize(example) @http_health_checks = HttpHealthChecksFactory.new(example) @servers = ServersFactory.new(example) super(Fog::Compute[:google].target_pools, example) end def cleanup super @servers.cleanup @http_health_checks.cleanup end def all @subject.all(region: TEST_REGION) end def params { :name => resource_name, :region => TEST_REGION, :instances => [@servers.create.self_link, @servers.create.self_link], :health_checks => [@http_health_checks.create.self_link] } end end fog-fog-google-4c8ece9/test/integration/factories/url_maps_factory.rb000066400000000000000000000007271514253314000262010ustar00rootroot00000000000000require "integration/factories/collection_factory" require "integration/factories/backend_services_factory" class UrlMapsFactory < CollectionFactory def initialize(example) @backend_services = BackendServicesFactory.new(example) super(Fog::Compute[:google].url_maps, example) end def cleanup super @backend_services.cleanup end def params { :name => resource_name, :default_service => @backend_services.create.self_link } end end fog-fog-google-4c8ece9/test/integration/monitoring/000077500000000000000000000000001514253314000225035ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/integration/monitoring/test_coverage.rb000066400000000000000000000004331514253314000256620ustar00rootroot00000000000000require "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:monitoring" if ENV["COVERAGE"] fog-fog-google-4c8ece9/test/integration/monitoring/test_metric_descriptors.rb000066400000000000000000000112361514253314000277760ustar00rootroot00000000000000require "helpers/integration_test_helper" require "helpers/client_helper" class TestMetricDescriptors < FogIntegrationTest TEST_METRIC_TYPE_PREFIX = "custom.googleapis.com/fog-google-test/test-metric-descriptors".freeze def setup @client = Fog::Google::Monitoring.new # Ensure any resources we create with test prefixes are removed Minitest.after_run do delete_test_resources end end def delete_test_resources test_resources = @client.monitoring.list_project_metric_descriptors( "projects/#{@project}", :filter => "metric.type = starts_with(\"#{TEST_METRIC_TYPE_PREFIX}\")" ) unless test_resources.metric_descriptors.nil? test_resources.metric_descriptors.each do |md| @client.monitoring.delete_project_metric_descriptors(md.name) end end rescue # Do nothing end def test_list_metric_descriptors list_resp = @client.list_metric_descriptors assert_operator(list_resp.metric_descriptors.size, :>, 0, "metric descriptor count should be positive") resp = @client.list_metric_descriptors( :filter => 'metric.type = starts_with("compute.googleapis.com")', :page_size => 5 ) assert_operator(resp.metric_descriptors.size, :<=, 5, "metric descriptor count should be <= page size 5") resp = @client.list_metric_descriptors(:page_size => 1) assert_equal(resp.metric_descriptors.size, 1, "metric descriptor count should be page size 1") next_resp = @client.list_metric_descriptors( :page_size => 1, :page_token => resp.next_page_token ) assert_equal(next_resp.metric_descriptors.size, 1, "metric descriptor count should be page size 1") assert(resp.metric_descriptors[0].name != next_resp.metric_descriptors[0].name, "paginated result should not be the same value") end def test_create_custom_metric_descriptors metric_type = "#{TEST_METRIC_TYPE_PREFIX}/test-create" label = { :key => "foo", :value_type => "INT64", :description => "test label for a metric descriptor" } options = { :metric_type => metric_type, :unit => "1", :value_type => "INT64", :description => "A custom metric descriptor for fog-google metric descriptor tests.", :display_name => "fog-google/test-metric-descriptor", :metric_kind => "GAUGE", :labels => [label] } created = @client.create_metric_descriptor(**options) # Check created metric descriptor assert_equal(_full_name(metric_type), created.name) assert_equal(metric_type, created.type) assert_equal(options[:metric_kind], created.metric_kind) assert_equal(options[:value_type], created.value_type) assert_equal(options[:unit], created.unit) assert_equal(options[:description], created.description) assert_equal(options[:display_name], created.display_name) assert_equal(created.labels.size, 1, "expected 1 label, got #{created.labels.size}") label_descriptor = created.labels.first assert_equal(label[:key], label_descriptor.key) assert_equal(label[:value_type], label_descriptor.value_type) assert_equal(label[:description], label_descriptor.description) Fog.wait_for(30) do begin get_resp = @client.get_metric_descriptor(metric_type) return !get_resp.nil? rescue return false end end list_resp = @client.list_metric_descriptor(:filter => "metric.type = \"#{metric_type}\"", :page_size => 1) assert(!list_resp.metric_descriptors.nil?, "expected non-empty list request for metric descriptors") assert_empty(@client.delete_metric_descriptor(metric_type)) end def test_metric_descriptors_all descriptors = @client.metric_descriptors.all assert_operator(descriptors.size, :>, 0, "metric descriptor count should be positive") end def test_metric_descriptors_all_page_size descriptors = @client.metric_descriptors.all( :filter => 'metric.type = starts_with("compute.googleapis.com")', :page_size => 5 ) assert_operator(descriptors.size, :<=, 5, "metric descriptor count should be <= page size 5") descriptors = @client.metric_descriptors.all(:page_size => 2) assert_equal(descriptors.size, 2, "metric descriptor count should be page size 2") end def test_metric_descriptors_get builtin_test_type = "compute.googleapis.com/instance/cpu/usage_time" descriptor = @client.metric_descriptors.get("compute.googleapis.com/instance/cpu/usage_time") assert_equal(descriptor.type, builtin_test_type) end def _full_name(metric_type) "projects/#{@client.project}/metricDescriptors/#{metric_type}" end end fog-fog-google-4c8ece9/test/integration/monitoring/test_monitored_resource_descriptors.rb000066400000000000000000000017451514253314000324260ustar00rootroot00000000000000require "helpers/integration_test_helper" class TestMetricDescriptors < FogIntegrationTest def setup @client = Fog::Google::Monitoring.new end def test_list_and_get resp = @client.list_monitored_resource_descriptors assert_operator(resp.resource_descriptors.size, :>, 0, "resource descriptor count should be positive") @client.get_monitored_resource_descriptor( resp.resource_descriptors.first.type ) end def test_all resp = @client.monitored_resource_descriptors.all assert_operator(resp.size, :>, 0, "resource descriptor count should be positive") end def test_get resource = "global" descriptor = @client.monitored_resource_descriptors.get(resource) assert_equal( descriptor.name, "projects/#{@client.project}/monitoredResourceDescriptors/#{resource}" ) assert_equal(descriptor.labels.size, 1) assert_equal(descriptor.labels.first[:key], "project_id") end end fog-fog-google-4c8ece9/test/integration/monitoring/test_timeseries.rb000066400000000000000000000173741514253314000262540ustar00rootroot00000000000000require "helpers/integration_test_helper" class TestMetricDescriptors < FogIntegrationTest # This module has a decent amount of retry wrappers as the Stackdriver API # can be quite slow with metric propagation (sometimes 80+ seconds) and client # returning errors, e.g. Google::Apis::ClientError: badRequest if the metric # hasn't yet been created instead of a 404. TEST_METRIC_PREFIX = "custom.googleapis.com/fog-google-test/timeseries".freeze LABEL_DESCRIPTORS = [ { :key => "test_string_label", :value_type => "STRING", :description => "test string label" }, { :key => "test_bool_label", :value_type => "BOOL", :description => "test boolean label" }, { :key => "test_int_label", :value_type => "INT64", :description => "test integer label" } ].freeze def setup @client = Fog::Google::Monitoring.new # Ensure any resources we create with test prefixes are removed Minitest.after_run do _delete_test_resources end end def test_timeseries_collection metric_type = "#{TEST_METRIC_PREFIX}/test_requests" _some_custom_metric_descriptor(metric_type) start_time = Time.now labels = { :test_string_label => "foo", :test_bool_label => "false", :test_int_label => "1" } expected = _some_timeseries(start_time, metric_type, labels) # Retrying since this is prone to errors in test environment due to # constant creation/deletion of resources resp = retry_on(Google::Apis::ServerError) do @client.create_timeseries(:timeseries => [expected]) end assert_empty(resp.to_h) # Wait for TimeSeries to be created # Google Monitoring backend is not exactly designed for synchronous retrieval so this retry is necessary Fog.wait_for(30) do begin test_ts = @client.list_timeseries( :filter => "metric.type = \"#{metric_type}\"", :interval => { # Subtracting one second because timeSeries.list API # doesn't return points that are exactly the same time # as the interval for some reason. :start_time => (start_time - 1).to_datetime.rfc3339, :end_time => Time.now.to_datetime.rfc3339 } ).time_series return !test_ts.nil? rescue return false end end series = retry_on(Google::Apis::ClientError) do @client.timeseries_collection.all( :filter => "metric.type = \"#{metric_type}\"", :interval => { # Subtracting one second because timeSeries.list API # doesn't return points that are exactly the same time # as the interval for some reason. :start_time => (start_time - 1).to_datetime.rfc3339, :end_time => Time.now.to_datetime.rfc3339 } ) end assert_equal(1, series.size) actual = series.first assert_equal(expected[:metric], actual.metric) assert_equal(expected[:metric_kind], actual.metric_kind) assert_equal(expected[:resource], actual.resource) assert_equal(expected[:value_type], actual.value_type) assert_equal(1, actual.points.size) assert_equal(expected[:points].first[:value], actual.points.first[:value]) end def test_multiple_timeseries metric_type = "#{TEST_METRIC_PREFIX}/test_multiple" _some_custom_metric_descriptor(metric_type) start_time = Time.now metric_labels = [ { :test_string_label => "first", :test_bool_label => "true", :test_int_label => "1" }, { :test_string_label => "second", :test_bool_label => "false", :test_int_label => "2" } ] timeseries = metric_labels.map do |labels| _some_timeseries(start_time, metric_type, labels) end # Retrying since this is prone to errors in test environment due to # constant creation/deletion of resources retry_on(Google::Apis::ServerError) do @client.create_timeseries(:timeseries => timeseries) end interval = { # Subtracting one second because timeSeries.list API # doesn't return points that are exactly the same time # as the interval for some reason. :start_time => (start_time - 1).to_datetime.rfc3339, :end_time => Time.now.to_datetime.rfc3339 } # Wait for TimeSeries to be created # Google Monitoring backend is not exactly designed for synchronous retrieval so this retry is necessary Fog.wait_for(30) do begin test_ts = @client.list_timeseries( :filter => "metric.type = \"#{metric_type}\"", :interval => interval ).time_series return !test_ts.nil? rescue return false end end # Test page size resp = retry_on(Google::Apis::ClientError) do @client.list_timeseries( :filter => "metric.type = \"#{metric_type}\"", :interval => interval, :page_size => 1 ) end refute_nil(resp.time_series, "expected timeseries to not be nil") assert_equal(resp.time_series.size, 1, "expected timeseries count to be equal to page size 1") next_resp = @client.list_timeseries( :filter => "metric.type = \"#{metric_type}\"", :interval => interval, :page_size => 1, :page_token => resp.next_page_token ) assert_equal(next_resp.time_series.size, 1, "expected timeseries count to be equal to page size 1") labels = resp.time_series.first.metric.labels labels_next = next_resp.time_series.first.metric.labels refute_equal(labels, labels_next, "expected different timeseries when using page_token") # Test filter series = retry_on(Google::Apis::ClientError) do @client.timeseries_collection.all( :filter => %[ metric.type = "#{metric_type}" AND metric.label.test_string_label = "first" ], :interval => interval ) end assert_equal(series.size, 1, "expected returned timeseries to be filtered to 1 value") assert_equal("true", series.first.metric[:labels][:test_bool_label]) assert_equal("1", series.first.metric[:labels][:test_int_label]) end def _delete_test_resources list_resp = @client.monitoring.list_project_metric_descriptors( "projects/#{@client.project}", filter: "metric.type = starts_with(\"#{TEST_METRIC_PREFIX}\")" ) unless list_resp.metric_descriptors.nil? list_resp.metric_descriptors.each do |md| @client.monitoring.delete_project_metric_descriptor(md.name) end end rescue # Do nothing end def _some_custom_metric_descriptor(metric_type) # Create custom metric to write test timeseries for. @client.create_metric_descriptor( :labels => LABEL_DESCRIPTORS, :metric_type => metric_type, :unit => "1", :value_type => "INT64", :description => "A custom metric descriptor for fog-google timeseries test.", :display_name => "fog-google-test/#{metric_type}", :metric_kind => "GAUGE" ) # Wait for metric descriptor to be created Fog.wait_for(180, 2) do begin @client.get_metric_descriptor(metric_type) true rescue false end end end def _some_timeseries(start_time, metric_type, labels) { :metric => { :type => metric_type, :labels => labels }, :resource => { :type => "global", :labels => { :project_id => @client.project } }, :metric_kind => "GAUGE", :value_type => "INT64", :points => [ { :interval => { :end_time => start_time.to_datetime.rfc3339, :start_time => start_time.to_datetime.rfc3339 }, :value => { :int64_value => rand(10) } } ] } end end fog-fog-google-4c8ece9/test/integration/pubsub/000077500000000000000000000000001514253314000216165ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/integration/pubsub/pubsub_shared.rb000066400000000000000000000046211514253314000247740ustar00rootroot00000000000000require "helpers/integration_test_helper" require "securerandom" require "base64" class PubSubShared < FogIntegrationTest def setup @client = Fog::Google::Pubsub.new # Ensure any resources we create with test prefixes are removed Minitest.after_run do delete_test_resources end end def delete_test_resources topics_result = @client.list_topics unless topics_result.topics.nil? begin topics_result.topics .map(&:name) .select { |t| t.start_with?(topic_resource_prefix) } .each { |t| @client.delete_topic(t) } # We ignore errors here as list operations may not represent changes applied recently. # Hence, list operations can return a topic which has already been deleted but which we # will attempt to delete again. rescue Google::Apis::Error Fog::Logger.warning("ignoring Google Api error during delete_test_resources") end end subscriptions_result = @client.list_subscriptions unless subscriptions_result.subscriptions.nil? begin subscriptions_result.subscriptions .map(&:name) .select { |s| s.start_with?(subscription_resource_prefix) } .each { |s| @client.delete_subscription(s) } # We ignore errors here as list operations may not represent changes applied recently. # Hence, list operations can return a topic which has already been deleted but which we # will attempt to delete again. rescue Google::Apis::Error Fog::Logger.warning("ignoring Google Api error during delete_test_resources") end end end def topic_resource_prefix "projects/#{@client.project}/topics/fog-integration-test" end def subscription_resource_prefix "projects/#{@client.project}/subscriptions/fog-integration-test" end def new_topic_name "#{topic_resource_prefix}-#{SecureRandom.uuid}" end def new_subscription_name "#{subscription_resource_prefix}-#{SecureRandom.uuid}" end def some_topic_name # create lazily to speed tests up @some_topic ||= new_topic_name.tap do |t| @client.create_topic(t) end end def some_subscription_name # create lazily to speed tests up @some_subscription ||= new_subscription_name.tap do |s| @client.create_subscription(s, some_topic_name) end end end fog-fog-google-4c8ece9/test/integration/pubsub/test_coverage.rb000066400000000000000000000004271514253314000250000ustar00rootroot00000000000000require "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:pubsub" if ENV["COVERAGE"] fog-fog-google-4c8ece9/test/integration/pubsub/test_pubsub_models.rb000066400000000000000000000106421514253314000260500ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/pubsub/pubsub_shared" require "securerandom" require "base64" class TestPubsubModels < PubSubShared def test_topics_create name = new_topic_name result = @client.topics.create(:name => name) assert_equal(result.name, name) end def test_topics_get result = @client.topics.get(some_topic_name) assert_equal(result.name, some_topic_name) end def test_topics_all # Force a topic to be created just so we have at least 1 to list name = new_topic_name @client.create_topic(name) Fog.wait_for(5) do result = @client.topics.all if result.nil? false end result.any? { |topic| topic.name == name } end end def test_topic_publish_string @client.topics.get(some_topic_name) message_ids = @client.topics.get(some_topic_name).publish(["apples"]) assert_operator(message_ids.length, :>, 0) end def test_topic_publish_hash @client.topics.get(some_topic_name) message_ids = @client.topics.get(some_topic_name).publish(["data" => "apples"]) assert_operator(message_ids.length, :>, 0) end def test_topic_delete topic_to_delete = new_topic_name topic = @client.topics.create(:name => topic_to_delete) topic.destroy end def test_subscriptions_create push_config = {} ack_deadline_seconds = 18 subscription_name = new_subscription_name result = @client.subscriptions.create(:name => subscription_name, :topic => some_topic_name, :push_config => push_config, :ack_deadline_seconds => ack_deadline_seconds) assert_equal(result.name, subscription_name) end def test_subscriptions_get subscription_name = some_subscription_name result = @client.subscriptions.get(subscription_name) assert_equal(result.name, subscription_name) end def test_subscriptions_list # Force a subscription to be created just so we have at least 1 to list subscription_name = new_subscription_name @client.subscriptions.create(:name => subscription_name, :topic => some_topic_name) Fog.wait_for(5) do result = @client.subscriptions.all if result.nil? false end result.any? { |subscription| subscription.name == subscription_name } end end def test_subscription_delete push_config = {} ack_deadline_seconds = 18 subscription_name = new_subscription_name subscription = @client.subscriptions.create(:name => subscription_name, :topic => some_topic_name, :push_config => push_config, :ack_deadline_seconds => ack_deadline_seconds) subscription.destroy end def test_subscription_pull subscription_name = new_subscription_name message_bytes = Base64.strict_encode64("some message") subscription = @client.subscriptions.create(:name => subscription_name, :topic => some_topic_name) @client.topics.get(some_topic_name).publish(["data" => message_bytes]) result = subscription.pull(:return_immediately => false) assert_operator(result.length, :>, 0) contained = result.any? { |received| received.message[:data] == message_bytes } assert_equal(true, contained, "sent messsage not contained within pulled responses") end def test_subscription_acknowledge subscription_name = new_subscription_name subscription = @client.subscriptions.create(:name => subscription_name, :topic => some_topic_name) @client.topics.get(some_topic_name).publish(["data" => Base64.strict_encode64("some message")]) result = subscription.pull(:return_immediately => false) assert_operator(result.length, :>, 0) subscription.acknowledge([result[0].ack_id]) end def test_message_acknowledge subscription_name = new_subscription_name subscription = @client.subscriptions.create(:name => subscription_name, :topic => some_topic_name) @client.topics.get(some_topic_name).publish(["data" => Base64.strict_encode64("some message")]) result = subscription.pull(:return_immediately => false) assert_operator(result.length, :>, 0) result[0].acknowledge end end fog-fog-google-4c8ece9/test/integration/pubsub/test_pubsub_requests.rb000066400000000000000000000063701514253314000264430ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/pubsub/pubsub_shared" require "securerandom" require "base64" class TestPubsubRequests < PubSubShared def test_create_topic name = new_topic_name result = @client.create_topic(name) assert_equal(result.name, name) end def test_get_topic result = @client.get_topic(some_topic_name) assert_equal(result.name, some_topic_name) end def test_list_topics # Force a topic to be created just so we have at least 1 to list name = new_topic_name @client.create_topic(name) Fog.wait_for(5) do result = @client.list_topics if result.topics.nil? false end result.topics.any? { |topic| topic.name == name } end end def test_delete_topic topic_to_delete = new_topic_name @client.create_topic(topic_to_delete) @client.delete_topic(topic_to_delete) end def test_publish_topic @client.publish_topic(some_topic_name, [:data => Base64.strict_encode64("some message")]) end def test_create_subscription push_config = {} ack_deadline_seconds = 18 subscription_name = new_subscription_name result = @client.create_subscription(subscription_name, some_topic_name, push_config, ack_deadline_seconds) assert_equal(result.name, subscription_name) end def test_get_subscription subscription_name = some_subscription_name result = @client.get_subscription(subscription_name) assert_equal(result.name, subscription_name) end def test_list_subscriptions # Force a subscription to be created just so we have at least 1 to list subscription_name = new_subscription_name @client.create_subscription(subscription_name, some_topic_name) Fog.wait_for(5) do result = @client.list_subscriptions if result.subscriptions.nil? false end result.subscriptions.any? { |sub| sub.name == subscription_name } end end def test_delete_subscription subscription_to_delete = new_subscription_name @client.create_subscription(subscription_to_delete, some_topic_name) @client.delete_subscription(subscription_to_delete) end def test_pull_subscription subscription_name = new_subscription_name message_bytes = Base64.strict_encode64("some message") @client.create_subscription(subscription_name, some_topic_name) @client.publish_topic(some_topic_name, [:data => message_bytes]) result = @client.pull_subscription(subscription_name, {:return_immediately => false}) contained = result.received_messages.any? { |received| received.message.data == message_bytes } assert_equal(true, contained, "sent messsage not contained within pulled responses") end def test_acknowledge_subscription subscription_name = new_subscription_name @client.create_subscription(subscription_name, some_topic_name) @client.publish_topic(some_topic_name, [:data => Base64.strict_encode64("some message")]) pull_result = @client.pull_subscription(subscription_name, {:return_immediately => false}) assert_operator(pull_result.received_messages.length, :>, 0) @client.acknowledge_subscription(subscription_name, pull_result.received_messages[0].ack_id) end end fog-fog-google-4c8ece9/test/integration/sql/000077500000000000000000000000001514253314000211155ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/integration/sql/test_certs.rb000066400000000000000000000031201514253314000236150ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/sql_certs_factory" class TestSQLCerts < FogIntegrationTest # This test doesn't include TestCollection as certs are not an independent resource. def setup @subject = Fog::Google[:sql].ssl_certs @factory = SqlCertsFactory.new(namespaced_name) @client = Fog::Google::SQL.new end def teardown @factory.cleanup end def test_ssl_certs # Create an instance and an SSL cert ssl_cert = @factory.create instance_name = ssl_cert.instance # Create a second cert and attach to the same instance ssl_cert2 = @subject.new(:common_name => "#{ssl_cert.common_name}-2", :instance => instance_name) ssl_cert2.save # Verify it can be retrieved @subject.get(instance_name, ssl_cert2.sha1_fingerprint).tap do |result| assert_equal(ssl_cert2.common_name, result.common_name) assert_equal("sql#sslCert", result.kind) end # Verify instance returns 2 certs list_result = @subject.all(instance_name) assert_equal(2, list_result.size, "expected 2 SSL certs") # Delete one cert ssl_cert2.destroy(:async => false) list_result = @subject.all(instance_name) assert_equal(1, list_result.size, "expected one less SSL cert after deletion") # Test if SSL config is reset correctly instance = @client.instances.get(instance_name) instance.reset_ssl_config(:async => false) assert_equal(0, @subject.all(instance_name).size, "expected no SSL certs after reset") end end fog-fog-google-4c8ece9/test/integration/sql/test_common_flags.rb000066400000000000000000000013731514253314000251510ustar00rootroot00000000000000require "helpers/integration_test_helper" class TestCommonFlags < FogIntegrationTest def setup @client = Fog::Google::SQL.new end def test_list resp = @client.list_flags assert_operator(resp.items.size, :>, 0, "resource descriptor count should be positive") _sanity_check_flag(resp.items.first) end def test_all resp = @client.flags.all assert_operator(resp.size, :>, 0, "resource descriptor count should be positive") _sanity_check_flag(resp.first) end def _sanity_check_flag(flag) assert_equal(flag.kind, "sql#flag") refute(flag.name.nil?, "flag name should not be empty") refute_empty(flag.applies_to, "flag should apply to some database version") end end fog-fog-google-4c8ece9/test/integration/sql/test_common_tiers.rb000066400000000000000000000013501514253314000251760ustar00rootroot00000000000000require "helpers/integration_test_helper" class TestCommonTiers < FogIntegrationTest def setup @subject = Fog::Google[:sql].tiers end def test_all tiers = @subject.all assert_operator(tiers.size, :>, 0, "tier count should be positive") _sanity_check_tier(tiers.first) end def _sanity_check_tier(tier) assert_equal(tier.kind, "sql#tier") refute(tier.tier.nil?, "tier name should not be empty") assert_operator(tier.disk_quota, :>, 0, "tier disk quota should be positive") assert_operator(tier.ram, :>, 0, "tier ram should be positive") assert_operator(tier.region.size, :>, 0, "tier should have regions") end end fog-fog-google-4c8ece9/test/integration/sql/test_coverage.rb000066400000000000000000000004241514253314000242740ustar00rootroot00000000000000require "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:sql" if ENV["COVERAGE"] fog-fog-google-4c8ece9/test/integration/sql/test_instances.rb000066400000000000000000000062171514253314000244760ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/sql_instances_factory" # Client helper is imported for `wait_until_complete` # TODO: Remove when fog-google#339 or fog-google#340 is resolved require "helpers/client_helper" class TestSQLV2Instances < FogIntegrationTest include TestCollection # TODO: Remove when fog-google#339 or fog-google#340 is resolved include ClientHelper attr_reader :client def setup @subject = Fog::Google[:sql].instances @factory = SqlInstancesFactory.new(namespaced_name) @backup_runs = Fog::Google[:sql].backup_runs # TODO: Remove after BackupRuns get save/reload - fog-google#339 # See https://github.com/fog/fog-google/issues/339 @client = Fog::Google::SQL.new end def test_update instance = @factory.create settings_version = instance.settings_version labels = { :foo => "bar" } instance.settings[:user_labels] = labels instance.save updated = @subject.get(instance.name) assert_equal(labels, updated.settings[:user_labels]) assert_operator(updated.settings_version, :>, settings_version) end def test_default_settings instance = @factory.create assert_equal([], instance.ssl_certs, "new instance should have 0 initial ssl certs") end def test_restore_backup_run instance = @factory.create data = { :description => "test", :instance => instance.name } wait_until_complete { @client.insert_backup_run(instance.name, data) } backup_run = @backup_runs.all(instance.name).first # Wait for backup operation to be finished # or fail if it never finishes. instance.restore_backup(backup_run.id, :async => false) end def test_backup_runs # TODO: This probably can get pulled into the test above as those tests # very expensive time-wize (5 minutes or so each) instance = @factory.create description = "test backup run" operation = wait_until_complete do @client.insert_backup_run( instance.name, :description => description ) end assert_equal(operation.operation_type, "BACKUP_VOLUME") runs = @backup_runs.all(instance.name) assert_operator(runs.size, :>, 0, "expected at least one backup run") assert_equal(description, runs.first.description) created_run = @backup_runs.get(instance.name, runs.first.id) assert_equal(created_run, runs.first) wait_until_complete do @client.delete_backup_run(instance.name, runs.first.id) end deleted_run = @backup_runs.get(instance.name, runs.first.id) assert_equal("DELETED", deleted_run.status) end def test_clone instance = @factory.create instance.clone("#{instance.name}-clone", :async => false) cloned = @client.instances.get("#{instance.name}-clone") # Sanity check some attributes compare = %i(current_disk_size project region ip_configuration_require_ssl activation_policy) compare.each do |k| v = instance.attributes[k] cloned_v = cloned.attributes[k] if v.nil? assert_nil(cloned_v) else assert_equal(v, cloned_v, "attribute #{k} in original instance is #{v}, cloned = #{cloned_v}") end end end end fog-fog-google-4c8ece9/test/integration/sql/test_users.rb000066400000000000000000000021151514253314000236410ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/factories/sql_instances_factory" require "integration/factories/sql_users_factory" class TestSQLUsers < FogIntegrationTest # This test doesn't include TestCollection as Users is not a # classical Fog model, as it's tied to a particular instance # I.e.: # - Fog::Google::SQL.users.all() requires an instance # - API doesn't provide a GET request for Users model # See: https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/users def setup @subject = Fog::Google[:sql].users @factory = SqlUsersFactory.new(namespaced_name) end def teardown @factory.cleanup end def test_users # Create user user = @factory.create # Check user was created users = @subject.all(user.instance).select { |u| u.name == user.name } assert_equal(1, users.size, "expected user to have been created") # Delete user users.first.destroy(:async => false) assert_empty( @subject.all(user.instance).select { |u| u.name == user.name }, "expected no user #{user.name}" ) end end fog-fog-google-4c8ece9/test/integration/storage/000077500000000000000000000000001514253314000217625ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/integration/storage/storage_shared.rb000066400000000000000000000054131514253314000253040ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/pubsub/pubsub_shared" require "securerandom" require "base64" require "tempfile" class StorageShared < FogIntegrationTest def setup @client = Fog::Google::Storage.new # Enable retries during the suite. This prevents us from # having to manually rate limit our requests. ::Google::Apis::RequestOptions.default.retries = 5 # Ensure any resources we create with test prefixes are removed Minitest.after_run do delete_test_resources ::Google::Apis::RequestOptions.default.retries = 0 end end def delete_test_resources unless @some_temp_file.nil? @some_temp_file.unlink end buckets_result = @client.list_buckets unless buckets_result.items.nil? begin buckets_result.items .map(&:name) .select { |t| t.start_with?(bucket_prefix) } .each do |t| object_result = @client.list_objects(t) unless object_result.items.nil? object_result.items.each { |object| @client.delete_object(t, object.name) } end begin @client.delete_bucket(t) # Given that bucket operations are specifically rate-limited, we handle that # by waiting a significant amount of time and trying. rescue Google::Apis::RateLimitError Fog::Logger.warning("encountered rate limit, backing off") sleep(10) @client.delete_bucket(t) end end # We ignore errors here as list operations may not represent changes applied recently. rescue Google::Apis::Error Fog::Logger.warning("ignoring Google Api error during delete_test_resources") end end end def bucket_prefix "fog-integration-test" end def object_prefix "fog-integration-test-object" end def new_bucket_name "#{bucket_prefix}-#{SecureRandom.uuid}" end def new_object_name "#{object_prefix}-#{SecureRandom.uuid}" end def some_bucket_name # create lazily to speed tests up @some_bucket ||= new_bucket_name.tap do |t| @client.put_bucket(t) end end def some_object_name # create lazily to speed tests up @some_object ||= new_object_name.tap do |t| @client.put_object(some_bucket_name, t, some_temp_file) end end def temp_file_content "hello world" end def binary_file_content "PK\x03\x04\x14\x00\x00\x00\b\x00\x18\x89\x8AM\xE7!\xB7\x1C\x1C\x15j\x00\xB4\xB9".force_encoding(Encoding::ASCII_8BIT) end def some_temp_file(content = temp_file_content) @some_temp_file ||= Tempfile.new("fog-google-storage").tap do |t| t.binmode t.write(content) t.close end File.open(@some_temp_file.path, "r") end end fog-fog-google-4c8ece9/test/integration/storage/test_buckets.rb000066400000000000000000000062571514253314000250200ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/storage/storage_shared" require "securerandom" require "base64" require "tempfile" class TestStorageRequests < StorageShared def test_put_bucket bucket_name = new_bucket_name bucket = @client.put_bucket(bucket_name) assert_equal(bucket.name, bucket_name) end # We cannot test the state of the ACL as there are two cases to consider # * The authenticated service account has Owner permisions, which allows # it to read the ACLs after the predefined ACL is applied. # * The authenticated service account does not have Owner permissions, # then, we cannot read the ACLs after the predefined ACL is applied. # # As we cannot control the service account used for testing, we'll # just ensure that a valid operation succeeds and an invalid operation fails. def test_put_bucket_predefined_acl @client.put_bucket(new_bucket_name, :predefined_acl => "publicRead") end def test_put_bucket_invalid_predefined_acl assert_raises(Google::Apis::ClientError) do @client.put_bucket(new_bucket_name, :predefined_acl => "invalidAcl") end end def test_get_bucket bucket = @client.get_bucket(some_bucket_name) assert_equal(bucket.name, some_bucket_name) end def test_delete_bucket # Create a new bucket to delete it bucket_to_delete = new_bucket_name @client.put_bucket(bucket_to_delete) @client.delete_bucket(bucket_to_delete) assert_raises(Google::Apis::ClientError) do @client.get_bucket(bucket_to_delete) end end def test_list_buckets # Create a new bucket to ensure at least one exists to find bucket_name = new_bucket_name @client.put_bucket(bucket_name) result = @client.list_buckets if result.items.nil? raise StandardError.new("no buckets found") end contained = result.items.any? { |bucket| bucket.name == bucket_name } assert_equal(true, contained, "expected bucket not present") end def test_put_bucket_acl bucket_name = new_bucket_name @client.put_bucket(bucket_name) acl = { :entity => "allUsers", :role => "READER" } @client.put_bucket_acl(bucket_name, acl) end def test_list_bucket_acl bucket_name = new_bucket_name @client.put_bucket(bucket_name) acl = { :entity => "allUsers", :role => "READER" } @client.put_bucket_acl(bucket_name, acl) result = @client.list_bucket_acl(bucket_name) if result.items.nil? raise StandardError.new("no bucket access controls found") end contained = result.items.any? do |control| control.entity == acl[:entity] && control.role == acl[:role] end assert_equal(true, contained, "expected bucket access control not present") end def test_get_bucket_acl bucket_name = new_bucket_name @client.put_bucket(bucket_name) acl = { :entity => "allUsers", :role => "READER" } @client.put_bucket_acl(bucket_name, acl) result = @client.get_bucket_acl(bucket_name, "allUsers") if result.nil? raise StandardError.new("no bucket access control found") end assert_equal(result.role, acl[:role], "incorrect bucket access control role") end end fog-fog-google-4c8ece9/test/integration/storage/test_coverage.rb000066400000000000000000000004301514253314000251360ustar00rootroot00000000000000require "helpers/integration_test_helper" # This is a simple coverage helper that helps differentiate # the tests when run in parallel so the final coverage report # can be properly combined together from multiple runners SimpleCov.command_name "test:storage" if ENV["COVERAGE"] fog-fog-google-4c8ece9/test/integration/storage/test_directories.rb000066400000000000000000000033661514253314000256720ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/storage/storage_shared" require "securerandom" require "base64" require "tempfile" class TestStorageRequests < StorageShared def test_directories_put dir_name = new_bucket_name directory = @client.directories.create(:key => dir_name) assert_equal(directory.key, dir_name) end def test_directories_put_predefined_acl @client.directories.create( :key => new_bucket_name, :predefined_acl => "publicRead" ) end def test_directories_put_invalid_predefined_acl assert_raises(Google::Apis::ClientError) do @client.directories.create( :key => new_bucket_name, :predefined_acl => "invalidAcl" ) end end def test_directories_get directory = @client.directories.get(some_bucket_name) assert_equal(directory.key, some_bucket_name) end def test_directory_files file = @client.directories.get(some_bucket_name).files.get(some_object_name) assert_equal(some_object_name, file.key) end def test_directory_public_url url = @client.directories.get(some_bucket_name).public_url assert_match(/storage.googleapis.com/, url) end def test_directories_destroy dir_name = new_bucket_name @client.directories.create(:key => dir_name) @client.directories.destroy(dir_name) assert_nil(@client.directories.get(dir_name)) end def test_directories_all dir_name = new_bucket_name @client.directories.create(:key => dir_name) result = @client.directories.all if result.nil? raise StandardError.new("no directories found") end unless result.any? { |directory| directory.key == dir_name } raise StandardError.new("failed to find expected directory") end end end fog-fog-google-4c8ece9/test/integration/storage/test_files.rb000066400000000000000000000115721514253314000244560ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/storage/storage_shared" require "securerandom" require "base64" require "tempfile" class TestStorageRequests < StorageShared def test_files_create_file file_name = new_object_name @client.directories.get(some_bucket_name).files.create( :key => file_name, :body => some_temp_file ) object = @client.get_object(some_bucket_name, file_name) assert_equal(object[:body], temp_file_content) end def test_files_create_string expected_body = "A file body" file_name = new_object_name @client.directories.get(some_bucket_name).files.create( :key => file_name, :body => expected_body ) object = @client.get_object(some_bucket_name, file_name) assert_equal(object[:body], expected_body) end def test_files_create_predefined_acl @client.directories.get(some_bucket_name).files.create( :key => new_object_name, :body => some_temp_file, :predefined_acl => "publicRead" ) end def test_files_create_invalid_predefined_acl assert_raises(ArgumentError) do @client.directories.get(some_bucket_name).files.create( :key => new_object_name, :body => some_temp_file, :predefined_acl => "invalidAcl" ) end end def test_files_get content = @client.directories.get(some_bucket_name).files.get(some_object_name) assert_equal(content.body, temp_file_content) end def test_files_set_body_string file_name = new_object_name directory = @client.directories.get(some_bucket_name) file = directory.files.create( :key => file_name, :body => temp_file_content ) assert_equal(file.body, temp_file_content) new_body = "Changed file body" file.body = new_body file.save updated_file = directory.files.get(file_name) assert_equal(updated_file.body, new_body) end def test_files_set_body_file file_name = new_object_name directory = @client.directories.get(some_bucket_name) file = directory.files.create( :key => file_name, :body => some_temp_file ) new_body = "Changed file body" file.body = new_body file.save updated_file = directory.files.get(file_name) assert_equal(updated_file.body, new_body) end def test_files_metadata content = @client.directories.get(some_bucket_name).files.metadata(some_object_name) assert_equal(content.content_length, temp_file_content.length) assert_equal(content.key, some_object_name) end def test_files_destroy file_name = new_object_name @client.directories.get(some_bucket_name).files.create( :key => file_name, :body => some_temp_file ) @client.directories.get(some_bucket_name).files.destroy(file_name) assert_nil(@client.directories.get(some_bucket_name).files.get(file_name)) end def test_files_all file_name = new_object_name @client.directories.get(some_bucket_name).files.create( :key => file_name, :body => some_temp_file ) result = @client.directories.get(some_bucket_name).files.all if result.nil? raise StandardError.new("no files found") end unless result.any? { |file| file.key == file_name } raise StandardError.new("failed to find expected file") end end def test_files_each file_name = new_object_name @client.directories.get(some_bucket_name).files.create( :key => file_name, :body => some_temp_file ) found_file = false @client.directories.get(some_bucket_name).files.each do |file| if file.key == file_name found_file = true end end assert_equal(true, found_file, "failed to find expected file while iterating") end def test_files_copy target_object_name = new_object_name @client.directories.get(some_bucket_name).files.get(some_object_name).copy(some_bucket_name, target_object_name) content = @client.directories.get(some_bucket_name).files.get(target_object_name) assert_equal(content.body, temp_file_content) end def test_files_public_url url = @client.directories.get(some_bucket_name).files.get(some_object_name).public_url assert_match(/storage.googleapis.com/, url) end def test_files_get_https_url directory = @client.directories.get(some_bucket_name) https_url = directory.files.get_https_url("fog-testfile", (Time.now + 60).to_i) assert_match(/https/, https_url) assert_match(/#{bucket_prefix}/, https_url) assert_match(/fog-testfile/, https_url) end def test_files_get_https_url_whitespace directory = @client.directories.get(some_bucket_name) https_url = directory.files.get_https_url("fog -testfile", (Time.now + 60).to_i) assert_match(/https/, https_url) assert_match(/#{bucket_prefix}/, https_url) assert_match(/fog\%20-testfile/, https_url) end end fog-fog-google-4c8ece9/test/integration/storage/test_objects.rb000066400000000000000000000156431514253314000250100ustar00rootroot00000000000000require "helpers/integration_test_helper" require "integration/storage/storage_shared" require "securerandom" require "base64" require "tempfile" require "net/http" require "ostruct" class TestStorageRequests < StorageShared def test_put_object_string object_name = new_object_name @client.put_object(some_bucket_name, object_name, some_temp_file) object = @client.get_object(some_bucket_name, object_name) assert_equal(object_name, object[:name]) assert_equal(temp_file_content, object[:body]) end def test_put_object_nil assert_raises(ArgumentError) do @client.put_object(some_bucket_name, new_object_name, nil) end end def test_put_object_file object_name = new_object_name expected_body = "A file body" @client.put_object(some_bucket_name, object_name, expected_body) object = @client.get_object(some_bucket_name, object_name) assert_equal(object_name, object[:name]) assert_equal(expected_body, object[:body]) end def test_put_object_paperclip object_name = new_object_name paperclip_file = OpenStruct.new(:path => some_temp_file(binary_file_content), :content_type => "image/png") @client.put_object(some_bucket_name, object_name, paperclip_file, :content_type => "image/png") object = @client.get_object(some_bucket_name, object_name) assert_equal(object_name, object[:name]) assert_equal(Encoding::ASCII_8BIT, object[:body].encoding) assert_equal(binary_file_content, object[:body]) assert_equal("image/png", object[:content_type]) end def test_put_object_contradictory_content_type object_name = new_object_name file = OpenStruct.new(:path => some_temp_file, :content_type => "text/plain") @client.put_object(some_bucket_name, object_name, file, :content_type => "image/png") object = @client.get_object(some_bucket_name, object_name) assert_equal(object_name, object[:name]) assert_equal("image/png", object[:content_type]) end def test_put_object_predefined_acl @client.put_object(some_bucket_name, new_object_name, some_temp_file, :predefined_acl => "publicRead") end def test_put_object_invalid_predefined_acl assert_raises(Google::Apis::ClientError) do @client.put_object(some_bucket_name, new_object_name, some_temp_file, :predefined_acl => "invalidAcl") end end def test_get_object object = @client.get_object(some_bucket_name, some_object_name) assert_equal(temp_file_content, object[:body]) end def test_delete_object object_name = new_object_name @client.put_object(some_bucket_name, object_name, some_temp_file) @client.delete_object(some_bucket_name, object_name) assert_raises(Google::Apis::ClientError) do @client.get_object(some_bucket_name, object_name) end end def test_object_metadata object = @client.get_object_metadata(some_bucket_name, some_object_name) assert_equal(temp_file_content.length, object.size) assert_equal(some_bucket_name, object.bucket) end def test_copy_object target_object_name = new_object_name @client.copy_object(some_bucket_name, some_object_name, some_bucket_name, target_object_name) object = @client.get_object(some_bucket_name, target_object_name) assert_equal(temp_file_content, object[:body]) end def test_copy_object_predefined_acl target_object_name = new_object_name res = @client.copy_object(some_bucket_name, some_object_name, some_bucket_name, target_object_name, destination_predefined_acl: "publicRead") result = @client.get_object(some_bucket_name, target_object_name) response = Net::HTTP.get_response(URI(result[:self_link])) assert_kind_of(Net::HTTPOK, response) end def test_copy_object_with_request_options assert_raises(Google::Apis::AuthorizationError) do target_object_name = new_object_name @client.copy_object(some_bucket_name, some_object_name, some_bucket_name, target_object_name, authorization: false) end end def test_copy_object_with_object_property target_object_name = new_object_name @client.copy_object(some_bucket_name, some_object_name, some_bucket_name, target_object_name, content_type: 'text/plain') object = @client.get_object(some_bucket_name, target_object_name) assert_equal("text/plain", object[:content_type]) end def test_list_objects expected_object = some_object_name result = @client.list_objects(some_bucket_name) if result.items.nil? raise StandardError.new("no objects found") end contained = result.items.any? { |object| object.name == expected_object } assert_equal(true, contained, "expected object not present") end def test_put_object_acl object_name = new_object_name @client.put_object(some_bucket_name, object_name, some_temp_file) acl = { :entity => "allUsers", :role => "READER" } @client.put_object_acl(some_bucket_name, object_name, acl) end def test_list_object_acl object_name = new_object_name acls = [ { :entity => "allUsers", :role => "READER" }, { :entity => "allAuthenticatedUsers", :role => "READER" } ] @client.put_object(some_bucket_name, object_name, some_temp_file, :acl => acls) result = @client.list_object_acl(some_bucket_name, object_name) if result.items.nil? raise StandardError.new("no object access controls found") end assert_operator(acls.length, :<=, result.items.length, "expected at least #{acls.length} ACL items") expected_acls = Hash[acls.map { |acl| [acl[:entity], acl[:role]] }] num_found = 0 result.items.each do |actual_acl| if expected_acls[actual_acl.entity] == actual_acl.role num_found += 1 end end assert_equal(acls.length, num_found, "only found #{num_found} of #{acls.length} expected ACLs") end def test_get_object_acl object_name = new_object_name @client.put_object(some_bucket_name, object_name, some_temp_file) data = { :entity => "allUsers", :role => "READER" } @client.put_object_acl(some_bucket_name, object_name, data) result = @client.get_object_acl(some_bucket_name, object_name, "allUsers") if result.nil? raise StandardError.new("expected object access control not found") end end def test_get_object_https_url result = @client.get_object_https_url(some_bucket_name, some_object_name, 0) assert_operator(result.length, :>, 0) end def test_get_object_http_url result = @client.get_object_http_url(some_bucket_name, some_object_name, 0) assert_operator(result.length, :>, 0) end def test_put_object_url result = @client.put_object_url(some_bucket_name, new_object_name, 0) assert_operator(result.length, :>, 0) end end fog-fog-google-4c8ece9/test/integration/test_authentication.rb000066400000000000000000000032041514253314000247200ustar00rootroot00000000000000require "helpers/integration_test_helper" # TODO: this is a port over from legacy tests. It shouldn't be scoped under Google, but under Google::Shared. class TestAuthentication < FogIntegrationTest def setup @google_json_key_location = Fog.credentials[:google_json_key_location] @google_json_key_string = File.open(File.expand_path(@google_json_key_location), "rb", &:read) end def test_authenticates_with_json_key_location c = Fog::Google::Compute.new(:google_key_location => nil, :google_key_string => nil, :google_json_key_location => @google_json_key_location, :google_json_key_string => nil) assert_kind_of(Fog::Google::Compute::Real, c) end def test_authenticates_with_json_key_string c = Fog::Google::Compute.new(:google_key_location => nil, :google_key_string => nil, :google_json_key_location => nil, :google_json_key_string => @google_json_key_string) assert_kind_of(Fog::Google::Compute::Real, c) end def test_raises_argument_error_when_google_project_is_missing assert_raises(ArgumentError) { Fog::Google::Compute.new(:google_project => nil) } end def test_raises_argument_error_when_google_keys_are_given assert_raises(ArgumentError) do Fog::Google::Compute.new(:google_key_location => nil, :google_key_string => nil, :google_json_key_location => nil, :google_json_key_string => nil) end end end fog-fog-google-4c8ece9/test/unit/000077500000000000000000000000001514253314000167525ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/unit/compute/000077500000000000000000000000001514253314000204265ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/unit/compute/test_common_collections.rb000066400000000000000000000025521514253314000257040ustar00rootroot00000000000000require "helpers/test_helper" class UnitTestCollections < Minitest::Test def setup Fog.mock! @client = Fog::Compute.new(provider: "google", google_project: "foo") # Exceptions that do not pass test_common_methods: # # Projects do not have a "list" method in compute API, so 'all' is not implemented @common_method_exceptions = [Fog::Google::Compute::Projects] # Enumerate all descendants of Fog::Collection descendants = ObjectSpace.each_object(Fog::Collection.singleton_class).to_a @collections = descendants.select { |d| d.name.match(/Fog::Google::Compute/) } end def teardown Fog.unmock! end # This tests whether Fog::Google::Compute collections have common lifecycle methods def test_common_methods subjects = @collections - @common_method_exceptions subjects.each do |klass| obj = klass.new assert obj.respond_to?(:all), "#{klass} should have an .all method" assert obj.respond_to?(:get), "#{klass} should have a .get method" assert obj.respond_to?(:each), "#{klass} should behave like Enumerable" end end def test_collection_get_arguments @collections.each do |klass| obj = klass.new assert_operator(obj.method(:get).arity, :<=, 1, "#{klass} should have at most 1 required parameter in get()") end end end fog-fog-google-4c8ece9/test/unit/compute/test_common_models.rb000066400000000000000000000022641514253314000246510ustar00rootroot00000000000000require "helpers/test_helper" class UnitTestModels < Minitest::Test def setup Fog.mock! @client = Fog::Compute.new(provider: "google", google_project: "foo") # Do not test models that do not have a create method in API exceptions = [Fog::Google::Compute::MachineType, Fog::Google::Compute::Region, Fog::Google::Compute::DiskType, Fog::Google::Compute::Operation, Fog::Google::Compute::Zone, Fog::Google::Compute::Snapshot, Fog::Google::Compute::Project] # Enumerate all descendants of Fog::Model descendants = ObjectSpace.each_object(Fog::Model.singleton_class).to_a @models = descendants.select { |d| d.name.match(/Fog::Google::Compute/) } - exceptions end def teardown Fog.unmock! end def test_common_methods # This tests whether Fog::Google::Compute models have common lifecycle methods @models.each do |klass| obj = klass.new assert obj.respond_to?(:save), "#{klass} should have a .save method" assert obj.respond_to?(:destroy), "#{klass} should have a .destroy method" end end end fog-fog-google-4c8ece9/test/unit/compute/test_disk.rb000066400000000000000000000017251514253314000227510ustar00rootroot00000000000000require "helpers/test_helper" class UnitTestDisk < Minitest::Test def setup Fog.mock! @client = Fog::Compute.new(provider: "google", google_project: "foo") end def teardown Fog.unmock! end def test_new_disk disk = Fog::Google::Compute::Disk.new( :name => "fog-1", :size_gb => 10, :zone => "us-central1-a", :source_image => "debian-7-wheezy-v20131120" ) assert_equal("fog-1", disk.name, "Fog::Google::Compute::Disk name is incorrect: #{disk.name}") assert_equal(10, disk.size_gb, "Fog::Google::Compute::Disk size_gb is incorrect: #{disk.size_gb}") assert_equal("us-central1-a", disk.zone, "Fog::Google::Compute::Disk zone is incorrect: #{disk.zone}") assert_equal("debian-7-wheezy-v20131120", disk.source_image, "Fog::Google::Compute::Disk source_image is incorrect: #{disk.source_image}") end end fog-fog-google-4c8ece9/test/unit/compute/test_operation.rb000066400000000000000000000220411514253314000240110ustar00rootroot00000000000000require "helpers/test_helper" class UnitTestOperation < Minitest::Test OP_NAME = "operation-1765631023137-645d501f04210-ccccdddd-eeeeffff" OP_REGION = "us-central1" OP_CLIENT_OPERATION_ID = 3188330303322222222 OP_CREATION_TIMESTAMP = "2023-12-13T05:03:43.789-08:00" OP_END_TIME = "2023-12-13T05:03:43.000-08:00" OP_ERROR = {} OP_HTTP_ERROR_MESSAGE = "http error message" OP_HTTP_ERROR_STATUS_CODE = 499 OP_ID = 3188330303311111111 OP_INSERT_TIME = "2023-12-13T05:03:43.456-08:00" OP_KIND = "compute#operation" OP_OPERATION_TYPE = "insert" OP_PROGRESS = 0 OP_SELF_LINK = "https://www.googleapis.com/compute/v1/projects/projname/zones/#{OP_REGION}-f/operations/#{OP_NAME}" OP_START_TIME = "2023-12-13T05:03:43.461-08:00" OP_STATUS_MESSAGE = "status message" OP_STATUS = "RUNNING" OP_TARGET_ID = 8208437032700000000 OP_TARGET_LINK = "https://www.googleapis.com/compute/v1/projects/projname/zones/#{OP_REGION}-f/disks/diskname" OP_USER = "username@projname.iam.gserviceaccount.com" OP_WARNINGS = [] OP_ZONE = "https://www.googleapis.com/compute/v1/projects/projname/zones/#{OP_REGION}-f" def setup Fog.mock! @client = Fog::Compute.new(provider: "google", google_project: "foo") end def teardown Fog.unmock! end def test_new_operation op = Fog::Google::Compute::Operation.new( :client_operation_id => OP_CLIENT_OPERATION_ID, :creation_timestamp => OP_CREATION_TIMESTAMP, :end_time => OP_END_TIME, :error => OP_ERROR, :http_error_message => OP_HTTP_ERROR_MESSAGE, :http_error_status_code => OP_HTTP_ERROR_STATUS_CODE, :id => OP_ID, :insert_time => OP_INSERT_TIME, :kind => OP_KIND, :name => OP_NAME, :operation_type => OP_OPERATION_TYPE, :progress => OP_PROGRESS, :region => OP_REGION, :self_link => OP_SELF_LINK, :start_time => OP_START_TIME, :status_message => OP_STATUS_MESSAGE, :status => OP_STATUS, :target_id => OP_TARGET_ID, :target_link => OP_TARGET_LINK, :user => OP_USER, :warnings => OP_WARNINGS, :zone => OP_ZONE ) assert_equal(OP_CLIENT_OPERATION_ID, op.client_operation_id, "Fog::Google::Compute::Operation client_operation_id is incorrect: #{op.client_operation_id}") assert_equal(OP_CREATION_TIMESTAMP, op.creation_timestamp, "Fog::Google::Compute::Operation creation_timestamp is incorrect: #{op.creation_timestamp}") assert_equal(OP_END_TIME, op.end_time, "Fog::Google::Compute::Operation end_time is incorrect: #{op.end_time}") assert_equal(OP_ERROR, op.error, "Fog::Google::Compute::Operation name is incorrect: #{op.error}") assert_equal(OP_HTTP_ERROR_MESSAGE, op.http_error_message, "Fog::Google::Compute::Operation http_error_message is incorrect: #{op.http_error_message}") assert_equal(OP_HTTP_ERROR_STATUS_CODE, op.http_error_status_code, "Fog::Google::Compute::Operation http_error_status_code is incorrect: #{op.http_error_status_code}") assert_equal(OP_ID, op.id, "Fog::Google::Compute::Operation id is incorrect: #{op.id}") assert_equal(OP_INSERT_TIME, op.insert_time, "Fog::Google::Compute::Operation insert_time is incorrect: #{op.insert_time}") assert_equal(OP_KIND, op.kind, "Fog::Google::Compute::Operation kind is incorrect: #{op.kind}") assert_equal(OP_NAME, op.name, "Fog::Google::Compute::Operation name is incorrect: #{op.name}") assert_equal(OP_OPERATION_TYPE, op.operation_type, "Fog::Google::Compute::Operation operation_type is incorrect: #{op.operation_type}") assert_equal(OP_PROGRESS, op.progress, "Fog::Google::Compute::Operation progress is incorrect: #{op.progress}") assert_equal(OP_REGION, op.region, "Fog::Google::Compute::Operation region is incorrect: #{op.region}") assert_equal(OP_SELF_LINK, op.self_link, "Fog::Google::Compute::Operation self_link is incorrect: #{op.self_link}") assert_equal(OP_START_TIME, op.start_time, "Fog::Google::Compute::Operation start_time is incorrect: #{op.start_time}") assert_equal(OP_STATUS_MESSAGE, op.status_message, "Fog::Google::Compute::Operation status_message is incorrect: #{op.status_message}") assert_equal(OP_STATUS, op.status, "Fog::Google::Compute::Operation status is incorrect: #{op.status}") assert_equal(OP_TARGET_ID, op.target_id, "Fog::Google::Compute::Operation target_id is incorrect: #{op.target_id}") assert_equal(OP_TARGET_LINK, op.target_link, "Fog::Google::Compute::Operation target_link is incorrect: #{op.target_link}") assert_equal(OP_USER, op.user, "Fog::Google::Compute::Operation user is incorrect: #{op.user}") assert_equal(OP_WARNINGS, op.warnings, "Fog::Google::Compute::Operation warnings incorrect: #{op.warnings}") assert_equal(OP_ZONE, op.zone, "Fog::Google::Compute::Operation zone is incorrect: #{op.zone}") end def test_message_pretty error= {:errors => [ { :code =>"PERMISSIONS_ERROR", :error_details => [ ], :location => "location", :message => "Permissions error." } ]} op = Fog::Google::Compute::Operation.new(:error => error, :name => OP_NAME) err = op.primary_error assert_equal "Permissions error.", err.message_pretty end def test_message_pretty_quota_single error= {: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"}} ], :location => "location", :message => "Quota 'SSD_TOTAL_GB' exceeded. Limit: 500.0 in region us-east4." } ]} op = Fog::Google::Compute::Operation.new(:error => error, :name => OP_NAME) err = op.primary_error assert_equal "Quota 'SSD_TOTAL_GB' exceeded. Limit: 500.0 compute.googleapis.com/ssd_total_storage in region us-east4.", err.message_pretty end def test_message_pretty_quota_multi error= {:errors => [ { :code =>"QUOTA_EXCEEDED", :error_details => [ {:quota_info => {:dimensions => {:region=>"us-east4"}, :limit => 500, :limit_name => "limit-name1", :metric_name => "compute.googleapis.com/ssd_total_storage"}}, {:quota_info => {:dimensions => {:region=>"us-west1"}, :limit => 999, :limit_name => "limit-name2", :metric_name => "compute.googleapis.com/ssd_xxxxx_storage"}} ], :location => "location", :message => "Quota 'SSD_TOTAL_GB' exceeded. Limit: 500.0 in region us-east4." } ] } op = Fog::Google::Compute::Operation.new(:error => error, :name => OP_NAME) err = op.primary_error assert_equal "Quota 'SSD_TOTAL_GB' exceeded. Limit: 500.0 compute.googleapis.com/ssd_total_storage in region us-east4. Limit: 999.0 compute.googleapis.com/ssd_xxxxx_storage in region us-west1.", err.message_pretty end def test_message_pretty_quota_multi_missing_elements error= {:errors => [ { :code =>"QUOTA_EXCEEDED", :error_details => [ {:quota_info => { :limit => 500, :limit_name => "limit-name1", :metric_name => "compute.googleapis.com/ssd_total_storage"}}, {:quota_info => {:dimensions => {:region=>"us-east4"}, :limit_name => "limit-name2", :metric_name => "compute.googleapis.com/ssd_xxxxx_storage"}}, {:quota_info => {:dimensions => {:region=>"us-west1"}, :limit => 999, :limit_name => "limit-name2"}} ], :location => "location", :message => "Quota 'SSD_TOTAL_GB' exceeded." } ] } op = Fog::Google::Compute::Operation.new(:error => error, :name => OP_NAME) err = op.primary_error assert_equal "Quota 'SSD_TOTAL_GB' exceeded. Limit: 500.0 compute.googleapis.com/ssd_total_storage. Limit: 999.0 in region us-west1.", err.message_pretty end end fog-fog-google-4c8ece9/test/unit/compute/test_server.rb000066400000000000000000000013211514253314000233150ustar00rootroot00000000000000require "helpers/test_helper" class UnitTestServer < Minitest::Test def setup Fog.mock! @client = Fog::Compute.new(provider: "google", google_project: "foo") end def teardown Fog.unmock! end def test_if_server_accepts_ssh_keys key = "ssh-rsa IAMNOTAREALSSHKEYAMA== user@host.subdomain.example.com" File.stub :read, key do server = Fog::Google::Compute::Server.new( :name => "foo", :machine_type => "bar", :disks => ["baz"], :zone => "foo", :public_key_path => key ) assert_equal(server.public_key, key, "Fog::Google::Compute::Server loads public_key properly") end end end fog-fog-google-4c8ece9/test/unit/dns/000077500000000000000000000000001514253314000175365ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/unit/dns/test_common_collections.rb000066400000000000000000000025701514253314000250140ustar00rootroot00000000000000require "helpers/test_helper" class UnitTestDNSCollections < Minitest::Test def setup Fog.mock! @client = Fog::DNS.new(provider: "google", google_project: "foo") # Exceptions that do not pass test_common_methods: # # DNS Projects API does not support 'list', so 'all' method is not possible @common_methods_exceptions = [Fog::Google::DNS::Projects] # Enumerate all descendants of Fog::Collection descendants = ObjectSpace.each_object(Fog::Collection.singleton_class) @collections = descendants.select { |d| d.name.match(/Fog::Google::DNS/) } end def teardown Fog.unmock! end # This tests whether Fog::Google::Compute collections have common lifecycle methods def test_common_methods subjects = @collections - @common_methods_exceptions subjects.each do |klass| obj = klass.new assert obj.respond_to?(:all), "#{klass} should have an .all method" assert obj.respond_to?(:get), "#{klass} should have a .get method" assert obj.respond_to?(:each), "#{klass} should behave like Enumerable" end end def test_collection_get_arguments # TODO: Fixture for #352 skip @collections.each do |klass| obj = klass.new assert_operator(obj.method(:get).arity, :<=, 1, "#{klass} should have at most 1 required parameter in get()") end end end fog-fog-google-4c8ece9/test/unit/monitoring/000077500000000000000000000000001514253314000211375ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/unit/monitoring/test_comon_collections.rb000066400000000000000000000026131514253314000262360ustar00rootroot00000000000000require "helpers/test_helper" class UnitTestMonitoringCollections < Minitest::Test def setup Fog.mock! @client = Fog::Monitoring.new(provider: "google", google_project: "foo") # Exceptions that do not pass test_common_methods: # # TimeSeries API has no 'get' method @common_method_exceptions = [Fog::Google::Monitoring::TimeseriesCollection] # Enumerate all descendants of Fog::Collection descendants = ObjectSpace.each_object(Fog::Collection.singleton_class).to_a @collections = descendants.select { |d| d.name.match(/Fog::Google::Monitoring/) } end def teardown Fog.unmock! end # This tests whether Fog::Google::Compute collections have common lifecycle methods def test_common_methods subjects = @collections - @common_method_exceptions subjects.each do |klass| obj = klass.new assert obj.respond_to?(:all), "#{klass} should have an .all method" assert obj.respond_to?(:get), "#{klass} should have a .get method" assert obj.respond_to?(:each), "#{klass} should behave like Enumerable" end end def test_collection_get_arguments @collections.each do |klass| obj = klass.new if obj.respond_to?(:get) assert_operator(obj.method(:get).arity, :<=, 1, "#{klass} should have at most 1 required parameter in get()") end end end end fog-fog-google-4c8ece9/test/unit/pubsub/000077500000000000000000000000001514253314000202525ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/unit/pubsub/test_common_collections.rb000066400000000000000000000020661514253314000255300ustar00rootroot00000000000000require "helpers/test_helper" class UnitTestPubsubCollections < Minitest::Test def setup Fog.mock! @client = Fog::Google::Pubsub.new(google_project: "foo") # Enumerate all descendants of Fog::Collection descendants = ObjectSpace.each_object(Fog::Collection.singleton_class) @collections = descendants.select { |d| d.name.match(/Fog::Google::Pubsub/) } end def teardown Fog.unmock! end def test_common_methods # This tests whether Fog::Google::Compute collections have common lifecycle methods @collections.each do |klass| obj = klass.new assert obj.respond_to?(:all), "#{klass} should have an .all method" assert obj.respond_to?(:get), "#{klass} should have a .get method" assert obj.respond_to?(:each), "#{klass} should behave like Enumerable" end end def test_collection_get_arguments @collections.each do |klass| obj = klass.new assert_operator(obj.method(:get).arity, :<=, 1, "#{klass} should have at most 1 required parameter in get()") end end end fog-fog-google-4c8ece9/test/unit/sql/000077500000000000000000000000001514253314000175515ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/unit/sql/test_common_collections.rb000066400000000000000000000030021514253314000250160ustar00rootroot00000000000000require "helpers/test_helper" class UnitTestSQLCollections < Minitest::Test def setup Fog.mock! @client = Fog::Google::SQL.new(google_project: "foo") # Exceptions that do not pass test_common_methods: # # SQL Users API doesn't have a 'get' method # SQL Flags API has only one method - 'list' # SQL Tiers API has only one method - 'list' @common_method_exceptions = [Fog::Google::SQL::Users, Fog::Google::SQL::Tiers, Fog::Google::SQL::Flags] # Enumerate all descendants of Fog::Collection descendants = ObjectSpace.each_object(Fog::Collection.singleton_class) @collections = descendants.select { |d| d.name.match(/Fog::Google::SQL/) } end def teardown Fog.unmock! end # This tests whether Fog::Google::Compute collections have common lifecycle methods def test_common_methods subjects = @collections - @common_method_exceptions subjects.each do |klass| obj = klass.new assert obj.respond_to?(:all), "#{klass} should have an .all method" assert obj.respond_to?(:get), "#{klass} should have a .get method" assert obj.respond_to?(:each), "#{klass} should behave like Enumerable" end end def test_collection_get_arguments # TODO: Fixture for #352 skip @collections.each do |klass| obj = klass.new assert_operator(obj.method(:get).arity, :<=, 1, "#{klass} should have at most 1 required parameter in get()") end end end fog-fog-google-4c8ece9/test/unit/storage/000077500000000000000000000000001514253314000204165ustar00rootroot00000000000000fog-fog-google-4c8ece9/test/unit/storage/test_common_json_collections.rb000066400000000000000000000021711514253314000267220ustar00rootroot00000000000000require "helpers/test_helper" class UnitTestStorageJSONCollections < Minitest::Test def setup Fog.mock! @client = Fog::Storage.new(provider: "google", google_project: "foo") # Enumerate all descendants of Fog::Collection descendants = ObjectSpace.each_object(Fog::Collection.singleton_class) @collections = descendants.select do |d| d.name.match(/Fog::Google::StorageJSON/) end end def teardown Fog.unmock! end def test_common_methods # This tests whether Fog::Google::Compute collections have common lifecycle methods @collections.each do |klass| obj = klass.new assert obj.respond_to?(:all), "#{klass} should have an .all method" assert obj.respond_to?(:get), "#{klass} should have a .get method" assert obj.respond_to?(:each), "#{klass} should behave like Enumerable" end end def test_collection_get_arguments @collections.each do |klass| obj = klass.new assert_operator(obj.method(:get).arity, :<=, 1, "#{klass} should have at most 1 required parameter in get()") end end end fog-fog-google-4c8ece9/test/unit/storage/test_common_xml_collections.rb000066400000000000000000000031001514253314000265420ustar00rootroot00000000000000require "helpers/test_helper" class UnitTestStorageXMLCollections < Minitest::Test def setup Fog.mock! @client = Fog::Storage.new(provider: "google", google_storage_access_key_id: "", google_storage_secret_access_key: "") @bucket = @client.directories.create(key: "testbucket-#{SecureRandom.hex}") # Enumerate all descendants of Fog::Collection descendants = ObjectSpace.each_object(Fog::Collection.singleton_class) @collections = descendants.select do |d| d.name.match(/Fog::Google::StorageXML/) end end def teardown Fog.unmock! end def test_common_methods # This tests whether Fog::Google::Compute collections have common lifecycle methods @collections.each do |klass| obj = klass.new assert obj.respond_to?(:all), "#{klass} should have an .all method" assert obj.respond_to?(:get), "#{klass} should have a .get method" assert obj.respond_to?(:each), "#{klass} should behave like Enumerable" end end def test_collection_get_arguments @collections.each do |klass| obj = klass.new assert_operator(obj.method(:get).arity, :<=, 1, "#{klass} should have at most 1 required parameter in get()") end end def test_metadata attr = { key: "test-file", body: "hello world\x00" } f = @bucket.files.new(attr) assert_equal({}, f.metadata) metadata = { "x-goog-meta-my-header" => "hello world" } f = @bucket.files.new(attr.merge(metadata)) assert_equal(metadata, f.metadata) end end fog-fog-google-4c8ece9/test/unit/storage/test_json_requests.rb000066400000000000000000000067241514253314000247170ustar00rootroot00000000000000require "helpers/test_helper" class UnitTestJsonRequests < Minitest::Test def setup Fog.mock! @client = Fog::Storage.new(provider: "google", google_project: "", google_json_key_location: "") end def teardown Fog.unmock! end def test_get_url_path_has_query_params url = @client.get_object_url("bucket", "just some file.json", Time.now + 2 * 60, query: { "projection" => 'full, noAcl"' }) assert_match(/projection=full%2C%20noAcl/, url, "query string should be escaped") end def test_get_url_filter_nil_query_params url = @client.get_object_url("bucket", "just some file.json", Time.now + 2 * 60, query: { "projection" => nil }) refute_match(/projection/, url, "nil query params should be omitted") end def test_put_url_path_is_properly_escaped url = @client.put_object_url("bucket", "just some file.json", Time.now + 2 * 60, "Content-Type" => "application/json") assert_match(/just%20some%20file\.json/, url, "space should be escaped with '%20'") end def test_unescaped_slashes_in_url url = @client.get_object_https_url("bucket", "a/b/c.ext", Time.now + 2 * 60) assert_match(/a\/b\/c/, url, "slashes should not be escaped with '%2F'") end def test_unescaped_pluses_in_url url = @client.get_object_https_url("bucket", "a+c.ext", Time.now + 2 * 60) assert_match(/a\+c/, url, "pluses should not be escaped with '%2B'") end def test_get_object_https_url_uses_default_host url = @client.get_object_https_url("my-bucket", "my-file.txt", Time.now + 2 * 60) assert_match(%r{^https://storage\.googleapis\.com/}, url, "URL should use default storage.googleapis.com host") end def test_get_object_https_url_with_custom_universe_domain Fog.unmock! Fog.mock! client = Fog::Storage.new( provider: "google", google_project: "test-project", universe_domain: "example.com" ) url = client.get_object_https_url("my-bucket", "my-file.txt", Time.now + 2 * 60) assert_match(%r{^https://storage\.example\.com/}, url, "URL should use custom universe domain host") ensure Fog.unmock! Fog.mock! end def test_host_attribute_set_correctly assert_equal Fog::Google::Storage::GOOGLE_STORAGE_HOST, @client.host, "host attribute should be set to GOOGLE_STORAGE_HOST by default" end def test_host_attribute_with_custom_universe_domain Fog.unmock! Fog.mock! client = Fog::Storage.new( provider: "google", google_project: "test-project", universe_domain: "custom-universe.com" ) assert_equal "storage.custom-universe.com", client.host, "host attribute should match custom universe domain" ensure Fog.unmock! Fog.mock! end end fog-fog-google-4c8ece9/test/unit/storage/test_universe_domain.rb000066400000000000000000000142501514253314000251730ustar00rootroot00000000000000require "helpers/test_helper" require "google/apis/storage_v1" class TestStorageJSONUniverseDomain < Minitest::Test # Simple stub class to avoid minitest-mock bug in Ruby 3.1 class StorageServiceStub attr_reader :universe_domain_called_with def initialize @universe_domain_called_with = [] end def universe_domain=(value) @universe_domain_called_with << value end end def setup Fog.mock! # Clear any existing env variable @original_env = ENV["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] ENV.delete("GOOGLE_CLOUD_UNIVERSE_DOMAIN") end def teardown Fog.unmock! # Restore original env variable if @original_env ENV["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = @original_env else ENV.delete("GOOGLE_CLOUD_UNIVERSE_DOMAIN") end end def test_default_universe_domain client = Fog::Storage.new(provider: "google", google_project: "test-project") assert_equal "https://storage.googleapis.com/", client.bucket_base_url assert_equal Fog::Google::Storage::GOOGLE_STORAGE_HOST, client.host end def test_custom_universe_domain_via_option client = Fog::Storage.new( provider: "google", google_project: "test-project", universe_domain: "example.com" ) assert_equal "https://storage.example.com/", client.bucket_base_url assert_equal "storage.example.com", client.host end def test_custom_universe_domain_via_env_variable ENV["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = "test-universe.com" client = Fog::Storage.new(provider: "google", google_project: "test-project") assert_equal "https://storage.test-universe.com/", client.bucket_base_url assert_equal "storage.test-universe.com", client.host end def test_option_takes_precedence_over_env_variable ENV["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = "env-universe.com" client = Fog::Storage.new( provider: "google", google_project: "test-project", universe_domain: "option-universe.com" ) assert_equal "https://storage.option-universe.com/", client.bucket_base_url assert_equal "storage.option-universe.com", client.host end def test_universe_domain_with_real_client Fog.unmock! json_key_text = { client_id: "test-client-id.apps.googleusercontent.com", client_secret: "notsosecret", refresh_token: "refreshing-token", type: "authorized_user", universe_domain: "custom.universe.com" }.to_json mock_credentials = Google::Auth::UserRefreshCredentials.make_creds( json_key_io: StringIO.new(json_key_text) ) mock_storage_service = StorageServiceStub.new ::Google::Auth.stub(:get_application_default, mock_credentials) do ::Google::Apis::StorageV1::StorageService.stub(:new, mock_storage_service) do client = Fog::Google::StorageJSON::Real.new( google_project: "test-project", universe_domain: "custom.universe.com", google_application_default: true ) assert_equal "https://storage.custom.universe.com/", client.bucket_base_url assert_equal ["custom.universe.com"], mock_storage_service.universe_domain_called_with end end ensure Fog.mock! end def test_universe_domain_not_set_on_service_when_nil Fog.unmock! json_key_text = { client_id: "test-client-id.apps.googleusercontent.com", client_secret: "notsosecret", refresh_token: "refreshing-token", type: "authorized_user" }.to_json mock_credentials = Google::Auth::UserRefreshCredentials.make_creds( json_key_io: StringIO.new(json_key_text) ) mock_storage_service = StorageServiceStub.new ::Google::Auth.stub(:get_application_default, mock_credentials) do ::Google::Apis::StorageV1::StorageService.stub(:new, mock_storage_service) do client = Fog::Google::StorageJSON::Real.new( google_project: "test-project", google_application_default: true ) assert_equal "https://storage.googleapis.com/", client.bucket_base_url # Verify universe_domain= was NOT called assert_empty mock_storage_service.universe_domain_called_with end end ensure Fog.mock! end def test_universe_domain_set_on_application_default_credentials Fog.unmock! json_key_text = { client_id: "test-client-id.apps.googleusercontent.com", client_secret: "notsosecret", refresh_token: "refreshing-token", type: "authorized_user", universe_domain: "custom.universe.com" }.to_json mock_credentials = Google::Auth::UserRefreshCredentials.make_creds( json_key_io: StringIO.new(json_key_text) ) mock_storage_service = StorageServiceStub.new ::Google::Auth.stub(:get_application_default, mock_credentials) do ::Google::Apis::StorageV1::StorageService.stub(:new, mock_storage_service) do Fog::Google::StorageJSON::Real.new( google_project: "test-project", universe_domain: "custom.universe.com", google_application_default: true ) end end assert_equal ["custom.universe.com"], mock_storage_service.universe_domain_called_with ensure Fog.mock! end def test_universe_domain_set_on_json_key_credentials Fog.unmock! json_key = { client_secret: "privatekey", client_id: "client123", refresh_token: "refreshtoken", type: "authorized_user", quota_project_id: "test_project", private_key: OpenSSL::PKey::RSA.new(2048), universe_domain: "custom.universe.com" }.to_json mock_credentials = Google::Auth::UserRefreshCredentials.make_creds( json_key_io: StringIO.new(json_key), scope: "https://www.googleapis.com/auth/userinfo.profile" ) mock_storage_service = StorageServiceStub.new ::Google::Auth::ServiceAccountCredentials.stub(:make_creds, mock_credentials) do ::Google::Apis::StorageV1::StorageService.stub(:new, mock_storage_service) do Fog::Google::StorageJSON::Real.new( google_project: "test-project", universe_domain: "custom.universe.com", google_json_key_string: json_key ) end end assert_equal ["custom.universe.com"], mock_storage_service.universe_domain_called_with ensure Fog.mock! end end fog-fog-google-4c8ece9/test/unit/storage/test_xml_requests.rb000066400000000000000000000071651514253314000245460ustar00rootroot00000000000000require "helpers/test_helper" class UnitTestXMLRequests < Minitest::Test def setup Fog.mock! @client = Fog::Storage.new(provider: "google", google_storage_access_key_id: "", google_storage_secret_access_key: "") end def teardown Fog.unmock! end def test_get_http_url url = @client.get_object_http_url("bucket", "just some file.json", Time.now + 2 * 60) assert_match(/^http:\/\//, url, "URL starts with HTTP") end def test_get_https_url url = @client.get_object_https_url("bucket", "just some file.json", Time.now + 2 * 60) assert_match(/^https:\/\//, url, "URL starts with HTTPS") end def test_get_url_path_has_query_params url = @client.get_object_url("bucket", "just some file.json", Time.now + 2 * 60, query: { "Response-Content-Disposition" => 'inline; filename="test.json"' }) assert_match(/Response-Content-Disposition=inline%3B%20filename%3D%22test.json/, url, "query string should be escaped") end def test_get_url_filter_nil_query_params url = @client.get_object_url("bucket", "just some file.json", Time.now + 2 * 60, query: { "Response-Content-Disposition" => nil }) refute_match(/Response-Content-Disposition/, url, "nil query params should be omitted") end def test_put_url_path_is_properly_escaped url = @client.put_object_url("bucket", "just some file.json", Time.now + 2 * 60, "Content-Type" => "application/json") assert_match(/just%20some%20file\.json/, url, "space should be escaped with '%20'") end def test_get_object_https_url_uses_default_host url = @client.get_object_https_url("my-bucket", "my-file.txt", Time.now + 2 * 60) assert_match(%r{^https://storage\.googleapis\.com/}, url, "URL should use default storage.googleapis.com host") end def test_host_attribute_defaults_to_storage_googleapis_com assert_equal Fog::Google::Storage::GOOGLE_STORAGE_HOST, @client.host, "host attribute should default to GOOGLE_STORAGE_HOST" end def test_universe_domain_support Fog.unmock! Fog.mock! client = Fog::Storage.new( provider: "google", google_storage_access_key_id: "", google_storage_secret_access_key: "", universe_domain: "example.com" ) assert_equal "storage.example.com", client.host, "host should be derived from universe_domain" ensure Fog.unmock! Fog.mock! end def test_get_object_https_url_with_universe_domain Fog.unmock! Fog.mock! client = Fog::Storage.new( provider: "google", google_storage_access_key_id: "", google_storage_secret_access_key: "", universe_domain: "custom-universe.com" ) url = client.get_object_https_url("my-bucket", "my-file.txt", Time.now + 2 * 60) assert_match(%r{^https://storage\.custom-universe\.com/}, url, "URL should use universe domain host") ensure Fog.unmock! Fog.mock! end end fog-fog-google-4c8ece9/test/unit/test_shared.rb000066400000000000000000000046541514253314000216150ustar00rootroot00000000000000require "helpers/test_helper" class TestShared < Minitest::Test # Test class that includes Fog::Google::Shared class TestClient include Fog::Google::Shared end # Simple stub service class class ServiceStub attr_reader :universe_domain_called_with attr_accessor :client_options def initialize @universe_domain_called_with = [] @client_options = Struct.new(:members, :test_option).new([:test_option], nil) end def universe_domain=(value) @universe_domain_called_with << value end end def setup @client = TestClient.new @service = ServiceStub.new end def test_apply_client_options_sets_universe_domain options = { universe_domain: "custom.universe.com" } @client.apply_client_options(@service, options) assert_equal ["custom.universe.com"], @service.universe_domain_called_with end def test_apply_client_options_does_not_set_universe_domain_when_nil options = {} @client.apply_client_options(@service, options) assert_empty @service.universe_domain_called_with end def test_apply_client_options_uses_env_variable ENV["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = "env.universe.com" options = {} @client.apply_client_options(@service, options) assert_equal ["env.universe.com"], @service.universe_domain_called_with ensure ENV.delete("GOOGLE_CLOUD_UNIVERSE_DOMAIN") end def test_apply_client_options_prefers_option_over_env ENV["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = "env.universe.com" options = { universe_domain: "option.universe.com" } @client.apply_client_options(@service, options) assert_equal ["option.universe.com"], @service.universe_domain_called_with ensure ENV.delete("GOOGLE_CLOUD_UNIVERSE_DOMAIN") end def test_apply_client_options_sets_google_client_options options = { universe_domain: "custom.universe.com", google_client_options: { test_option: "test_value" } } @client.apply_client_options(@service, options) assert_equal ["custom.universe.com"], @service.universe_domain_called_with assert_equal "test_value", @service.client_options.test_option end def test_apply_client_options_works_without_google_client_options options = { universe_domain: "custom.universe.com" } @client.apply_client_options(@service, options) assert_equal ["custom.universe.com"], @service.universe_domain_called_with end end