Merged master
[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     # these attrs can be modified by "save" -- we should update our copies
139     %w(uuid owner_uuid created_at
140        modified_at modified_by_user_uuid modified_by_client_uuid
141       ).each do |attr|
142       if self.respond_to? "#{attr}=".to_sym
143         self.send(attr + '=', resp[attr.to_sym])
144       end
145     end
146
147     @new_record = false
148
149     self
150   end
151
152   def save!
153     self.save or raise Exception.new("Save failed")
154   end
155
156   def destroy
157     if etag || uuid
158       postdata = { '_method' => 'DELETE' }
159       resp = $arvados_api_client.api(self.class, '/' + uuid, postdata)
160       resp[:etag] && resp[:uuid] && resp
161     else
162       true
163     end
164   end
165
166   def links(*args)
167     o = {}
168     o.merge!(args.pop) if args[-1].is_a? Hash
169     o[:link_class] ||= args.shift
170     o[:name] ||= args.shift
171     o[:tail_uuid] = self.uuid
172     if all_links
173       return all_links.select do |m|
174         ok = true
175         o.each do |k,v|
176           if !v.nil?
177             test_v = m.send(k)
178             if (v.respond_to?(:uuid) ? v.uuid : v.to_s) != (test_v.respond_to?(:uuid) ? test_v.uuid : test_v.to_s)
179               ok = false
180             end
181           end
182         end
183         ok
184       end
185     end
186     @links = $arvados_api_client.api Link, '', { _method: 'GET', where: o, eager: true }
187     @links = $arvados_api_client.unpack_api_response(@links)
188   end
189
190   def all_links
191     return @all_links if @all_links
192     res = $arvados_api_client.api Link, '', {
193       _method: 'GET',
194       where: {
195         tail_kind: self.kind,
196         tail_uuid: self.uuid
197       },
198       eager: true
199     }
200     @all_links = $arvados_api_client.unpack_api_response(res)
201   end
202
203   def reload
204     private_reload(self.uuid)
205   end
206
207   def private_reload(uuid_or_hash)
208     raise "No such object" if !uuid_or_hash
209     if uuid_or_hash.is_a? Hash
210       hash = uuid_or_hash
211     else
212       hash = $arvados_api_client.api(self.class, '/' + uuid_or_hash)
213     end
214     hash.each do |k,v|
215       if self.respond_to?(k.to_s + '=')
216         self.send(k.to_s + '=', v)
217       else
218         # When ArvadosApiClient#schema starts telling us what to expect
219         # in API responses (not just the server side database
220         # columns), this sort of awfulness can be avoided:
221         self.instance_variable_set('@' + k.to_s, v)
222         if !self.respond_to? k
223           singleton = class << self; self end
224           singleton.send :define_method, k, lambda { instance_variable_get('@' + k.to_s) }
225         end
226       end
227     end
228     @all_links = nil
229     @new_record = false
230     self
231   end
232
233   def to_param
234     uuid
235   end
236
237   def dup
238     super.forget_uuid!
239   end
240
241   def attributes_for_display
242     self.attributes.reject { |k,v|
243       attribute_sortkey.has_key?(k) and !attribute_sortkey[k]
244     }.sort_by { |k,v|
245       attribute_sortkey[k] or k
246     }
247   end
248
249   def self.creatable?
250     current_user
251   end
252
253   def editable?
254     (current_user and current_user.is_active and
255      (current_user.is_admin or
256       current_user.uuid == self.owner_uuid))
257   end
258
259   def attribute_editable?(attr)
260     if "created_at modified_at modified_by_user_uuid modified_by_client_uuid updated_at".index(attr.to_s)
261       false
262     elsif not (current_user.andand.is_active)
263       false
264     elsif "uuid owner_uuid".index(attr.to_s) or current_user.is_admin
265       current_user.is_admin
266     else
267       current_user.uuid == self.owner_uuid or current_user.uuid == self.uuid
268     end
269   end
270
271   def self.resource_class_for_uuid(uuid, opts={})
272     if uuid.is_a? ArvadosBase
273       return uuid.class
274     end
275     unless uuid.is_a? String
276       return nil
277     end
278     if opts[:class].is_a? Class
279       return opts[:class]
280     end
281     if uuid.match /^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/
282       return Collection
283     end
284     resource_class = nil
285     uuid.match /^[0-9a-z]{5}-([0-9a-z]{5})-[0-9a-z]{15}$/ do |re|
286       resource_class ||= $arvados_api_client.
287         kind_class(self.uuid_infix_object_kind[re[1]])
288     end
289     if opts[:referring_object] and
290         opts[:referring_attr] and
291         opts[:referring_attr].match /_uuid$/
292       resource_class ||= $arvados_api_client.
293         kind_class(opts[:referring_object].
294                    attributes[opts[:referring_attr].
295                               sub(/_uuid$/, '_kind')])
296     end
297     resource_class
298   end
299
300   def friendly_link_name
301     (name if self.respond_to? :name) || uuid
302   end
303
304   def selection_label
305     friendly_link_name
306   end
307
308   protected
309
310   def forget_uuid!
311     self.uuid = nil
312     @etag = nil
313     self
314   end
315
316   def self.current_user
317     Thread.current[:user] ||= User.current if Thread.current[:arvados_api_token]
318     Thread.current[:user]
319   end
320   def current_user
321     self.class.current_user
322   end
323 end