Merge branch '3415-py-sdk-api-errors-wip'
[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 import apiclient.discovery
10 import apiclient.errors
11 import config
12 import errors
13 import util
14
15 services = {}
16
17 class CredentialsFromEnv(object):
18     @staticmethod
19     def http_request(self, uri, **kwargs):
20         from httplib import BadStatusLine
21         if 'headers' not in kwargs:
22             kwargs['headers'] = {}
23
24         if config.get("ARVADOS_EXTERNAL_CLIENT", "") == "true":
25             kwargs['headers']['X-External-Client'] = '1'
26
27         kwargs['headers']['Authorization'] = 'OAuth2 %s' % config.get('ARVADOS_API_TOKEN', 'ARVADOS_API_TOKEN_not_set')
28         try:
29             return self.orig_http_request(uri, **kwargs)
30         except BadStatusLine:
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
36             # risky.
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)
41         return http
42
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):
47     global _cast_orig
48     if (type(value) != type('') and
49         (schema_type == 'object' or schema_type == 'array')):
50         return json.dumps(value)
51     else:
52         return _cast_orig(value, schema_type)
53 apiclient.discovery._cast = _cast_objects_too
54
55 # Convert apiclient's HttpErrors into our own API error subclass for better
56 # error reporting.
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)
63
64 def http_cache(data_type):
65     path = os.environ['HOME'] + '/.cache/arvados/' + data_type
66     try:
67         util.mkdir_dash_p(path)
68     except OSError:
69         path = None
70     return path
71
72 def api(version=None, cache=True, **kwargs):
73     """Return an apiclient Resources object for an Arvados instance.
74
75     Arguments:
76     * version: A string naming the version of the Arvados API to use (for
77       example, 'v1').
78     * cache: If True (default), return an existing resources object, or use
79       a cached discovery document to build one.
80
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)
87
88     if not cache or not services.get(version):
89         if not version:
90             version = 'v1'
91             logging.info("Using default API version. " +
92                          "Call arvados.api('%s') instead." %
93                          version)
94
95         if 'discoveryServiceUrl' not in kwargs:
96             api_host = config.get('ARVADOS_API_HOST')
97             if not api_host:
98                 raise ValueError(
99                     "No discoveryServiceUrl or ARVADOS_API_HOST set.")
100             kwargs['discoveryServiceUrl'] = (
101                 'https://%s/discovery/v1/apis/{api}/{apiVersion}/rest' %
102                 (api_host,))
103
104         if 'http' not in kwargs:
105             http_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
110             if cache:
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)
116
117         kwargs['http'] = CredentialsFromEnv().authorize(kwargs['http'])
118         services[version] = apiclient.discovery.build('arvados', version,
119                                                       **kwargs)
120         kwargs['http'].cache = None
121     return services[version]
122
123 def uncache_api(version):
124     if version in services:
125         del services[version]