1 class Job < ArvadosModel
4 include CommonApiTemplate
5 attr_protected :arvados_sdk_version, :docker_image_locator
6 serialize :script_parameters, Hash
7 serialize :runtime_constraints, Hash
8 serialize :tasks_summary, Hash
9 before_create :ensure_unique_submit_id
10 after_commit :trigger_crunch_dispatch_if_cancelled, :on => :update
11 before_validation :set_priority
12 before_validation :update_state_from_old_state_attrs
13 validate :ensure_script_version_is_commit
14 validate :find_arvados_sdk_version
15 validate :find_docker_image_locator
16 validate :validate_status
17 validate :validate_state_change
18 validate :ensure_no_collection_uuids_in_script_params
19 before_save :tag_version_in_internal_repository
20 before_save :update_timestamps_when_state_changes
22 has_many :commit_ancestors, :foreign_key => :descendant, :primary_key => :script_version
23 has_many(:nodes, foreign_key: :job_uuid, primary_key: :uuid)
25 class SubmitIdReused < StandardError
28 api_accessible :user, extend: :common do |t|
32 t.add :script_parameters
35 t.add :cancelled_by_client_uuid
36 t.add :cancelled_by_user_uuid
43 t.add :is_locked_by_uuid
45 t.add :runtime_constraints
47 t.add :nondeterministic
49 t.add :supplied_script_version
50 t.add :arvados_sdk_version
51 t.add :docker_image_locator
57 # Supported states for a job
60 (Running = 'Running'),
61 (Cancelled = 'Cancelled'),
63 (Complete = 'Complete'),
67 update_attributes(finished_at: finished_at || db_current_time,
68 success: success.nil? ? false : success,
77 self.where('state = ?', Queued).order('priority desc, created_at')
81 Job::queue.each_with_index do |job, index|
82 if job[:uuid] == self.uuid
90 self.where('running = ?', true).
91 order('priority desc, created_at')
94 def lock locked_by_uuid
97 unless self.state == Queued and self.is_locked_by_uuid.nil?
98 raise AlreadyLockedError
101 self.is_locked_by_uuid = locked_by_uuid
108 def foreign_key_attributes
109 super + %w(output log)
112 def skip_uuid_read_permission_check
113 super + %w(cancelled_by_client_uuid)
116 def skip_uuid_existence_check
117 super + %w(output log)
121 if self.priority.nil?
127 def ensure_script_version_is_commit
128 if self.state == Running
129 # Apparently client has already decided to go for it. This is
130 # needed to run a local job using a local working directory
131 # instead of a commit-ish.
134 if new_record? or repository_changed? or script_version_changed?
135 sha1 = Commit.find_commit_range(current_user, repository,
136 nil, script_version, nil).first
138 errors.add :script_version, "#{script_version} does not resolve to a commit"
141 if supplied_script_version.nil? or supplied_script_version.empty?
142 self.supplied_script_version = script_version
144 self.script_version = sha1
149 def tag_version_in_internal_repository
150 if self.state == Running
151 # No point now. See ensure_script_version_is_commit.
153 elsif new_record? or repository_changed? or script_version_changed?
157 Commit.tag_in_internal_repository repository, script_version, uuid
165 def ensure_unique_submit_id
167 if Job.where('submit_id=?',self.submit_id).first
168 raise SubmitIdReused.new
174 def resolve_runtime_constraint(key, attr_sym)
175 if ((runtime_constraints.is_a? Hash) and
176 (search = runtime_constraints[key]))
177 ok, result = yield search
179 ok, result = true, nil
182 send("#{attr_sym}=".to_sym, result)
184 errors.add(attr_sym, result)
189 def find_arvados_sdk_version
190 resolve_runtime_constraint("arvados_sdk_version",
191 :arvados_sdk_version) do |git_search|
192 commits = Commit.find_commit_range(current_user, "arvados",
193 nil, git_search, nil)
195 [false, "#{git_search} does not resolve to a commit"]
196 elsif not runtime_constraints["docker_image"]
197 [false, "cannot be specified without a Docker image constraint"]
199 [true, commits.first]
204 def find_docker_image_locator
205 resolve_runtime_constraint("docker_image",
206 :docker_image_locator) do |image_search|
207 image_tag = runtime_constraints['docker_image_tag']
208 if coll = Collection.for_latest_docker_image(image_search, image_tag)
209 [true, coll.portable_data_hash]
211 [false, "not found for #{image_search}"]
216 def permission_to_update
217 if is_locked_by_uuid_was and !(current_user and
218 (current_user.uuid == is_locked_by_uuid_was or
219 current_user.uuid == system_user.uuid))
220 if script_changed? or
221 script_parameters_changed? or
222 script_version_changed? or
223 (!cancelled_at_was.nil? and
224 (cancelled_by_client_uuid_changed? or
225 cancelled_by_user_uuid_changed? or
226 cancelled_at_changed?)) or
227 started_at_changed? or
228 finished_at_changed? or
233 tasks_summary_changed? or
235 logger.warn "User #{current_user.uuid if current_user} tried to change protected job attributes on locked #{self.class.to_s} #{uuid_was}"
239 if !is_locked_by_uuid_changed?
243 logger.warn "Anonymous user tried to change lock on #{self.class.to_s} #{uuid_was}"
245 elsif is_locked_by_uuid_was and is_locked_by_uuid_was != current_user.uuid
246 logger.warn "User #{current_user.uuid} tried to steal lock on #{self.class.to_s} #{uuid_was} from #{is_locked_by_uuid_was}"
248 elsif !is_locked_by_uuid.nil? and is_locked_by_uuid != current_user.uuid
249 logger.warn "User #{current_user.uuid} tried to lock #{self.class.to_s} #{uuid_was} with uuid #{is_locked_by_uuid}"
257 def update_modified_by_fields
258 if self.cancelled_at_changed?
259 # Ensure cancelled_at cannot be set to arbitrary non-now times,
260 # or changed once it is set.
261 if self.cancelled_at and not self.cancelled_at_was
262 self.cancelled_at = db_current_time
263 self.cancelled_by_user_uuid = current_user.uuid
264 self.cancelled_by_client_uuid = current_api_client.andand.uuid
265 @need_crunch_dispatch_trigger = true
267 self.cancelled_at = self.cancelled_at_was
268 self.cancelled_by_user_uuid = self.cancelled_by_user_uuid_was
269 self.cancelled_by_client_uuid = self.cancelled_by_client_uuid_was
275 def trigger_crunch_dispatch_if_cancelled
276 if @need_crunch_dispatch_trigger
277 File.open(Rails.configuration.crunch_refresh_trigger, 'wb') do
278 # That's all, just create/touch a file for crunch-job to see.
283 def update_timestamps_when_state_changes
284 return if not (state_changed? or new_record?)
288 self.started_at ||= db_current_time
289 when Failed, Complete
290 self.finished_at ||= db_current_time
292 self.cancelled_at ||= db_current_time
295 # TODO: Remove the following case block when old "success" and
296 # "running" attrs go away. Until then, this ensures we still
297 # expose correct success/running flags to older clients, even if
298 # some new clients are writing only the new state attribute.
306 when Cancelled, Failed
313 self.running ||= false # Default to false instead of nil.
315 @need_crunch_dispatch_trigger = true
320 def update_state_from_old_state_attrs
321 # If a client has touched the legacy state attrs, update the
322 # "state" attr to agree with the updated values of the legacy
325 # TODO: Remove this method when old "success" and "running" attrs
327 if cancelled_at_changed? or
332 self.state = Cancelled
333 elsif success == false
335 elsif success == true
336 self.state = Complete
337 elsif running == true
347 if self.state.in?(States)
350 errors.add :state, "#{state.inspect} must be one of: #{States.inspect}"
355 def validate_state_change
357 if self.state_changed?
358 ok = case self.state_was
360 # state isn't set yet
363 # Permit going from queued to any state
366 # From running, may only transition to a finished state
367 [Complete, Failed, Cancelled].include? self.state
368 when Complete, Failed, Cancelled
369 # Once in a finished state, don't permit any more state changes
372 # Any other state transition is also invalid
376 errors.add :state, "invalid change from #{self.state_was} to #{self.state}"
382 def ensure_no_collection_uuids_in_script_params
383 # recursive_hash_search searches recursively through hashes and
384 # arrays in 'thing' for string fields matching regular expression
385 # 'pattern'. Returns true if pattern is found, false otherwise.
386 def recursive_hash_search thing, pattern
389 return true if recursive_hash_search v, pattern
391 elsif thing.is_a? Array
393 return true if recursive_hash_search k, pattern
395 elsif thing.is_a? String
396 return true if thing.match pattern
401 # Fail validation if any script_parameters field includes a string containing a
402 # collection uuid pattern.
403 if self.script_parameters_changed?
404 if recursive_hash_search(self.script_parameters, Collection.uuid_regex)
405 self.errors.add :script_parameters, "must use portable_data_hash instead of collection uuid"