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