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