Merge branch '5043-crunchstat-long-lines' closes #5043
[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 class CredentialsFromToken(object):
18     def __init__(self, api_token):
19         self.api_token = api_token
20
21     @staticmethod
22     def http_request(self, uri, **kwargs):
23         from httplib import BadStatusLine
24         if 'headers' not in kwargs:
25             kwargs['headers'] = {}
26
27         if config.get("ARVADOS_EXTERNAL_CLIENT", "") == "true":
28             kwargs['headers']['X-External-Client'] = '1'
29
30         kwargs['headers']['Authorization'] = 'OAuth2 %s' % self.arvados_api_token
31         try:
32             return self.orig_http_request(uri, **kwargs)
33         except BadStatusLine:
34             # This is how httplib tells us that it tried to reuse an
35             # existing connection but it was already closed by the
36             # server. In that case, yes, we would like to retry.
37             # Unfortunately, we are not absolutely certain that the
38             # previous call did not succeed, so this is slightly
39             # risky.
40             return self.orig_http_request(uri, **kwargs)
41     def authorize(self, http):
42         http.arvados_api_token = self.api_token
43         http.orig_http_request = http.request
44         http.request = types.MethodType(self.http_request, http)
45         return http
46
47 # Monkey patch discovery._cast() so objects and arrays get serialized
48 # with json.dumps() instead of str().
49 _cast_orig = apiclient_discovery._cast
50 def _cast_objects_too(value, schema_type):
51     global _cast_orig
52     if (type(value) != type('') and
53         (schema_type == 'object' or schema_type == 'array')):
54         return json.dumps(value)
55     else:
56         return _cast_orig(value, schema_type)
57 apiclient_discovery._cast = _cast_objects_too
58
59 # Convert apiclient's HttpErrors into our own API error subclass for better
60 # error reporting.
61 # Reassigning apiclient_errors.HttpError is not sufficient because most of the
62 # apiclient submodules import the class into their own namespace.
63 def _new_http_error(cls, *args, **kwargs):
64     return super(apiclient_errors.HttpError, cls).__new__(
65         errors.ApiError, *args, **kwargs)
66 apiclient_errors.HttpError.__new__ = staticmethod(_new_http_error)
67
68 def http_cache(data_type):
69     path = os.environ['HOME'] + '/.cache/arvados/' + data_type
70     try:
71         util.mkdir_dash_p(path)
72     except OSError:
73         path = None
74     return path
75
76 def api(version=None, cache=True, host=None, token=None, insecure=False, **kwargs):
77     """Return an apiclient Resources object for an Arvados instance.
78
79     :version:
80       A string naming the version of the Arvados API to use (for
81       example, 'v1').
82
83     :cache:
84       Use a cache (~/.cache/arvados/discovery) for the discovery
85       document.
86
87     :host:
88       The Arvados API server host (and optional :port) to connect to.
89
90     :token:
91       The authentication token to send with each API call.
92
93     :insecure:
94       If True, ignore SSL certificate validation errors.
95
96     Additional keyword arguments will be passed directly to
97     `apiclient_discovery.build` if a new Resource object is created.
98     If the `discoveryServiceUrl` or `http` keyword arguments are
99     missing, this function will set default values for them, based on
100     the current Arvados configuration settings.
101
102     """
103
104     if not version:
105         version = 'v1'
106         _logger.info("Using default API version. " +
107                      "Call arvados.api('%s') instead." %
108                      version)
109     if 'discoveryServiceUrl' in kwargs:
110         if host:
111             raise ValueError("both discoveryServiceUrl and host provided")
112         # Here we can't use a token from environment, config file,
113         # etc. Those probably have nothing to do with the host
114         # provided by the caller.
115         if not token:
116             raise ValueError("discoveryServiceUrl provided, but token missing")
117     elif host and token:
118         pass
119     elif not host and not token:
120         return api_from_config(version=version, cache=cache, **kwargs)
121     else:
122         # Caller provided one but not the other
123         if not host:
124             raise ValueError("token argument provided, but host missing.")
125         else:
126             raise ValueError("host argument provided, but token missing.")
127
128     if host:
129         # Caller wants us to build the discoveryServiceUrl
130         kwargs['discoveryServiceUrl'] = (
131             'https://%s/discovery/v1/apis/{api}/{apiVersion}/rest' % (host,))
132
133     if 'http' not in kwargs:
134         http_kwargs = {}
135         # Prefer system's CA certificates (if available) over httplib2's.
136         certs_path = '/etc/ssl/certs/ca-certificates.crt'
137         if os.path.exists(certs_path):
138             http_kwargs['ca_certs'] = certs_path
139         if cache:
140             http_kwargs['cache'] = http_cache('discovery')
141         if insecure:
142             http_kwargs['disable_ssl_certificate_validation'] = True
143         kwargs['http'] = httplib2.Http(**http_kwargs)
144
145     credentials = CredentialsFromToken(api_token=token)
146     kwargs['http'] = credentials.authorize(kwargs['http'])
147
148     svc = apiclient_discovery.build('arvados', version, **kwargs)
149     svc.api_token = token
150     kwargs['http'].cache = None
151     return svc
152
153 def api_from_config(version=None, apiconfig=None, **kwargs):
154     """Return an apiclient Resources object enabling access to an Arvados server
155     instance.
156
157     :version:
158       A string naming the version of the Arvados REST API to use (for
159       example, 'v1').
160
161     :apiconfig:
162       If provided, this should be a dict-like object (must support the get()
163       method) with entries for ARVADOS_API_HOST, ARVADOS_API_TOKEN, and
164       optionally ARVADOS_API_HOST_INSECURE.  If not provided, use
165       arvados.config (which gets these parameters from the environment by
166       default.)
167
168     Other keyword arguments such as `cache` will be passed along `api()`
169
170     """
171     # Load from user configuration or environment
172     if apiconfig is None:
173         apiconfig = config.settings()
174
175     for x in ['ARVADOS_API_HOST', 'ARVADOS_API_TOKEN']:
176         if x not in apiconfig:
177             raise ValueError("%s is not set. Aborting." % x)
178     host = apiconfig.get('ARVADOS_API_HOST')
179     token = apiconfig.get('ARVADOS_API_TOKEN')
180     insecure = config.flag_is_true('ARVADOS_API_HOST_INSECURE', apiconfig)
181
182     return api(version=version, host=host, token=token, insecure=insecure, **kwargs)