8784: Fix test for latest firefox.
[arvados.git] / apps / workbench / app / models / arvados_base.rb
1 class ArvadosBase < ActiveRecord::Base
2   self.abstract_class = true
3   attr_accessor :attribute_sortkey
4   attr_accessor :create_params
5
6   def self.arvados_api_client
7     ArvadosApiClient.new_or_current
8   end
9
10   def arvados_api_client
11     ArvadosApiClient.new_or_current
12   end
13
14   def self.uuid_infix_object_kind
15     @@uuid_infix_object_kind ||=
16       begin
17         infix_kind = {}
18         arvados_api_client.discovery[:schemas].each do |name, schema|
19           if schema[:uuidPrefix]
20             infix_kind[schema[:uuidPrefix]] =
21               'arvados#' + name.to_s.camelcase(:lower)
22           end
23         end
24
25         # Recognize obsolete types.
26         infix_kind.
27           merge('mxsvm' => 'arvados#pipelineTemplate', # Pipeline
28                 'uo14g' => 'arvados#pipelineInstance', # PipelineInvocation
29                 'ldvyl' => 'arvados#group') # Project
30       end
31   end
32
33   def initialize raw_params={}, create_params={}
34     super self.class.permit_attribute_params(raw_params)
35     @create_params = create_params
36     @attribute_sortkey ||= {
37       'id' => nil,
38       'name' => '000',
39       'owner_uuid' => '002',
40       'event_type' => '100',
41       'link_class' => '100',
42       'group_class' => '100',
43       'tail_uuid' => '101',
44       'head_uuid' => '102',
45       'object_uuid' => '102',
46       'summary' => '104',
47       'description' => '104',
48       'properties' => '150',
49       'info' => '150',
50       'created_at' => '200',
51       'modified_at' => '201',
52       'modified_by_user_uuid' => '202',
53       'modified_by_client_uuid' => '203',
54       'uuid' => '999',
55     }
56     @loaded_attributes = {}
57   end
58
59   def self.columns
60     return @columns if @columns.andand.any?
61     @columns = []
62     @attribute_info ||= {}
63     schema = arvados_api_client.discovery[:schemas][self.to_s.to_sym]
64     return @columns if schema.nil?
65     schema[:properties].each do |k, coldef|
66       case k
67       when :etag, :kind
68         attr_reader k
69       else
70         if coldef[:type] == coldef[:type].downcase
71           # boolean, integer, etc.
72           @columns << column(k, coldef[:type].to_sym)
73         else
74           # Hash, Array
75           @columns << column(k, :text)
76           serialize k, coldef[:type].constantize
77         end
78         define_method k do
79           unless new_record? or @loaded_attributes.include? k.to_s
80             Rails.logger.debug "BUG: access non-loaded attribute #{k}"
81             # We should...
82             # raise ActiveModel::MissingAttributeError, "missing attribute: #{k}"
83           end
84           super()
85         end
86         @attribute_info[k] = coldef
87       end
88     end
89     @columns
90   end
91
92   def self.column(name, sql_type = nil, default = nil, null = true)
93     ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
94   end
95
96   def self.attribute_info
97     self.columns
98     @attribute_info
99   end
100
101   def self.find(uuid, opts={})
102     if uuid.class != String or uuid.length < 27 then
103       raise 'argument to find() must be a uuid string. Acceptable formats: warehouse locator or string with format xxxxx-xxxxx-xxxxxxxxxxxxxxx'
104     end
105
106     if self == ArvadosBase
107       # Determine type from uuid and defer to the appropriate subclass.
108       return resource_class_for_uuid(uuid).find(uuid, opts)
109     end
110
111     # Only do one lookup on the API side per {class, uuid, workbench
112     # request} unless {cache: false} is given via opts.
113     cache_key = "request_#{Thread.current.object_id}_#{self.to_s}_#{uuid}"
114     if opts[:cache] == false
115       Rails.cache.write cache_key, arvados_api_client.api(self, '/' + uuid)
116     end
117     hash = Rails.cache.fetch cache_key do
118       arvados_api_client.api(self, '/' + uuid)
119     end
120     new.private_reload(hash)
121   end
122
123   def self.find?(*args)
124     find(*args) rescue nil
125   end
126
127   def self.order(*args)
128     ArvadosResourceList.new(self).order(*args)
129   end
130
131   def self.filter(*args)
132     ArvadosResourceList.new(self).filter(*args)
133   end
134
135   def self.where(*args)
136     ArvadosResourceList.new(self).where(*args)
137   end
138
139   def self.limit(*args)
140     ArvadosResourceList.new(self).limit(*args)
141   end
142
143   def self.select(*args)
144     ArvadosResourceList.new(self).select(*args)
145   end
146
147   def self.with_count(*args)
148     ArvadosResourceList.new(self).with_count(*args)
149   end
150
151   def self.distinct(*args)
152     ArvadosResourceList.new(self).distinct(*args)
153   end
154
155   def self.include_trash(*args)
156     ArvadosResourceList.new(self).include_trash(*args)
157   end
158
159   def self.recursive(*args)
160     ArvadosResourceList.new(self).recursive(*args)
161   end
162
163   def self.eager(*args)
164     ArvadosResourceList.new(self).eager(*args)
165   end
166
167   def self.all
168     ArvadosResourceList.new(self)
169   end
170
171   def self.permit_attribute_params raw_params
172     # strong_parameters does not provide security in Workbench: anyone
173     # who can get this far can just as well do a call directly to our
174     # database (Arvados) with the same credentials we use.
175     #
176     # The following permit! is necessary even with
177     # "ActionController::Parameters.permit_all_parameters = true",
178     # because permit_all does not permit nested attributes.
179     ActionController::Parameters.new(raw_params).permit!
180   end
181
182   def self.create raw_params={}, create_params={}
183     x = super(permit_attribute_params(raw_params))
184     x.create_params = create_params
185     x
186   end
187
188   def update_attributes raw_params={}
189     super(self.class.permit_attribute_params(raw_params))
190   end
191
192   def save
193     obdata = {}
194     self.class.columns.each do |col|
195       # Non-nil serialized values must be sent because we can't tell
196       # whether they've changed. Other than that, any given attribute
197       # is either unchanged (in which case there's no need to send its
198       # old value in the update/create command) or has been added to
199       # #changed by ActiveRecord's #attr= method.
200       if changed.include? col.name or
201           (self.class.serialized_attributes.include? col.name and
202            @loaded_attributes[col.name])
203         obdata[col.name.to_sym] = self.send col.name
204       end
205     end
206     obdata.delete :id
207     postdata = { self.class.to_s.underscore => obdata }
208     if etag
209       postdata['_method'] = 'PUT'
210       obdata.delete :uuid
211       resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
212     else
213       postdata.merge!(@create_params) if @create_params
214       resp = arvados_api_client.api(self.class, '', postdata)
215     end
216     return false if !resp[:etag] || !resp[:uuid]
217
218     # set read-only non-database attributes
219     @etag = resp[:etag]
220     @kind = resp[:kind]
221
222     # attributes can be modified during "save" -- we should update our copies
223     resp.keys.each do |attr|
224       if self.respond_to? "#{attr}=".to_sym
225         self.send(attr.to_s + '=', resp[attr.to_sym])
226       end
227     end
228
229     changes_applied
230     @new_record = false
231
232     self
233   end
234
235   def save!
236     self.save or raise Exception.new("Save failed")
237   end
238
239   def destroy
240     if etag || uuid
241       postdata = { '_method' => 'DELETE' }
242       resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
243       resp[:etag] && resp[:uuid] && resp
244     else
245       true
246     end
247   end
248
249   def links(*args)
250     o = {}
251     o.merge!(args.pop) if args[-1].is_a? Hash
252     o[:link_class] ||= args.shift
253     o[:name] ||= args.shift
254     o[:tail_uuid] = self.uuid
255     if all_links
256       return all_links.select do |m|
257         ok = true
258         o.each do |k,v|
259           if !v.nil?
260             test_v = m.send(k)
261             if (v.respond_to?(:uuid) ? v.uuid : v.to_s) != (test_v.respond_to?(:uuid) ? test_v.uuid : test_v.to_s)
262               ok = false
263             end
264           end
265         end
266         ok
267       end
268     end
269     @links = arvados_api_client.api Link, '', { _method: 'GET', where: o, eager: true }
270     @links = arvados_api_client.unpack_api_response(@links)
271   end
272
273   def all_links
274     return @all_links if @all_links
275     res = arvados_api_client.api Link, '', {
276       _method: 'GET',
277       where: {
278         tail_kind: self.kind,
279         tail_uuid: self.uuid
280       },
281       eager: true
282     }
283     @all_links = arvados_api_client.unpack_api_response(res)
284   end
285
286   def reload
287     private_reload(self.uuid)
288   end
289
290   def private_reload(uuid_or_hash)
291     raise "No such object" if !uuid_or_hash
292     if uuid_or_hash.is_a? Hash
293       hash = uuid_or_hash
294     else
295       hash = arvados_api_client.api(self.class, '/' + uuid_or_hash)
296     end
297     hash.each do |k,v|
298       @loaded_attributes[k.to_s] = true
299       if self.respond_to?(k.to_s + '=')
300         self.send(k.to_s + '=', v)
301       else
302         # When ArvadosApiClient#schema starts telling us what to expect
303         # in API responses (not just the server side database
304         # columns), this sort of awfulness can be avoided:
305         self.instance_variable_set('@' + k.to_s, v)
306         if !self.respond_to? k
307           singleton = class << self; self end
308           singleton.send :define_method, k, lambda { instance_variable_get('@' + k.to_s) }
309         end
310       end
311     end
312     @all_links = nil
313     changes_applied
314     @new_record = false
315     self
316   end
317
318   def to_param
319     uuid
320   end
321
322   def initialize_copy orig
323     super
324     forget_uuid!
325   end
326
327   def attributes_for_display
328     self.attributes.reject { |k,v|
329       attribute_sortkey.has_key?(k) and !attribute_sortkey[k]
330     }.sort_by { |k,v|
331       attribute_sortkey[k] or k
332     }
333   end
334
335   def class_for_display
336     self.class.to_s.underscore.humanize
337   end
338
339   def self.class_for_display
340     self.to_s.underscore.humanize
341   end
342
343   # Array of strings that are names of attributes that should be rendered as textile.
344   def textile_attributes
345     []
346   end
347
348   def self.creatable?
349     current_user.andand.is_active && api_exists?(:create)
350   end
351
352   def self.goes_in_projects?
353     false
354   end
355
356   # can this class of object be copied into a project?
357   # override to false on indivudal model classes for which this should not be true
358   def self.copies_to_projects?
359     self.goes_in_projects?
360   end
361
362   def editable?
363     (current_user and current_user.is_active and
364      (current_user.is_admin or
365       current_user.uuid == self.owner_uuid or
366       new_record? or
367       (respond_to?(:writable_by) ?
368        writable_by.include?(current_user.uuid) :
369        (ArvadosBase.find(owner_uuid).writable_by.include? current_user.uuid rescue false)))) or false
370   end
371
372   def deletable?
373     editable?
374   end
375
376   def self.api_exists?(method)
377     arvados_api_client.discovery[:resources][self.to_s.underscore.pluralize.to_sym].andand[:methods].andand[method]
378   end
379
380   # Array of strings that are the names of attributes that can be edited
381   # with X-Editable.
382   def editable_attributes
383     self.class.columns.map(&:name) -
384       %w(created_at modified_at modified_by_user_uuid modified_by_client_uuid updated_at)
385   end
386
387   def attribute_editable?(attr, ever=nil)
388     if not editable_attributes.include?(attr.to_s)
389       false
390     elsif not (current_user.andand.is_active)
391       false
392     elsif attr == 'uuid'
393       current_user.is_admin
394     elsif ever
395       true
396     else
397       editable?
398     end
399   end
400
401   def self.resource_class_for_uuid(uuid, opts={})
402     if uuid.is_a? ArvadosBase
403       return uuid.class
404     end
405     unless uuid.is_a? String
406       return nil
407     end
408     if opts[:class].is_a? Class
409       return opts[:class]
410     end
411     if uuid.match /^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/
412       return Collection
413     end
414     resource_class = nil
415     uuid.match /^[0-9a-z]{5}-([0-9a-z]{5})-[0-9a-z]{15}$/ do |re|
416       resource_class ||= arvados_api_client.
417         kind_class(self.uuid_infix_object_kind[re[1]])
418     end
419     if opts[:referring_object] and
420         opts[:referring_attr] and
421         opts[:referring_attr].match /_uuid$/
422       resource_class ||= arvados_api_client.
423         kind_class(opts[:referring_object].
424                    attributes[opts[:referring_attr].
425                               sub(/_uuid$/, '_kind')])
426     end
427     resource_class
428   end
429
430   def resource_param_name
431     self.class.to_s.underscore
432   end
433
434   def friendly_link_name lookup=nil
435     (name if self.respond_to? :name) || default_name
436   end
437
438   def content_summary
439     self.class_for_display
440   end
441
442   def selection_label
443     friendly_link_name
444   end
445
446   def self.default_name
447     self.to_s.underscore.humanize
448   end
449
450   def controller
451     (self.class.to_s.pluralize + 'Controller').constantize
452   end
453
454   def controller_name
455     self.class.to_s.tableize
456   end
457
458   # Placeholder for name when name is missing or empty
459   def default_name
460     if self.respond_to? :name
461       "New #{class_for_display.downcase}"
462     else
463       uuid
464     end
465   end
466
467   def owner
468     ArvadosBase.find(owner_uuid) rescue nil
469   end
470
471   protected
472
473   def forget_uuid!
474     self.uuid = nil
475     @etag = nil
476     self
477   end
478
479   def self.current_user
480     Thread.current[:user] ||= User.current if Thread.current[:arvados_api_token]
481     Thread.current[:user]
482   end
483   def current_user
484     self.class.current_user
485   end
486 end