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