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