Merge branch 'master' into 2352-use-state
[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(*args)
25     super(*args)
26     @attribute_sortkey ||= {
27       'id' => nil,
28       'name' => '000',
29       'owner_uuid' => '002',
30       'event_type' => '100',
31       'link_class' => '100',
32       'group_class' => '100',
33       'tail_uuid' => '101',
34       'head_uuid' => '102',
35       'object_uuid' => '102',
36       'summary' => '104',
37       'description' => '104',
38       'properties' => '150',
39       'info' => '150',
40       'created_at' => '200',
41       'modified_at' => '201',
42       'modified_by_user_uuid' => '202',
43       'modified_by_client_uuid' => '203',
44       'uuid' => '999',
45     }
46   end
47
48   def self.columns
49     return @columns unless @columns.nil?
50     @columns = []
51     @attribute_info ||= {}
52     schema = $arvados_api_client.discovery[:schemas][self.to_s.to_sym]
53     return @columns if schema.nil?
54     schema[:properties].each do |k, coldef|
55       case k
56       when :etag, :kind
57         attr_reader k
58       else
59         if coldef[:type] == coldef[:type].downcase
60           # boolean, integer, etc.
61           @columns << column(k, coldef[:type].to_sym)
62         else
63           # Hash, Array
64           @columns << column(k, :text)
65           serialize k, coldef[:type].constantize
66         end
67         attr_accessible k
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     if self == ArvadosBase
89       # Determine type from uuid and defer to the appropriate subclass.
90       return resource_class_for_uuid(uuid).find(uuid, opts)
91     end
92
93     # Only do one lookup on the API side per {class, uuid, workbench
94     # request} unless {cache: false} is given via opts.
95     cache_key = "request_#{Thread.current.object_id}_#{self.to_s}_#{uuid}"
96     if opts[:cache] == false
97       Rails.cache.write cache_key, $arvados_api_client.api(self, '/' + uuid)
98     end
99     hash = Rails.cache.fetch cache_key do
100       $arvados_api_client.api(self, '/' + uuid)
101     end
102     new.private_reload(hash)
103   end
104
105   def self.order(*args)
106     ArvadosResourceList.new(self).order(*args)
107   end
108
109   def self.filter(*args)
110     ArvadosResourceList.new(self).filter(*args)
111   end
112
113   def self.where(*args)
114     ArvadosResourceList.new(self).where(*args)
115   end
116
117   def self.limit(*args)
118     ArvadosResourceList.new(self).limit(*args)
119   end
120
121   def self.eager(*args)
122     ArvadosResourceList.new(self).eager(*args)
123   end
124
125   def self.all(*args)
126     ArvadosResourceList.new(self).all(*args)
127   end
128
129   def save
130     obdata = {}
131     self.class.columns.each do |col|
132       obdata[col.name.to_sym] = self.send(col.name.to_sym)
133     end
134     obdata.delete :id
135     postdata = { self.class.to_s.underscore => obdata }
136     if etag
137       postdata['_method'] = 'PUT'
138       obdata.delete :uuid
139       resp = $arvados_api_client.api(self.class, '/' + uuid, postdata)
140     else
141       resp = $arvados_api_client.api(self.class, '', postdata)
142     end
143     return false if !resp[:etag] || !resp[:uuid]
144
145     # set read-only non-database attributes
146     @etag = resp[:etag]
147     @kind = resp[:kind]
148
149     # attributes can be modified during "save" -- we should update our copies
150     resp.keys.each do |attr|
151       if self.respond_to? "#{attr}=".to_sym
152         self.send(attr.to_s + '=', resp[attr.to_sym])
153       end
154     end
155
156     @new_record = false
157
158     self
159   end
160
161   def save!
162     self.save or raise Exception.new("Save failed")
163   end
164
165   def destroy
166     if etag || uuid
167       postdata = { '_method' => 'DELETE' }
168       resp = $arvados_api_client.api(self.class, '/' + uuid, postdata)
169       resp[:etag] && resp[:uuid] && resp
170     else
171       true
172     end
173   end
174
175   def links(*args)
176     o = {}
177     o.merge!(args.pop) if args[-1].is_a? Hash
178     o[:link_class] ||= args.shift
179     o[:name] ||= args.shift
180     o[:tail_uuid] = self.uuid
181     if all_links
182       return all_links.select do |m|
183         ok = true
184         o.each do |k,v|
185           if !v.nil?
186             test_v = m.send(k)
187             if (v.respond_to?(:uuid) ? v.uuid : v.to_s) != (test_v.respond_to?(:uuid) ? test_v.uuid : test_v.to_s)
188               ok = false
189             end
190           end
191         end
192         ok
193       end
194     end
195     @links = $arvados_api_client.api Link, '', { _method: 'GET', where: o, eager: true }
196     @links = $arvados_api_client.unpack_api_response(@links)
197   end
198
199   def all_links
200     return @all_links if @all_links
201     res = $arvados_api_client.api Link, '', {
202       _method: 'GET',
203       where: {
204         tail_kind: self.kind,
205         tail_uuid: self.uuid
206       },
207       eager: true
208     }
209     @all_links = $arvados_api_client.unpack_api_response(res)
210   end
211
212   def reload
213     private_reload(self.uuid)
214   end
215
216   def private_reload(uuid_or_hash)
217     raise "No such object" if !uuid_or_hash
218     if uuid_or_hash.is_a? Hash
219       hash = uuid_or_hash
220     else
221       hash = $arvados_api_client.api(self.class, '/' + uuid_or_hash)
222     end
223     hash.each do |k,v|
224       if self.respond_to?(k.to_s + '=')
225         self.send(k.to_s + '=', v)
226       else
227         # When ArvadosApiClient#schema starts telling us what to expect
228         # in API responses (not just the server side database
229         # columns), this sort of awfulness can be avoided:
230         self.instance_variable_set('@' + k.to_s, v)
231         if !self.respond_to? k
232           singleton = class << self; self end
233           singleton.send :define_method, k, lambda { instance_variable_get('@' + k.to_s) }
234         end
235       end
236     end
237     @all_links = nil
238     @new_record = false
239     self
240   end
241
242   def to_param
243     uuid
244   end
245
246   def dup
247     super.forget_uuid!
248   end
249
250   def attributes_for_display
251     self.attributes.reject { |k,v|
252       attribute_sortkey.has_key?(k) and !attribute_sortkey[k]
253     }.sort_by { |k,v|
254       attribute_sortkey[k] or k
255     }
256   end
257
258   def class_for_display
259     self.class.to_s
260   end
261
262   def self.creatable?
263     current_user
264   end
265
266   def editable?
267     (current_user and current_user.is_active and
268      (current_user.is_admin or
269       current_user.uuid == self.owner_uuid or
270       new_record?))
271   end
272
273   def attribute_editable?(attr)
274     if "created_at modified_at modified_by_user_uuid modified_by_client_uuid updated_at".index(attr.to_s)
275       false
276     elsif not (current_user.andand.is_active)
277       false
278     elsif "uuid owner_uuid".index(attr.to_s) or current_user.is_admin
279       current_user.is_admin
280     else
281       current_user.uuid == self.owner_uuid or
282         current_user.uuid == self.uuid or
283         new_record?
284     end
285   end
286
287   def self.resource_class_for_uuid(uuid, opts={})
288     if uuid.is_a? ArvadosBase
289       return uuid.class
290     end
291     unless uuid.is_a? String
292       return nil
293     end
294     if opts[:class].is_a? Class
295       return opts[:class]
296     end
297     if uuid.match /^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/
298       return Collection
299     end
300     resource_class = nil
301     uuid.match /^[0-9a-z]{5}-([0-9a-z]{5})-[0-9a-z]{15}$/ do |re|
302       resource_class ||= $arvados_api_client.
303         kind_class(self.uuid_infix_object_kind[re[1]])
304     end
305     if opts[:referring_object] and
306         opts[:referring_attr] and
307         opts[:referring_attr].match /_uuid$/
308       resource_class ||= $arvados_api_client.
309         kind_class(opts[:referring_object].
310                    attributes[opts[:referring_attr].
311                               sub(/_uuid$/, '_kind')])
312     end
313     resource_class
314   end
315
316   def friendly_link_name
317     (name if self.respond_to? :name) || uuid
318   end
319
320   def content_summary
321     self.class_for_display
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