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