3 class Job < ArvadosModel
6 include CommonApiTemplate
7 extend CurrentApiClient
8 serialize :components, Hash
9 attr_protected :arvados_sdk_version, :docker_image_locator
10 serialize :script_parameters, Hash
11 serialize :runtime_constraints, Hash
12 serialize :tasks_summary, Hash
13 before_create :ensure_unique_submit_id
14 after_commit :trigger_crunch_dispatch_if_cancelled, :on => :update
15 before_validation :set_priority
16 before_validation :update_state_from_old_state_attrs
17 before_validation :update_script_parameters_digest
18 validate :ensure_script_version_is_commit
19 validate :find_docker_image_locator
20 validate :find_arvados_sdk_version
21 validate :validate_status
22 validate :validate_state_change
23 validate :ensure_no_collection_uuids_in_script_params
24 before_save :tag_version_in_internal_repository
25 before_save :update_timestamps_when_state_changes
27 has_many :commit_ancestors, :foreign_key => :descendant, :primary_key => :script_version
28 has_many(:nodes, foreign_key: :job_uuid, primary_key: :uuid)
30 class SubmitIdReused < StandardError
33 api_accessible :user, extend: :common do |t|
37 t.add :script_parameters
40 t.add :cancelled_by_client_uuid
41 t.add :cancelled_by_user_uuid
48 t.add :is_locked_by_uuid
50 t.add :runtime_constraints
52 t.add :nondeterministic
54 t.add :supplied_script_version
55 t.add :arvados_sdk_version
56 t.add :docker_image_locator
63 # Supported states for a job
66 (Running = 'Running'),
67 (Cancelled = 'Cancelled'),
69 (Complete = 'Complete'),
73 @need_crunch_dispatch_trigger = false
77 update_attributes(finished_at: finished_at || db_current_time,
78 success: success.nil? ? false : success,
87 self.where('state = ?', Queued).order('priority desc, created_at')
91 # We used to report this accurately, but the implementation made queue
92 # API requests O(n**2) for the size of the queue. See #8800.
93 # We've soft-disabled it because it's not clear we even want this
94 # functionality: now that we have Node Manager with support for multiple
95 # node sizes, "queue position" tells you very little about when a job will
97 state == Queued ? 0 : nil
101 self.where('running = ?', true).
102 order('priority desc, created_at')
105 def lock locked_by_uuid
107 unless self.state == Queued and self.is_locked_by_uuid.nil?
108 raise AlreadyLockedError
111 self.is_locked_by_uuid = locked_by_uuid
116 def update_script_parameters_digest
117 self.script_parameters_digest = self.class.sorted_hash_digest(script_parameters)
120 def self.searchable_columns operator
121 super - ["script_parameters_digest"]
124 def self.full_text_searchable_columns
125 super - ["script_parameters_digest"]
128 def self.load_job_specific_filters attrs, orig_filters, read_users
129 # Convert Job-specific @filters entries into general SQL filters.
130 script_info = {"repository" => nil, "script" => nil}
131 git_filters = Hash.new do |hash, key|
132 hash[key] = {"max_version" => "HEAD", "exclude_versions" => []}
135 orig_filters.each do |attr, operator, operand|
136 if (script_info.has_key? attr) and (operator == "=")
137 if script_info[attr].nil?
138 script_info[attr] = operand
139 elsif script_info[attr] != operand
140 raise ArgumentError.new("incompatible #{attr} filters")
145 git_filters[attr]["min_version"] = operand
147 git_filters[attr]["exclude_versions"] += Array.wrap(operand)
148 when "in docker", "not in docker"
149 image_hashes = Array.wrap(operand).flat_map do |search_term|
150 image_search, image_tag = search_term.split(':', 2)
152 find_all_for_docker_image(image_search, image_tag, read_users, filter_compatible_format: false).
153 map(&:portable_data_hash)
155 filters << [attr, operator.sub(/ docker$/, ""), image_hashes]
157 filters << [attr, operator, operand]
161 # Build a real script_version filter from any "not? in git" filters.
162 git_filters.each_pair do |attr, filter|
164 when "script_version"
165 script_info.each_pair do |key, value|
167 raise ArgumentError.new("script_version filter needs #{key} filter")
170 filter["repository"] = script_info["repository"]
171 if attrs[:script_version]
172 filter["max_version"] = attrs[:script_version]
174 # Using HEAD, set earlier by the hash default, is fine.
176 when "arvados_sdk_version"
177 filter["repository"] = "arvados"
179 raise ArgumentError.new("unknown attribute for git filter: #{attr}")
181 revisions = Commit.find_commit_range(filter["repository"],
182 filter["min_version"],
183 filter["max_version"],
184 filter["exclude_versions"])
187 new("error searching #{filter['repository']} from " +
188 "'#{filter['min_version']}' to '#{filter['max_version']}', " +
189 "excluding #{filter['exclude_versions']}")
191 filters.append([attr, "in", revisions])
197 def self.find_reusable attrs, params, filters, read_users
198 if filters.empty? # Translate older creation parameters into filters.
200 [["repository", "=", attrs[:repository]],
201 ["script", "=", attrs[:script]],
202 ["script_version", "not in git", params[:exclude_script_versions]],
203 ].reject { |filter| filter.last.nil? or filter.last.empty? }
204 if !params[:minimum_script_version].blank?
205 filters << ["script_version", "in git",
206 params[:minimum_script_version]]
208 filters += default_git_filters("script_version", attrs[:repository],
209 attrs[:script_version])
211 if image_search = attrs[:runtime_constraints].andand["docker_image"]
212 if image_tag = attrs[:runtime_constraints]["docker_image_tag"]
213 image_search += ":#{image_tag}"
215 image_locator = Collection.
216 for_latest_docker_image(image_search).andand.portable_data_hash
220 filters << ["docker_image_locator", "=", image_locator]
221 if sdk_version = attrs[:runtime_constraints].andand["arvados_sdk_version"]
222 filters += default_git_filters("arvados_sdk_version", "arvados", sdk_version)
224 filters = load_job_specific_filters(attrs, filters, read_users)
227 # Check specified filters for some reasonableness.
228 filter_names = filters.map { |f| f.first }.uniq
229 ["repository", "script"].each do |req_filter|
230 if not filter_names.include?(req_filter)
231 return send_error("#{req_filter} filter required")
235 # Search for a reusable Job, and return it if found.
237 readable_by(current_user).
238 where('state = ? or (owner_uuid = ? and state in (?))',
239 Job::Complete, current_user.uuid, [Job::Queued, Job::Running]).
240 where('script_parameters_digest = ?', Job.sorted_hash_digest(attrs[:script_parameters])).
241 where('nondeterministic is distinct from ?', true).
242 order('state desc, created_at') # prefer Running jobs over Queued
243 candidates = apply_filters candidates, filters
246 candidates.each do |j|
247 if j.state != Job::Complete
248 # We'll use this if we don't find a job that has completed
254 # We have already decided not to reuse any completed job
257 if chosen.output != j.output
258 # If two matching jobs produced different outputs, run a new
259 # job (or use one that's already running/queued) instead of
260 # choosing one arbitrarily.
263 # ...and that's the only thing we need to do once we've chosen
265 elsif !Collection.readable_by(current_user).find_by_portable_data_hash(j.output)
266 # As soon as the output we will end up returning (if any) is
267 # decided, check whether it will be visible to the user; if
268 # not, any further investigation of reusable jobs is futile.
274 chosen || incomplete_job
277 def self.default_git_filters(attr_name, repo_name, refspec)
278 # Add a filter to @filters for `attr_name` = the latest commit available
279 # in `repo_name` at `refspec`. No filter is added if refspec can't be
281 commits = Commit.find_commit_range(repo_name, nil, refspec, nil)
282 if commit_hash = commits.first
283 [[attr_name, "=", commit_hash]]
289 def cancel(cascade: false, need_transaction: true)
291 ActiveRecord::Base.transaction do
292 cancel(cascade: cascade, need_transaction: false)
297 if self.state.in?([Queued, Running])
298 self.state = Cancelled
300 elsif self.state != Cancelled
301 raise InvalidStateTransitionError
306 # cancel all children; they could be jobs or pipeline instances
307 children = self.components.andand.collect{|_, u| u}.compact
309 return if children.empty?
311 # cancel any child jobs
312 Job.where(uuid: children, state: [Queued, Running]).each do |job|
313 job.cancel(cascade: cascade, need_transaction: false)
316 # cancel any child pipelines
317 PipelineInstance.where(uuid: children, state: [PipelineInstance::RunningOnServer, PipelineInstance::RunningOnClient]).each do |pi|
318 pi.cancel(cascade: cascade, need_transaction: false)
324 def self.sorted_hash_digest h
325 Digest::MD5.hexdigest(Oj.dump(deep_sort_hash(h)))
328 def foreign_key_attributes
329 super + %w(output log)
332 def skip_uuid_read_permission_check
333 super + %w(cancelled_by_client_uuid)
336 def skip_uuid_existence_check
337 super + %w(output log)
341 if self.priority.nil?
347 def ensure_script_version_is_commit
349 # Apparently client has already decided to go for it. This is
350 # needed to run a local job using a local working directory
351 # instead of a commit-ish.
354 if new_record? or repository_changed? or script_version_changed?
355 sha1 = Commit.find_commit_range(repository,
356 nil, script_version, nil).first
358 errors.add :script_version, "#{script_version} does not resolve to a commit"
361 if supplied_script_version.nil? or supplied_script_version.empty?
362 self.supplied_script_version = script_version
364 self.script_version = sha1
369 def tag_version_in_internal_repository
371 # No point now. See ensure_script_version_is_commit.
374 # Won't be saved, and script_version might not even be valid.
376 elsif new_record? or repository_changed? or script_version_changed?
380 Commit.tag_in_internal_repository repository, script_version, uuid
388 def ensure_unique_submit_id
390 if Job.where('submit_id=?',self.submit_id).first
391 raise SubmitIdReused.new
397 def resolve_runtime_constraint(key, attr_sym)
398 if ((runtime_constraints.is_a? Hash) and
399 (search = runtime_constraints[key]))
400 ok, result = yield search
402 ok, result = true, nil
405 send("#{attr_sym}=".to_sym, result)
407 errors.add(attr_sym, result)
412 def find_arvados_sdk_version
413 resolve_runtime_constraint("arvados_sdk_version",
414 :arvados_sdk_version) do |git_search|
415 commits = Commit.find_commit_range("arvados",
416 nil, git_search, nil)
418 [false, "#{git_search} does not resolve to a commit"]
419 elsif not runtime_constraints["docker_image"]
420 [false, "cannot be specified without a Docker image constraint"]
422 [true, commits.first]
427 def find_docker_image_locator
428 if runtime_constraints.is_a? Hash
429 runtime_constraints['docker_image'] ||=
430 Rails.configuration.default_docker_image_for_jobs
433 resolve_runtime_constraint("docker_image",
434 :docker_image_locator) do |image_search|
435 image_tag = runtime_constraints['docker_image_tag']
436 if coll = Collection.for_latest_docker_image(image_search, image_tag)
437 [true, coll.portable_data_hash]
439 [false, "not found for #{image_search}"]
444 def permission_to_update
445 if is_locked_by_uuid_was and !(current_user and
446 (current_user.uuid == is_locked_by_uuid_was or
447 current_user.uuid == system_user.uuid))
448 if script_changed? or
449 script_parameters_changed? or
450 script_version_changed? or
451 (!cancelled_at_was.nil? and
452 (cancelled_by_client_uuid_changed? or
453 cancelled_by_user_uuid_changed? or
454 cancelled_at_changed?)) or
455 started_at_changed? or
456 finished_at_changed? or
461 tasks_summary_changed? or
462 (state_changed? && state != Cancelled) or
464 logger.warn "User #{current_user.uuid if current_user} tried to change protected job attributes on locked #{self.class.to_s} #{uuid_was}"
468 if !is_locked_by_uuid_changed?
472 logger.warn "Anonymous user tried to change lock on #{self.class.to_s} #{uuid_was}"
474 elsif is_locked_by_uuid_was and is_locked_by_uuid_was != current_user.uuid
475 logger.warn "User #{current_user.uuid} tried to steal lock on #{self.class.to_s} #{uuid_was} from #{is_locked_by_uuid_was}"
477 elsif !is_locked_by_uuid.nil? and is_locked_by_uuid != current_user.uuid
478 logger.warn "User #{current_user.uuid} tried to lock #{self.class.to_s} #{uuid_was} with uuid #{is_locked_by_uuid}"
486 def update_modified_by_fields
487 if self.cancelled_at_changed?
488 # Ensure cancelled_at cannot be set to arbitrary non-now times,
489 # or changed once it is set.
490 if self.cancelled_at and not self.cancelled_at_was
491 self.cancelled_at = db_current_time
492 self.cancelled_by_user_uuid = current_user.uuid
493 self.cancelled_by_client_uuid = current_api_client.andand.uuid
494 @need_crunch_dispatch_trigger = true
496 self.cancelled_at = self.cancelled_at_was
497 self.cancelled_by_user_uuid = self.cancelled_by_user_uuid_was
498 self.cancelled_by_client_uuid = self.cancelled_by_client_uuid_was
504 def trigger_crunch_dispatch_if_cancelled
505 if @need_crunch_dispatch_trigger
506 File.open(Rails.configuration.crunch_refresh_trigger, 'wb') do
507 # That's all, just create/touch a file for crunch-job to see.
512 def update_timestamps_when_state_changes
513 return if not (state_changed? or new_record?)
517 self.started_at ||= db_current_time
518 when Failed, Complete
519 self.finished_at ||= db_current_time
521 self.cancelled_at ||= db_current_time
524 # TODO: Remove the following case block when old "success" and
525 # "running" attrs go away. Until then, this ensures we still
526 # expose correct success/running flags to older clients, even if
527 # some new clients are writing only the new state attribute.
535 when Cancelled, Failed
542 self.running ||= false # Default to false instead of nil.
544 @need_crunch_dispatch_trigger = true
549 def update_state_from_old_state_attrs
550 # If a client has touched the legacy state attrs, update the
551 # "state" attr to agree with the updated values of the legacy
554 # TODO: Remove this method when old "success" and "running" attrs
556 if cancelled_at_changed? or
561 self.state = Cancelled
562 elsif success == false
564 elsif success == true
565 self.state = Complete
566 elsif running == true
576 if self.state.in?(States)
579 errors.add :state, "#{state.inspect} must be one of: #{States.inspect}"
584 def validate_state_change
586 if self.state_changed?
587 ok = case self.state_was
589 # state isn't set yet
592 # Permit going from queued to any state
595 # From running, may only transition to a finished state
596 [Complete, Failed, Cancelled].include? self.state
597 when Complete, Failed, Cancelled
598 # Once in a finished state, don't permit any more state changes
601 # Any other state transition is also invalid
605 errors.add :state, "invalid change from #{self.state_was} to #{self.state}"
611 def ensure_no_collection_uuids_in_script_params
612 # Fail validation if any script_parameters field includes a string containing a
613 # collection uuid pattern.
614 if self.script_parameters_changed?
615 if recursive_hash_search(self.script_parameters, Collection.uuid_regex)
616 self.errors.add :script_parameters, "must use portable_data_hash instead of collection uuid"
623 # recursive_hash_search searches recursively through hashes and
624 # arrays in 'thing' for string fields matching regular expression
625 # 'pattern'. Returns true if pattern is found, false otherwise.
626 def recursive_hash_search thing, pattern
629 return true if recursive_hash_search v, pattern
631 elsif thing.is_a? Array
633 return true if recursive_hash_search k, pattern
635 elsif thing.is_a? String
636 return true if thing.match pattern