9 import apiclient.discovery
10 import apiclient.errors
17 class CredentialsFromEnv(object):
19 def http_request(self, uri, **kwargs):
20 from httplib import BadStatusLine
21 if 'headers' not in kwargs:
22 kwargs['headers'] = {}
24 if config.get("ARVADOS_EXTERNAL_CLIENT", "") == "true":
25 kwargs['headers']['X-External-Client'] = '1'
27 kwargs['headers']['Authorization'] = 'OAuth2 %s' % config.get('ARVADOS_API_TOKEN', 'ARVADOS_API_TOKEN_not_set')
29 return self.orig_http_request(uri, **kwargs)
31 # This is how httplib tells us that it tried to reuse an
32 # existing connection but it was already closed by the
33 # server. In that case, yes, we would like to retry.
34 # Unfortunately, we are not absolutely certain that the
35 # previous call did not succeed, so this is slightly
37 return self.orig_http_request(uri, **kwargs)
38 def authorize(self, http):
39 http.orig_http_request = http.request
40 http.request = types.MethodType(self.http_request, http)
43 # Monkey patch discovery._cast() so objects and arrays get serialized
44 # with json.dumps() instead of str().
45 _cast_orig = apiclient.discovery._cast
46 def _cast_objects_too(value, schema_type):
48 if (type(value) != type('') and
49 (schema_type == 'object' or schema_type == 'array')):
50 return json.dumps(value)
52 return _cast_orig(value, schema_type)
53 apiclient.discovery._cast = _cast_objects_too
55 # Convert apiclient's HttpErrors into our own API error subclass for better
57 # Reassigning apiclient.errors.HttpError is not sufficient because most of the
58 # apiclient submodules import the class into their own namespace.
59 def _new_http_error(cls, *args, **kwargs):
60 return super(apiclient.errors.HttpError, cls).__new__(
61 errors.ApiError, *args, **kwargs)
62 apiclient.errors.HttpError.__new__ = staticmethod(_new_http_error)
64 def http_cache(data_type):
65 path = os.environ['HOME'] + '/.cache/arvados/' + data_type
67 util.mkdir_dash_p(path)
72 def api(version=None, cache=True, **kwargs):
73 """Return an apiclient Resources object for an Arvados instance.
76 * version: A string naming the version of the Arvados API to use (for
78 * cache: If True (default), return an existing resources object, or use
79 a cached discovery document to build one.
81 Additional keyword arguments will be passed directly to
82 `apiclient.discovery.build`. If the `discoveryServiceUrl` or `http`
83 keyword arguments are missing, this function will set default values for
84 them, based on the current Arvados configuration settings."""
85 if config.get('ARVADOS_DEBUG'):
86 logging.basicConfig(level=logging.DEBUG)
88 if not cache or not services.get(version):
91 logging.info("Using default API version. " +
92 "Call arvados.api('%s') instead." %
95 if 'discoveryServiceUrl' not in kwargs:
96 api_host = config.get('ARVADOS_API_HOST')
99 "No discoveryServiceUrl or ARVADOS_API_HOST set.")
100 kwargs['discoveryServiceUrl'] = (
101 'https://%s/discovery/v1/apis/{api}/{apiVersion}/rest' %
104 if 'http' not in kwargs:
106 # Prefer system's CA certificates (if available) over httplib2's.
107 certs_path = '/etc/ssl/certs/ca-certificates.crt'
108 if os.path.exists(certs_path):
109 http_kwargs['ca_certs'] = certs_path
111 http_kwargs['cache'] = http_cache('discovery')
112 if (config.get('ARVADOS_API_HOST_INSECURE', '').lower() in
113 ('yes', 'true', '1')):
114 http_kwargs['disable_ssl_certificate_validation'] = True
115 kwargs['http'] = httplib2.Http(**http_kwargs)
117 kwargs['http'] = CredentialsFromEnv().authorize(kwargs['http'])
118 services[version] = apiclient.discovery.build('arvados', version,
120 kwargs['http'].cache = None
121 return services[version]
123 def uncache_api(version):
124 if version in services:
125 del services[version]