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