google-cloud-env-1.6.0/0000755000004100000410000000000014235144407014720 5ustar www-datawww-datagoogle-cloud-env-1.6.0/README.md0000644000004100000410000000360514235144407016203 0ustar www-datawww-data# google-cloud-env This library provides information on the application hosting environment for apps running on Google Cloud Platform. - [google-cloud-env API documentation](https://googleapis.dev/ruby/google-cloud-env/latest) ## Supported Ruby Versions This library is supported on Ruby 2.5+. Google provides official support for Ruby versions that are actively supported by Ruby Core—that is, Ruby versions that are either in normal maintenance or in security maintenance, and not end of life. Currently, this means Ruby 2.5 and later. Older versions of Ruby _may_ still work, but are unsupported and not recommended. See https://www.ruby-lang.org/en/downloads/branches/ for details about the Ruby support schedule. ## Versioning This library follows [Semantic Versioning](http://semver.org/). It is currently in major version zero (0.y.z), which means that anything may change at any time and the public API should not be considered stable. ## Contributing Contributions to this library are always welcome and highly encouraged. See the [Contributing Guide](https://googleapis.dev/ruby/google-cloud-env/latest/file.CONTRIBUTING.html) for more information on how to get started. Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See [Code of Conduct](https://googleapis.dev/ruby/google-cloud-env/latest/file.CODE_OF_CONDUCT.html) for more information. ## License This library is licensed under Apache 2.0. Full license text is available in [LICENSE](https://googleapis.dev/ruby/google-cloud-env/latest/file.LICENSE.html). ## Support Please [report bugs at the project on Github](https://github.com/googleapis/google-cloud-ruby/issues). Don't hesitate to [ask questions](http://stackoverflow.com/questions/tagged/google-cloud-platform+ruby) about the client or APIs on [StackOverflow](http://stackoverflow.com). google-cloud-env-1.6.0/CHANGELOG.md0000644000004100000410000000350214235144407016531 0ustar www-datawww-data# Release History ## [1.6.0](https://www.github.com/googleapis/ruby-cloud-env/compare/google-cloud-env/v1.5.0...google-cloud-env/v1.6.0) (2022-03-21) ### Features * **deps:** update actions/setup-node action to v3 ([#27](https://www.github.com/googleapis/ruby-cloud-env/issues/27)) ([ffb9430](https://www.github.com/googleapis/ruby-cloud-env/commit/ffb9430e67bc4504d8c4f69203a0f911a90bff5a)) ### 1.5.0 (2021-03-08) #### Features * Drop support for Ruby 2.4 and add support for Ruby 3.0 ### 1.4.0 / 2020-10-12 #### Features * Honor GCE_METADATA_HOST environment variable ### 1.3.3 / 2020-07-10 #### Bug Fixes * Project ID logic honors GOOGLE_CLOUD_PROJECT ### 1.3.2 / 2020-05-28 #### Documentation * Fix a few broken links ### 1.3.1 / 2020-03-02 #### Bug Fixes * support faraday 1.x ### 1.3.0 / 2019-10-23 Now requires Ruby 2.4 or later. #### Features * Recognize App Engine Standard and Knative ### 1.2.1 / 2019-08-23 #### Bug Fixes * Send Metadata-Flavor header when testing the metadata server root #### Documentation * Update documentation ### 1.2.0 / 2019-06-19 * Support separate timeout for connecting to the metadata server vs the entire request ### 1.1.0 / 2019-05-29 * Support disabling of the metadata cache * Support configurable retries when querying the metadata server * Support configuration of the metadata request timeout ### 1.0.5 / 2018-09-20 * Update documentation. * Change documentation URL to googleapis GitHub org. ### 1.0.4 / 2018-09-12 * Add missing documentation files to package. ### 1.0.3 / 2018-09-10 * Update documentation. ### 1.0.2 / 2018-06-28 * Use Kubernetes Engine names. * Alias old method names for backwards compatibility. * Handle EHOSTDOWN error when connecting to env. ### 1.0.1 / 2017-07-11 * Update gem spec homepage links. ### 1.0.0 / 2017-03-31 * Initial release google-cloud-env-1.6.0/CODE_OF_CONDUCT.md0000644000004100000410000000367714235144407017534 0ustar www-datawww-data# Contributor Code of Conduct As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery * Personal attacks * Trolling or insulting/derogatory comments * Public or private harassment * Publishing other's private information, such as physical or electronic addresses, without explicit permission * Other unethical or unprofessional conduct. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) google-cloud-env-1.6.0/google-cloud-env.gemspec0000644000004100000410000000646214235144407021443 0ustar www-datawww-data######################################################### # This file has been automatically generated by gem2tgz # ######################################################### # -*- encoding: utf-8 -*- # stub: google-cloud-env 1.6.0 ruby lib Gem::Specification.new do |s| s.name = "google-cloud-env".freeze s.version = "1.6.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.metadata = { "bug_tracker_uri" => "https://github.com/googleapis/ruby-cloud-env/issues", "changelog_uri" => "https://googleapis.dev/ruby/google-cloud-env/v1.6.0/file.CHANGELOG.html", "documentation_uri" => "https://googleapis.dev/ruby/google-cloud-env/v1.6.0", "source_code_uri" => "https://github.com/googleapis/ruby-cloud-env" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze] s.authors = ["Daniel Azuma".freeze] s.date = "2022-03-25" s.description = "google-cloud-env provides information on the Google Cloud Platform hosting environment. Applications can use this library to determine hosting context information such as the project ID, whether App Engine is running, what tags are set on the VM instance, and much more.".freeze s.email = ["dazuma@google.com".freeze] s.files = [".yardopts".freeze, "CHANGELOG.md".freeze, "CODE_OF_CONDUCT.md".freeze, "CONTRIBUTING.md".freeze, "LICENSE".freeze, "README.md".freeze, "SECURITY.md".freeze, "lib/google-cloud-env.rb".freeze, "lib/google/cloud/env.rb".freeze, "lib/google/cloud/env/version.rb".freeze] s.homepage = "https://github.com/googleapis/ruby-cloud-env".freeze s.licenses = ["Apache-2.0".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.5".freeze) s.rubygems_version = "3.2.5".freeze s.summary = "Google Cloud Platform hosting environment information.".freeze if s.respond_to? :specification_version then s.specification_version = 4 end if s.respond_to? :add_runtime_dependency then s.add_development_dependency(%q.freeze, ["~> 1.1"]) s.add_runtime_dependency(%q.freeze, [">= 0.17.3", "< 3.0"]) s.add_development_dependency(%q.freeze, ["~> 1.25.1"]) s.add_development_dependency(%q.freeze, ["~> 5.10"]) s.add_development_dependency(%q.freeze, ["~> 1.0"]) s.add_development_dependency(%q.freeze, ["~> 1.1"]) s.add_development_dependency(%q.freeze, ["~> 5.2"]) s.add_development_dependency(%q.freeze, ["~> 3.0"]) s.add_development_dependency(%q.freeze, ["~> 0.9"]) s.add_development_dependency(%q.freeze, ["~> 0.9"]) s.add_development_dependency(%q.freeze, ["~> 0.1.13"]) else s.add_dependency(%q.freeze, ["~> 1.1"]) s.add_dependency(%q.freeze, [">= 0.17.3", "< 3.0"]) s.add_dependency(%q.freeze, ["~> 1.25.1"]) s.add_dependency(%q.freeze, ["~> 5.10"]) s.add_dependency(%q.freeze, ["~> 1.0"]) s.add_dependency(%q.freeze, ["~> 1.1"]) s.add_dependency(%q.freeze, ["~> 5.2"]) s.add_dependency(%q.freeze, ["~> 3.0"]) s.add_dependency(%q.freeze, ["~> 0.9"]) s.add_dependency(%q.freeze, ["~> 0.9"]) s.add_dependency(%q.freeze, ["~> 0.1.13"]) end end google-cloud-env-1.6.0/LICENSE0000644000004100000410000002613514235144407015734 0ustar www-datawww-data Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. google-cloud-env-1.6.0/lib/0000755000004100000410000000000014235144407015466 5ustar www-datawww-datagoogle-cloud-env-1.6.0/lib/google-cloud-env.rb0000644000004100000410000000117714235144407021167 0ustar www-datawww-data# Copyright 2017 Google LLC # # 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 # # https://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. require "google/cloud/env" require "google/cloud/env/version" google-cloud-env-1.6.0/lib/google/0000755000004100000410000000000014235144407016742 5ustar www-datawww-datagoogle-cloud-env-1.6.0/lib/google/cloud/0000755000004100000410000000000014235144407020050 5ustar www-datawww-datagoogle-cloud-env-1.6.0/lib/google/cloud/env.rb0000644000004100000410000003752314235144407021177 0ustar www-datawww-data# Copyright 2017 Google LLC # # 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 # # https://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. require "faraday" require "json" module Google module Cloud ## # # Google Cloud hosting environment # # This library provides access to information about the application's # hosting environment if it is running on Google Cloud Platform. You may # use this library to determine which Google Cloud product is hosting your # application (e.g. App Engine, Kubernetes Engine), information about the # Google Cloud project hosting the application, information about the # virtual machine instance, authentication information, and so forth. # # ## Usage # # Obtain an instance of the environment info with: # # ```ruby # require "google/cloud/env" # env = Google::Cloud.env # ``` # # Then you can interrogate any fields using methods on the object. # # ```ruby # if env.app_engine? # # App engine specific logic # end # ``` # # Any item that does not apply to the current environment will return nil. # For example: # # ```ruby # unless env.app_engine? # service = env.app_engine_service_id # => nil # end # ``` # class Env # @private Base (host) URL for the metadata server. METADATA_HOST = "http://169.254.169.254".freeze # @private URL path for v1 of the metadata service. METADATA_PATH_BASE = "/computeMetadata/v1".freeze # @private URL path for metadata server root. METADATA_ROOT_PATH = "/".freeze # @private METADATA_FAILURE_EXCEPTIONS = [ Faraday::TimeoutError, Faraday::ConnectionFailed, Errno::EHOSTDOWN, Errno::ETIMEDOUT, Timeout::Error ].freeze ## # Create a new instance of the environment information. # Most client should not need to call this directly. Obtain a singleton # instance of the information from `Google::Cloud.env`. This constructor # is provided to allow customization of the timeout/retry settings, as # well as mocking for testing. # # @param [Hash] env Mock environment variables. # @param [String] host The hostname or IP address of the metadata server. # Optional. If not specified, uses the `GCE_METADATA_HOST`, # environment variable or falls back to `169.254.167.254`. # @param [Hash,false] metadata_cache The metadata cache. You may pass # a prepopuated cache, an empty cache (the default) or `false` to # disable the cache completely. # @param [Numeric] open_timeout Timeout for opening http connections. # Defaults to 0.1. # @param [Numeric] request_timeout Timeout for entire http requests. # Defaults to 1.0. # @param [Integer] retry_count Number of times to retry http requests. # Defaults to 1. Note that retry remains in effect even if a custom # `connection` is provided. # @param [Numeric] retry_interval Time between retries in seconds. # Defaults to 0.1. # @param [Numeric] retry_backoff_factor Multiplier applied to the retry # interval on each retry. Defaults to 1.5. # @param [Numeric] retry_max_interval Maximum time between retries in # seconds. Defaults to 0.5. # @param [Faraday::Connection] connection Faraday connection to use. # If specified, overrides the `request_timeout` and `open_timeout` # settings. # def initialize env: nil, host: nil, connection: nil, metadata_cache: nil, open_timeout: 0.1, request_timeout: 1.0, retry_count: 2, retry_interval: 0.1, retry_backoff_factor: 1.5, retry_max_interval: 0.5 @disable_metadata_cache = metadata_cache == false @metadata_cache = metadata_cache || {} @env = env || ::ENV @retry_count = retry_count @retry_interval = retry_interval @retry_backoff_factor = retry_backoff_factor @retry_max_interval = retry_max_interval request_opts = { timeout: request_timeout, open_timeout: open_timeout } host ||= @env["GCE_METADATA_HOST"] || METADATA_HOST host = "http://#{host}" unless host.start_with? "http://" @connection = connection || ::Faraday.new(url: host, request: request_opts) end ## # Determine whether the application is running on a Knative-based # hosting platform, such as Cloud Run or Cloud Functions. # # @return [Boolean] # def knative? env["K_SERVICE"] ? true : false end ## # Determine whether the application is running on Google App Engine. # # @return [Boolean] # def app_engine? env["GAE_INSTANCE"] ? true : false end ## # Determine whether the application is running on Google App Engine # Flexible Environment. # # @return [Boolean] # def app_engine_flexible? app_engine? && env["GAE_ENV"] != "standard" end ## # Determine whether the application is running on Google App Engine # Standard Environment. # # @return [Boolean] # def app_engine_standard? app_engine? && env["GAE_ENV"] == "standard" end ## # Determine whether the application is running on Google Kubernetes # Engine (GKE). # # @return [Boolean] # def kubernetes_engine? kubernetes_engine_cluster_name ? true : false end alias container_engine? kubernetes_engine? ## # Determine whether the application is running on Google Cloud Shell. # # @return [Boolean] # def cloud_shell? env["DEVSHELL_GCLOUD_CONFIG"] ? true : false end ## # Determine whether the application is running on Google Compute Engine. # # Note that most other products (e.g. App Engine, Kubernetes Engine, # Cloud Shell) themselves use Compute Engine under the hood, so this # method will return true for all the above products. If you want to # determine whether the application is running on a "raw" Compute Engine # VM without using a higher level hosting product, use # {Env#raw_compute_engine?}. # # @return [Boolean] # def compute_engine? metadata? end ## # Determine whether the application is running on "raw" Google Compute # Engine without using a higher level hosting product such as App # Engine or Kubernetes Engine. # # @return [Boolean] # def raw_compute_engine? !knative? && !app_engine? && !cloud_shell? && metadata? && !kubernetes_engine? end ## # Returns the unique string ID of the project hosting the application, # or `nil` if the application is not running on Google Cloud. # # @return [String,nil] # def project_id env["GOOGLE_CLOUD_PROJECT"] || env["GCLOUD_PROJECT"] || env["DEVSHELL_PROJECT_ID"] || lookup_metadata("project", "project-id") end ## # Returns the unique numeric ID of the project hosting the application, # or `nil` if the application is not running on Google Cloud. # # Caveat: this method does not work and returns `nil` on CloudShell. # # @return [Integer,nil] # def numeric_project_id # CloudShell's metadata server seems to run in a dummy project. # We can get the user's normal project ID via environment variables, # but the numeric ID from the metadata service is not correct. So # disable this for CloudShell to avoid confusion. return nil if cloud_shell? result = lookup_metadata "project", "numeric-project-id" result.nil? ? nil : result.to_i end ## # Returns the name of the VM instance hosting the application, or `nil` # if the application is not running on Google Cloud. # # @return [String,nil] # def instance_name env["GAE_INSTANCE"] || lookup_metadata("instance", "name") end ## # Returns the description field (which may be the empty string) of the # VM instance hosting the application, or `nil` if the application is # not running on Google Cloud. # # @return [String,nil] # def instance_description lookup_metadata "instance", "description" end ## # Returns the zone (for example "`us-central1-c`") in which the instance # hosting the application lives. Returns `nil` if the application is # not running on Google Cloud. # # @return [String,nil] # def instance_zone result = lookup_metadata "instance", "zone" result.nil? ? nil : result.split("/").last end ## # Returns the machine type of the VM instance hosting the application, # or `nil` if the application is not running on Google Cloud. # # @return [String,nil] # def instance_machine_type result = lookup_metadata "instance", "machine-type" result.nil? ? nil : result.split("/").last end ## # Returns an array (which may be empty) of all tags set on the VM # instance hosting the application, or `nil` if the application is not # running on Google Cloud. # # @return [Array,nil] # def instance_tags result = lookup_metadata "instance", "tags" result.nil? ? nil : JSON.parse(result) end ## # Returns an array (which may be empty) of all attribute keys present # for the VM instance hosting the application, or `nil` if the # application is not running on Google Cloud. # # @return [Array,nil] # def instance_attribute_keys result = lookup_metadata "instance", "attributes/" result.nil? ? nil : result.split end ## # Returns the value of the given instance attribute for the VM instance # hosting the application, or `nil` if the given key does not exist or # application is not running on Google Cloud. # # @param [String] key Attribute key to look up. # @return [String,nil] # def instance_attribute key lookup_metadata "instance", "attributes/#{key}" end ## # Returns the name of the running Knative service, or `nil` if the # current code is not running on Knative. # # @return [String,nil] # def knative_service_id env["K_SERVICE"] end alias knative_service_name knative_service_id ## # Returns the revision of the running Knative service, or `nil` if the # current code is not running on Knative. # # @return [String,nil] # def knative_service_revision env["K_REVISION"] end ## # Returns the name of the running App Engine service, or `nil` if the # current code is not running in App Engine. # # @return [String,nil] # def app_engine_service_id env["GAE_SERVICE"] end alias app_engine_service_name app_engine_service_id ## # Returns the version of the running App Engine service, or `nil` if the # current code is not running in App Engine. # # @return [String,nil] # def app_engine_service_version env["GAE_VERSION"] end ## # Returns the amount of memory reserved for the current App Engine # instance, or `nil` if the current code is not running in App Engine. # # @return [Integer,nil] # def app_engine_memory_mb result = env["GAE_MEMORY_MB"] result.nil? ? nil : result.to_i end ## # Returns the name of the Kubernetes Engine cluster hosting the # application, or `nil` if the current code is not running in # Kubernetes Engine. # # @return [String,nil] # def kubernetes_engine_cluster_name instance_attribute "cluster-name" end alias container_engine_cluster_name kubernetes_engine_cluster_name ## # Returns the name of the Kubernetes Engine namespace hosting the # application, or `nil` if the current code is not running in # Kubernetes Engine. # # @return [String,nil] # def kubernetes_engine_namespace_id # The Kubernetes namespace is difficult to obtain without help from # the application using the Downward API. The environment variable # below is set in some older versions of GKE, and the file below is # present in Kubernetes as of version 1.9, but it is possible that # alternatives will need to be found in the future. env["GKE_NAMESPACE_ID"] || ::IO.read("/var/run/secrets/kubernetes.io/serviceaccount/namespace") rescue SystemCallError nil end alias container_engine_namespace_id kubernetes_engine_namespace_id ## # Determine whether the Google Compute Engine Metadata Service is running. # # @return [Boolean] # def metadata? path = METADATA_ROOT_PATH if @disable_metadata_cache || !metadata_cache.include?(path) metadata_cache[path] = retry_or_fail_with false do resp = connection.get path do |req| req.headers = { "Metadata-Flavor" => "Google" } end resp.status == 200 && resp.headers["Metadata-Flavor"] == "Google" end end metadata_cache[path] end ## # Retrieve info from the Google Compute Engine Metadata Service. # Returns `nil` if the Metadata Service is not running or the given # data is not present. # # @param [String] type Type of metadata to look up. Currently supported # values are "project" and "instance". # @param [String] entry Metadata entry path to look up. # @return [String,nil] # def lookup_metadata type, entry return nil unless metadata? path = "#{METADATA_PATH_BASE}/#{type}/#{entry}" if @disable_metadata_cache || !metadata_cache.include?(path) metadata_cache[path] = retry_or_fail_with nil do resp = connection.get path do |req| req.headers = { "Metadata-Flavor" => "Google" } end resp.status == 200 ? resp.body.strip : nil end end metadata_cache[path] end ## # Returns the global instance of {Google::Cloud::Env}. # # @return [Google::Cloud::Env] # def self.get ::Google::Cloud.env end private attr_reader :connection attr_reader :env attr_reader :metadata_cache def retry_or_fail_with error_result retries_remaining = @retry_count retry_interval = @retry_interval begin yield rescue *METADATA_FAILURE_EXCEPTIONS retries_remaining -= 1 if retries_remaining >= 0 sleep retry_interval retry_interval *= @retry_backoff_factor retry_interval = @retry_max_interval if retry_interval > @retry_max_interval retry end error_result end end end @env = Env.new ## # Returns the global instance of {Google::Cloud::Env}. # # @return [Google::Cloud::Env] # def self.env @env end end end google-cloud-env-1.6.0/lib/google/cloud/env/0000755000004100000410000000000014235144407020640 5ustar www-datawww-datagoogle-cloud-env-1.6.0/lib/google/cloud/env/version.rb0000644000004100000410000000123514235144407022653 0ustar www-datawww-data# Copyright 2017 Google LLC # # 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 # # https://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. module Google module Cloud class Env VERSION = "1.6.0".freeze end end end google-cloud-env-1.6.0/CONTRIBUTING.md0000644000004100000410000000512314235144407017152 0ustar www-datawww-data# Contributing to Google Cloud Ruby Client 1. **Sign one of the contributor license agreements below.** 2. Fork the repo, develop and test your code changes. 3. Send a pull request. ## Contributor License Agreements Before we can accept your pull requests you'll need to sign a Contributor License Agreement (CLA): - **If you are an individual writing original source code** and **you own the intellectual property**, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). - **If you work for a company that wants to allow you to contribute your work**, then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). You can sign these electronically (just scroll to the bottom). After that, we'll be able to accept your pull requests. ## Setup In order to use the google-cloud-ruby console and run the project's tests, there is a small amount of setup: 1. Install Ruby. google-cloud-env requires Ruby 2.4+. You may choose to manage your Ruby and gem installations with [RVM](https://rvm.io/), [rbenv](https://github.com/rbenv/rbenv), or [chruby](https://github.com/postmodern/chruby). 2. Install [Bundler](http://bundler.io/). ```sh $ gem install bundler ``` 3. Install the project dependencies. ```sh $ bundle install ``` ## Tests All contributions should include tests that ensure the contributed code behaves as expected. To run the tests and code style checks together: ``` sh $ bundle exec rake ci ``` ### Unit Tests The project uses the [minitest](https://github.com/seattlerb/minitest) library, including [specs](https://github.com/seattlerb/minitest#specs), [mocks](https://github.com/seattlerb/minitest#mocks) and [minitest-autotest](https://github.com/seattlerb/minitest-autotest). To run the unit tests for a package: ``` sh $ bundle exec rake test ``` ### Coding Style Please follow the established coding style in the library. The style is is largely based on [The Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) with a few exceptions based on seattle-style: * Avoid parenthesis when possible, including in method definitions. * Always use double quotes strings. ([Option B](https://github.com/bbatsov/ruby-style-guide#strings)) You can check your code against these rules by running Rubocop like so: ```sh $ bundle exec rake rubocop ``` ## Code of Conduct Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See {file:CODE_OF_CONDUCT.md Code of Conduct} for more information. google-cloud-env-1.6.0/.yardopts0000644000004100000410000000024714235144407016571 0ustar www-datawww-data--no-private --title=Google Cloud Env --markup markdown --markup-provider redcarpet ./lib/**/*.rb - README.md CONTRIBUTING.md CHANGELOG.md CODE_OF_CONDUCT.md LICENSE google-cloud-env-1.6.0/SECURITY.md0000644000004100000410000000051114235144407016506 0ustar www-datawww-data# Security Policy To report a security issue, please use [g.co/vulnz](https://g.co/vulnz). The Google Security Team will respond within 5 working days of your report on g.co/vulnz. We use g.co/vulnz for our intake, and do coordination and disclosure here using GitHub Security Advisory to privately discuss and fix the issue.