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