Merge branch '2882-job-process-stats' refs #2882
[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 unless @columns.nil?
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.order(*args)
115     ArvadosResourceList.new(self).order(*args)
116   end
117
118   def self.filter(*args)
119     ArvadosResourceList.new(self).filter(*args)
120   end
121
122   def self.where(*args)
123     ArvadosResourceList.new(self).where(*args)
124   end
125
126   def self.limit(*args)
127     ArvadosResourceList.new(self).limit(*args)
128   end
129
130   def self.eager(*args)
131     ArvadosResourceList.new(self).eager(*args)
132   end
133
134   def self.all(*args)
135     ArvadosResourceList.new(self).all(*args)
136   end
137
138   def self.permit_attribute_params raw_params
139     # strong_parameters does not provide security in Workbench: anyone
140     # who can get this far can just as well do a call directly to our
141     # database (Arvados) with the same credentials we use.
142     #
143     # The following permit! is necessary even with
144     # "ActionController::Parameters.permit_all_parameters = true",
145     # because permit_all does not permit nested attributes.
146     ActionController::Parameters.new(raw_params).permit!
147   end
148
149   def self.create raw_params={}, create_params={}
150     x = super(permit_attribute_params(raw_params))
151     x.create_params = create_params
152     x
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       postdata.merge!(@create_params) if @create_params
172       resp = arvados_api_client.api(self.class, '', postdata)
173     end
174     return false if !resp[:etag] || !resp[:uuid]
175
176     # set read-only non-database attributes
177     @etag = resp[:etag]
178     @kind = resp[:kind]
179
180     # attributes can be modified during "save" -- we should update our copies
181     resp.keys.each do |attr|
182       if self.respond_to? "#{attr}=".to_sym
183         self.send(attr.to_s + '=', resp[attr.to_sym])
184       end
185     end
186
187     @new_record = false
188
189     self
190   end
191
192   def save!
193     self.save or raise Exception.new("Save failed")
194   end
195
196   def destroy
197     if etag || uuid
198       postdata = { '_method' => 'DELETE' }
199       resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
200       resp[:etag] && resp[:uuid] && resp
201     else
202       true
203     end
204   end
205
206   def links(*args)
207     o = {}
208     o.merge!(args.pop) if args[-1].is_a? Hash
209     o[:link_class] ||= args.shift
210     o[:name] ||= args.shift
211     o[:tail_uuid] = self.uuid
212     if all_links
213       return all_links.select do |m|
214         ok = true
215         o.each do |k,v|
216           if !v.nil?
217             test_v = m.send(k)
218             if (v.respond_to?(:uuid) ? v.uuid : v.to_s) != (test_v.respond_to?(:uuid) ? test_v.uuid : test_v.to_s)
219               ok = false
220             end
221           end
222         end
223         ok
224       end
225     end
226     @links = arvados_api_client.api Link, '', { _method: 'GET', where: o, eager: true }
227     @links = arvados_api_client.unpack_api_response(@links)
228   end
229
230   def all_links
231     return @all_links if @all_links
232     res = arvados_api_client.api Link, '', {
233       _method: 'GET',
234       where: {
235         tail_kind: self.kind,
236         tail_uuid: self.uuid
237       },
238       eager: true
239     }
240     @all_links = arvados_api_client.unpack_api_response(res)
241   end
242
243   def reload
244     private_reload(self.uuid)
245   end
246
247   def private_reload(uuid_or_hash)
248     raise "No such object" if !uuid_or_hash
249     if uuid_or_hash.is_a? Hash
250       hash = uuid_or_hash
251     else
252       hash = arvados_api_client.api(self.class, '/' + uuid_or_hash)
253     end
254     hash.each do |k,v|
255       if self.respond_to?(k.to_s + '=')
256         self.send(k.to_s + '=', v)
257       else
258         # When ArvadosApiClient#schema starts telling us what to expect
259         # in API responses (not just the server side database
260         # columns), this sort of awfulness can be avoided:
261         self.instance_variable_set('@' + k.to_s, v)
262         if !self.respond_to? k
263           singleton = class << self; self end
264           singleton.send :define_method, k, lambda { instance_variable_get('@' + k.to_s) }
265         end
266       end
267     end
268     @all_links = nil
269     @new_record = false
270     self
271   end
272
273   def to_param
274     uuid
275   end
276
277   def dup
278     super.forget_uuid!
279   end
280
281   def attributes_for_display
282     self.attributes.reject { |k,v|
283       attribute_sortkey.has_key?(k) and !attribute_sortkey[k]
284     }.sort_by { |k,v|
285       attribute_sortkey[k] or k
286     }
287   end
288
289   def class_for_display
290     self.class.to_s
291   end
292
293   def self.creatable?
294     current_user
295   end
296
297   def self.goes_in_folders?
298     false
299   end
300
301   def editable?
302     (current_user and current_user.is_active and
303      (current_user.is_admin or
304       current_user.uuid == self.owner_uuid or
305       new_record? or
306       (writable_by.include? current_user.uuid rescue false)))
307   end
308
309   def attribute_editable?(attr, ever=nil)
310     if "created_at modified_at modified_by_user_uuid modified_by_client_uuid updated_at".index(attr.to_s)
311       false
312     elsif not (current_user.andand.is_active)
313       false
314     elsif attr == 'uuid'
315       current_user.is_admin
316     elsif ever
317       true
318     else
319       editable?
320     end
321   end
322
323   def self.resource_class_for_uuid(uuid, opts={})
324     if uuid.is_a? ArvadosBase
325       return uuid.class
326     end
327     unless uuid.is_a? String
328       return nil
329     end
330     if opts[:class].is_a? Class
331       return opts[:class]
332     end
333     if uuid.match /^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/
334       return Collection
335     end
336     resource_class = nil
337     uuid.match /^[0-9a-z]{5}-([0-9a-z]{5})-[0-9a-z]{15}$/ do |re|
338       resource_class ||= arvados_api_client.
339         kind_class(self.uuid_infix_object_kind[re[1]])
340     end
341     if opts[:referring_object] and
342         opts[:referring_attr] and
343         opts[:referring_attr].match /_uuid$/
344       resource_class ||= arvados_api_client.
345         kind_class(opts[:referring_object].
346                    attributes[opts[:referring_attr].
347                               sub(/_uuid$/, '_kind')])
348     end
349     resource_class
350   end
351
352   def friendly_link_name
353     (name if self.respond_to? :name) || uuid
354   end
355
356   def content_summary
357     self.class_for_display
358   end
359
360   def selection_label
361     friendly_link_name
362   end
363
364   def owner
365     ArvadosBase.find(owner_uuid) rescue nil
366   end
367
368   protected
369
370   def forget_uuid!
371     self.uuid = nil
372     @etag = nil
373     self
374   end
375
376   def self.current_user
377     Thread.current[:user] ||= User.current if Thread.current[:arvados_api_token]
378     Thread.current[:user]
379   end
380   def current_user
381     self.class.current_user
382   end
383 end