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