9888: Move record-filtering code into model classes.
[arvados.git] / services / api / app / models / job.rb
1 class Job < ArvadosModel
2   include HasUuid
3   include KindAndEtag
4   include CommonApiTemplate
5   serialize :components, Hash
6   attr_protected :arvados_sdk_version, :docker_image_locator
7   serialize :script_parameters, Hash
8   serialize :runtime_constraints, Hash
9   serialize :tasks_summary, Hash
10   before_create :ensure_unique_submit_id
11   after_commit :trigger_crunch_dispatch_if_cancelled, :on => :update
12   before_validation :set_priority
13   before_validation :update_state_from_old_state_attrs
14   before_validation :update_script_parameters_digest
15   validate :ensure_script_version_is_commit
16   validate :find_docker_image_locator
17   validate :find_arvados_sdk_version
18   validate :validate_status
19   validate :validate_state_change
20   validate :ensure_no_collection_uuids_in_script_params
21   before_save :tag_version_in_internal_repository
22   before_save :update_timestamps_when_state_changes
23
24   has_many :commit_ancestors, :foreign_key => :descendant, :primary_key => :script_version
25   has_many(:nodes, foreign_key: :job_uuid, primary_key: :uuid)
26
27   class SubmitIdReused < StandardError
28   end
29
30   api_accessible :user, extend: :common do |t|
31     t.add :submit_id
32     t.add :priority
33     t.add :script
34     t.add :script_parameters
35     t.add :script_version
36     t.add :cancelled_at
37     t.add :cancelled_by_client_uuid
38     t.add :cancelled_by_user_uuid
39     t.add :started_at
40     t.add :finished_at
41     t.add :output
42     t.add :success
43     t.add :running
44     t.add :state
45     t.add :is_locked_by_uuid
46     t.add :log
47     t.add :runtime_constraints
48     t.add :tasks_summary
49     t.add :nondeterministic
50     t.add :repository
51     t.add :supplied_script_version
52     t.add :arvados_sdk_version
53     t.add :docker_image_locator
54     t.add :queue_position
55     t.add :node_uuids
56     t.add :description
57     t.add :components
58   end
59
60   # Supported states for a job
61   States = [
62             (Queued = 'Queued'),
63             (Running = 'Running'),
64             (Cancelled = 'Cancelled'),
65             (Failed = 'Failed'),
66             (Complete = 'Complete'),
67            ]
68
69   def assert_finished
70     update_attributes(finished_at: finished_at || db_current_time,
71                       success: success.nil? ? false : success,
72                       running: false)
73   end
74
75   def node_uuids
76     nodes.map(&:uuid)
77   end
78
79   def self.queue
80     self.where('state = ?', Queued).order('priority desc, created_at')
81   end
82
83   def queue_position
84     # We used to report this accurately, but the implementation made queue
85     # API requests O(n**2) for the size of the queue.  See #8800.
86     # We've soft-disabled it because it's not clear we even want this
87     # functionality: now that we have Node Manager with support for multiple
88     # node sizes, "queue position" tells you very little about when a job will
89     # run.
90     state == Queued ? 0 : nil
91   end
92
93   def self.running
94     self.where('running = ?', true).
95       order('priority desc, created_at')
96   end
97
98   def lock locked_by_uuid
99     with_lock do
100       unless self.state == Queued and self.is_locked_by_uuid.nil?
101         raise AlreadyLockedError
102       end
103       self.state = Running
104       self.is_locked_by_uuid = locked_by_uuid
105       self.save!
106     end
107   end
108
109   def update_script_parameters_digest
110     self.script_parameters_digest = self.class.sorted_hash_digest(script_parameters)
111   end
112
113   def self.searchable_columns operator
114     super - ["script_parameters_digest"]
115   end
116
117   def self.load_job_specific_filters attrs, orig_filters, read_users
118     # Convert Job-specific @filters entries into general SQL filters.
119     script_info = {"repository" => nil, "script" => nil}
120     git_filters = Hash.new do |hash, key|
121       hash[key] = {"max_version" => "HEAD", "exclude_versions" => []}
122     end
123     filters = []
124     orig_filters.each do |attr, operator, operand|
125       if (script_info.has_key? attr) and (operator == "=")
126         if script_info[attr].nil?
127           script_info[attr] = operand
128         elsif script_info[attr] != operand
129           raise ArgumentError.new("incompatible #{attr} filters")
130         end
131       end
132       case operator
133       when "in git"
134         git_filters[attr]["min_version"] = operand
135       when "not in git"
136         git_filters[attr]["exclude_versions"] += Array.wrap(operand)
137       when "in docker", "not in docker"
138         image_hashes = Array.wrap(operand).flat_map do |search_term|
139           image_search, image_tag = search_term.split(':', 2)
140           Collection.
141             find_all_for_docker_image(image_search, image_tag, read_users).
142             map(&:portable_data_hash)
143         end
144         filters << [attr, operator.sub(/ docker$/, ""), image_hashes]
145       else
146         filters << [attr, operator, operand]
147       end
148     end
149
150     # Build a real script_version filter from any "not? in git" filters.
151     git_filters.each_pair do |attr, filter|
152       case attr
153       when "script_version"
154         script_info.each_pair do |key, value|
155           if value.nil?
156             raise ArgumentError.new("script_version filter needs #{key} filter")
157           end
158         end
159         filter["repository"] = script_info["repository"]
160         if attrs[:script_version]
161           filter["max_version"] = attrs[:script_version]
162         else
163           # Using HEAD, set earlier by the hash default, is fine.
164         end
165       when "arvados_sdk_version"
166         filter["repository"] = "arvados"
167       else
168         raise ArgumentError.new("unknown attribute for git filter: #{attr}")
169       end
170       revisions = Commit.find_commit_range(filter["repository"],
171                                            filter["min_version"],
172                                            filter["max_version"],
173                                            filter["exclude_versions"])
174       if revisions.empty?
175         raise ArgumentError.
176           new("error searching #{filter['repository']} from " +
177               "'#{filter['min_version']}' to '#{filter['max_version']}', " +
178               "excluding #{filter['exclude_versions']}")
179       end
180       filters.append([attr, "in", revisions])
181     end
182
183     filters
184   end
185
186   def self.find_reusable attrs, params, filters, read_users
187     if filters.empty?  # Translate older creation parameters into filters.
188       filters =
189         [["repository", "=", attrs[:repository]],
190          ["script", "=", attrs[:script]],
191          ["script_version", "not in git", params[:exclude_script_versions]],
192         ].reject { |filter| filter.last.nil? or filter.last.empty? }
193       if !params[:minimum_script_version].blank?
194         filters << ["script_version", "in git",
195                      params[:minimum_script_version]]
196       else
197         filters += default_git_filters("script_version", attrs[:repository],
198                                        attrs[:script_version])
199       end
200       if image_search = attrs[:runtime_constraints].andand["docker_image"]
201         if image_tag = attrs[:runtime_constraints]["docker_image_tag"]
202           image_search += ":#{image_tag}"
203         end
204         image_locator = Collection.
205           for_latest_docker_image(image_search).andand.portable_data_hash
206       else
207         image_locator = nil
208       end
209       filters << ["docker_image_locator", "=", image_locator]
210       if sdk_version = attrs[:runtime_constraints].andand["arvados_sdk_version"]
211         filters += default_git_filters("arvados_sdk_version", "arvados", sdk_version)
212       end
213       filters = load_job_specific_filters(attrs, filters, read_users)
214     end
215
216     # Check specified filters for some reasonableness.
217     filter_names = filters.map { |f| f.first }.uniq
218     ["repository", "script"].each do |req_filter|
219       if not filter_names.include?(req_filter)
220         return send_error("#{req_filter} filter required")
221       end
222     end
223
224     # Search for a reusable Job, and return it if found.
225     candidates = Job.
226       readable_by(current_user).
227       where('state = ? or (owner_uuid = ? and state in (?))',
228             Job::Complete, current_user.uuid, [Job::Queued, Job::Running]).
229       where('script_parameters_digest = ?', Job.sorted_hash_digest(attrs[:script_parameters])).
230       where('nondeterministic is distinct from ?', true).
231       order('state desc, created_at') # prefer Running jobs over Queued
232     candidates = apply_filters candidates, filters
233     chosen = nil
234     incomplete_job = nil
235     candidates.each do |j|
236       if j.state != Job::Complete
237         # We'll use this if we don't find a job that has completed
238         incomplete_job ||= j
239         next
240       end
241
242       if chosen == false
243         # We have already decided not to reuse any completed job
244         next
245       elsif chosen
246         if chosen.output != j.output
247           # If two matching jobs produced different outputs, run a new
248           # job (or use one that's already running/queued) instead of
249           # choosing one arbitrarily.
250           chosen = false
251         end
252         # ...and that's the only thing we need to do once we've chosen
253         # a job to reuse.
254       elsif !Collection.readable_by(current_user).find_by_portable_data_hash(j.output)
255         # As soon as the output we will end up returning (if any) is
256         # decided, check whether it will be visible to the user; if
257         # not, any further investigation of reusable jobs is futile.
258         chosen = false
259       else
260         chosen = j
261       end
262     end
263     chosen || incomplete_job
264   end
265
266   def self.default_git_filters(attr_name, repo_name, refspec)
267     # Add a filter to @filters for `attr_name` = the latest commit available
268     # in `repo_name` at `refspec`.  No filter is added if refspec can't be
269     # resolved.
270     commits = Commit.find_commit_range(repo_name, nil, refspec, nil)
271     if commit_hash = commits.first
272       [[attr_name, "=", commit_hash]]
273     else
274       []
275     end
276   end
277
278   protected
279
280   def self.sorted_hash_digest h
281     Digest::MD5.hexdigest(Oj.dump(deep_sort_hash(h)))
282   end
283
284   def self.deep_sort_hash h
285     return h unless h.is_a? Hash
286     h.sort.collect do |k, v|
287       [k, deep_sort_hash(v)]
288     end.to_h
289   end
290
291   def foreign_key_attributes
292     super + %w(output log)
293   end
294
295   def skip_uuid_read_permission_check
296     super + %w(cancelled_by_client_uuid)
297   end
298
299   def skip_uuid_existence_check
300     super + %w(output log)
301   end
302
303   def set_priority
304     if self.priority.nil?
305       self.priority = 0
306     end
307     true
308   end
309
310   def ensure_script_version_is_commit
311     if state == Running
312       # Apparently client has already decided to go for it. This is
313       # needed to run a local job using a local working directory
314       # instead of a commit-ish.
315       return true
316     end
317     if new_record? or repository_changed? or script_version_changed?
318       sha1 = Commit.find_commit_range(repository,
319                                       nil, script_version, nil).first
320       if not sha1
321         errors.add :script_version, "#{script_version} does not resolve to a commit"
322         return false
323       end
324       if supplied_script_version.nil? or supplied_script_version.empty?
325         self.supplied_script_version = script_version
326       end
327       self.script_version = sha1
328     end
329     true
330   end
331
332   def tag_version_in_internal_repository
333     if state == Running
334       # No point now. See ensure_script_version_is_commit.
335       true
336     elsif errors.any?
337       # Won't be saved, and script_version might not even be valid.
338       true
339     elsif new_record? or repository_changed? or script_version_changed?
340       uuid_was = uuid
341       begin
342         assign_uuid
343         Commit.tag_in_internal_repository repository, script_version, uuid
344       rescue
345         uuid = uuid_was
346         raise
347       end
348     end
349   end
350
351   def ensure_unique_submit_id
352     if !submit_id.nil?
353       if Job.where('submit_id=?',self.submit_id).first
354         raise SubmitIdReused.new
355       end
356     end
357     true
358   end
359
360   def resolve_runtime_constraint(key, attr_sym)
361     if ((runtime_constraints.is_a? Hash) and
362         (search = runtime_constraints[key]))
363       ok, result = yield search
364     else
365       ok, result = true, nil
366     end
367     if ok
368       send("#{attr_sym}=".to_sym, result)
369     else
370       errors.add(attr_sym, result)
371     end
372     ok
373   end
374
375   def find_arvados_sdk_version
376     resolve_runtime_constraint("arvados_sdk_version",
377                                :arvados_sdk_version) do |git_search|
378       commits = Commit.find_commit_range("arvados",
379                                          nil, git_search, nil)
380       if commits.empty?
381         [false, "#{git_search} does not resolve to a commit"]
382       elsif not runtime_constraints["docker_image"]
383         [false, "cannot be specified without a Docker image constraint"]
384       else
385         [true, commits.first]
386       end
387     end
388   end
389
390   def find_docker_image_locator
391     runtime_constraints['docker_image'] =
392         Rails.configuration.default_docker_image_for_jobs if ((runtime_constraints.is_a? Hash) and
393                                                               (runtime_constraints['docker_image']).nil? and
394                                                               Rails.configuration.default_docker_image_for_jobs)
395     resolve_runtime_constraint("docker_image",
396                                :docker_image_locator) do |image_search|
397       image_tag = runtime_constraints['docker_image_tag']
398       if coll = Collection.for_latest_docker_image(image_search, image_tag)
399         [true, coll.portable_data_hash]
400       else
401         [false, "not found for #{image_search}"]
402       end
403     end
404   end
405
406   def permission_to_update
407     if is_locked_by_uuid_was and !(current_user and
408                                    (current_user.uuid == is_locked_by_uuid_was or
409                                     current_user.uuid == system_user.uuid))
410       if script_changed? or
411           script_parameters_changed? or
412           script_version_changed? or
413           (!cancelled_at_was.nil? and
414            (cancelled_by_client_uuid_changed? or
415             cancelled_by_user_uuid_changed? or
416             cancelled_at_changed?)) or
417           started_at_changed? or
418           finished_at_changed? or
419           running_changed? or
420           success_changed? or
421           output_changed? or
422           log_changed? or
423           tasks_summary_changed? or
424           state_changed? or
425           components_changed?
426         logger.warn "User #{current_user.uuid if current_user} tried to change protected job attributes on locked #{self.class.to_s} #{uuid_was}"
427         return false
428       end
429     end
430     if !is_locked_by_uuid_changed?
431       super
432     else
433       if !current_user
434         logger.warn "Anonymous user tried to change lock on #{self.class.to_s} #{uuid_was}"
435         false
436       elsif is_locked_by_uuid_was and is_locked_by_uuid_was != current_user.uuid
437         logger.warn "User #{current_user.uuid} tried to steal lock on #{self.class.to_s} #{uuid_was} from #{is_locked_by_uuid_was}"
438         false
439       elsif !is_locked_by_uuid.nil? and is_locked_by_uuid != current_user.uuid
440         logger.warn "User #{current_user.uuid} tried to lock #{self.class.to_s} #{uuid_was} with uuid #{is_locked_by_uuid}"
441         false
442       else
443         super
444       end
445     end
446   end
447
448   def update_modified_by_fields
449     if self.cancelled_at_changed?
450       # Ensure cancelled_at cannot be set to arbitrary non-now times,
451       # or changed once it is set.
452       if self.cancelled_at and not self.cancelled_at_was
453         self.cancelled_at = db_current_time
454         self.cancelled_by_user_uuid = current_user.uuid
455         self.cancelled_by_client_uuid = current_api_client.andand.uuid
456         @need_crunch_dispatch_trigger = true
457       else
458         self.cancelled_at = self.cancelled_at_was
459         self.cancelled_by_user_uuid = self.cancelled_by_user_uuid_was
460         self.cancelled_by_client_uuid = self.cancelled_by_client_uuid_was
461       end
462     end
463     super
464   end
465
466   def trigger_crunch_dispatch_if_cancelled
467     if @need_crunch_dispatch_trigger
468       File.open(Rails.configuration.crunch_refresh_trigger, 'wb') do
469         # That's all, just create/touch a file for crunch-job to see.
470       end
471     end
472   end
473
474   def update_timestamps_when_state_changes
475     return if not (state_changed? or new_record?)
476
477     case state
478     when Running
479       self.started_at ||= db_current_time
480     when Failed, Complete
481       self.finished_at ||= db_current_time
482     when Cancelled
483       self.cancelled_at ||= db_current_time
484     end
485
486     # TODO: Remove the following case block when old "success" and
487     # "running" attrs go away. Until then, this ensures we still
488     # expose correct success/running flags to older clients, even if
489     # some new clients are writing only the new state attribute.
490     case state
491     when Queued
492       self.running = false
493       self.success = nil
494     when Running
495       self.running = true
496       self.success = nil
497     when Cancelled, Failed
498       self.running = false
499       self.success = false
500     when Complete
501       self.running = false
502       self.success = true
503     end
504     self.running ||= false # Default to false instead of nil.
505
506     @need_crunch_dispatch_trigger = true
507
508     true
509   end
510
511   def update_state_from_old_state_attrs
512     # If a client has touched the legacy state attrs, update the
513     # "state" attr to agree with the updated values of the legacy
514     # attrs.
515     #
516     # TODO: Remove this method when old "success" and "running" attrs
517     # go away.
518     if cancelled_at_changed? or
519         success_changed? or
520         running_changed? or
521         state.nil?
522       if cancelled_at
523         self.state = Cancelled
524       elsif success == false
525         self.state = Failed
526       elsif success == true
527         self.state = Complete
528       elsif running == true
529         self.state = Running
530       else
531         self.state = Queued
532       end
533     end
534     true
535   end
536
537   def validate_status
538     if self.state.in?(States)
539       true
540     else
541       errors.add :state, "#{state.inspect} must be one of: #{States.inspect}"
542       false
543     end
544   end
545
546   def validate_state_change
547     ok = true
548     if self.state_changed?
549       ok = case self.state_was
550            when nil
551              # state isn't set yet
552              true
553            when Queued
554              # Permit going from queued to any state
555              true
556            when Running
557              # From running, may only transition to a finished state
558              [Complete, Failed, Cancelled].include? self.state
559            when Complete, Failed, Cancelled
560              # Once in a finished state, don't permit any more state changes
561              false
562            else
563              # Any other state transition is also invalid
564              false
565            end
566       if not ok
567         errors.add :state, "invalid change from #{self.state_was} to #{self.state}"
568       end
569     end
570     ok
571   end
572
573   def ensure_no_collection_uuids_in_script_params
574     # recursive_hash_search searches recursively through hashes and
575     # arrays in 'thing' for string fields matching regular expression
576     # 'pattern'.  Returns true if pattern is found, false otherwise.
577     def recursive_hash_search thing, pattern
578       if thing.is_a? Hash
579         thing.each do |k, v|
580           return true if recursive_hash_search v, pattern
581         end
582       elsif thing.is_a? Array
583         thing.each do |k|
584           return true if recursive_hash_search k, pattern
585         end
586       elsif thing.is_a? String
587         return true if thing.match pattern
588       end
589       false
590     end
591
592     # Fail validation if any script_parameters field includes a string containing a
593     # collection uuid pattern.
594     if self.script_parameters_changed?
595       if recursive_hash_search(self.script_parameters, Collection.uuid_regex)
596         self.errors.add :script_parameters, "must use portable_data_hash instead of collection uuid"
597         return false
598       end
599     end
600     true
601   end
602 end