2809: Merge branch 'master' refs #2809
[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
5   def self.arvados_api_client
6     ArvadosApiClient.new_or_current
7   end
8
9   def arvados_api_client
10     ArvadosApiClient.new_or_current
11   end
12
13   def self.uuid_infix_object_kind
14     @@uuid_infix_object_kind ||=
15       begin
16         infix_kind = {}
17         arvados_api_client.discovery[:schemas].each do |name, schema|
18           if schema[:uuidPrefix]
19             infix_kind[schema[:uuidPrefix]] =
20               'arvados#' + name.to_s.camelcase(:lower)
21           end
22         end
23
24         # Recognize obsolete types.
25         infix_kind.
26           merge('mxsvm' => 'arvados#pipelineTemplate', # Pipeline
27                 'uo14g' => 'arvados#pipelineInstance', # PipelineInvocation
28                 'ldvyl' => 'arvados#group') # Project
29       end
30   end
31
32   def initialize raw_params={}
33     begin
34       super self.class.permit_attribute_params(raw_params)
35     rescue Exception => e
36       logger.debug raw_params
37       logger.debug self.class.permit_attribute_params(raw_params).inspect
38       logger.debug self.class.attribute_info.inspect
39       raise e
40     end
41     @attribute_sortkey ||= {
42       'id' => nil,
43       'name' => '000',
44       'owner_uuid' => '002',
45       'event_type' => '100',
46       'link_class' => '100',
47       'group_class' => '100',
48       'tail_uuid' => '101',
49       'head_uuid' => '102',
50       'object_uuid' => '102',
51       'summary' => '104',
52       'description' => '104',
53       'properties' => '150',
54       'info' => '150',
55       'created_at' => '200',
56       'modified_at' => '201',
57       'modified_by_user_uuid' => '202',
58       'modified_by_client_uuid' => '203',
59       'uuid' => '999',
60     }
61   end
62
63   def self.columns
64     return @columns unless @columns.nil?
65     @columns = []
66     @attribute_info ||= {}
67     schema = arvados_api_client.discovery[:schemas][self.to_s.to_sym]
68     return @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           @columns << column(k, coldef[:type].to_sym)
77         else
78           # Hash, Array
79           @columns << column(k, :text)
80           serialize k, coldef[:type].constantize
81         end
82         @attribute_info[k] = coldef
83       end
84     end
85     @columns
86   end
87
88   def self.column(name, sql_type = nil, default = nil, null = true)
89     ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
90   end
91
92   def self.attribute_info
93     self.columns
94     @attribute_info
95   end
96
97   def self.find(uuid, opts={})
98     if uuid.class != String or uuid.length < 27 then
99       raise 'argument to find() must be a uuid string. Acceptable formats: warehouse locator or string with format xxxxx-xxxxx-xxxxxxxxxxxxxxx'
100     end
101
102     if self == ArvadosBase
103       # Determine type from uuid and defer to the appropriate subclass.
104       return resource_class_for_uuid(uuid).find(uuid, opts)
105     end
106
107     # Only do one lookup on the API side per {class, uuid, workbench
108     # request} unless {cache: false} is given via opts.
109     cache_key = "request_#{Thread.current.object_id}_#{self.to_s}_#{uuid}"
110     if opts[:cache] == false
111       Rails.cache.write cache_key, arvados_api_client.api(self, '/' + uuid)
112     end
113     hash = Rails.cache.fetch cache_key do
114       arvados_api_client.api(self, '/' + uuid)
115     end
116     new.private_reload(hash)
117   end
118
119   def self.order(*args)
120     ArvadosResourceList.new(self).order(*args)
121   end
122
123   def self.filter(*args)
124     ArvadosResourceList.new(self).filter(*args)
125   end
126
127   def self.where(*args)
128     ArvadosResourceList.new(self).where(*args)
129   end
130
131   def self.limit(*args)
132     ArvadosResourceList.new(self).limit(*args)
133   end
134
135   def self.eager(*args)
136     ArvadosResourceList.new(self).eager(*args)
137   end
138
139   def self.all(*args)
140     ArvadosResourceList.new(self).all(*args)
141   end
142
143   def self.permit_attribute_params raw_params
144     # strong_parameters does not provide security in Workbench: anyone
145     # who can get this far can just as well do a call directly to our
146     # database (Arvados) with the same credentials we use.
147     ActionController::Parameters.new(raw_params).permit!
148   end
149
150   def self.create raw_params={}
151     logger.error permit_attribute_params(raw_params).inspect
152     super(permit_attribute_params(raw_params))
153   end
154
155   def update_attributes raw_params={}
156     super(self.class.permit_attribute_params(raw_params))
157   end
158
159   def save
160     obdata = {}
161     self.class.columns.each do |col|
162       obdata[col.name.to_sym] = self.send(col.name.to_sym)
163     end
164     obdata.delete :id
165     postdata = { self.class.to_s.underscore => obdata }
166     if etag
167       postdata['_method'] = 'PUT'
168       obdata.delete :uuid
169       resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
170     else
171       resp = arvados_api_client.api(self.class, '', postdata)
172     end
173     return false if !resp[:etag] || !resp[:uuid]
174
175     # set read-only non-database attributes
176     @etag = resp[:etag]
177     @kind = resp[:kind]
178
179     # attributes can be modified during "save" -- we should update our copies
180     resp.keys.each do |attr|
181       if self.respond_to? "#{attr}=".to_sym
182         self.send(attr.to_s + '=', resp[attr.to_sym])
183       end
184     end
185
186     @new_record = false
187
188     self
189   end
190
191   def save!
192     self.save or raise Exception.new("Save failed")
193   end
194
195   def destroy
196     if etag || uuid
197       postdata = { '_method' => 'DELETE' }
198       resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
199       resp[:etag] && resp[:uuid] && resp
200     else
201       true
202     end
203   end
204
205   def links(*args)
206     o = {}
207     o.merge!(args.pop) if args[-1].is_a? Hash
208     o[:link_class] ||= args.shift
209     o[:name] ||= args.shift
210     o[:tail_uuid] = self.uuid
211     if all_links
212       return all_links.select do |m|
213         ok = true
214         o.each do |k,v|
215           if !v.nil?
216             test_v = m.send(k)
217             if (v.respond_to?(:uuid) ? v.uuid : v.to_s) != (test_v.respond_to?(:uuid) ? test_v.uuid : test_v.to_s)
218               ok = false
219             end
220           end
221         end
222         ok
223       end
224     end
225     @links = arvados_api_client.api Link, '', { _method: 'GET', where: o, eager: true }
226     @links = arvados_api_client.unpack_api_response(@links)
227   end
228
229   def all_links
230     return @all_links if @all_links
231     res = arvados_api_client.api Link, '', {
232       _method: 'GET',
233       where: {
234         tail_kind: self.kind,
235         tail_uuid: self.uuid
236       },
237       eager: true
238     }
239     @all_links = arvados_api_client.unpack_api_response(res)
240   end
241
242   def reload
243     private_reload(self.uuid)
244   end
245
246   def private_reload(uuid_or_hash)
247     raise "No such object" if !uuid_or_hash
248     if uuid_or_hash.is_a? Hash
249       hash = uuid_or_hash
250     else
251       hash = arvados_api_client.api(self.class, '/' + uuid_or_hash)
252     end
253     hash.each do |k,v|
254       if self.respond_to?(k.to_s + '=')
255         self.send(k.to_s + '=', v)
256       else
257         # When ArvadosApiClient#schema starts telling us what to expect
258         # in API responses (not just the server side database
259         # columns), this sort of awfulness can be avoided:
260         self.instance_variable_set('@' + k.to_s, v)
261         if !self.respond_to? k
262           singleton = class << self; self end
263           singleton.send :define_method, k, lambda { instance_variable_get('@' + k.to_s) }
264         end
265       end
266     end
267     @all_links = nil
268     @new_record = false
269     self
270   end
271
272   def to_param
273     uuid
274   end
275
276   def dup
277     super.forget_uuid!
278   end
279
280   def attributes_for_display
281     self.attributes.reject { |k,v|
282       attribute_sortkey.has_key?(k) and !attribute_sortkey[k]
283     }.sort_by { |k,v|
284       attribute_sortkey[k] or k
285     }
286   end
287
288   def class_for_display
289     self.class.to_s
290   end
291
292   def self.creatable?
293     current_user
294   end
295
296   def editable?
297     (current_user and current_user.is_active and
298      (current_user.is_admin or
299       current_user.uuid == self.owner_uuid or
300       new_record?))
301   end
302
303   def attribute_editable?(attr)
304     if "created_at modified_at modified_by_user_uuid modified_by_client_uuid updated_at".index(attr.to_s)
305       false
306     elsif not (current_user.andand.is_active)
307       false
308     elsif "uuid owner_uuid".index(attr.to_s) or current_user.is_admin
309       current_user.is_admin
310     else
311       current_user.uuid == self.owner_uuid or
312         current_user.uuid == self.uuid or
313         new_record?
314     end
315   end
316
317   def self.resource_class_for_uuid(uuid, opts={})
318     if uuid.is_a? ArvadosBase
319       return uuid.class
320     end
321     unless uuid.is_a? String
322       return nil
323     end
324     if opts[:class].is_a? Class
325       return opts[:class]
326     end
327     if uuid.match /^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/
328       return Collection
329     end
330     resource_class = nil
331     uuid.match /^[0-9a-z]{5}-([0-9a-z]{5})-[0-9a-z]{15}$/ do |re|
332       resource_class ||= arvados_api_client.
333         kind_class(self.uuid_infix_object_kind[re[1]])
334     end
335     if opts[:referring_object] and
336         opts[:referring_attr] and
337         opts[:referring_attr].match /_uuid$/
338       resource_class ||= arvados_api_client.
339         kind_class(opts[:referring_object].
340                    attributes[opts[:referring_attr].
341                               sub(/_uuid$/, '_kind')])
342     end
343     resource_class
344   end
345
346   def friendly_link_name
347     (name if self.respond_to? :name) || uuid
348   end
349
350   def content_summary
351     self.class_for_display
352   end
353
354   def selection_label
355     friendly_link_name
356   end
357
358   protected
359
360   def forget_uuid!
361     self.uuid = nil
362     @etag = nil
363     self
364   end
365
366   def self.current_user
367     Thread.current[:user] ||= User.current if Thread.current[:arvados_api_token]
368     Thread.current[:user]
369   end
370   def current_user
371     self.class.current_user
372   end
373 end