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