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