1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
5 require 'google/api_client'
6 # Monkeypatch google-api-client gem to avoid sending newline characters
7 # on headers to make ruby-2.3.7+ happy.
8 # See: https://dev.arvados.org/issues/13920
9 # Addendum: OS_VERSION sometimes is not mutable, that's why we duplicate it (See: #17738)
10 Google::APIClient::ENV::OS_VERSION = +Google::APIClient::ENV::OS_VERSION.strip!
15 class Google::APIClient
16 def discovery_document(api, version)
18 discovery_uri = self.discovery_uri(api, version)
19 discovery_uri_hash = Digest::MD5.hexdigest(discovery_uri)
20 discovery_cache_path =
21 File.expand_path("~/.cache/arvados/discovery-#{discovery_uri_hash}.json")
22 @discovery_documents[discovery_uri_hash] ||=
23 disk_cached_discovery_document(discovery_cache_path) or
24 fetched_discovery_document(discovery_uri, discovery_cache_path)
29 def disk_cached_discovery_document(cache_path)
31 if (Time.now - File.mtime(cache_path)) < 86400
32 open(cache_path) do |cache_file|
33 return JSON.load(cache_file)
36 rescue IOError, SystemCallError, JSON::JSONError
37 # Error reading the cache. Act like it doesn't exist.
42 def write_cached_discovery_document(cache_path, body)
43 cache_dir = File.dirname(cache_path)
46 FileUtils.makedirs(cache_dir)
47 cache_file = Tempfile.new("discovery", cache_dir)
48 cache_file.write(body)
50 File.rename(cache_file.path, cache_path)
51 rescue IOError, SystemCallError
52 # Failure to write the cache is non-fatal. Do nothing.
54 cache_file.close! unless cache_file.nil?
58 def fetched_discovery_document(uri, cache_path)
59 response = self.execute!(:http_method => :get,
61 :authenticated => false)
62 write_cached_discovery_document(cache_path, response.body)
63 JSON.load(response.body)