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