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