6087: Use HTTPClient's compression feature (instead of adding the
[arvados.git] / apps / workbench / app / models / arvados_api_client.rb
1 require 'httpclient'
2 require 'thread'
3
4 class ArvadosApiClient
5   class ApiError < StandardError
6     attr_reader :api_response, :api_response_s, :api_status, :request_url
7
8     def initialize(request_url, errmsg)
9       @request_url = request_url
10       @api_response ||= {}
11       errors = @api_response[:errors]
12       if not errors.is_a?(Array)
13         @api_response[:errors] = [errors || errmsg]
14       end
15       super(errmsg)
16     end
17   end
18
19   class NoApiResponseException < ApiError
20     def initialize(request_url, exception)
21       @api_response_s = exception.to_s
22       super(request_url,
23             "#{exception.class.to_s} error connecting to API server")
24     end
25   end
26
27   class InvalidApiResponseException < ApiError
28     def initialize(request_url, api_response)
29       @api_status = api_response.status_code
30       @api_response_s = api_response.content
31       super(request_url, "Unparseable response from API server")
32     end
33   end
34
35   class ApiErrorResponseException < ApiError
36     def initialize(request_url, api_response)
37       @api_status = api_response.status_code
38       @api_response_s = api_response.content
39       @api_response = Oj.load(@api_response_s, :symbol_keys => true)
40       errors = @api_response[:errors]
41       if errors.respond_to?(:join)
42         errors = errors.join("\n\n")
43       else
44         errors = errors.to_s
45       end
46       super(request_url, "#{errors} [API: #{@api_status}]")
47     end
48   end
49
50   class AccessForbiddenException < ApiErrorResponseException; end
51   class NotFoundException < ApiErrorResponseException; end
52   class NotLoggedInException < ApiErrorResponseException; end
53
54   ERROR_CODE_CLASSES = {
55     401 => NotLoggedInException,
56     403 => AccessForbiddenException,
57     404 => NotFoundException,
58   }
59
60   @@profiling_enabled = Rails.configuration.profiling_enabled
61   @@discovery = nil
62
63   # An API client object suitable for handling API requests on behalf
64   # of the current thread.
65   def self.new_or_current
66     # If this thread doesn't have an API client yet, *or* this model
67     # has been reloaded since the existing client was created, create
68     # a new client. Otherwise, keep using the latest client created in
69     # the current thread.
70     unless Thread.current[:arvados_api_client].andand.class == self
71       Thread.current[:arvados_api_client] = new
72     end
73     Thread.current[:arvados_api_client]
74   end
75
76   def initialize *args
77     @api_client = nil
78     @client_mtx = Mutex.new
79   end
80
81   def api(resources_kind, action, data=nil, tokens={})
82
83     profile_checkpoint
84
85     if not @api_client
86       @client_mtx.synchronize do
87         @api_client = HTTPClient.new
88         if Rails.configuration.arvados_insecure_https
89           @api_client.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE
90         else
91           # Use system CA certificates
92           @api_client.ssl_config.add_trust_ca('/etc/ssl/certs')
93         end
94         if Rails.configuration.api_response_compression
95           @api_client.transparent_gzip_decompression = true
96         end
97       end
98     end
99
100     resources_kind = class_kind(resources_kind).pluralize if resources_kind.is_a? Class
101     url = "#{self.arvados_v1_base}/#{resources_kind}#{action}"
102
103     # Clean up /arvados/v1/../../discovery/v1 to /discovery/v1
104     url.sub! '/arvados/v1/../../', '/'
105
106     query = {
107       'api_token' => (tokens[:arvados_api_token] ||
108                       Thread.current[:arvados_api_token] ||
109                       ''),
110       'reader_tokens' => ((tokens[:reader_tokens] ||
111                            Thread.current[:reader_tokens] ||
112                            []) +
113                           [Rails.configuration.anonymous_user_token]).to_json,
114     }
115     if !data.nil?
116       data.each do |k,v|
117         if v.is_a? String or v.nil?
118           query[k] = v
119         elsif v == true
120           query[k] = 1
121         elsif v == false
122           query[k] = 0
123         else
124           query[k] = JSON.dump(v)
125         end
126       end
127     else
128       query["_method"] = "GET"
129     end
130
131     if @@profiling_enabled
132       query["_profile"] = "true"
133     end
134
135     header = {"Accept" => "application/json"}
136
137     profile_checkpoint { "Prepare request #{url} #{query[:uuid]} #{query[:where]} #{query[:filters]} #{query[:order]}" }
138     msg = @client_mtx.synchronize do
139       begin
140         @api_client.post(url, query, header: header)
141       rescue => exception
142         raise NoApiResponseException.new(url, exception)
143       end
144     end
145     profile_checkpoint 'API transaction'
146
147     begin
148       resp = Oj.load(msg.content, :symbol_keys => true)
149     rescue Oj::ParseError
150       resp = nil
151     end
152
153     if not resp.is_a? Hash
154       raise InvalidApiResponseException.new(url, msg)
155     elsif msg.status_code != 200
156       error_class = ERROR_CODE_CLASSES.fetch(msg.status_code,
157                                              ApiErrorResponseException)
158       raise error_class.new(url, msg)
159     end
160
161     if resp[:_profile]
162       Rails.logger.info "API client: " \
163       "#{resp.delete(:_profile)[:request_time]} request_time"
164     end
165     profile_checkpoint 'Parse response'
166     resp
167   end
168
169   def self.patch_paging_vars(ary, items_available, offset, limit, links=nil)
170     if items_available
171       (class << ary; self; end).class_eval { attr_accessor :items_available }
172       ary.items_available = items_available
173     end
174     if offset
175       (class << ary; self; end).class_eval { attr_accessor :offset }
176       ary.offset = offset
177     end
178     if limit
179       (class << ary; self; end).class_eval { attr_accessor :limit }
180       ary.limit = limit
181     end
182     if links
183       (class << ary; self; end).class_eval { attr_accessor :links }
184       ary.links = links
185     end
186     ary
187   end
188
189   def unpack_api_response(j, kind=nil)
190     if j.is_a? Hash and j[:items].is_a? Array and j[:kind].match(/(_list|List)$/)
191       ary = j[:items].collect { |x| unpack_api_response x, x[:kind] }
192       links = ArvadosResourceList.new Link
193       links.results = (j[:links] || []).collect do |x|
194         unpack_api_response x, x[:kind]
195       end
196       self.class.patch_paging_vars(ary, j[:items_available], j[:offset], j[:limit], links)
197     elsif j.is_a? Hash and (kind || j[:kind])
198       oclass = self.kind_class(kind || j[:kind])
199       if oclass
200         j.keys.each do |k|
201           childkind = j["#{k.to_s}_kind".to_sym]
202           if childkind
203             j[k] = self.unpack_api_response(j[k], childkind)
204           end
205         end
206         oclass.new.private_reload(j)
207       else
208         j
209       end
210     else
211       j
212     end
213   end
214
215   def arvados_login_url(params={})
216     if Rails.configuration.respond_to? :arvados_login_base
217       uri = Rails.configuration.arvados_login_base
218     else
219       uri = self.arvados_v1_base.sub(%r{/arvados/v\d+.*}, '/login')
220     end
221     if params.size > 0
222       uri += '?' << params.collect { |k,v|
223         CGI.escape(k.to_s) + '=' + CGI.escape(v.to_s)
224       }.join('&')
225     end
226     uri
227   end
228
229   def arvados_logout_url(params={})
230     arvados_login_url(params).sub('/login','/logout')
231   end
232
233   def arvados_v1_base
234     Rails.configuration.arvados_v1_base
235   end
236
237   def discovery
238     @@discovery ||= api '../../discovery/v1/apis/arvados/v1/rest', ''
239   end
240
241   def kind_class(kind)
242     kind.match(/^arvados\#(.+?)(_list|List)?$/)[1].pluralize.classify.constantize rescue nil
243   end
244
245   def class_kind(resource_class)
246     resource_class.to_s.underscore
247   end
248
249   def self.class_kind(resource_class)
250     resource_class.to_s.underscore
251   end
252
253   protected
254   def profile_checkpoint label=nil
255     return if !@@profiling_enabled
256     label = yield if block_given?
257     t = Time.now
258     if label and @profile_t0
259       Rails.logger.info "API client: #{t - @profile_t0} #{label}"
260     end
261     @profile_t0 = t
262   end
263 end