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