Merge branch 'pete-fixes' of git.curoverse.com:arvados into pete-fixes
[arvados.git] / apps / workbench / app / controllers / collections_controller.rb
1 class CollectionsController < ApplicationController
2   skip_around_filter(:require_thread_api_token,
3                      only: [:show_file, :show_file_links])
4   skip_before_filter(:find_object_by_uuid,
5                      only: [:provenance, :show_file, :show_file_links])
6   # We depend on show_file to display the user agreement:
7   skip_before_filter :check_user_agreements, only: [:show_file]
8
9   RELATION_LIMIT = 5
10
11   def show_pane_list
12     %w(Files Provenance_graph Used_by Advanced)
13   end
14
15   def set_persistent
16     case params[:value]
17     when 'persistent', 'cache'
18       persist_links = Link.filter([['owner_uuid', '=', current_user.uuid],
19                                    ['link_class', '=', 'resources'],
20                                    ['name', '=', 'wants'],
21                                    ['tail_uuid', '=', current_user.uuid],
22                                    ['head_uuid', '=', @object.uuid]])
23       logger.debug persist_links.inspect
24     else
25       return unprocessable "Invalid value #{value.inspect}"
26     end
27     if params[:value] == 'persistent'
28       if not persist_links.any?
29         Link.create(link_class: 'resources',
30                     name: 'wants',
31                     tail_uuid: current_user.uuid,
32                     head_uuid: @object.uuid)
33       end
34     else
35       persist_links.each do |link|
36         link.destroy || raise
37       end
38     end
39
40     respond_to do |f|
41       f.json { render json: @object }
42     end
43   end
44
45   def choose
46     params[:limit] ||= 40
47
48     filter = [['link_class','=','name'],
49               ['head_uuid','is_a','arvados#collection']]
50
51     if params[:project_uuid] and !params[:project_uuid].empty?
52       filter << ['tail_uuid', '=', params[:project_uuid]]
53     end
54
55     @objects = Link.filter(filter)
56
57     find_objects_for_index
58     @next_page_href = (next_page_offset and
59                        url_for(offset: next_page_offset, partial: true))
60     @name_links = @objects
61
62     @objects = Collection.
63       filter([['uuid','in',@name_links.collect(&:head_uuid)]])
64     super
65   end
66
67   def index
68     if params[:search].andand.length.andand > 0
69       tags = Link.where(any: ['contains', params[:search]])
70       @collections = (Collection.where(uuid: tags.collect(&:head_uuid)) |
71                       Collection.where(any: ['contains', params[:search]])).
72         uniq { |c| c.uuid }
73     else
74       if params[:limit]
75         limit = params[:limit].to_i
76       else
77         limit = 100
78       end
79
80       if params[:offset]
81         offset = params[:offset].to_i
82       else
83         offset = 0
84       end
85
86       @collections = Collection.limit(limit).offset(offset)
87     end
88     @links = Link.limit(1000).
89       where(head_uuid: @collections.collect(&:uuid))
90     @collection_info = {}
91     @collections.each do |c|
92       @collection_info[c.uuid] = {
93         tag_links: [],
94         wanted: false,
95         wanted_by_me: false,
96         provenance: [],
97         links: []
98       }
99     end
100     @links.each do |link|
101       @collection_info[link.head_uuid] ||= {}
102       info = @collection_info[link.head_uuid]
103       case link.link_class
104       when 'tag'
105         info[:tag_links] << link
106       when 'resources'
107         info[:wanted] = true
108         info[:wanted_by_me] ||= link.tail_uuid == current_user.uuid
109       when 'provenance'
110         info[:provenance] << link.name
111       end
112       info[:links] << link
113     end
114     @request_url = request.url
115
116     render_index
117   end
118
119   def show_file_links
120     Thread.current[:reader_tokens] = [params[:reader_token]]
121     find_object_by_uuid
122     render layout: false
123   end
124
125   def show_file
126     # We pipe from arv-get to send the file to the user.  Before we start it,
127     # we ask the API server if the file actually exists.  This serves two
128     # purposes: it lets us return a useful status code for common errors, and
129     # helps us figure out which token to provide to arv-get.
130     coll = nil
131     tokens = [Thread.current[:arvados_api_token], params[:reader_token]].compact
132     usable_token = find_usable_token(tokens) do
133       coll = Collection.find(params[:uuid])
134     end
135     if usable_token.nil?
136       return  # Response already rendered.
137     elsif params[:file].nil? or not file_in_collection?(coll, params[:file])
138       return render_not_found
139     end
140     opts = params.merge(arvados_api_token: usable_token)
141     ext = File.extname(params[:file])
142     self.response.headers['Content-Type'] =
143       Rack::Mime::MIME_TYPES[ext] || 'application/octet-stream'
144     self.response.headers['Content-Length'] = params[:size] if params[:size]
145     self.response.headers['Content-Disposition'] = params[:disposition] if params[:disposition]
146     self.response_body = file_enumerator opts
147   end
148
149   def sharing_scopes
150     ["GET /arvados/v1/collections/#{@object.uuid}", "GET /arvados/v1/collections/#{@object.uuid}/", "GET /arvados/v1/keep_services/accessible"]
151   end
152
153   def search_scopes
154     begin
155       ApiClientAuthorization.filter([['scopes', '=', sharing_scopes]]).results
156     rescue ArvadosApiClient::AccessForbiddenException
157       nil
158     end
159   end
160
161   def show
162     return super if !@object
163     if current_user
164       jobs_with = lambda do |conds|
165         Job.limit(RELATION_LIMIT).where(conds)
166           .results.sort_by { |j| j.finished_at || j.created_at }
167       end
168       @output_of = jobs_with.call(output: @object.uuid)
169       @log_of = jobs_with.call(log: @object.uuid)
170       @project_links = Link.limit(RELATION_LIMIT).order("modified_at DESC")
171         .where(head_uuid: @object.uuid, link_class: 'name').results
172       project_hash = Group.where(uuid: @project_links.map(&:tail_uuid)).to_hash
173       @projects = project_hash.values
174       @permissions = Link.limit(RELATION_LIMIT).order("modified_at DESC")
175         .where(head_uuid: @object.uuid, link_class: 'permission',
176                name: 'can_read').results
177       @logs = Log.limit(RELATION_LIMIT).order("created_at DESC")
178         .where(object_uuid: @object.uuid).results
179       @is_persistent = Link.limit(1)
180         .where(head_uuid: @object.uuid, tail_uuid: current_user.uuid,
181                link_class: 'resources', name: 'wants')
182         .results.any?
183       @search_sharing = search_scopes
184     end
185
186     if params["tab_pane"] == "Provenance_graph"
187       @prov_svg = ProvenanceHelper::create_provenance_graph(@object.provenance, "provenance_svg",
188                                                             {:request => request,
189                                                               :direction => :bottom_up,
190                                                               :combine_jobs => :script_only}) rescue nil
191     end
192     if params["tab_pane"] == "Used_by"
193       @used_by_svg = ProvenanceHelper::create_provenance_graph(@object.used_by, "used_by_svg",
194                                                                {:request => request,
195                                                                  :direction => :top_down,
196                                                                  :combine_jobs => :script_only,
197                                                                  :pdata_only => true}) rescue nil
198     end
199     super
200   end
201
202   def sharing_popup
203     @search_sharing = search_scopes
204     respond_to do |format|
205       format.html
206       format.js
207     end
208   end
209
210   helper_method :download_link
211
212   def download_link
213     collections_url + "/download/#{@object.uuid}/#{@search_sharing.first.api_token}/"
214   end
215
216   def share
217     a = ApiClientAuthorization.create(scopes: sharing_scopes)
218     @search_sharing = search_scopes
219     render 'sharing_popup'
220   end
221
222   def unshare
223     @search_sharing = search_scopes
224     @search_sharing.each do |s|
225       s.destroy
226     end
227     @search_sharing = search_scopes
228     render 'sharing_popup'
229   end
230
231   protected
232
233   def find_usable_token(token_list)
234     # Iterate over every given token to make it the current token and
235     # yield the given block.
236     # If the block succeeds, return the token it used.
237     # Otherwise, render an error response based on the most specific
238     # error we encounter, and return nil.
239     most_specific_error = [401]
240     token_list.each do |api_token|
241       using_specific_api_token(api_token) do
242         begin
243           yield
244           return api_token
245         rescue ArvadosApiClient::NotLoggedInException => error
246           status = 401
247         rescue => error
248           status = (error.message =~ /\[API: (\d+)\]$/) ? $1.to_i : nil
249           raise unless [401, 403, 404].include?(status)
250         end
251         if status >= most_specific_error.first
252           most_specific_error = [status, error]
253         end
254       end
255     end
256     case most_specific_error.shift
257     when 401, 403
258       redirect_to_login
259     when 404
260       render_not_found(*most_specific_error)
261     end
262     return nil
263   end
264
265   def file_in_collection?(collection, filename)
266     target = CollectionsHelper.file_path(File.split(filename))
267     collection.files.each do |file_spec|
268       return true if (CollectionsHelper.file_path(file_spec) == target)
269     end
270     false
271   end
272
273   def file_enumerator(opts)
274     FileStreamer.new opts
275   end
276
277   class FileStreamer
278     include ArvadosApiClientHelper
279     def initialize(opts={})
280       @opts = opts
281     end
282     def each
283       return unless @opts[:uuid] && @opts[:file]
284
285       env = Hash[ENV].dup
286
287       require 'uri'
288       u = URI.parse(arvados_api_client.arvados_v1_base)
289       env['ARVADOS_API_HOST'] = "#{u.host}:#{u.port}"
290       env['ARVADOS_API_TOKEN'] = @opts[:arvados_api_token]
291       env['ARVADOS_API_HOST_INSECURE'] = "true" if Rails.configuration.arvados_insecure_https
292
293       IO.popen([env, 'arv-get', "#{@opts[:uuid]}/#{@opts[:file]}"],
294                'rb') do |io|
295         while buf = io.read(2**16)
296           yield buf
297         end
298       end
299       Rails.logger.warn("#{@opts[:uuid]}/#{@opts[:file]}: #{$?}") if $? != 0
300     end
301   end
302 end