1 class Job < ArvadosModel
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 validate :ensure_script_version_is_commit
15 validate :find_docker_image_locator
16 validate :find_arvados_sdk_version
17 validate :validate_status
18 validate :validate_state_change
19 validate :ensure_no_collection_uuids_in_script_params
20 before_save :tag_version_in_internal_repository
21 before_save :update_timestamps_when_state_changes
23 has_many :commit_ancestors, :foreign_key => :descendant, :primary_key => :script_version
24 has_many(:nodes, foreign_key: :job_uuid, primary_key: :uuid)
26 class SubmitIdReused < StandardError
29 api_accessible :user, extend: :common do |t|
33 t.add :script_parameters
36 t.add :cancelled_by_client_uuid
37 t.add :cancelled_by_user_uuid
44 t.add :is_locked_by_uuid
46 t.add :runtime_constraints
48 t.add :nondeterministic
50 t.add :supplied_script_version
51 t.add :arvados_sdk_version
52 t.add :docker_image_locator
59 # Supported states for a job
62 (Running = 'Running'),
63 (Cancelled = 'Cancelled'),
65 (Complete = 'Complete'),
69 update_attributes(finished_at: finished_at || db_current_time,
70 success: success.nil? ? false : success,
79 self.where('state = ?', Queued).order('priority desc, created_at')
83 # We used to report this accurately, but the implementation made queue
84 # API requests O(n**2) for the size of the queue. See #8800.
85 # We've soft-disabled it because it's not clear we even want this
86 # functionality: now that we have Node Manager with support for multiple
87 # node sizes, "queue position" tells you very little about when a job will
89 state == Queued ? 0 : nil
93 self.where('running = ?', true).
94 order('priority desc, created_at')
97 def lock locked_by_uuid
99 unless self.state == Queued and self.is_locked_by_uuid.nil?
100 raise AlreadyLockedError
103 self.is_locked_by_uuid = locked_by_uuid
110 def foreign_key_attributes
111 super + %w(output log)
114 def skip_uuid_read_permission_check
115 super + %w(cancelled_by_client_uuid)
118 def skip_uuid_existence_check
119 super + %w(output log)
123 if self.priority.nil?
129 def ensure_script_version_is_commit
131 # Apparently client has already decided to go for it. This is
132 # needed to run a local job using a local working directory
133 # instead of a commit-ish.
136 if new_record? or repository_changed? or script_version_changed?
137 sha1 = Commit.find_commit_range(repository,
138 nil, script_version, nil).first
140 errors.add :script_version, "#{script_version} does not resolve to a commit"
143 if supplied_script_version.nil? or supplied_script_version.empty?
144 self.supplied_script_version = script_version
146 self.script_version = sha1
151 def tag_version_in_internal_repository
153 # No point now. See ensure_script_version_is_commit.
156 # Won't be saved, and script_version might not even be valid.
158 elsif new_record? or repository_changed? or script_version_changed?
162 Commit.tag_in_internal_repository repository, script_version, uuid
170 def ensure_unique_submit_id
172 if Job.where('submit_id=?',self.submit_id).first
173 raise SubmitIdReused.new
179 def resolve_runtime_constraint(key, attr_sym)
180 if ((runtime_constraints.is_a? Hash) and
181 (search = runtime_constraints[key]))
182 ok, result = yield search
184 ok, result = true, nil
187 send("#{attr_sym}=".to_sym, result)
189 errors.add(attr_sym, result)
194 def find_arvados_sdk_version
195 resolve_runtime_constraint("arvados_sdk_version",
196 :arvados_sdk_version) do |git_search|
197 commits = Commit.find_commit_range("arvados",
198 nil, git_search, nil)
200 [false, "#{git_search} does not resolve to a commit"]
201 elsif not runtime_constraints["docker_image"]
202 [false, "cannot be specified without a Docker image constraint"]
204 [true, commits.first]
209 def find_docker_image_locator
210 runtime_constraints['docker_image'] =
211 Rails.configuration.default_docker_image_for_jobs if ((runtime_constraints.is_a? Hash) and
212 (runtime_constraints['docker_image']).nil? and
213 Rails.configuration.default_docker_image_for_jobs)
214 resolve_runtime_constraint("docker_image",
215 :docker_image_locator) do |image_search|
216 image_tag = runtime_constraints['docker_image_tag']
217 if coll = Collection.for_latest_docker_image(image_search, image_tag)
218 [true, coll.portable_data_hash]
220 [false, "not found for #{image_search}"]
225 def permission_to_update
226 if is_locked_by_uuid_was and !(current_user and
227 (current_user.uuid == is_locked_by_uuid_was or
228 current_user.uuid == system_user.uuid))
229 if script_changed? or
230 script_parameters_changed? or
231 script_version_changed? or
232 (!cancelled_at_was.nil? and
233 (cancelled_by_client_uuid_changed? or
234 cancelled_by_user_uuid_changed? or
235 cancelled_at_changed?)) or
236 started_at_changed? or
237 finished_at_changed? or
242 tasks_summary_changed? or
245 logger.warn "User #{current_user.uuid if current_user} tried to change protected job attributes on locked #{self.class.to_s} #{uuid_was}"
249 if !is_locked_by_uuid_changed?
253 logger.warn "Anonymous user tried to change lock on #{self.class.to_s} #{uuid_was}"
255 elsif is_locked_by_uuid_was and is_locked_by_uuid_was != current_user.uuid
256 logger.warn "User #{current_user.uuid} tried to steal lock on #{self.class.to_s} #{uuid_was} from #{is_locked_by_uuid_was}"
258 elsif !is_locked_by_uuid.nil? and is_locked_by_uuid != current_user.uuid
259 logger.warn "User #{current_user.uuid} tried to lock #{self.class.to_s} #{uuid_was} with uuid #{is_locked_by_uuid}"
267 def update_modified_by_fields
268 if self.cancelled_at_changed?
269 # Ensure cancelled_at cannot be set to arbitrary non-now times,
270 # or changed once it is set.
271 if self.cancelled_at and not self.cancelled_at_was
272 self.cancelled_at = db_current_time
273 self.cancelled_by_user_uuid = current_user.uuid
274 self.cancelled_by_client_uuid = current_api_client.andand.uuid
275 @need_crunch_dispatch_trigger = true
277 self.cancelled_at = self.cancelled_at_was
278 self.cancelled_by_user_uuid = self.cancelled_by_user_uuid_was
279 self.cancelled_by_client_uuid = self.cancelled_by_client_uuid_was
285 def trigger_crunch_dispatch_if_cancelled
286 if @need_crunch_dispatch_trigger
287 File.open(Rails.configuration.crunch_refresh_trigger, 'wb') do
288 # That's all, just create/touch a file for crunch-job to see.
293 def update_timestamps_when_state_changes
294 return if not (state_changed? or new_record?)
298 self.started_at ||= db_current_time
299 when Failed, Complete
300 self.finished_at ||= db_current_time
302 self.cancelled_at ||= db_current_time
305 # TODO: Remove the following case block when old "success" and
306 # "running" attrs go away. Until then, this ensures we still
307 # expose correct success/running flags to older clients, even if
308 # some new clients are writing only the new state attribute.
316 when Cancelled, Failed
323 self.running ||= false # Default to false instead of nil.
325 @need_crunch_dispatch_trigger = true
330 def update_state_from_old_state_attrs
331 # If a client has touched the legacy state attrs, update the
332 # "state" attr to agree with the updated values of the legacy
335 # TODO: Remove this method when old "success" and "running" attrs
337 if cancelled_at_changed? or
342 self.state = Cancelled
343 elsif success == false
345 elsif success == true
346 self.state = Complete
347 elsif running == true
357 if self.state.in?(States)
360 errors.add :state, "#{state.inspect} must be one of: #{States.inspect}"
365 def validate_state_change
367 if self.state_changed?
368 ok = case self.state_was
370 # state isn't set yet
373 # Permit going from queued to any state
376 # From running, may only transition to a finished state
377 [Complete, Failed, Cancelled].include? self.state
378 when Complete, Failed, Cancelled
379 # Once in a finished state, don't permit any more state changes
382 # Any other state transition is also invalid
386 errors.add :state, "invalid change from #{self.state_was} to #{self.state}"
392 def ensure_no_collection_uuids_in_script_params
393 # recursive_hash_search searches recursively through hashes and
394 # arrays in 'thing' for string fields matching regular expression
395 # 'pattern'. Returns true if pattern is found, false otherwise.
396 def recursive_hash_search thing, pattern
399 return true if recursive_hash_search v, pattern
401 elsif thing.is_a? Array
403 return true if recursive_hash_search k, pattern
405 elsif thing.is_a? String
406 return true if thing.match pattern
411 # Fail validation if any script_parameters field includes a string containing a
412 # collection uuid pattern.
413 if self.script_parameters_changed?
414 if recursive_hash_search(self.script_parameters, Collection.uuid_regex)
415 self.errors.add :script_parameters, "must use portable_data_hash instead of collection uuid"