10231: validate_runtime_constraints should occur before set_container filter.
[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 foreign_key_attributes
286     super + %w(output log)
287   end
288
289   def skip_uuid_read_permission_check
290     super + %w(cancelled_by_client_uuid)
291   end
292
293   def skip_uuid_existence_check
294     super + %w(output log)
295   end
296
297   def set_priority
298     if self.priority.nil?
299       self.priority = 0
300     end
301     true
302   end
303
304   def ensure_script_version_is_commit
305     if state == Running
306       # Apparently client has already decided to go for it. This is
307       # needed to run a local job using a local working directory
308       # instead of a commit-ish.
309       return true
310     end
311     if new_record? or repository_changed? or script_version_changed?
312       sha1 = Commit.find_commit_range(repository,
313                                       nil, script_version, nil).first
314       if not sha1
315         errors.add :script_version, "#{script_version} does not resolve to a commit"
316         return false
317       end
318       if supplied_script_version.nil? or supplied_script_version.empty?
319         self.supplied_script_version = script_version
320       end
321       self.script_version = sha1
322     end
323     true
324   end
325
326   def tag_version_in_internal_repository
327     if state == Running
328       # No point now. See ensure_script_version_is_commit.
329       true
330     elsif errors.any?
331       # Won't be saved, and script_version might not even be valid.
332       true
333     elsif new_record? or repository_changed? or script_version_changed?
334       uuid_was = uuid
335       begin
336         assign_uuid
337         Commit.tag_in_internal_repository repository, script_version, uuid
338       rescue
339         uuid = uuid_was
340         raise
341       end
342     end
343   end
344
345   def ensure_unique_submit_id
346     if !submit_id.nil?
347       if Job.where('submit_id=?',self.submit_id).first
348         raise SubmitIdReused.new
349       end
350     end
351     true
352   end
353
354   def resolve_runtime_constraint(key, attr_sym)
355     if ((runtime_constraints.is_a? Hash) and
356         (search = runtime_constraints[key]))
357       ok, result = yield search
358     else
359       ok, result = true, nil
360     end
361     if ok
362       send("#{attr_sym}=".to_sym, result)
363     else
364       errors.add(attr_sym, result)
365     end
366     ok
367   end
368
369   def find_arvados_sdk_version
370     resolve_runtime_constraint("arvados_sdk_version",
371                                :arvados_sdk_version) do |git_search|
372       commits = Commit.find_commit_range("arvados",
373                                          nil, git_search, nil)
374       if commits.empty?
375         [false, "#{git_search} does not resolve to a commit"]
376       elsif not runtime_constraints["docker_image"]
377         [false, "cannot be specified without a Docker image constraint"]
378       else
379         [true, commits.first]
380       end
381     end
382   end
383
384   def find_docker_image_locator
385     runtime_constraints['docker_image'] =
386         Rails.configuration.default_docker_image_for_jobs if ((runtime_constraints.is_a? Hash) and
387                                                               (runtime_constraints['docker_image']).nil? and
388                                                               Rails.configuration.default_docker_image_for_jobs)
389     resolve_runtime_constraint("docker_image",
390                                :docker_image_locator) do |image_search|
391       image_tag = runtime_constraints['docker_image_tag']
392       if coll = Collection.for_latest_docker_image(image_search, image_tag)
393         [true, coll.portable_data_hash]
394       else
395         [false, "not found for #{image_search}"]
396       end
397     end
398   end
399
400   def permission_to_update
401     if is_locked_by_uuid_was and !(current_user and
402                                    (current_user.uuid == is_locked_by_uuid_was or
403                                     current_user.uuid == system_user.uuid))
404       if script_changed? or
405           script_parameters_changed? or
406           script_version_changed? or
407           (!cancelled_at_was.nil? and
408            (cancelled_by_client_uuid_changed? or
409             cancelled_by_user_uuid_changed? or
410             cancelled_at_changed?)) or
411           started_at_changed? or
412           finished_at_changed? or
413           running_changed? or
414           success_changed? or
415           output_changed? or
416           log_changed? or
417           tasks_summary_changed? or
418           state_changed? or
419           components_changed?
420         logger.warn "User #{current_user.uuid if current_user} tried to change protected job attributes on locked #{self.class.to_s} #{uuid_was}"
421         return false
422       end
423     end
424     if !is_locked_by_uuid_changed?
425       super
426     else
427       if !current_user
428         logger.warn "Anonymous user tried to change lock on #{self.class.to_s} #{uuid_was}"
429         false
430       elsif is_locked_by_uuid_was and is_locked_by_uuid_was != current_user.uuid
431         logger.warn "User #{current_user.uuid} tried to steal lock on #{self.class.to_s} #{uuid_was} from #{is_locked_by_uuid_was}"
432         false
433       elsif !is_locked_by_uuid.nil? and is_locked_by_uuid != current_user.uuid
434         logger.warn "User #{current_user.uuid} tried to lock #{self.class.to_s} #{uuid_was} with uuid #{is_locked_by_uuid}"
435         false
436       else
437         super
438       end
439     end
440   end
441
442   def update_modified_by_fields
443     if self.cancelled_at_changed?
444       # Ensure cancelled_at cannot be set to arbitrary non-now times,
445       # or changed once it is set.
446       if self.cancelled_at and not self.cancelled_at_was
447         self.cancelled_at = db_current_time
448         self.cancelled_by_user_uuid = current_user.uuid
449         self.cancelled_by_client_uuid = current_api_client.andand.uuid
450         @need_crunch_dispatch_trigger = true
451       else
452         self.cancelled_at = self.cancelled_at_was
453         self.cancelled_by_user_uuid = self.cancelled_by_user_uuid_was
454         self.cancelled_by_client_uuid = self.cancelled_by_client_uuid_was
455       end
456     end
457     super
458   end
459
460   def trigger_crunch_dispatch_if_cancelled
461     if @need_crunch_dispatch_trigger
462       File.open(Rails.configuration.crunch_refresh_trigger, 'wb') do
463         # That's all, just create/touch a file for crunch-job to see.
464       end
465     end
466   end
467
468   def update_timestamps_when_state_changes
469     return if not (state_changed? or new_record?)
470
471     case state
472     when Running
473       self.started_at ||= db_current_time
474     when Failed, Complete
475       self.finished_at ||= db_current_time
476     when Cancelled
477       self.cancelled_at ||= db_current_time
478     end
479
480     # TODO: Remove the following case block when old "success" and
481     # "running" attrs go away. Until then, this ensures we still
482     # expose correct success/running flags to older clients, even if
483     # some new clients are writing only the new state attribute.
484     case state
485     when Queued
486       self.running = false
487       self.success = nil
488     when Running
489       self.running = true
490       self.success = nil
491     when Cancelled, Failed
492       self.running = false
493       self.success = false
494     when Complete
495       self.running = false
496       self.success = true
497     end
498     self.running ||= false # Default to false instead of nil.
499
500     @need_crunch_dispatch_trigger = true
501
502     true
503   end
504
505   def update_state_from_old_state_attrs
506     # If a client has touched the legacy state attrs, update the
507     # "state" attr to agree with the updated values of the legacy
508     # attrs.
509     #
510     # TODO: Remove this method when old "success" and "running" attrs
511     # go away.
512     if cancelled_at_changed? or
513         success_changed? or
514         running_changed? or
515         state.nil?
516       if cancelled_at
517         self.state = Cancelled
518       elsif success == false
519         self.state = Failed
520       elsif success == true
521         self.state = Complete
522       elsif running == true
523         self.state = Running
524       else
525         self.state = Queued
526       end
527     end
528     true
529   end
530
531   def validate_status
532     if self.state.in?(States)
533       true
534     else
535       errors.add :state, "#{state.inspect} must be one of: #{States.inspect}"
536       false
537     end
538   end
539
540   def validate_state_change
541     ok = true
542     if self.state_changed?
543       ok = case self.state_was
544            when nil
545              # state isn't set yet
546              true
547            when Queued
548              # Permit going from queued to any state
549              true
550            when Running
551              # From running, may only transition to a finished state
552              [Complete, Failed, Cancelled].include? self.state
553            when Complete, Failed, Cancelled
554              # Once in a finished state, don't permit any more state changes
555              false
556            else
557              # Any other state transition is also invalid
558              false
559            end
560       if not ok
561         errors.add :state, "invalid change from #{self.state_was} to #{self.state}"
562       end
563     end
564     ok
565   end
566
567   def ensure_no_collection_uuids_in_script_params
568     # recursive_hash_search searches recursively through hashes and
569     # arrays in 'thing' for string fields matching regular expression
570     # 'pattern'.  Returns true if pattern is found, false otherwise.
571     def recursive_hash_search thing, pattern
572       if thing.is_a? Hash
573         thing.each do |k, v|
574           return true if recursive_hash_search v, pattern
575         end
576       elsif thing.is_a? Array
577         thing.each do |k|
578           return true if recursive_hash_search k, pattern
579         end
580       elsif thing.is_a? String
581         return true if thing.match pattern
582       end
583       false
584     end
585
586     # Fail validation if any script_parameters field includes a string containing a
587     # collection uuid pattern.
588     if self.script_parameters_changed?
589       if recursive_hash_search(self.script_parameters, Collection.uuid_regex)
590         self.errors.add :script_parameters, "must use portable_data_hash instead of collection uuid"
591         return false
592       end
593     end
594     true
595   end
596 end