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