Merge branch 'master' into 5145-combine-collections-repeated-filenames
[arvados.git] / sdk / python / arvados / api.py
1 import httplib2
2 import json
3 import logging
4 import os
5 import re
6 import types
7
8 import apiclient
9 from apiclient import discovery as apiclient_discovery
10 from apiclient import errors as apiclient_errors
11 import config
12 import errors
13 import util
14
15 _logger = logging.getLogger('arvados.api')
16
17 def _intercept_http_request(self, uri, **kwargs):
18     from httplib import BadStatusLine
19
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))
24
25     if 'headers' not in kwargs:
26         kwargs['headers'] = {}
27
28     if config.get("ARVADOS_EXTERNAL_CLIENT", "") == "true":
29         kwargs['headers']['X-External-Client'] = '1'
30
31     kwargs['headers']['Authorization'] = 'OAuth2 %s' % self.arvados_api_token
32     try:
33         return self.orig_http_request(uri, **kwargs)
34     except BadStatusLine:
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
40         # risky.
41         return self.orig_http_request(uri, **kwargs)
42
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)
48     return http
49
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):
54     global _cast_orig
55     if (type(value) != type('') and
56         (schema_type == 'object' or schema_type == 'array')):
57         return json.dumps(value)
58     else:
59         return _cast_orig(value, schema_type)
60 apiclient_discovery._cast = _cast_objects_too
61
62 # Convert apiclient's HttpErrors into our own API error subclass for better
63 # error reporting.
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)
70
71 def http_cache(data_type):
72     path = os.environ['HOME'] + '/.cache/arvados/' + data_type
73     try:
74         util.mkdir_dash_p(path)
75     except OSError:
76         path = None
77     return path
78
79 def api(version=None, cache=True, host=None, token=None, insecure=False, **kwargs):
80     """Return an apiclient Resources object for an Arvados instance.
81
82     :version:
83       A string naming the version of the Arvados API to use (for
84       example, 'v1').
85
86     :cache:
87       Use a cache (~/.cache/arvados/discovery) for the discovery
88       document.
89
90     :host:
91       The Arvados API server host (and optional :port) to connect to.
92
93     :token:
94       The authentication token to send with each API call.
95
96     :insecure:
97       If True, ignore SSL certificate validation errors.
98
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.
104
105     """
106
107     if not version:
108         version = 'v1'
109         _logger.info("Using default API version. " +
110                      "Call arvados.api('%s') instead." %
111                      version)
112     if 'discoveryServiceUrl' in kwargs:
113         if host:
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.
118         if not token:
119             raise ValueError("discoveryServiceUrl provided, but token missing")
120     elif host and token:
121         pass
122     elif not host and not token:
123         return api_from_config(version=version, cache=cache, **kwargs)
124     else:
125         # Caller provided one but not the other
126         if not host:
127             raise ValueError("token argument provided, but host missing.")
128         else:
129             raise ValueError("host argument provided, but token missing.")
130
131     if host:
132         # Caller wants us to build the discoveryServiceUrl
133         kwargs['discoveryServiceUrl'] = (
134             'https://%s/discovery/v1/apis/{api}/{apiVersion}/rest' % (host,))
135
136     if 'http' not in kwargs:
137         http_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
142         if cache:
143             http_kwargs['cache'] = http_cache('discovery')
144         if insecure:
145             http_kwargs['disable_ssl_certificate_validation'] = True
146         kwargs['http'] = httplib2.Http(**http_kwargs)
147
148     kwargs['http'] = _patch_http_request(kwargs['http'], token)
149
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
154     return svc
155
156 def api_from_config(version=None, apiconfig=None, **kwargs):
157     """Return an apiclient Resources object enabling access to an Arvados server
158     instance.
159
160     :version:
161       A string naming the version of the Arvados REST API to use (for
162       example, 'v1').
163
164     :apiconfig:
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
169       default.)
170
171     Other keyword arguments such as `cache` will be passed along `api()`
172
173     """
174     # Load from user configuration or environment
175     if apiconfig is None:
176         apiconfig = config.settings()
177
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)
184
185     return api(version=version, host=host, token=token, insecure=insecure, **kwargs)