Add 'apps/arv-web/' from commit 'f9732ad8460d013c2f28363655d0d1b91894dca5'
[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 conncache = {}
17
18 class CredentialsFromToken(object):
19     def __init__(self, api_token):
20         self.api_token = api_token
21
22     @staticmethod
23     def http_request(self, uri, **kwargs):
24         from httplib import BadStatusLine
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     def authorize(self, http):
43         http.arvados_api_token = self.api_token
44         http.orig_http_request = http.request
45         http.request = types.MethodType(self.http_request, http)
46         return http
47
48 # Monkey patch discovery._cast() so objects and arrays get serialized
49 # with json.dumps() instead of str().
50 _cast_orig = apiclient_discovery._cast
51 def _cast_objects_too(value, schema_type):
52     global _cast_orig
53     if (type(value) != type('') and
54         (schema_type == 'object' or schema_type == 'array')):
55         return json.dumps(value)
56     else:
57         return _cast_orig(value, schema_type)
58 apiclient_discovery._cast = _cast_objects_too
59
60 # Convert apiclient's HttpErrors into our own API error subclass for better
61 # error reporting.
62 # Reassigning apiclient_errors.HttpError is not sufficient because most of the
63 # apiclient submodules import the class into their own namespace.
64 def _new_http_error(cls, *args, **kwargs):
65     return super(apiclient_errors.HttpError, cls).__new__(
66         errors.ApiError, *args, **kwargs)
67 apiclient_errors.HttpError.__new__ = staticmethod(_new_http_error)
68
69 def http_cache(data_type):
70     path = os.environ['HOME'] + '/.cache/arvados/' + data_type
71     try:
72         util.mkdir_dash_p(path)
73     except OSError:
74         path = None
75     return path
76
77 def api(version=None, cache=True, host=None, token=None, insecure=False, **kwargs):
78     """Return an apiclient Resources object for an Arvados instance.
79
80     Arguments:
81     * version: A string naming the version of the Arvados API to use (for
82       example, 'v1').
83     * cache: If True (default), return an existing Resources object if
84       one already exists with the same endpoint and credentials. If
85       False, create a new one, and do not keep it in the cache (i.e.,
86       do not return it from subsequent api(cache=True) calls with
87       matching endpoint and credentials).
88     * host: The Arvados API server host (and optional :port) to connect to.
89     * token: The authentication token to send with each API call.
90     * insecure: If True, ignore SSL certificate validation errors.
91
92     Additional keyword arguments will be passed directly to
93     `apiclient_discovery.build` if a new Resource object is created.
94     If the `discoveryServiceUrl` or `http` keyword arguments are
95     missing, this function will set default values for them, based on
96     the current Arvados configuration settings.
97
98     """
99
100     if not version:
101         version = 'v1'
102         _logger.info("Using default API version. " +
103                      "Call arvados.api('%s') instead." %
104                      version)
105     if 'discoveryServiceUrl' in kwargs:
106         if host:
107             raise ValueError("both discoveryServiceUrl and host provided")
108         # Here we can't use a token from environment, config file,
109         # etc. Those probably have nothing to do with the host
110         # provided by the caller.
111         if not token:
112             raise ValueError("discoveryServiceUrl provided, but token missing")
113     elif host and token:
114         pass
115     elif not host and not token:
116         # Load from user configuration or environment
117         for x in ['ARVADOS_API_HOST', 'ARVADOS_API_TOKEN']:
118             if x not in config.settings():
119                 raise ValueError("%s is not set. Aborting." % x)
120         host = config.get('ARVADOS_API_HOST')
121         token = config.get('ARVADOS_API_TOKEN')
122         insecure = config.flag_is_true('ARVADOS_API_HOST_INSECURE')
123     else:
124         # Caller provided one but not the other
125         if not host:
126             raise ValueError("token argument provided, but host missing.")
127         else:
128             raise ValueError("host argument provided, but token missing.")
129
130     if host:
131         # Caller wants us to build the discoveryServiceUrl
132         kwargs['discoveryServiceUrl'] = (
133             'https://%s/discovery/v1/apis/{api}/{apiVersion}/rest' % (host,))
134
135     if cache:
136         connprofile = (version, host, token, insecure)
137         svc = conncache.get(connprofile)
138         if svc:
139             return svc
140
141     if 'http' not in kwargs:
142         http_kwargs = {}
143         # Prefer system's CA certificates (if available) over httplib2's.
144         certs_path = '/etc/ssl/certs/ca-certificates.crt'
145         if os.path.exists(certs_path):
146             http_kwargs['ca_certs'] = certs_path
147         if cache:
148             http_kwargs['cache'] = http_cache('discovery')
149         if insecure:
150             http_kwargs['disable_ssl_certificate_validation'] = True
151         kwargs['http'] = httplib2.Http(**http_kwargs)
152
153     credentials = CredentialsFromToken(api_token=token)
154     kwargs['http'] = credentials.authorize(kwargs['http'])
155
156     svc = apiclient_discovery.build('arvados', version, **kwargs)
157     svc.api_token = token
158     kwargs['http'].cache = None
159     if cache:
160         conncache[connprofile] = svc
161     return svc