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