5 class NotLoggedInException < StandardError
7 class InvalidApiResponseException < StandardError
10 @@profiling_enabled = Rails.configuration.profiling_enabled
13 # An API client object suitable for handling API requests on behalf
14 # of the current thread.
15 def self.new_or_current
16 # If this thread doesn't have an API client yet, *or* this model
17 # has been reloaded since the existing client was created, create
18 # a new client. Otherwise, keep using the latest client created in
20 unless Thread.current[:arvados_api_client].andand.class == self
21 Thread.current[:arvados_api_client] = new
23 Thread.current[:arvados_api_client]
28 @client_mtx = Mutex.new
31 def api(resources_kind, action, data=nil)
35 @client_mtx.synchronize do
36 @api_client = HTTPClient.new
37 if Rails.configuration.arvados_insecure_https
38 @api_client.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE
40 # Use system CA certificates
41 @api_client.ssl_config.add_trust_ca('/etc/ssl/certs')
46 resources_kind = class_kind(resources_kind).pluralize if resources_kind.is_a? Class
47 url = "#{self.arvados_v1_base}/#{resources_kind}#{action}"
49 # Clean up /arvados/v1/../../discovery/v1 to /discovery/v1
50 url.sub! '/arvados/v1/../../', '/'
53 'api_token' => Thread.current[:arvados_api_token] || '',
54 'reader_tokens' => (Thread.current[:reader_tokens] || []).to_json,
58 if v.is_a? String or v.nil?
65 query[k] = JSON.dump(v)
69 query["_method"] = "GET"
71 if @@profiling_enabled
72 query["_profile"] = "true"
75 header = {"Accept" => "application/json"}
77 profile_checkpoint { "Prepare request #{url} #{query[:uuid]} #{query[:where]} #{query[:filters]}" }
78 msg = @client_mtx.synchronize do
83 profile_checkpoint 'API transaction'
85 if msg.status_code == 401
86 raise NotLoggedInException.new
92 resp = Oj.load(json, :symbol_keys => true)
94 raise InvalidApiResponseException.new json
96 if not resp.is_a? Hash
97 raise InvalidApiResponseException.new json
99 if msg.status_code != 200
100 errors = resp[:errors]
101 errors = errors.join("\n\n") if errors.is_a? Array
102 raise "#{errors} [API: #{msg.status_code}]"
105 Rails.logger.info "API client: " \
106 "#{resp.delete(:_profile)[:request_time]} request_time"
108 profile_checkpoint 'Parse response'
112 def self.patch_paging_vars(ary, items_available, offset, limit, links=nil)
114 (class << ary; self; end).class_eval { attr_accessor :items_available }
115 ary.items_available = items_available
118 (class << ary; self; end).class_eval { attr_accessor :offset }
122 (class << ary; self; end).class_eval { attr_accessor :limit }
126 (class << ary; self; end).class_eval { attr_accessor :links }
132 def unpack_api_response(j, kind=nil)
133 if j.is_a? Hash and j[:items].is_a? Array and j[:kind].match(/(_list|List)$/)
134 ary = j[:items].collect { |x| unpack_api_response x, x[:kind] }
135 links = ArvadosResourceList.new Link
136 links.results = (j[:links] || []).collect do |x|
137 unpack_api_response x, x[:kind]
139 self.class.patch_paging_vars(ary, j[:items_available], j[:offset], j[:limit], links)
140 elsif j.is_a? Hash and (kind || j[:kind])
141 oclass = self.kind_class(kind || j[:kind])
144 childkind = j["#{k.to_s}_kind".to_sym]
146 j[k] = self.unpack_api_response(j[k], childkind)
149 oclass.new.private_reload(j)
158 def arvados_login_url(params={})
159 if Rails.configuration.respond_to? :arvados_login_base
160 uri = Rails.configuration.arvados_login_base
162 uri = self.arvados_v1_base.sub(%r{/arvados/v\d+.*}, '/login')
165 uri += '?' << params.collect { |k,v|
166 CGI.escape(k.to_s) + '=' + CGI.escape(v.to_s)
171 def arvados_logout_url(params={})
172 arvados_login_url(params).sub('/login','/logout')
176 Rails.configuration.arvados_v1_base
180 @@discovery ||= api '../../discovery/v1/apis/arvados/v1/rest', ''
184 kind.match(/^arvados\#(.+?)(_list|List)?$/)[1].pluralize.classify.constantize rescue nil
187 def class_kind(resource_class)
188 resource_class.to_s.underscore
192 def profile_checkpoint label=nil
193 return if !@@profiling_enabled
194 label = yield if block_given?
196 if label and @profile_t0
197 Rails.logger.info "API client: #{t - @profile_t0} #{label}"