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