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