Include first link of a given type even on reruns of the setup method.
[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.where(*args)
101     ArvadosResourceList.new(self).where(*args)
102   end
103
104   def self.limit(*args)
105     ArvadosResourceList.new(self).limit(*args)
106   end
107
108   def self.eager(*args)
109     ArvadosResourceList.new(self).eager(*args)
110   end
111
112   def self.all(*args)
113     ArvadosResourceList.new(self).all(*args)
114   end
115
116   def save
117     obdata = {}
118     self.class.columns.each do |col|
119       obdata[col.name.to_sym] = self.send(col.name.to_sym)
120     end
121     obdata.delete :id
122     postdata = { self.class.to_s.underscore => obdata }
123     if etag
124       postdata['_method'] = 'PUT'
125       obdata.delete :uuid
126       resp = $arvados_api_client.api(self.class, '/' + uuid, postdata)
127     else
128       resp = $arvados_api_client.api(self.class, '', postdata)
129     end
130     return false if !resp[:etag] || !resp[:uuid]
131
132     # set read-only non-database attributes
133     @etag = resp[:etag]
134     @kind = resp[:kind]
135
136     # these attrs can be modified by "save" -- we should update our copies
137     %w(uuid owner_uuid created_at
138        modified_at modified_by_user_uuid modified_by_client_uuid
139       ).each do |attr|
140       if self.respond_to? "#{attr}=".to_sym
141         self.send(attr + '=', 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[:head_kind] ||= args.shift
170     o[:tail_kind] = self.kind
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