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