Merge branch '6358-put-rendezvous' closes #6358
[arvados.git] / apps / workbench / app / controllers / collections_controller.rb
1 require "arvados/keep"
2
3 class CollectionsController < ApplicationController
4   include ActionController::Live
5
6   skip_around_filter :require_thread_api_token, if: proc { |ctrl|
7     Rails.configuration.anonymous_user_token and
8     'show' == ctrl.action_name
9   }
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
17
18   RELATION_LIMIT = 5
19
20   def show_pane_list
21     panes = %w(Files Upload Provenance_graph Used_by Advanced)
22     panes = panes - %w(Upload) unless (@object.editable? rescue false)
23     panes
24   end
25
26   def set_persistent
27     case params[:value]
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
35     else
36       return unprocessable "Invalid value #{value.inspect}"
37     end
38     if params[:value] == 'persistent'
39       if not persist_links.any?
40         Link.create(link_class: 'resources',
41                     name: 'wants',
42                     tail_uuid: current_user.uuid,
43                     head_uuid: @object.uuid)
44       end
45     else
46       persist_links.each do |link|
47         link.destroy || raise
48       end
49     end
50
51     respond_to do |f|
52       f.json { render json: @object }
53     end
54   end
55
56   def index
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]])).
65         uniq { |c| c.uuid }
66     else
67       if params[:limit]
68         limit = params[:limit].to_i
69       else
70         limit = 100
71       end
72
73       if params[:offset]
74         offset = params[:offset].to_i
75       else
76         offset = 0
77       end
78
79       @objects = base_search.limit(limit).offset(offset)
80     end
81     @links = Link.where(head_uuid: @objects.collect(&:uuid))
82     @collection_info = {}
83     @objects.each do |c|
84       @collection_info[c.uuid] = {
85         tag_links: [],
86         wanted: false,
87         wanted_by_me: false,
88         provenance: [],
89         links: []
90       }
91     end
92     @links.each do |link|
93       @collection_info[link.head_uuid] ||= {}
94       info = @collection_info[link.head_uuid]
95       case link.link_class
96       when 'tag'
97         info[:tag_links] << link
98       when 'resources'
99         info[:wanted] = true
100         info[:wanted_by_me] ||= link.tail_uuid == current_user.uuid
101       when 'provenance'
102         info[:provenance] << link.name
103       end
104       info[:links] << link
105     end
106     @request_url = request.url
107
108     render_index
109   end
110
111   def show_file_links
112     Thread.current[:reader_tokens] = [params[:reader_token]]
113     return if false.equal?(find_object_by_uuid)
114     render layout: false
115   end
116
117   def show_file
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.
122     # The order of searched tokens is important: because the anonymous user
123     # token is passed along with every API request, we have to check it first.
124     # Otherwise, it's impossible to know whether any other request succeeded
125     # because of the reader token.
126     coll = nil
127     tokens = [(Rails.configuration.anonymous_user_token || nil),
128               params[:reader_token],
129               Thread.current[:arvados_api_token]].compact
130     usable_token = find_usable_token(tokens) do
131       coll = Collection.find(params[:uuid])
132     end
133
134     file_name = params[:file].andand.sub(/^(\.\/|\/|)/, './')
135     if usable_token.nil?
136       return  # Response already rendered.
137     elsif file_name.nil? or not coll.manifest.has_file?(file_name)
138       return render_not_found
139     end
140
141     opts = params.merge(arvados_api_token: usable_token)
142
143     # Handle Range requests. Currently we support only 'bytes=0-....'
144     if request.headers.include? 'HTTP_RANGE'
145       if m = /^bytes=0-(\d+)/.match(request.headers['HTTP_RANGE'])
146         opts[:maxbytes] = m[1]
147         size = params[:size] || '*'
148         self.response.status = 206
149         self.response.headers['Content-Range'] = "bytes 0-#{m[1]}/#{size}"
150       end
151     end
152
153     ext = File.extname(params[:file])
154     self.response.headers['Content-Type'] =
155       Rack::Mime::MIME_TYPES[ext] || 'application/octet-stream'
156     if params[:size]
157       size = params[:size].to_i
158       if opts[:maxbytes]
159         size = [size, opts[:maxbytes].to_i].min
160       end
161       self.response.headers['Content-Length'] = size.to_s
162     end
163     self.response.headers['Content-Disposition'] = params[:disposition] if params[:disposition]
164     begin
165       file_enumerator(opts).each do |bytes|
166         response.stream.write bytes
167       end
168     ensure
169       response.stream.close
170     end
171   end
172
173   def sharing_scopes
174     ["GET /arvados/v1/collections/#{@object.uuid}", "GET /arvados/v1/collections/#{@object.uuid}/", "GET /arvados/v1/keep_services/accessible"]
175   end
176
177   def search_scopes
178     begin
179       ApiClientAuthorization.filter([['scopes', '=', sharing_scopes]]).results
180     rescue ArvadosApiClient::AccessForbiddenException
181       nil
182     end
183   end
184
185   def find_object_by_uuid
186     if not Keep::Locator.parse params[:id]
187       super
188     end
189   end
190
191   def show
192     return super if !@object
193
194     @logs = []
195
196     if params["tab_pane"] == "Provenance_graph"
197       @prov_svg = ProvenanceHelper::create_provenance_graph(@object.provenance, "provenance_svg",
198                                                             {:request => request,
199                                                              :direction => :bottom_up,
200                                                              :combine_jobs => :script_only}) rescue nil
201     end
202
203     if current_user
204       if Keep::Locator.parse params["uuid"]
205         @same_pdh = Collection.filter([["portable_data_hash", "=", @object.portable_data_hash]]).limit(20)
206         if @same_pdh.results.size == 1
207           redirect_to collection_path(@same_pdh[0]["uuid"])
208           return
209         end
210         owners = @same_pdh.map(&:owner_uuid).to_a.uniq
211         preload_objects_for_dataclass Group, owners
212         preload_objects_for_dataclass User, owners
213         uuids = @same_pdh.map(&:uuid).to_a.uniq
214         preload_links_for_objects uuids
215         render 'hash_matches'
216         return
217       else
218         jobs_with = lambda do |conds|
219           Job.limit(RELATION_LIMIT).where(conds)
220             .results.sort_by { |j| j.finished_at || j.created_at }
221         end
222         @output_of = jobs_with.call(output: @object.portable_data_hash)
223         @log_of = jobs_with.call(log: @object.portable_data_hash)
224         @project_links = Link.limit(RELATION_LIMIT).order("modified_at DESC")
225           .where(head_uuid: @object.uuid, link_class: 'name').results
226         project_hash = Group.where(uuid: @project_links.map(&:tail_uuid)).to_hash
227         @projects = project_hash.values
228
229         @permissions = Link.limit(RELATION_LIMIT).order("modified_at DESC")
230           .where(head_uuid: @object.uuid, link_class: 'permission',
231                  name: 'can_read').results
232         @logs = Log.limit(RELATION_LIMIT).order("created_at DESC")
233           .select(%w(uuid event_type object_uuid event_at summary))
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')
238           .results.any?
239         @search_sharing = search_scopes
240
241         if params["tab_pane"] == "Used_by"
242           @used_by_svg = ProvenanceHelper::create_provenance_graph(@object.used_by, "used_by_svg",
243                                                                    {:request => request,
244                                                                      :direction => :top_down,
245                                                                      :combine_jobs => :script_only,
246                                                                      :pdata_only => true}) rescue nil
247         end
248       end
249     end
250     super
251   end
252
253   def sharing_popup
254     @search_sharing = search_scopes
255     render("sharing_popup.js", content_type: "text/javascript")
256   end
257
258   helper_method :download_link
259
260   def download_link
261     collections_url + "/download/#{@object.uuid}/#{@search_sharing.first.api_token}/"
262   end
263
264   def share
265     ApiClientAuthorization.create(scopes: sharing_scopes)
266     sharing_popup
267   end
268
269   def unshare
270     search_scopes.each do |s|
271       s.destroy
272     end
273     sharing_popup
274   end
275
276   protected
277
278   def find_usable_token(token_list)
279     # Iterate over every given token to make it the current token and
280     # yield the given block.
281     # If the block succeeds, return the token it used.
282     # Otherwise, render an error response based on the most specific
283     # error we encounter, and return nil.
284     most_specific_error = [401]
285     token_list.each do |api_token|
286       begin
287         # We can't load the corresponding user, because the token may not
288         # be scoped for that.
289         using_specific_api_token(api_token, load_user: false) do
290           yield
291           return api_token
292         end
293       rescue ArvadosApiClient::ApiError => error
294         if error.api_status >= most_specific_error.first
295           most_specific_error = [error.api_status, error]
296         end
297       end
298     end
299     case most_specific_error.shift
300     when 401, 403
301       redirect_to_login
302     when 404
303       render_not_found(*most_specific_error)
304     end
305     return nil
306   end
307
308   # Note: several controller and integration tests rely on stubbing
309   # file_enumerator to return fake file content.
310   def file_enumerator opts
311     FileStreamer.new opts
312   end
313
314   class FileStreamer
315     include ArvadosApiClientHelper
316     def initialize(opts={})
317       @opts = opts
318     end
319     def each
320       return unless @opts[:uuid] && @opts[:file]
321
322       env = Hash[ENV].dup
323
324       require 'uri'
325       u = URI.parse(arvados_api_client.arvados_v1_base)
326       env['ARVADOS_API_HOST'] = "#{u.host}:#{u.port}"
327       env['ARVADOS_API_TOKEN'] = @opts[:arvados_api_token]
328       env['ARVADOS_API_HOST_INSECURE'] = "true" if Rails.configuration.arvados_insecure_https
329
330       bytesleft = @opts[:maxbytes].andand.to_i || 2**16
331       io = IO.popen([env, 'arv-get', "#{@opts[:uuid]}/#{@opts[:file]}"], 'rb')
332       while bytesleft > 0 && (buf = io.read([bytesleft, 2**16].min)) != nil
333         # shrink the bytesleft count, if we were given a maximum byte
334         # count to read
335         if @opts.include? :maxbytes
336           bytesleft = bytesleft - buf.length
337         end
338         yield buf
339       end
340       io.close
341       # "If ios is opened by IO.popen, close sets $?."
342       # http://www.ruby-doc.org/core-2.1.3/IO.html#method-i-close
343       Rails.logger.warn("#{@opts[:uuid]}/#{@opts[:file]}: #{$?}") if $? != 0
344     end
345   end
346 end