1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 class ArvadosBase < ActiveRecord::Base
6 self.abstract_class = true
7 attr_accessor :attribute_sortkey
8 attr_accessor :create_params
10 def self.arvados_api_client
11 ArvadosApiClient.new_or_current
14 def arvados_api_client
15 ArvadosApiClient.new_or_current
18 def self.uuid_infix_object_kind
19 @@uuid_infix_object_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)
29 # Recognize obsolete types.
31 merge('mxsvm' => 'arvados#pipelineTemplate', # Pipeline
32 'uo14g' => 'arvados#pipelineInstance', # PipelineInvocation
33 'ldvyl' => 'arvados#group') # Project
37 def initialize raw_params={}, create_params={}
38 super self.class.permit_attribute_params(raw_params)
39 @create_params = create_params
40 @attribute_sortkey ||= {
43 'owner_uuid' => '002',
44 'event_type' => '100',
45 'link_class' => '100',
46 'group_class' => '100',
49 'object_uuid' => '102',
51 'description' => '104',
52 'properties' => '150',
54 'created_at' => '200',
55 'modified_at' => '201',
56 'modified_by_user_uuid' => '202',
57 'modified_by_client_uuid' => '203',
60 @loaded_attributes = {}
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|
74 if coldef[:type] == coldef[:type].downcase
75 # boolean, integer, etc.
76 @discovered_columns << column(k, coldef[:type])
79 @discovered_columns << column(k, coldef[:type], coldef[:type].constantize.new)
80 serialize k, coldef[:type].constantize
83 unless new_record? or @loaded_attributes.include? k.to_s
84 Rails.logger.debug "BUG: access non-loaded attribute #{k}"
86 # raise ActiveModel::MissingAttributeError, "missing attribute: #{k}"
90 @attribute_info[k] = coldef
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
100 cast_type = ActiveRecord::Base.connection.lookup_cast_type(sql_type)
102 ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, cast_type, sql_type.to_s, null)
105 def self.attribute_info
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'
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)
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)
126 hash = Rails.cache.fetch cache_key do
127 arvados_api_client.api(self, '/' + uuid)
129 new.private_reload(hash)
132 def self.find?(*args)
133 find(*args) rescue nil
136 def self.order(*args)
137 ArvadosResourceList.new(self).order(*args)
140 def self.filter(*args)
141 ArvadosResourceList.new(self).filter(*args)
144 def self.where(*args)
145 ArvadosResourceList.new(self).where(*args)
148 def self.limit(*args)
149 ArvadosResourceList.new(self).limit(*args)
152 def self.select(*args)
153 ArvadosResourceList.new(self).select(*args)
156 def self.with_count(*args)
157 ArvadosResourceList.new(self).with_count(*args)
160 def self.distinct(*args)
161 ArvadosResourceList.new(self).distinct(*args)
164 def self.include_trash(*args)
165 ArvadosResourceList.new(self).include_trash(*args)
168 def self.recursive(*args)
169 ArvadosResourceList.new(self).recursive(*args)
172 def self.eager(*args)
173 ArvadosResourceList.new(self).eager(*args)
177 ArvadosResourceList.new(self)
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.
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!
191 def self.create raw_params={}, create_params={}
192 x = super(permit_attribute_params(raw_params))
193 x.create_params = create_params
197 def update_attributes raw_params={}
198 super(self.class.permit_attribute_params(raw_params))
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
216 postdata = { self.class.to_s.underscore => obdata }
218 postdata['_method'] = 'PUT'
220 resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
222 postdata.merge!(@create_params) if @create_params
223 resp = arvados_api_client.api(self.class, '', postdata)
225 return false if !resp[:etag] || !resp[:uuid]
227 # set read-only non-database attributes
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])
245 self.save or raise Exception.new("Save failed")
250 postdata = { '_method' => 'DELETE' }
251 resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
252 resp[:etag] && resp[:uuid] && resp
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
265 return all_links.select do |m|
270 if (v.respond_to?(:uuid) ? v.uuid : v.to_s) != (test_v.respond_to?(:uuid) ? test_v.uuid : test_v.to_s)
278 @links = arvados_api_client.api Link, '', { _method: 'GET', where: o, eager: true }
279 @links = arvados_api_client.unpack_api_response(@links)
283 return @all_links if @all_links
284 res = arvados_api_client.api Link, '', {
287 tail_kind: self.kind,
292 @all_links = arvados_api_client.unpack_api_response(res)
296 private_reload(self.uuid)
299 def private_reload(uuid_or_hash)
300 raise "No such object" if !uuid_or_hash
301 if uuid_or_hash.is_a? Hash
304 hash = arvados_api_client.api(self.class, '/' + uuid_or_hash)
307 @loaded_attributes[k.to_s] = true
308 if self.respond_to?(k.to_s + '=')
309 self.send(k.to_s + '=', v)
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) }
331 def initialize_copy orig
336 def attributes_for_display
337 self.attributes.reject { |k,v|
338 attribute_sortkey.has_key?(k) and !attribute_sortkey[k]
340 attribute_sortkey[k] or k
344 def class_for_display
345 self.class.to_s.underscore.humanize
348 def self.class_for_display
349 self.to_s.underscore.humanize
352 # Array of strings that are names of attributes that should be rendered as textile.
353 def textile_attributes
358 current_user.andand.is_active && api_exists?(:create)
361 def self.goes_in_projects?
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?
372 (current_user and current_user.is_active and
373 (current_user.is_admin or
374 current_user.uuid == self.owner_uuid 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
385 def self.api_exists?(method)
386 arvados_api_client.discovery[:resources][self.to_s.underscore.pluralize.to_sym].andand[:methods].andand[method]
389 # Array of strings that are the names of attributes that can be edited
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)
396 def attribute_editable?(attr, ever=nil)
397 if not editable_attributes.include?(attr.to_s)
399 elsif not (current_user.andand.is_active)
402 current_user.is_admin
410 def self.resource_class_for_uuid(uuid, opts={})
411 if uuid.is_a? ArvadosBase
414 unless uuid.is_a? String
417 if opts[:class].is_a? Class
420 if uuid.match /^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/
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]])
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')])
439 def resource_param_name
440 self.class.to_s.underscore
443 def friendly_link_name lookup=nil
444 (name if self.respond_to? :name) || default_name
448 self.class_for_display
455 def self.default_name
456 self.to_s.underscore.humanize
460 (self.class.to_s.pluralize + 'Controller').constantize
464 self.class.to_s.tableize
467 # Placeholder for name when name is missing or empty
469 if self.respond_to? :name
470 "New #{class_for_display.downcase}"
477 ArvadosBase.find(owner_uuid) rescue nil
488 def self.current_user
489 Thread.current[:user] ||= User.current if Thread.current[:arvados_api_token]
490 Thread.current[:user]
493 self.class.current_user