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