Merge remote-tracking branch 'refs/remotes/origin/2939-create-params' into origin...
[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={}
34     super self.class.permit_attribute_params(raw_params)
35     @attribute_sortkey ||= {
36       'id' => nil,
37       'name' => '000',
38       'owner_uuid' => '002',
39       'event_type' => '100',
40       'link_class' => '100',
41       'group_class' => '100',
42       'tail_uuid' => '101',
43       'head_uuid' => '102',
44       'object_uuid' => '102',
45       'summary' => '104',
46       'description' => '104',
47       'properties' => '150',
48       'info' => '150',
49       'created_at' => '200',
50       'modified_at' => '201',
51       'modified_by_user_uuid' => '202',
52       'modified_by_client_uuid' => '203',
53       'uuid' => '999',
54     }
55   end
56
57   def self.columns
58     return @columns unless @columns.nil?
59     @columns = []
60     @attribute_info ||= {}
61     schema = arvados_api_client.discovery[:schemas][self.to_s.to_sym]
62     return @columns if schema.nil?
63     schema[:properties].each do |k, coldef|
64       case k
65       when :etag, :kind
66         attr_reader k
67       else
68         if coldef[:type] == coldef[:type].downcase
69           # boolean, integer, etc.
70           @columns << column(k, coldef[:type].to_sym)
71         else
72           # Hash, Array
73           @columns << column(k, :text)
74           serialize k, coldef[:type].constantize
75         end
76         @attribute_info[k] = coldef
77       end
78     end
79     @columns
80   end
81
82   def self.column(name, sql_type = nil, default = nil, null = true)
83     ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
84   end
85
86   def self.attribute_info
87     self.columns
88     @attribute_info
89   end
90
91   def self.find(uuid, opts={})
92     if uuid.class != String or uuid.length < 27 then
93       raise 'argument to find() must be a uuid string. Acceptable formats: warehouse locator or string with format xxxxx-xxxxx-xxxxxxxxxxxxxxx'
94     end
95
96     if self == ArvadosBase
97       # Determine type from uuid and defer to the appropriate subclass.
98       return resource_class_for_uuid(uuid).find(uuid, opts)
99     end
100
101     # Only do one lookup on the API side per {class, uuid, workbench
102     # request} unless {cache: false} is given via opts.
103     cache_key = "request_#{Thread.current.object_id}_#{self.to_s}_#{uuid}"
104     if opts[:cache] == false
105       Rails.cache.write cache_key, arvados_api_client.api(self, '/' + uuid)
106     end
107     hash = Rails.cache.fetch cache_key do
108       arvados_api_client.api(self, '/' + uuid)
109     end
110     new.private_reload(hash)
111   end
112
113   def self.order(*args)
114     ArvadosResourceList.new(self).order(*args)
115   end
116
117   def self.filter(*args)
118     ArvadosResourceList.new(self).filter(*args)
119   end
120
121   def self.where(*args)
122     ArvadosResourceList.new(self).where(*args)
123   end
124
125   def self.limit(*args)
126     ArvadosResourceList.new(self).limit(*args)
127   end
128
129   def self.eager(*args)
130     ArvadosResourceList.new(self).eager(*args)
131   end
132
133   def self.all(*args)
134     ArvadosResourceList.new(self).all(*args)
135   end
136
137   def self.permit_attribute_params raw_params
138     # strong_parameters does not provide security in Workbench: anyone
139     # who can get this far can just as well do a call directly to our
140     # database (Arvados) with the same credentials we use.
141     #
142     # The following permit! is necessary even with
143     # "ActionController::Parameters.permit_all_parameters = true",
144     # because permit_all does not permit nested attributes.
145     ActionController::Parameters.new(raw_params).permit!
146   end
147
148   def self.create raw_params={}, create_params={}
149     x = super(permit_attribute_params(raw_params))
150     x.create_params = create_params
151     x
152   end
153
154   def update_attributes raw_params={}
155     super(self.class.permit_attribute_params(raw_params))
156   end
157
158   def save
159     obdata = {}
160     self.class.columns.each do |col|
161       obdata[col.name.to_sym] = self.send(col.name.to_sym)
162     end
163     obdata.delete :id
164     postdata = { self.class.to_s.underscore => obdata }
165     if etag
166       postdata['_method'] = 'PUT'
167       obdata.delete :uuid
168       resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
169     else
170       postdata.merge!(@create_params) if @create_params
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 self.goes_in_folders?
297     false
298   end
299
300   def editable?
301     (current_user and current_user.is_active and
302      (current_user.is_admin or
303       current_user.uuid == self.owner_uuid or
304       new_record? or
305       (writable_by.include? current_user.uuid rescue false)))
306   end
307
308   def attribute_editable?(attr)
309     if "created_at modified_at modified_by_user_uuid modified_by_client_uuid updated_at".index(attr.to_s)
310       false
311     elsif not (current_user.andand.is_active)
312       false
313     elsif attr == 'uuid'
314       current_user.is_admin
315     else
316       editable?
317     end
318   end
319
320   def self.resource_class_for_uuid(uuid, opts={})
321     if uuid.is_a? ArvadosBase
322       return uuid.class
323     end
324     unless uuid.is_a? String
325       return nil
326     end
327     if opts[:class].is_a? Class
328       return opts[:class]
329     end
330     if uuid.match /^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/
331       return Collection
332     end
333     resource_class = nil
334     uuid.match /^[0-9a-z]{5}-([0-9a-z]{5})-[0-9a-z]{15}$/ do |re|
335       resource_class ||= arvados_api_client.
336         kind_class(self.uuid_infix_object_kind[re[1]])
337     end
338     if opts[:referring_object] and
339         opts[:referring_attr] and
340         opts[:referring_attr].match /_uuid$/
341       resource_class ||= arvados_api_client.
342         kind_class(opts[:referring_object].
343                    attributes[opts[:referring_attr].
344                               sub(/_uuid$/, '_kind')])
345     end
346     resource_class
347   end
348
349   def friendly_link_name
350     (name if self.respond_to? :name) || uuid
351   end
352
353   def content_summary
354     self.class_for_display
355   end
356
357   def selection_label
358     friendly_link_name
359   end
360
361   def owner
362     ArvadosBase.find(owner_uuid) rescue nil
363   end
364
365   protected
366
367   def forget_uuid!
368     self.uuid = nil
369     @etag = nil
370     self
371   end
372
373   def self.current_user
374     Thread.current[:user] ||= User.current if Thread.current[:arvados_api_token]
375     Thread.current[:user]
376   end
377   def current_user
378     self.class.current_user
379   end
380 end