3 class CollectionsController < ApplicationController
4 include ActionController::Live
6 if Rails.configuration.anonymous_user_token
7 skip_around_filter(:require_thread_api_token,
8 only: [:show_file, :show_file_links, :show])
10 skip_around_filter(:require_thread_api_token,
11 only: [:show_file, :show_file_links])
13 skip_before_filter(:find_object_by_uuid,
14 only: [:provenance, :show_file, :show_file_links])
15 # We depend on show_file to display the user agreement:
16 skip_before_filter :check_user_agreements, only: :show_file
17 skip_before_filter :check_user_profile, only: :show_file
22 panes = %w(Files Upload Provenance_graph Used_by Advanced)
23 panes = panes - %w(Upload) unless (@object.editable? rescue false)
29 when 'persistent', 'cache'
30 persist_links = Link.filter([['owner_uuid', '=', current_user.uuid],
31 ['link_class', '=', 'resources'],
32 ['name', '=', 'wants'],
33 ['tail_uuid', '=', current_user.uuid],
34 ['head_uuid', '=', @object.uuid]])
35 logger.debug persist_links.inspect
37 return unprocessable "Invalid value #{value.inspect}"
39 if params[:value] == 'persistent'
40 if not persist_links.any?
41 Link.create(link_class: 'resources',
43 tail_uuid: current_user.uuid,
44 head_uuid: @object.uuid)
47 persist_links.each do |link|
53 f.json { render json: @object }
58 # API server index doesn't return manifest_text by default, but our
59 # callers want it unless otherwise specified.
60 @select ||= Collection.columns.map(&:name)
61 base_search = Collection.select(@select)
62 if params[:search].andand.length.andand > 0
63 tags = Link.where(any: ['contains', params[:search]])
64 @objects = (base_search.where(uuid: tags.collect(&:head_uuid)) |
65 base_search.where(any: ['contains', params[:search]])).
69 limit = params[:limit].to_i
75 offset = params[:offset].to_i
80 @objects = base_search.limit(limit).offset(offset)
82 @links = Link.where(head_uuid: @objects.collect(&:uuid))
85 @collection_info[c.uuid] = {
94 @collection_info[link.head_uuid] ||= {}
95 info = @collection_info[link.head_uuid]
98 info[:tag_links] << link
101 info[:wanted_by_me] ||= link.tail_uuid == current_user.uuid
103 info[:provenance] << link.name
107 @request_url = request.url
113 Thread.current[:reader_tokens] = [params[:reader_token]]
114 return if false.equal?(find_object_by_uuid)
119 # We pipe from arv-get to send the file to the user. Before we start it,
120 # we ask the API server if the file actually exists. This serves two
121 # purposes: it lets us return a useful status code for common errors, and
122 # helps us figure out which token to provide to arv-get.
124 tokens = [Thread.current[:arvados_api_token], params[:reader_token]].compact
125 usable_token = find_usable_token(tokens) do
126 coll = Collection.find(params[:uuid])
129 file_name = params[:file].andand.sub(/^(\.\/|\/|)/, './')
131 return # Response already rendered.
132 elsif file_name.nil? or not coll.manifest.has_file?(file_name)
133 return render_not_found
136 opts = params.merge(arvados_api_token: usable_token)
138 # Handle Range requests. Currently we support only 'bytes=0-....'
139 if request.headers.include? 'HTTP_RANGE'
140 if m = /^bytes=0-(\d+)/.match(request.headers['HTTP_RANGE'])
141 opts[:maxbytes] = m[1]
142 size = params[:size] || '*'
143 self.response.status = 206
144 self.response.headers['Content-Range'] = "bytes 0-#{m[1]}/#{size}"
148 ext = File.extname(params[:file])
149 self.response.headers['Content-Type'] =
150 Rack::Mime::MIME_TYPES[ext] || 'application/octet-stream'
152 size = params[:size].to_i
154 size = [size, opts[:maxbytes].to_i].min
156 self.response.headers['Content-Length'] = size.to_s
158 self.response.headers['Content-Disposition'] = params[:disposition] if params[:disposition]
160 file_enumerator(opts).each do |bytes|
161 response.stream.write bytes
164 response.stream.close
169 ["GET /arvados/v1/collections/#{@object.uuid}", "GET /arvados/v1/collections/#{@object.uuid}/", "GET /arvados/v1/keep_services/accessible"]
174 ApiClientAuthorization.filter([['scopes', '=', sharing_scopes]]).results
175 rescue ArvadosApiClient::AccessForbiddenException
180 def find_object_by_uuid
181 if not Keep::Locator.parse params[:id]
187 return super if !@object
191 if params["tab_pane"] == "Provenance_graph"
192 @prov_svg = ProvenanceHelper::create_provenance_graph(@object.provenance, "provenance_svg",
193 {:request => request,
194 :direction => :bottom_up,
195 :combine_jobs => :script_only}) rescue nil
199 if Keep::Locator.parse params["uuid"]
200 @same_pdh = Collection.filter([["portable_data_hash", "=", @object.portable_data_hash]])
201 if @same_pdh.results.size == 1
202 redirect_to collection_path(@same_pdh[0]["uuid"])
205 owners = @same_pdh.map(&:owner_uuid).to_a.uniq
206 preload_objects_for_dataclass Group, owners
207 preload_objects_for_dataclass User, owners
208 render 'hash_matches'
211 jobs_with = lambda do |conds|
212 Job.limit(RELATION_LIMIT).where(conds)
213 .results.sort_by { |j| j.finished_at || j.created_at }
215 @output_of = jobs_with.call(output: @object.portable_data_hash)
216 @log_of = jobs_with.call(log: @object.portable_data_hash)
217 @project_links = Link.limit(RELATION_LIMIT).order("modified_at DESC")
218 .where(head_uuid: @object.uuid, link_class: 'name').results
219 project_hash = Group.where(uuid: @project_links.map(&:tail_uuid)).to_hash
220 @projects = project_hash.values
222 @permissions = Link.limit(RELATION_LIMIT).order("modified_at DESC")
223 .where(head_uuid: @object.uuid, link_class: 'permission',
224 name: 'can_read').results
225 @logs = Log.limit(RELATION_LIMIT).order("created_at DESC")
226 .where(object_uuid: @object.uuid).results
227 @is_persistent = Link.limit(1)
228 .where(head_uuid: @object.uuid, tail_uuid: current_user.uuid,
229 link_class: 'resources', name: 'wants')
231 @search_sharing = search_scopes
233 if params["tab_pane"] == "Used_by"
234 @used_by_svg = ProvenanceHelper::create_provenance_graph(@object.used_by, "used_by_svg",
235 {:request => request,
236 :direction => :top_down,
237 :combine_jobs => :script_only,
238 :pdata_only => true}) rescue nil
246 @search_sharing = search_scopes
247 render("sharing_popup.js", content_type: "text/javascript")
250 helper_method :download_link
253 collections_url + "/download/#{@object.uuid}/#{@search_sharing.first.api_token}/"
257 ApiClientAuthorization.create(scopes: sharing_scopes)
262 search_scopes.each do |s|
270 def find_usable_token(token_list)
271 # Iterate over every given token to make it the current token and
272 # yield the given block.
273 # If the block succeeds, return the token it used.
274 # Otherwise, render an error response based on the most specific
275 # error we encounter, and return nil.
276 most_specific_error = [401]
277 token_list.each do |api_token|
279 # We can't load the corresponding user, because the token may not
280 # be scoped for that.
281 using_specific_api_token(api_token, load_user: false) do
285 rescue ArvadosApiClient::ApiError => error
286 if error.api_status >= most_specific_error.first
287 most_specific_error = [error.api_status, error]
291 case most_specific_error.shift
295 render_not_found(*most_specific_error)
300 def file_enumerator(opts)
301 FileStreamer.new opts
305 include ArvadosApiClientHelper
306 def initialize(opts={})
310 return unless @opts[:uuid] && @opts[:file]
315 u = URI.parse(arvados_api_client.arvados_v1_base)
316 env['ARVADOS_API_HOST'] = "#{u.host}:#{u.port}"
317 env['ARVADOS_API_TOKEN'] = @opts[:arvados_api_token]
318 env['ARVADOS_API_HOST_INSECURE'] = "true" if Rails.configuration.arvados_insecure_https
320 bytesleft = @opts[:maxbytes].andand.to_i || 2**16
321 io = IO.popen([env, 'arv-get', "#{@opts[:uuid]}/#{@opts[:file]}"], 'rb')
322 while bytesleft > 0 && (buf = io.read([bytesleft, 2**16].min)) != nil
323 # shrink the bytesleft count, if we were given a maximum byte
325 if @opts.include? :maxbytes
326 bytesleft = bytesleft - buf.length
331 # "If ios is opened by IO.popen, close sets $?."
332 # http://www.ruby-doc.org/core-2.1.3/IO.html#method-i-close
333 Rails.logger.warn("#{@opts[:uuid]}/#{@opts[:file]}: #{$?}") if $? != 0