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