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