Merge branch 'master' into 5420-collection-checkbox-selections
[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     coll = nil
123     tokens = [Thread.current[:arvados_api_token],
124               params[:reader_token],
125               (Rails.configuration.anonymous_user_token || nil)].compact
126     usable_token = find_usable_token(tokens) do
127       coll = Collection.find(params[:uuid])
128     end
129
130     file_name = params[:file].andand.sub(/^(\.\/|\/|)/, './')
131     if usable_token.nil?
132       return  # Response already rendered.
133     elsif file_name.nil? or not coll.manifest.has_file?(file_name)
134       return render_not_found
135     end
136
137     opts = params.merge(arvados_api_token: usable_token)
138
139     # Handle Range requests. Currently we support only 'bytes=0-....'
140     if request.headers.include? 'HTTP_RANGE'
141       if m = /^bytes=0-(\d+)/.match(request.headers['HTTP_RANGE'])
142         opts[:maxbytes] = m[1]
143         size = params[:size] || '*'
144         self.response.status = 206
145         self.response.headers['Content-Range'] = "bytes 0-#{m[1]}/#{size}"
146       end
147     end
148
149     ext = File.extname(params[:file])
150     self.response.headers['Content-Type'] =
151       Rack::Mime::MIME_TYPES[ext] || 'application/octet-stream'
152     if params[:size]
153       size = params[:size].to_i
154       if opts[:maxbytes]
155         size = [size, opts[:maxbytes].to_i].min
156       end
157       self.response.headers['Content-Length'] = size.to_s
158     end
159     self.response.headers['Content-Disposition'] = params[:disposition] if params[:disposition]
160     begin
161       file_enumerator(opts).each do |bytes|
162         response.stream.write bytes
163       end
164     ensure
165       response.stream.close
166     end
167   end
168
169   def sharing_scopes
170     ["GET /arvados/v1/collections/#{@object.uuid}", "GET /arvados/v1/collections/#{@object.uuid}/", "GET /arvados/v1/keep_services/accessible"]
171   end
172
173   def search_scopes
174     begin
175       ApiClientAuthorization.filter([['scopes', '=', sharing_scopes]]).results
176     rescue ArvadosApiClient::AccessForbiddenException
177       nil
178     end
179   end
180
181   def find_object_by_uuid
182     if not Keep::Locator.parse params[:id]
183       super
184     end
185   end
186
187   def show
188     return super if !@object
189
190     @logs = []
191
192     if params["tab_pane"] == "Provenance_graph"
193       @prov_svg = ProvenanceHelper::create_provenance_graph(@object.provenance, "provenance_svg",
194                                                             {:request => request,
195                                                              :direction => :bottom_up,
196                                                              :combine_jobs => :script_only}) rescue nil
197     end
198
199     if current_user
200       if Keep::Locator.parse params["uuid"]
201         @same_pdh = Collection.filter([["portable_data_hash", "=", @object.portable_data_hash]])
202         if @same_pdh.results.size == 1
203           redirect_to collection_path(@same_pdh[0]["uuid"])
204           return
205         end
206         owners = @same_pdh.map(&:owner_uuid).to_a.uniq
207         preload_objects_for_dataclass Group, owners
208         preload_objects_for_dataclass User, owners
209         render 'hash_matches'
210         return
211       else
212         jobs_with = lambda do |conds|
213           Job.limit(RELATION_LIMIT).where(conds)
214             .results.sort_by { |j| j.finished_at || j.created_at }
215         end
216         @output_of = jobs_with.call(output: @object.portable_data_hash)
217         @log_of = jobs_with.call(log: @object.portable_data_hash)
218         @project_links = Link.limit(RELATION_LIMIT).order("modified_at DESC")
219           .where(head_uuid: @object.uuid, link_class: 'name').results
220         project_hash = Group.where(uuid: @project_links.map(&:tail_uuid)).to_hash
221         @projects = project_hash.values
222
223         @permissions = Link.limit(RELATION_LIMIT).order("modified_at DESC")
224           .where(head_uuid: @object.uuid, link_class: 'permission',
225                  name: 'can_read').results
226         @logs = Log.limit(RELATION_LIMIT).order("created_at DESC")
227           .select(%w(uuid event_type object_uuid event_at summary))
228           .where(object_uuid: @object.uuid).results
229         @is_persistent = Link.limit(1)
230           .where(head_uuid: @object.uuid, tail_uuid: current_user.uuid,
231                  link_class: 'resources', name: 'wants')
232           .results.any?
233         @search_sharing = search_scopes
234
235         if params["tab_pane"] == "Used_by"
236           @used_by_svg = ProvenanceHelper::create_provenance_graph(@object.used_by, "used_by_svg",
237                                                                    {:request => request,
238                                                                      :direction => :top_down,
239                                                                      :combine_jobs => :script_only,
240                                                                      :pdata_only => true}) rescue nil
241         end
242       end
243     end
244     super
245   end
246
247   def sharing_popup
248     @search_sharing = search_scopes
249     render("sharing_popup.js", content_type: "text/javascript")
250   end
251
252   helper_method :download_link
253
254   def download_link
255     collections_url + "/download/#{@object.uuid}/#{@search_sharing.first.api_token}/"
256   end
257
258   def share
259     ApiClientAuthorization.create(scopes: sharing_scopes)
260     sharing_popup
261   end
262
263   def unshare
264     search_scopes.each do |s|
265       s.destroy
266     end
267     sharing_popup
268   end
269
270   def update
271     @updates ||= params[@object.resource_param_name.to_sym]
272     if @updates && (@updates.keys - ["name", "description"]).empty?
273       # exclude manifest_text since only name or description is being updated
274       @object.manifest_text = nil
275     end
276     super
277   end
278
279   protected
280
281   def find_usable_token(token_list)
282     # Iterate over every given token to make it the current token and
283     # yield the given block.
284     # If the block succeeds, return the token it used.
285     # Otherwise, render an error response based on the most specific
286     # error we encounter, and return nil.
287     most_specific_error = [401]
288     token_list.each do |api_token|
289       begin
290         # We can't load the corresponding user, because the token may not
291         # be scoped for that.
292         using_specific_api_token(api_token, load_user: false) do
293           yield
294           return api_token
295         end
296       rescue ArvadosApiClient::ApiError => error
297         if error.api_status >= most_specific_error.first
298           most_specific_error = [error.api_status, error]
299         end
300       end
301     end
302     case most_specific_error.shift
303     when 401, 403
304       redirect_to_login
305     when 404
306       render_not_found(*most_specific_error)
307     end
308     return nil
309   end
310
311   # Note: several controller and integration tests rely on stubbing
312   # file_enumerator to return fake file content.
313   def file_enumerator opts
314     FileStreamer.new opts
315   end
316
317   class FileStreamer
318     include ArvadosApiClientHelper
319     def initialize(opts={})
320       @opts = opts
321     end
322     def each
323       return unless @opts[:uuid] && @opts[:file]
324
325       env = Hash[ENV].dup
326
327       require 'uri'
328       u = URI.parse(arvados_api_client.arvados_v1_base)
329       env['ARVADOS_API_HOST'] = "#{u.host}:#{u.port}"
330       env['ARVADOS_API_TOKEN'] = @opts[:arvados_api_token]
331       env['ARVADOS_API_HOST_INSECURE'] = "true" if Rails.configuration.arvados_insecure_https
332
333       bytesleft = @opts[:maxbytes].andand.to_i || 2**16
334       io = IO.popen([env, 'arv-get', "#{@opts[:uuid]}/#{@opts[:file]}"], 'rb')
335       while bytesleft > 0 && (buf = io.read([bytesleft, 2**16].min)) != nil
336         # shrink the bytesleft count, if we were given a maximum byte
337         # count to read
338         if @opts.include? :maxbytes
339           bytesleft = bytesleft - buf.length
340         end
341         yield buf
342       end
343       io.close
344       # "If ios is opened by IO.popen, close sets $?."
345       # http://www.ruby-doc.org/core-2.1.3/IO.html#method-i-close
346       Rails.logger.warn("#{@opts[:uuid]}/#{@opts[:file]}: #{$?}") if $? != 0
347     end
348   end
349 end