9 from apiclient import discovery as apiclient_discovery
10 from apiclient import errors as apiclient_errors
15 _logger = logging.getLogger('arvados.api')
18 class CredentialsFromToken(object):
19 def __init__(self, api_token):
20 self.api_token = api_token
23 def http_request(self, uri, **kwargs):
24 from httplib import BadStatusLine
25 if 'headers' not in kwargs:
26 kwargs['headers'] = {}
28 if config.get("ARVADOS_EXTERNAL_CLIENT", "") == "true":
29 kwargs['headers']['X-External-Client'] = '1'
31 kwargs['headers']['Authorization'] = 'OAuth2 %s' % self.arvados_api_token
33 return self.orig_http_request(uri, **kwargs)
35 # This is how httplib tells us that it tried to reuse an
36 # existing connection but it was already closed by the
37 # server. In that case, yes, we would like to retry.
38 # Unfortunately, we are not absolutely certain that the
39 # previous call did not succeed, so this is slightly
41 return self.orig_http_request(uri, **kwargs)
42 def authorize(self, http):
43 http.arvados_api_token = self.api_token
44 http.orig_http_request = http.request
45 http.request = types.MethodType(self.http_request, http)
48 # Monkey patch discovery._cast() so objects and arrays get serialized
49 # with json.dumps() instead of str().
50 _cast_orig = apiclient_discovery._cast
51 def _cast_objects_too(value, schema_type):
53 if (type(value) != type('') and
54 (schema_type == 'object' or schema_type == 'array')):
55 return json.dumps(value)
57 return _cast_orig(value, schema_type)
58 apiclient_discovery._cast = _cast_objects_too
60 # Convert apiclient's HttpErrors into our own API error subclass for better
62 # Reassigning apiclient_errors.HttpError is not sufficient because most of the
63 # apiclient submodules import the class into their own namespace.
64 def _new_http_error(cls, *args, **kwargs):
65 return super(apiclient_errors.HttpError, cls).__new__(
66 errors.ApiError, *args, **kwargs)
67 apiclient_errors.HttpError.__new__ = staticmethod(_new_http_error)
69 def http_cache(data_type):
70 path = os.environ['HOME'] + '/.cache/arvados/' + data_type
72 util.mkdir_dash_p(path)
77 def api(version=None, cache=True, host=None, token=None, insecure=False, **kwargs):
78 """Return an apiclient Resources object for an Arvados instance.
81 * version: A string naming the version of the Arvados API to use (for
83 * cache: If True (default), return an existing Resources object if
84 one already exists with the same endpoint and credentials. If
85 False, create a new one, and do not keep it in the cache (i.e.,
86 do not return it from subsequent api(cache=True) calls with
87 matching endpoint and credentials).
88 * host: The Arvados API server host (and optional :port) to connect to.
89 * token: The authentication token to send with each API call.
90 * insecure: If True, ignore SSL certificate validation errors.
92 Additional keyword arguments will be passed directly to
93 `apiclient_discovery.build` if a new Resource object is created.
94 If the `discoveryServiceUrl` or `http` keyword arguments are
95 missing, this function will set default values for them, based on
96 the current Arvados configuration settings.
102 _logger.info("Using default API version. " +
103 "Call arvados.api('%s') instead." %
105 if 'discoveryServiceUrl' in kwargs:
107 raise ValueError("both discoveryServiceUrl and host provided")
108 # Here we can't use a token from environment, config file,
109 # etc. Those probably have nothing to do with the host
110 # provided by the caller.
112 raise ValueError("discoveryServiceUrl provided, but token missing")
115 elif not host and not token:
116 # Load from user configuration or environment
117 for x in ['ARVADOS_API_HOST', 'ARVADOS_API_TOKEN']:
118 if x not in config.settings():
119 raise ValueError("%s is not set. Aborting." % x)
120 host = config.get('ARVADOS_API_HOST')
121 token = config.get('ARVADOS_API_TOKEN')
122 insecure = config.flag_is_true('ARVADOS_API_HOST_INSECURE')
124 # Caller provided one but not the other
126 raise ValueError("token argument provided, but host missing.")
128 raise ValueError("host argument provided, but token missing.")
131 # Caller wants us to build the discoveryServiceUrl
132 kwargs['discoveryServiceUrl'] = (
133 'https://%s/discovery/v1/apis/{api}/{apiVersion}/rest' % (host,))
136 connprofile = (version, host, token, insecure)
137 svc = conncache.get(connprofile)
141 if 'http' not in kwargs:
143 # Prefer system's CA certificates (if available) over httplib2's.
144 certs_path = '/etc/ssl/certs/ca-certificates.crt'
145 if os.path.exists(certs_path):
146 http_kwargs['ca_certs'] = certs_path
148 http_kwargs['cache'] = http_cache('discovery')
150 http_kwargs['disable_ssl_certificate_validation'] = True
151 kwargs['http'] = httplib2.Http(**http_kwargs)
153 credentials = CredentialsFromToken(api_token=token)
154 kwargs['http'] = credentials.authorize(kwargs['http'])
156 svc = apiclient_discovery.build('arvados', version, **kwargs)
157 svc.api_token = token
158 kwargs['http'].cache = None
160 conncache[connprofile] = svc