2872: Fix bookmark bar causing spurious window width.
[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.find?(*args)
113     find(*args) rescue nil
114   end
115
116   def self.order(*args)
117     ArvadosResourceList.new(self).order(*args)
118   end
119
120   def self.filter(*args)
121     ArvadosResourceList.new(self).filter(*args)
122   end
123
124   def self.where(*args)
125     ArvadosResourceList.new(self).where(*args)
126   end
127
128   def self.limit(*args)
129     ArvadosResourceList.new(self).limit(*args)
130   end
131
132   def self.eager(*args)
133     ArvadosResourceList.new(self).eager(*args)
134   end
135
136   def self.all(*args)
137     ArvadosResourceList.new(self).all(*args)
138   end
139
140   def self.permit_attribute_params raw_params
141     # strong_parameters does not provide security in Workbench: anyone
142     # who can get this far can just as well do a call directly to our
143     # database (Arvados) with the same credentials we use.
144     #
145     # The following permit! is necessary even with
146     # "ActionController::Parameters.permit_all_parameters = true",
147     # because permit_all does not permit nested attributes.
148     ActionController::Parameters.new(raw_params).permit!
149   end
150
151   def self.create raw_params={}
152     super(permit_attribute_params(raw_params))
153   end
154
155   def update_attributes raw_params={}
156     super(self.class.permit_attribute_params(raw_params))
157   end
158
159   def save
160     obdata = {}
161     self.class.columns.each do |col|
162       obdata[col.name.to_sym] = self.send(col.name.to_sym)
163     end
164     obdata.delete :id
165     postdata = { self.class.to_s.underscore => obdata }
166     if etag
167       postdata['_method'] = 'PUT'
168       obdata.delete :uuid
169       resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
170     else
171       resp = arvados_api_client.api(self.class, '', postdata)
172     end
173     return false if !resp[:etag] || !resp[:uuid]
174
175     # set read-only non-database attributes
176     @etag = resp[:etag]
177     @kind = resp[:kind]
178
179     # attributes can be modified during "save" -- we should update our copies
180     resp.keys.each do |attr|
181       if self.respond_to? "#{attr}=".to_sym
182         self.send(attr.to_s + '=', resp[attr.to_sym])
183       end
184     end
185
186     @new_record = false
187
188     self
189   end
190
191   def save!
192     self.save or raise Exception.new("Save failed")
193   end
194
195   def destroy
196     if etag || uuid
197       postdata = { '_method' => 'DELETE' }
198       resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
199       resp[:etag] && resp[:uuid] && resp
200     else
201       true
202     end
203   end
204
205   def links(*args)
206     o = {}
207     o.merge!(args.pop) if args[-1].is_a? Hash
208     o[:link_class] ||= args.shift
209     o[:name] ||= args.shift
210     o[:tail_uuid] = self.uuid
211     if all_links
212       return all_links.select do |m|
213         ok = true
214         o.each do |k,v|
215           if !v.nil?
216             test_v = m.send(k)
217             if (v.respond_to?(:uuid) ? v.uuid : v.to_s) != (test_v.respond_to?(:uuid) ? test_v.uuid : test_v.to_s)
218               ok = false
219             end
220           end
221         end
222         ok
223       end
224     end
225     @links = arvados_api_client.api Link, '', { _method: 'GET', where: o, eager: true }
226     @links = arvados_api_client.unpack_api_response(@links)
227   end
228
229   def all_links
230     return @all_links if @all_links
231     res = arvados_api_client.api Link, '', {
232       _method: 'GET',
233       where: {
234         tail_kind: self.kind,
235         tail_uuid: self.uuid
236       },
237       eager: true
238     }
239     @all_links = arvados_api_client.unpack_api_response(res)
240   end
241
242   def reload
243     private_reload(self.uuid)
244   end
245
246   def private_reload(uuid_or_hash)
247     raise "No such object" if !uuid_or_hash
248     if uuid_or_hash.is_a? Hash
249       hash = uuid_or_hash
250     else
251       hash = arvados_api_client.api(self.class, '/' + uuid_or_hash)
252     end
253     hash.each do |k,v|
254       if self.respond_to?(k.to_s + '=')
255         self.send(k.to_s + '=', v)
256       else
257         # When ArvadosApiClient#schema starts telling us what to expect
258         # in API responses (not just the server side database
259         # columns), this sort of awfulness can be avoided:
260         self.instance_variable_set('@' + k.to_s, v)
261         if !self.respond_to? k
262           singleton = class << self; self end
263           singleton.send :define_method, k, lambda { instance_variable_get('@' + k.to_s) }
264         end
265       end
266     end
267     @all_links = nil
268     @new_record = false
269     self
270   end
271
272   def to_param
273     uuid
274   end
275
276   def initialize_copy orig
277     super
278     forget_uuid!
279   end
280
281   def attributes_for_display
282     self.attributes.reject { |k,v|
283       attribute_sortkey.has_key?(k) and !attribute_sortkey[k]
284     }.sort_by { |k,v|
285       attribute_sortkey[k] or k
286     }
287   end
288
289   def class_for_display
290     self.class.to_s.underscore.humanize
291   end
292
293   def self.creatable?
294     current_user
295   end
296
297   def self.goes_in_projects?
298     false
299   end
300
301   def editable?
302     (current_user and current_user.is_active and
303      (current_user.is_admin or
304       current_user.uuid == self.owner_uuid or
305       new_record? or
306       (writable_by.include? current_user.uuid rescue false)))
307   end
308
309   def attribute_editable?(attr, ever=nil)
310     if "created_at modified_at modified_by_user_uuid modified_by_client_uuid updated_at".index(attr.to_s)
311       false
312     elsif not (current_user.andand.is_active)
313       false
314     elsif attr == 'uuid'
315       current_user.is_admin
316     elsif ever
317       true
318     else
319       editable?
320     end
321   end
322
323   def self.resource_class_for_uuid(uuid, opts={})
324     if uuid.is_a? ArvadosBase
325       return uuid.class
326     end
327     unless uuid.is_a? String
328       return nil
329     end
330     if opts[:class].is_a? Class
331       return opts[:class]
332     end
333     if uuid.match /^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/
334       return Collection
335     end
336     resource_class = nil
337     uuid.match /^[0-9a-z]{5}-([0-9a-z]{5})-[0-9a-z]{15}$/ do |re|
338       resource_class ||= arvados_api_client.
339         kind_class(self.uuid_infix_object_kind[re[1]])
340     end
341     if opts[:referring_object] and
342         opts[:referring_attr] and
343         opts[:referring_attr].match /_uuid$/
344       resource_class ||= arvados_api_client.
345         kind_class(opts[:referring_object].
346                    attributes[opts[:referring_attr].
347                               sub(/_uuid$/, '_kind')])
348     end
349     resource_class
350   end
351
352   def resource_param_name
353     self.class.to_s.underscore
354   end
355
356   def friendly_link_name
357     (name if self.respond_to? :name) || default_name
358   end
359
360   def content_summary
361     self.class_for_display
362   end
363
364   def selection_label
365     friendly_link_name
366   end
367
368   def self.default_name
369     self.to_s.underscore.humanize
370   end
371
372   def controller
373     (self.class.to_s.pluralize + 'Controller').constantize
374   end
375
376   def controller_name
377     self.class.to_s.tableize
378   end
379
380   # Placeholder for name when name is missing or empty
381   def default_name
382     if self.respond_to? :name
383       "New #{class_for_display.downcase}"
384     else
385       uuid
386     end
387   end
388
389   def owner
390     ArvadosBase.find(owner_uuid) rescue nil
391   end
392
393   protected
394
395   def forget_uuid!
396     self.uuid = nil
397     @etag = nil
398     self
399   end
400
401   def self.current_user
402     Thread.current[:user] ||= User.current if Thread.current[:arvados_api_token]
403     Thread.current[:user]
404   end
405   def current_user
406     self.class.current_user
407   end
408 end