3 class CollectionsController < ApplicationController
4 include ActionController::Live
6 skip_around_filter :require_thread_api_token, if: proc { |ctrl|
7 Rails.configuration.anonymous_user_token and
8 'show' == ctrl.action_name
10 skip_around_filter(:require_thread_api_token,
11 only: [:show_file, :show_file_links])
12 skip_before_filter(:find_object_by_uuid,
13 only: [:provenance, :show_file, :show_file_links])
14 # We depend on show_file to display the user agreement:
15 skip_before_filter :check_user_agreements, only: :show_file
16 skip_before_filter :check_user_profile, only: :show_file
21 panes = %w(Files Upload Provenance_graph Used_by Advanced)
22 panes = panes - %w(Upload) unless (@object.editable? rescue false)
28 when 'persistent', 'cache'
29 persist_links = Link.filter([['owner_uuid', '=', current_user.uuid],
30 ['link_class', '=', 'resources'],
31 ['name', '=', 'wants'],
32 ['tail_uuid', '=', current_user.uuid],
33 ['head_uuid', '=', @object.uuid]])
34 logger.debug persist_links.inspect
36 return unprocessable "Invalid value #{value.inspect}"
38 if params[:value] == 'persistent'
39 if not persist_links.any?
40 Link.create(link_class: 'resources',
42 tail_uuid: current_user.uuid,
43 head_uuid: @object.uuid)
46 persist_links.each do |link|
52 f.json { render json: @object }
57 # API server index doesn't return manifest_text by default, but our
58 # callers want it unless otherwise specified.
59 @select ||= Collection.columns.map(&:name)
60 base_search = Collection.select(@select)
61 if params[:search].andand.length.andand > 0
62 tags = Link.where(any: ['contains', params[:search]])
63 @objects = (base_search.where(uuid: tags.collect(&:head_uuid)) |
64 base_search.where(any: ['contains', params[:search]])).
68 limit = params[:limit].to_i
74 offset = params[:offset].to_i
79 @objects = base_search.limit(limit).offset(offset)
81 @links = Link.where(head_uuid: @objects.collect(&:uuid))
84 @collection_info[c.uuid] = {
93 @collection_info[link.head_uuid] ||= {}
94 info = @collection_info[link.head_uuid]
97 info[:tag_links] << link
100 info[:wanted_by_me] ||= link.tail_uuid == current_user.uuid
102 info[:provenance] << link.name
106 @request_url = request.url
112 Thread.current[:reader_tokens] = [params[:reader_token]]
113 return if false.equal?(find_object_by_uuid)
118 # We pipe from arv-get to send the file to the user. Before we start it,
119 # we ask the API server if the file actually exists. This serves two
120 # purposes: it lets us return a useful status code for common errors, and
121 # helps us figure out which token to provide to arv-get.
123 tokens = [Thread.current[:arvados_api_token], params[:reader_token]].compact
124 usable_token = find_usable_token(tokens) do
125 coll = Collection.find(params[:uuid])
128 file_name = params[:file].andand.sub(/^(\.\/|\/|)/, './')
130 return # Response already rendered.
131 elsif file_name.nil? or not coll.manifest.has_file?(file_name)
132 return render_not_found
135 opts = params.merge(arvados_api_token: usable_token)
137 # Handle Range requests. Currently we support only 'bytes=0-....'
138 if request.headers.include? 'HTTP_RANGE'
139 if m = /^bytes=0-(\d+)/.match(request.headers['HTTP_RANGE'])
140 opts[:maxbytes] = m[1]
141 size = params[:size] || '*'
142 self.response.status = 206
143 self.response.headers['Content-Range'] = "bytes 0-#{m[1]}/#{size}"
147 ext = File.extname(params[:file])
148 self.response.headers['Content-Type'] =
149 Rack::Mime::MIME_TYPES[ext] || 'application/octet-stream'
151 size = params[:size].to_i
153 size = [size, opts[:maxbytes].to_i].min
155 self.response.headers['Content-Length'] = size.to_s
157 self.response.headers['Content-Disposition'] = params[:disposition] if params[:disposition]
159 file_enumerator(opts).each do |bytes|
160 response.stream.write bytes
163 response.stream.close
168 ["GET /arvados/v1/collections/#{@object.uuid}", "GET /arvados/v1/collections/#{@object.uuid}/", "GET /arvados/v1/keep_services/accessible"]
173 ApiClientAuthorization.filter([['scopes', '=', sharing_scopes]]).results
174 rescue ArvadosApiClient::AccessForbiddenException
179 def find_object_by_uuid
180 if not Keep::Locator.parse params[:id]
186 return super if !@object
190 if params["tab_pane"] == "Provenance_graph"
191 @prov_svg = ProvenanceHelper::create_provenance_graph(@object.provenance, "provenance_svg",
192 {:request => request,
193 :direction => :bottom_up,
194 :combine_jobs => :script_only}) rescue nil
198 if Keep::Locator.parse params["uuid"]
199 @same_pdh = Collection.filter([["portable_data_hash", "=", @object.portable_data_hash]])
200 if @same_pdh.results.size == 1
201 redirect_to collection_path(@same_pdh[0]["uuid"])
204 owners = @same_pdh.map(&:owner_uuid).to_a.uniq
205 preload_objects_for_dataclass Group, owners
206 preload_objects_for_dataclass User, owners
207 render 'hash_matches'
210 jobs_with = lambda do |conds|
211 Job.limit(RELATION_LIMIT).where(conds)
212 .results.sort_by { |j| j.finished_at || j.created_at }
214 @output_of = jobs_with.call(output: @object.portable_data_hash)
215 @log_of = jobs_with.call(log: @object.portable_data_hash)
216 @project_links = Link.limit(RELATION_LIMIT).order("modified_at DESC")
217 .where(head_uuid: @object.uuid, link_class: 'name').results
218 project_hash = Group.where(uuid: @project_links.map(&:tail_uuid)).to_hash
219 @projects = project_hash.values
221 @permissions = Link.limit(RELATION_LIMIT).order("modified_at DESC")
222 .where(head_uuid: @object.uuid, link_class: 'permission',
223 name: 'can_read').results
224 @logs = Log.limit(RELATION_LIMIT).order("created_at DESC")
225 .where(object_uuid: @object.uuid).results
226 @is_persistent = Link.limit(1)
227 .where(head_uuid: @object.uuid, tail_uuid: current_user.uuid,
228 link_class: 'resources', name: 'wants')
230 @search_sharing = search_scopes
232 if params["tab_pane"] == "Used_by"
233 @used_by_svg = ProvenanceHelper::create_provenance_graph(@object.used_by, "used_by_svg",
234 {:request => request,
235 :direction => :top_down,
236 :combine_jobs => :script_only,
237 :pdata_only => true}) rescue nil
245 @search_sharing = search_scopes
246 render("sharing_popup.js", content_type: "text/javascript")
249 helper_method :download_link
252 collections_url + "/download/#{@object.uuid}/#{@search_sharing.first.api_token}/"
256 ApiClientAuthorization.create(scopes: sharing_scopes)
261 search_scopes.each do |s|
269 def find_usable_token(token_list)
270 # Iterate over every given token to make it the current token and
271 # yield the given block.
272 # If the block succeeds, return the token it used.
273 # Otherwise, render an error response based on the most specific
274 # error we encounter, and return nil.
275 most_specific_error = [401]
276 token_list.each do |api_token|
278 # We can't load the corresponding user, because the token may not
279 # be scoped for that.
280 using_specific_api_token(api_token, load_user: false) do
284 rescue ArvadosApiClient::ApiError => error
285 if error.api_status >= most_specific_error.first
286 most_specific_error = [error.api_status, error]
290 case most_specific_error.shift
294 render_not_found(*most_specific_error)
299 def file_enumerator(opts)
300 FileStreamer.new opts
304 include ArvadosApiClientHelper
305 def initialize(opts={})
309 return unless @opts[:uuid] && @opts[:file]
314 u = URI.parse(arvados_api_client.arvados_v1_base)
315 env['ARVADOS_API_HOST'] = "#{u.host}:#{u.port}"
316 env['ARVADOS_API_TOKEN'] = @opts[:arvados_api_token]
317 env['ARVADOS_API_HOST_INSECURE'] = "true" if Rails.configuration.arvados_insecure_https
319 bytesleft = @opts[:maxbytes].andand.to_i || 2**16
320 io = IO.popen([env, 'arv-get', "#{@opts[:uuid]}/#{@opts[:file]}"], 'rb')
321 while bytesleft > 0 && (buf = io.read([bytesleft, 2**16].min)) != nil
322 # shrink the bytesleft count, if we were given a maximum byte
324 if @opts.include? :maxbytes
325 bytesleft = bytesleft - buf.length
330 # "If ios is opened by IO.popen, close sets $?."
331 # http://www.ruby-doc.org/core-2.1.3/IO.html#method-i-close
332 Rails.logger.warn("#{@opts[:uuid]}/#{@opts[:file]}: #{$?}") if $? != 0