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