1 class CollectionsController < ApplicationController
2 include ActionController::Live
4 skip_around_filter(:require_thread_api_token,
5 only: [:show_file, :show_file_links])
6 skip_before_filter(:find_object_by_uuid,
7 only: [:provenance, :show_file, :show_file_links])
8 # We depend on show_file to display the user agreement:
9 skip_before_filter :check_user_agreements, only: :show_file
10 skip_before_filter :check_user_profile, only: :show_file
15 %w(Files Provenance_graph Used_by Advanced)
20 when 'persistent', 'cache'
21 persist_links = Link.filter([['owner_uuid', '=', current_user.uuid],
22 ['link_class', '=', 'resources'],
23 ['name', '=', 'wants'],
24 ['tail_uuid', '=', current_user.uuid],
25 ['head_uuid', '=', @object.uuid]])
26 logger.debug persist_links.inspect
28 return unprocessable "Invalid value #{value.inspect}"
30 if params[:value] == 'persistent'
31 if not persist_links.any?
32 Link.create(link_class: 'resources',
34 tail_uuid: current_user.uuid,
35 head_uuid: @object.uuid)
38 persist_links.each do |link|
44 f.json { render json: @object }
49 # Find collections using default find_objects logic, then search for name
50 # links, and preload any other links connected to the collections that are
52 # Name links will be obsolete when issue #3036 is merged,
53 # at which point this entire custom #choose function can probably be
58 find_objects_for_index
59 @collections = @objects
61 @filters += [['link_class','=','name'],
62 ['head_uuid','is_a','arvados#collection']]
65 find_objects_for_index
67 @name_links = @objects
69 @objects = Collection.
70 filter([['uuid','in',@name_links.collect(&:head_uuid)]])
72 preload_links_for_objects (@collections.to_a + @objects.to_a)
77 # API server index doesn't return manifest_text by default, but our
78 # callers want it unless otherwise specified.
79 @select ||= Collection.columns.map(&:name)
80 base_search = Collection.select(@select)
81 if params[:search].andand.length.andand > 0
82 tags = Link.where(any: ['contains', params[:search]])
83 @collections = (base_search.where(uuid: tags.collect(&:head_uuid)) |
84 base_search.where(any: ['contains', params[:search]])).
88 limit = params[:limit].to_i
94 offset = params[:offset].to_i
99 @collections = base_search.limit(limit).offset(offset)
101 @links = Link.limit(1000).
102 where(head_uuid: @collections.collect(&:uuid))
103 @collection_info = {}
104 @collections.each do |c|
105 @collection_info[c.uuid] = {
113 @links.each do |link|
114 @collection_info[link.head_uuid] ||= {}
115 info = @collection_info[link.head_uuid]
118 info[:tag_links] << link
121 info[:wanted_by_me] ||= link.tail_uuid == current_user.uuid
123 info[:provenance] << link.name
127 @request_url = request.url
133 Thread.current[:reader_tokens] = [params[:reader_token]]
134 return if false.equal?(find_object_by_uuid)
139 # We pipe from arv-get to send the file to the user. Before we start it,
140 # we ask the API server if the file actually exists. This serves two
141 # purposes: it lets us return a useful status code for common errors, and
142 # helps us figure out which token to provide to arv-get.
144 tokens = [Thread.current[:arvados_api_token], params[:reader_token]].compact
145 usable_token = find_usable_token(tokens) do
146 coll = Collection.find(params[:uuid])
149 return # Response already rendered.
150 elsif params[:file].nil? or not coll.manifest.has_file?(params[:file])
151 return render_not_found
154 opts = params.merge(arvados_api_token: usable_token)
156 # Handle Range requests. Currently we support only 'bytes=0-....'
157 if request.headers.include? 'HTTP_RANGE'
158 if m = /^bytes=0-(\d+)/.match(request.headers['HTTP_RANGE'])
159 opts[:maxbytes] = m[1]
160 size = params[:size] || '*'
161 self.response.status = 206
162 self.response.headers['Content-Range'] = "bytes 0-#{m[1]}/#{size}"
166 ext = File.extname(params[:file])
167 self.response.headers['Content-Type'] =
168 Rack::Mime::MIME_TYPES[ext] || 'application/octet-stream'
170 size = params[:size].to_i
172 size = [size, opts[:maxbytes].to_i].min
174 self.response.headers['Content-Length'] = size.to_s
176 self.response.headers['Content-Disposition'] = params[:disposition] if params[:disposition]
178 file_enumerator(opts).each do |bytes|
179 response.stream.write bytes
182 response.stream.close
187 ["GET /arvados/v1/collections/#{@object.uuid}", "GET /arvados/v1/collections/#{@object.uuid}/", "GET /arvados/v1/keep_services/accessible"]
192 ApiClientAuthorization.filter([['scopes', '=', sharing_scopes]]).results
193 rescue ArvadosApiClient::AccessForbiddenException
198 def find_object_by_uuid
199 if not Keep::Locator.parse params[:id]
205 return super if !@object
207 if Keep::Locator.parse params["uuid"]
208 @same_pdh = Collection.filter([["portable_data_hash", "=", @object.portable_data_hash]]).limit(1000)
209 if @same_pdh.results.size == 1
210 redirect_to collection_path(@same_pdh[0]["uuid"])
213 owners = @same_pdh.map(&:owner_uuid).to_a.uniq
214 preload_objects_for_dataclass Group, owners
215 preload_objects_for_dataclass User, owners
216 render 'hash_matches'
219 jobs_with = lambda do |conds|
220 Job.limit(RELATION_LIMIT).where(conds)
221 .results.sort_by { |j| j.finished_at || j.created_at }
223 @output_of = jobs_with.call(output: @object.portable_data_hash)
224 @log_of = jobs_with.call(log: @object.portable_data_hash)
225 @project_links = Link.limit(RELATION_LIMIT).order("modified_at DESC")
226 .where(head_uuid: @object.uuid, link_class: 'name').results
227 project_hash = Group.where(uuid: @project_links.map(&:tail_uuid)).to_hash
228 @projects = project_hash.values
230 @permissions = Link.limit(RELATION_LIMIT).order("modified_at DESC")
231 .where(head_uuid: @object.uuid, link_class: 'permission',
232 name: 'can_read').results
233 @logs = Log.limit(RELATION_LIMIT).order("created_at DESC")
234 .where(object_uuid: @object.uuid).results
235 @is_persistent = Link.limit(1)
236 .where(head_uuid: @object.uuid, tail_uuid: current_user.uuid,
237 link_class: 'resources', name: 'wants')
239 @search_sharing = search_scopes
241 if params["tab_pane"] == "Provenance_graph"
242 @prov_svg = ProvenanceHelper::create_provenance_graph(@object.provenance, "provenance_svg",
243 {:request => request,
244 :direction => :bottom_up,
245 :combine_jobs => :script_only}) rescue nil
247 if params["tab_pane"] == "Used_by"
248 @used_by_svg = ProvenanceHelper::create_provenance_graph(@object.used_by, "used_by_svg",
249 {:request => request,
250 :direction => :top_down,
251 :combine_jobs => :script_only,
252 :pdata_only => true}) rescue nil
260 @search_sharing = search_scopes
261 respond_to do |format|
267 helper_method :download_link
270 collections_url + "/download/#{@object.uuid}/#{@search_sharing.first.api_token}/"
274 a = ApiClientAuthorization.create(scopes: sharing_scopes)
275 @search_sharing = search_scopes
276 render 'sharing_popup'
280 @search_sharing = search_scopes
281 @search_sharing.each do |s|
284 @search_sharing = search_scopes
285 render 'sharing_popup'
290 def find_usable_token(token_list)
291 # Iterate over every given token to make it the current token and
292 # yield the given block.
293 # If the block succeeds, return the token it used.
294 # Otherwise, render an error response based on the most specific
295 # error we encounter, and return nil.
296 most_specific_error = [401]
297 token_list.each do |api_token|
299 using_specific_api_token(api_token) do
303 rescue ArvadosApiClient::ApiError => error
304 if error.api_status >= most_specific_error.first
305 most_specific_error = [error.api_status, error]
309 case most_specific_error.shift
313 render_not_found(*most_specific_error)
318 def file_enumerator(opts)
319 FileStreamer.new opts
323 include ArvadosApiClientHelper
324 def initialize(opts={})
328 return unless @opts[:uuid] && @opts[:file]
333 u = URI.parse(arvados_api_client.arvados_v1_base)
334 env['ARVADOS_API_HOST'] = "#{u.host}:#{u.port}"
335 env['ARVADOS_API_TOKEN'] = @opts[:arvados_api_token]
336 env['ARVADOS_API_HOST_INSECURE'] = "true" if Rails.configuration.arvados_insecure_https
338 bytesleft = @opts[:maxbytes].andand.to_i || 2**16
339 io = IO.popen([env, 'arv-get', "#{@opts[:uuid]}/#{@opts[:file]}"], 'rb')
340 while bytesleft > 0 && (buf = io.read([bytesleft, 2**16].min)) != nil
341 # shrink the bytesleft count, if we were given a maximum byte
343 if @opts.include? :maxbytes
344 bytesleft = bytesleft - buf.length
349 # "If ios is opened by IO.popen, close sets $?."
350 # http://www.ruby-doc.org/core-2.1.3/IO.html#method-i-close
351 Rails.logger.warn("#{@opts[:uuid]}/#{@opts[:file]}: #{$?}") if $? != 0