17738: Fixes the issue by strip!()ing a mutable version of OS_VERSION.
[arvados.git] / sdk / ruby / lib / arvados / google_api_client.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
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!
11
12 require 'json'
13 require 'tempfile'
14
15 class Google::APIClient
16   def discovery_document(api, version)
17     api = api.to_s
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)
25   end
26
27   private
28
29   def disk_cached_discovery_document(cache_path)
30     begin
31       if (Time.now - File.mtime(cache_path)) < 86400
32         open(cache_path) do |cache_file|
33           return JSON.load(cache_file)
34         end
35       end
36     rescue IOError, SystemCallError, JSON::JSONError
37       # Error reading the cache.  Act like it doesn't exist.
38     end
39     nil
40   end
41
42   def write_cached_discovery_document(cache_path, body)
43     cache_dir = File.dirname(cache_path)
44     cache_file = nil
45     begin
46       FileUtils.makedirs(cache_dir)
47       cache_file = Tempfile.new("discovery", cache_dir)
48       cache_file.write(body)
49       cache_file.flush
50       File.rename(cache_file.path, cache_path)
51     rescue IOError, SystemCallError
52       # Failure to write the cache is non-fatal.  Do nothing.
53     ensure
54       cache_file.close! unless cache_file.nil?
55     end
56   end
57
58   def fetched_discovery_document(uri, cache_path)
59     response = self.execute!(:http_method => :get,
60                              :uri => uri,
61                              :authenticated => false)
62     write_cached_discovery_document(cache_path, response.body)
63     JSON.load(response.body)
64   end
65 end