9 from apiclient import discovery as apiclient_discovery
10 from apiclient import errors as apiclient_errors
15 _logger = logging.getLogger('arvados.api')
17 def _intercept_http_request(self, uri, **kwargs):
18 from httplib import BadStatusLine
20 if (self.max_request_size and
21 kwargs.get('body') and
22 self.max_request_size < len(kwargs['body'])):
23 raise apiclient_errors.MediaUploadSizeError("Request size %i bytes exceeds published limit of %i bytes" % (len(kwargs['body']), self.max_request_size))
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)
43 def _patch_http_request(http, api_token):
44 http.arvados_api_token = api_token
45 http.max_request_size = 0
46 http.orig_http_request = http.request
47 http.request = types.MethodType(_intercept_http_request, http)
50 # Monkey patch discovery._cast() so objects and arrays get serialized
51 # with json.dumps() instead of str().
52 _cast_orig = apiclient_discovery._cast
53 def _cast_objects_too(value, schema_type):
55 if (type(value) != type('') and
56 (schema_type == 'object' or schema_type == 'array')):
57 return json.dumps(value)
59 return _cast_orig(value, schema_type)
60 apiclient_discovery._cast = _cast_objects_too
62 # Convert apiclient's HttpErrors into our own API error subclass for better
64 # Reassigning apiclient_errors.HttpError is not sufficient because most of the
65 # apiclient submodules import the class into their own namespace.
66 def _new_http_error(cls, *args, **kwargs):
67 return super(apiclient_errors.HttpError, cls).__new__(
68 errors.ApiError, *args, **kwargs)
69 apiclient_errors.HttpError.__new__ = staticmethod(_new_http_error)
71 def http_cache(data_type):
72 path = os.environ['HOME'] + '/.cache/arvados/' + data_type
74 util.mkdir_dash_p(path)
79 def api(version=None, cache=True, host=None, token=None, insecure=False, **kwargs):
80 """Return an apiclient Resources object for an Arvados instance.
83 A string naming the version of the Arvados API to use (for
87 Use a cache (~/.cache/arvados/discovery) for the discovery
91 The Arvados API server host (and optional :port) to connect to.
94 The authentication token to send with each API call.
97 If True, ignore SSL certificate validation errors.
99 Additional keyword arguments will be passed directly to
100 `apiclient_discovery.build` if a new Resource object is created.
101 If the `discoveryServiceUrl` or `http` keyword arguments are
102 missing, this function will set default values for them, based on
103 the current Arvados configuration settings.
109 _logger.info("Using default API version. " +
110 "Call arvados.api('%s') instead." %
112 if 'discoveryServiceUrl' in kwargs:
114 raise ValueError("both discoveryServiceUrl and host provided")
115 # Here we can't use a token from environment, config file,
116 # etc. Those probably have nothing to do with the host
117 # provided by the caller.
119 raise ValueError("discoveryServiceUrl provided, but token missing")
122 elif not host and not token:
123 return api_from_config(version=version, cache=cache, **kwargs)
125 # Caller provided one but not the other
127 raise ValueError("token argument provided, but host missing.")
129 raise ValueError("host argument provided, but token missing.")
132 # Caller wants us to build the discoveryServiceUrl
133 kwargs['discoveryServiceUrl'] = (
134 'https://%s/discovery/v1/apis/{api}/{apiVersion}/rest' % (host,))
136 if 'http' not in kwargs:
138 # Prefer system's CA certificates (if available) over httplib2's.
139 certs_path = '/etc/ssl/certs/ca-certificates.crt'
140 if os.path.exists(certs_path):
141 http_kwargs['ca_certs'] = certs_path
143 http_kwargs['cache'] = http_cache('discovery')
145 http_kwargs['disable_ssl_certificate_validation'] = True
146 kwargs['http'] = httplib2.Http(**http_kwargs)
148 kwargs['http'] = _patch_http_request(kwargs['http'], token)
150 svc = apiclient_discovery.build('arvados', version, **kwargs)
151 svc.api_token = token
152 kwargs['http'].max_request_size = svc._rootDesc.get('maxRequestSize', 0)
153 kwargs['http'].cache = None
156 def api_from_config(version=None, apiconfig=None, **kwargs):
157 """Return an apiclient Resources object enabling access to an Arvados server
161 A string naming the version of the Arvados REST API to use (for
165 If provided, this should be a dict-like object (must support the get()
166 method) with entries for ARVADOS_API_HOST, ARVADOS_API_TOKEN, and
167 optionally ARVADOS_API_HOST_INSECURE. If not provided, use
168 arvados.config (which gets these parameters from the environment by
171 Other keyword arguments such as `cache` will be passed along `api()`
174 # Load from user configuration or environment
175 if apiconfig is None:
176 apiconfig = config.settings()
178 for x in ['ARVADOS_API_HOST', 'ARVADOS_API_TOKEN']:
179 if x not in apiconfig:
180 raise ValueError("%s is not set. Aborting." % x)
181 host = apiconfig.get('ARVADOS_API_HOST')
182 token = apiconfig.get('ARVADOS_API_TOKEN')
183 insecure = config.flag_is_true('ARVADOS_API_HOST_INSECURE', apiconfig)
185 return api(version=version, host=host, token=token, insecure=insecure, **kwargs)