3 class CollectionsController < ApplicationController
4 include ActionController::Live
6 skip_around_filter(:require_thread_api_token,
7 only: [:show_file, :show_file_links])
8 skip_before_filter(:find_object_by_uuid,
9 only: [:provenance, :show_file, :show_file_links])
10 # We depend on show_file to display the user agreement:
11 skip_before_filter :check_user_agreements, only: :show_file
12 skip_before_filter :check_user_profile, only: :show_file
17 %w(Files Provenance_graph Used_by Advanced)
22 when 'persistent', 'cache'
23 persist_links = Link.filter([['owner_uuid', '=', current_user.uuid],
24 ['link_class', '=', 'resources'],
25 ['name', '=', 'wants'],
26 ['tail_uuid', '=', current_user.uuid],
27 ['head_uuid', '=', @object.uuid]])
28 logger.debug persist_links.inspect
30 return unprocessable "Invalid value #{value.inspect}"
32 if params[:value] == 'persistent'
33 if not persist_links.any?
34 Link.create(link_class: 'resources',
36 tail_uuid: current_user.uuid,
37 head_uuid: @object.uuid)
40 persist_links.each do |link|
46 f.json { render json: @object }
51 # API server index doesn't return manifest_text by default, but our
52 # callers want it unless otherwise specified.
53 @select ||= Collection.columns.map(&:name)
54 base_search = Collection.select(@select)
55 if params[:search].andand.length.andand > 0
56 tags = Link.where(any: ['contains', params[:search]])
57 @objects = (base_search.where(uuid: tags.collect(&:head_uuid)) |
58 base_search.where(any: ['contains', params[:search]])).
62 limit = params[:limit].to_i
68 offset = params[:offset].to_i
73 @objects = base_search.limit(limit).offset(offset)
75 @links = Link.where(head_uuid: @objects.collect(&:uuid))
78 @collection_info[c.uuid] = {
87 @collection_info[link.head_uuid] ||= {}
88 info = @collection_info[link.head_uuid]
91 info[:tag_links] << link
94 info[:wanted_by_me] ||= link.tail_uuid == current_user.uuid
96 info[:provenance] << link.name
100 @request_url = request.url
106 Thread.current[:reader_tokens] = [params[:reader_token]]
107 return if false.equal?(find_object_by_uuid)
112 # We pipe from arv-get to send the file to the user. Before we start it,
113 # we ask the API server if the file actually exists. This serves two
114 # purposes: it lets us return a useful status code for common errors, and
115 # helps us figure out which token to provide to arv-get.
117 tokens = [Thread.current[:arvados_api_token], params[:reader_token]].compact
118 usable_token = find_usable_token(tokens) do
119 coll = Collection.find(params[:uuid])
122 file_name = params[:file].andand.sub(/^(\.\/|\/|)/, './')
124 return # Response already rendered.
125 elsif file_name.nil? or not coll.manifest.has_file?(file_name)
126 return render_not_found
129 opts = params.merge(arvados_api_token: usable_token)
131 # Handle Range requests. Currently we support only 'bytes=0-....'
132 if request.headers.include? 'HTTP_RANGE'
133 if m = /^bytes=0-(\d+)/.match(request.headers['HTTP_RANGE'])
134 opts[:maxbytes] = m[1]
135 size = params[:size] || '*'
136 self.response.status = 206
137 self.response.headers['Content-Range'] = "bytes 0-#{m[1]}/#{size}"
141 ext = File.extname(params[:file])
142 self.response.headers['Content-Type'] =
143 Rack::Mime::MIME_TYPES[ext] || 'application/octet-stream'
145 size = params[:size].to_i
147 size = [size, opts[:maxbytes].to_i].min
149 self.response.headers['Content-Length'] = size.to_s
151 self.response.headers['Content-Disposition'] = params[:disposition] if params[:disposition]
153 file_enumerator(opts).each do |bytes|
154 response.stream.write bytes
157 response.stream.close
162 ["GET /arvados/v1/collections/#{@object.uuid}", "GET /arvados/v1/collections/#{@object.uuid}/", "GET /arvados/v1/keep_services/accessible"]
167 ApiClientAuthorization.filter([['scopes', '=', sharing_scopes]]).results
168 rescue ArvadosApiClient::AccessForbiddenException
173 def find_object_by_uuid
174 if not Keep::Locator.parse params[:id]
180 return super if !@object
182 if Keep::Locator.parse params["uuid"]
183 @same_pdh = Collection.filter([["portable_data_hash", "=", @object.portable_data_hash]])
184 if @same_pdh.results.size == 1
185 redirect_to collection_path(@same_pdh[0]["uuid"])
188 owners = @same_pdh.map(&:owner_uuid).to_a.uniq
189 preload_objects_for_dataclass Group, owners
190 preload_objects_for_dataclass User, owners
191 render 'hash_matches'
194 jobs_with = lambda do |conds|
195 Job.limit(RELATION_LIMIT).where(conds)
196 .results.sort_by { |j| j.finished_at || j.created_at }
198 @output_of = jobs_with.call(output: @object.portable_data_hash)
199 @log_of = jobs_with.call(log: @object.portable_data_hash)
200 @project_links = Link.limit(RELATION_LIMIT).order("modified_at DESC")
201 .where(head_uuid: @object.uuid, link_class: 'name').results
202 project_hash = Group.where(uuid: @project_links.map(&:tail_uuid)).to_hash
203 @projects = project_hash.values
205 @permissions = Link.limit(RELATION_LIMIT).order("modified_at DESC")
206 .where(head_uuid: @object.uuid, link_class: 'permission',
207 name: 'can_read').results
208 @logs = Log.limit(RELATION_LIMIT).order("created_at DESC")
209 .where(object_uuid: @object.uuid).results
210 @is_persistent = Link.limit(1)
211 .where(head_uuid: @object.uuid, tail_uuid: current_user.uuid,
212 link_class: 'resources', name: 'wants')
214 @search_sharing = search_scopes
216 if params["tab_pane"] == "Provenance_graph"
217 @prov_svg = ProvenanceHelper::create_provenance_graph(@object.provenance, "provenance_svg",
218 {:request => request,
219 :direction => :bottom_up,
220 :combine_jobs => :script_only}) rescue nil
222 if params["tab_pane"] == "Used_by"
223 @used_by_svg = ProvenanceHelper::create_provenance_graph(@object.used_by, "used_by_svg",
224 {:request => request,
225 :direction => :top_down,
226 :combine_jobs => :script_only,
227 :pdata_only => true}) rescue nil
235 @search_sharing = search_scopes
236 respond_to do |format|
242 helper_method :download_link
245 collections_url + "/download/#{@object.uuid}/#{@search_sharing.first.api_token}/"
249 a = ApiClientAuthorization.create(scopes: sharing_scopes)
250 @search_sharing = search_scopes
251 render 'sharing_popup'
255 @search_sharing = search_scopes
256 @search_sharing.each do |s|
259 @search_sharing = search_scopes
260 render 'sharing_popup'
265 def find_usable_token(token_list)
266 # Iterate over every given token to make it the current token and
267 # yield the given block.
268 # If the block succeeds, return the token it used.
269 # Otherwise, render an error response based on the most specific
270 # error we encounter, and return nil.
271 most_specific_error = [401]
272 token_list.each do |api_token|
274 # We can't load the corresponding user, because the token may not
275 # be scoped for that.
276 using_specific_api_token(api_token, load_user: false) do
280 rescue ArvadosApiClient::ApiError => error
281 if error.api_status >= most_specific_error.first
282 most_specific_error = [error.api_status, error]
286 case most_specific_error.shift
290 render_not_found(*most_specific_error)
295 def file_enumerator(opts)
296 FileStreamer.new opts
300 include ArvadosApiClientHelper
301 def initialize(opts={})
305 return unless @opts[:uuid] && @opts[:file]
310 u = URI.parse(arvados_api_client.arvados_v1_base)
311 env['ARVADOS_API_HOST'] = "#{u.host}:#{u.port}"
312 env['ARVADOS_API_TOKEN'] = @opts[:arvados_api_token]
313 env['ARVADOS_API_HOST_INSECURE'] = "true" if Rails.configuration.arvados_insecure_https
315 bytesleft = @opts[:maxbytes].andand.to_i || 2**16
316 io = IO.popen([env, 'arv-get', "#{@opts[:uuid]}/#{@opts[:file]}"], 'rb')
317 while bytesleft > 0 && (buf = io.read([bytesleft, 2**16].min)) != nil
318 # shrink the bytesleft count, if we were given a maximum byte
320 if @opts.include? :maxbytes
321 bytesleft = bytesleft - buf.length
326 # "If ios is opened by IO.popen, close sets $?."
327 # http://www.ruby-doc.org/core-2.1.3/IO.html#method-i-close
328 Rails.logger.warn("#{@opts[:uuid]}/#{@opts[:file]}: #{$?}") if $? != 0