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