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