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