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