Class: Google::Cloud::Env

Inherits:
Object
  • Object
show all
Defined in:
lib/google/cloud/env.rb,
lib/google/cloud/env/version.rb

Overview

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:

require "google/cloud/env"
env = Google::Cloud.env

Then you can interrogate any fields using methods on the object.

if env.app_engine?
  # App engine specific logic
end

Any item that does not apply to the current environment will return nil. For example:

unless env.app_engine?
  service = env.app_engine_service_id  # => nil
end

Constant Summary collapse

VERSION =
"1.6.0".freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#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) ⇒ Env

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.

Parameters:

  • env (Hash) (defaults to: nil)

    Mock environment variables.

  • host (String) (defaults to: nil)

    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.

  • metadata_cache (Hash, false) (defaults to: nil)

    The metadata cache. You may pass a prepopuated cache, an empty cache (the default) or false to disable the cache completely.

  • open_timeout (Numeric) (defaults to: 0.1)

    Timeout for opening http connections. Defaults to 0.1.

  • request_timeout (Numeric) (defaults to: 1.0)

    Timeout for entire http requests. Defaults to 1.0.

  • retry_count (Integer) (defaults to: 2)

    Number of times to retry http requests. Defaults to 1. Note that retry remains in effect even if a custom connection is provided.

  • retry_interval (Numeric) (defaults to: 0.1)

    Time between retries in seconds. Defaults to 0.1.

  • retry_backoff_factor (Numeric) (defaults to: 1.5)

    Multiplier applied to the retry interval on each retry. Defaults to 1.5.

  • retry_max_interval (Numeric) (defaults to: 0.5)

    Maximum time between retries in seconds. Defaults to 0.5.

  • connection (Faraday::Connection) (defaults to: nil)

    Faraday connection to use. If specified, overrides the request_timeout and open_timeout settings.



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/google/cloud/env.rb', line 108

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 =  == false
  @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

Class Method Details

.getGoogle::Cloud::Env

Returns the global instance of Google::Cloud::Env.

Returns:



455
456
457
# File 'lib/google/cloud/env.rb', line 455

def self.get
  ::Google::Cloud.env
end

Instance Method Details

#app_engine?Boolean

Determine whether the application is running on Google App Engine.

Returns:

  • (Boolean)


140
141
142
# File 'lib/google/cloud/env.rb', line 140

def app_engine?
  env["GAE_INSTANCE"] ? true : false
end

#app_engine_flexible?Boolean

Determine whether the application is running on Google App Engine Flexible Environment.

Returns:

  • (Boolean)


150
151
152
# File 'lib/google/cloud/env.rb', line 150

def app_engine_flexible?
  app_engine? && env["GAE_ENV"] != "standard"
end

#app_engine_memory_mbInteger?

Returns the amount of memory reserved for the current App Engine instance, or nil if the current code is not running in App Engine.

Returns:

  • (Integer, nil)


371
372
373
374
# File 'lib/google/cloud/env.rb', line 371

def app_engine_memory_mb
  result = env["GAE_MEMORY_MB"]
  result.nil? ? nil : result.to_i
end

#app_engine_service_idString? Also known as: app_engine_service_name

Returns the name of the running App Engine service, or nil if the current code is not running in App Engine.

Returns:

  • (String, nil)


350
351
352
# File 'lib/google/cloud/env.rb', line 350

def app_engine_service_id
  env["GAE_SERVICE"]
end

#app_engine_service_versionString?

Returns the version of the running App Engine service, or nil if the current code is not running in App Engine.

Returns:

  • (String, nil)


361
362
363
# File 'lib/google/cloud/env.rb', line 361

def app_engine_service_version
  env["GAE_VERSION"]
end

#app_engine_standard?Boolean

Determine whether the application is running on Google App Engine Standard Environment.

Returns:

  • (Boolean)


160
161
162
# File 'lib/google/cloud/env.rb', line 160

def app_engine_standard?
  app_engine? && env["GAE_ENV"] == "standard"
end

#cloud_shell?Boolean

Determine whether the application is running on Google Cloud Shell.

Returns:

  • (Boolean)


180
181
182
# File 'lib/google/cloud/env.rb', line 180

def cloud_shell?
  env["DEVSHELL_GCLOUD_CONFIG"] ? true : false
end

#compute_engine?Boolean

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 #raw_compute_engine?.

Returns:

  • (Boolean)


196
197
198
# File 'lib/google/cloud/env.rb', line 196

def compute_engine?
  metadata?
end

#instance_attribute(key) ⇒ String?

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.

Parameters:

  • key (String)

    Attribute key to look up.

Returns:

  • (String, nil)


319
320
321
# File 'lib/google/cloud/env.rb', line 319

def instance_attribute key
   "instance", "attributes/#{key}"
end

#instance_attribute_keysArray<String>?

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.

Returns:

  • (Array<String>, nil)


306
307
308
309
# File 'lib/google/cloud/env.rb', line 306

def instance_attribute_keys
  result =  "instance", "attributes/"
  result.nil? ? nil : result.split
end

#instance_descriptionString?

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.

Returns:

  • (String, nil)


260
261
262
# File 'lib/google/cloud/env.rb', line 260

def instance_description
   "instance", "description"
end

#instance_machine_typeString?

Returns the machine type of the VM instance hosting the application, or nil if the application is not running on Google Cloud.

Returns:

  • (String, nil)


282
283
284
285
# File 'lib/google/cloud/env.rb', line 282

def instance_machine_type
  result =  "instance", "machine-type"
  result.nil? ? nil : result.split("/").last
end

#instance_nameString?

Returns the name of the VM instance hosting the application, or nil if the application is not running on Google Cloud.

Returns:

  • (String, nil)


249
250
251
# File 'lib/google/cloud/env.rb', line 249

def instance_name
  env["GAE_INSTANCE"] || ("instance", "name")
end

#instance_tagsArray<String>?

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.

Returns:

  • (Array<String>, nil)


294
295
296
297
# File 'lib/google/cloud/env.rb', line 294

def instance_tags
  result =  "instance", "tags"
  result.nil? ? nil : JSON.parse(result)
end

#instance_zoneString?

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.

Returns:

  • (String, nil)


271
272
273
274
# File 'lib/google/cloud/env.rb', line 271

def instance_zone
  result =  "instance", "zone"
  result.nil? ? nil : result.split("/").last
end

#knative?Boolean

Determine whether the application is running on a Knative-based hosting platform, such as Cloud Run or Cloud Functions.

Returns:

  • (Boolean)


131
132
133
# File 'lib/google/cloud/env.rb', line 131

def knative?
  env["K_SERVICE"] ? true : false
end

#knative_service_idString? Also known as: knative_service_name

Returns the name of the running Knative service, or nil if the current code is not running on Knative.

Returns:

  • (String, nil)


329
330
331
# File 'lib/google/cloud/env.rb', line 329

def knative_service_id
  env["K_SERVICE"]
end

#knative_service_revisionString?

Returns the revision of the running Knative service, or nil if the current code is not running on Knative.

Returns:

  • (String, nil)


340
341
342
# File 'lib/google/cloud/env.rb', line 340

def knative_service_revision
  env["K_REVISION"]
end

#kubernetes_engine?Boolean Also known as: container_engine?

Determine whether the application is running on Google Kubernetes Engine (GKE).

Returns:

  • (Boolean)


170
171
172
# File 'lib/google/cloud/env.rb', line 170

def kubernetes_engine?
  kubernetes_engine_cluster_name ? true : false
end

#kubernetes_engine_cluster_nameString? Also known as: container_engine_cluster_name

Returns the name of the Kubernetes Engine cluster hosting the application, or nil if the current code is not running in Kubernetes Engine.

Returns:

  • (String, nil)


383
384
385
# File 'lib/google/cloud/env.rb', line 383

def kubernetes_engine_cluster_name
  instance_attribute "cluster-name"
end

#kubernetes_engine_namespace_idString? Also known as: container_engine_namespace_id

Returns the name of the Kubernetes Engine namespace hosting the application, or nil if the current code is not running in Kubernetes Engine.

Returns:

  • (String, nil)


395
396
397
398
399
400
401
402
403
404
# File 'lib/google/cloud/env.rb', line 395

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

#lookup_metadata(type, entry) ⇒ String?

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.

Parameters:

  • type (String)

    Type of metadata to look up. Currently supported values are "project" and "instance".

  • entry (String)

    Metadata entry path to look up.

Returns:

  • (String, nil)


435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/google/cloud/env.rb', line 435

def  type, entry
  return nil unless metadata?

  path = "#{METADATA_PATH_BASE}/#{type}/#{entry}"
  if @disable_metadata_cache || !.include?(path)
    [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
  [path]
end

#metadata?Boolean

Determine whether the Google Compute Engine Metadata Service is running.

Returns:

  • (Boolean)


412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/google/cloud/env.rb', line 412

def metadata?
  path = METADATA_ROOT_PATH
  if @disable_metadata_cache || !.include?(path)
    [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
  [path]
end

#numeric_project_idInteger?

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.

Returns:

  • (Integer, nil)


232
233
234
235
236
237
238
239
240
241
# File 'lib/google/cloud/env.rb', line 232

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 =  "project", "numeric-project-id"
  result.nil? ? nil : result.to_i
end

#project_idString?

Returns the unique string ID of the project hosting the application, or nil if the application is not running on Google Cloud.

Returns:

  • (String, nil)


217
218
219
220
221
222
# File 'lib/google/cloud/env.rb', line 217

def project_id
  env["GOOGLE_CLOUD_PROJECT"] ||
    env["GCLOUD_PROJECT"] ||
    env["DEVSHELL_PROJECT_ID"] ||
    ("project", "project-id")
end

#raw_compute_engine?Boolean

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.

Returns:

  • (Boolean)


207
208
209
# File 'lib/google/cloud/env.rb', line 207

def raw_compute_engine?
  !knative? && !app_engine? && !cloud_shell? && metadata? && !kubernetes_engine?
end