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