diff --git a/README.md b/README.md index c8966e9..c7ac1d1 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,9 @@ configuration options: w.sleep_delay = 3 # maximum attempts before marking the job as permanently failing (default 3) +# an attempt is counted when a job is picked up, so runs that never finish +# (e.g. the worker is OOM-killed) also count; a job that already used all +# its attempts is marked as failed instead of being run again w.max_attempts = 5 # sets a cap on how long a worker should wait between retry attempts. diff --git a/pyworker/worker.py b/pyworker/worker.py index 5a3e05c..c0264b4 100644 --- a/pyworker/worker.py +++ b/pyworker/worker.py @@ -10,6 +10,7 @@ class TimeoutException(Exception): pass class TerminatedException(Exception): pass +class AttemptsExhaustedException(Exception): pass class Worker(object): def __init__(self, dbstring, logger=None, @@ -126,12 +127,15 @@ def get_job_row(): now, expired = str(now), str(expired) queues = self.queue_names.split(',') queues = ', '.join(["'%s'" % q for q in queues]) - fields = ['id', 'attempts', 'run_at', 'queue', 'handler'] + # attempts is counted when the job is locked (see the UPDATE below), so a run + # that never reaches set_error_unlock (e.g. the process is OOM-killed) still + # uses an attempt; return the attempts made before this run + fields = ['id', 'attempts - 1', 'run_at', 'queue', 'handler'] if self.extra_delayed_job_fields: fields += self.extra_delayed_job_fields fields = ', '.join(fields) query = ''' - UPDATE delayed_jobs SET locked_at = '%s', locked_by = '%s' + UPDATE delayed_jobs SET locked_at = '%s', locked_by = '%s', attempts = attempts + 1 WHERE id IN (SELECT delayed_jobs.id FROM delayed_jobs WHERE ((run_at <= '%s' AND (locked_at IS NULL OR locked_at < '%s') @@ -142,7 +146,11 @@ def get_job_row(): ''' % (now, self.name, now, expired, self.name, queues, fields) self.logger.debug('query: %s' % query) self._cursor.execute(query) - return self._cursor.fetchone() + row = self._cursor.fetchone() + # commit the lock and the attempt now: if the process is killed while the + # job runs, an uncommitted UPDATE would be rolled back with it + self.database.commit() + return row job_row = get_job_row() if job_row: @@ -162,6 +170,12 @@ def handle_job(self, job): error = failed = False caught_exc_info = None try: + if job.attempts >= self.max_attempts: + # every previous run was counted but never finished, e.g. the + # worker was killed, so fail it instead of running it again + raise AttemptsExhaustedException(('Job %d was not run: it already used ' \ + + 'all %d attempts without finishing, the worker was likely killed ' \ + + '(e.g. out of memory)') % (job.job_id, self.max_attempts)) if job.abstract: raise ValueError(('Unsupported Job: %s, please import it ' \ + 'before you can handle it') % job.class_name) diff --git a/tests/test_worker.py b/tests/test_worker.py index 3b99a60..78546b0 100644 --- a/tests/test_worker.py +++ b/tests/test_worker.py @@ -1,7 +1,7 @@ import datetime from unittest import TestCase from unittest.mock import patch, MagicMock -from pyworker.worker import Worker, TerminatedException +from pyworker.worker import Worker, TerminatedException, AttemptsExhaustedException class TestWorker(TestCase): @patch('pyworker.worker.DBConnector') @@ -105,8 +105,74 @@ def test_worker_run_when_job_found_handles_job(self, mock_get_job, mock_handle_j mock_get_job.assert_called_once_with() mock_handle_job.assert_called_once_with(mock_get_job.return_value) + #********** .get_job tests **********# + + def test_worker_get_job_counts_the_attempt_when_locking_the_job(self): + self.worker._cursor = MagicMock() + self.worker._cursor.fetchone.return_value = None + + self.worker.get_job() + + query = self.worker._cursor.execute.call_args[0][0] + self.assertIn('attempts = attempts + 1', query) + # the job still sees the attempts made before this run + self.assertIn('RETURNING\n id, attempts - 1, run_at', query) + + def test_worker_get_job_commits_the_lock_and_attempt_before_running(self): + # an uncommitted UPDATE would be rolled back if the process is killed during run() + self.worker._cursor = MagicMock() + self.worker._cursor.fetchone.return_value = None + calls = MagicMock() + calls.attach_mock(self.worker._cursor.fetchone, 'fetchone') + calls.attach_mock(self.worker.database.commit, 'commit') + + self.worker.get_job() + + self.assertEqual([c[0] for c in calls.mock_calls], ['fetchone', 'commit']) + #********** .handle_job tests **********# + def test_worker_handle_job_when_attempts_exhausted_does_not_run_job(self): + # all previous runs were counted but never finished, e.g. the worker was OOM-killed + job = self.mock_job + job.attempts = self.worker.max_attempts + + self.worker.handle_job(job) + + job.before.assert_not_called() + job.run.assert_not_called() + job.remove.assert_not_called() + job.set_error_unlock.assert_called_once() + error = job.set_error_unlock.call_args[0][0] + assert 'AttemptsExhaustedException' in error + assert 'already used all 3 attempts' in error + + @patch('pyworker.worker.get_current_time') + def test_worker_handle_job_when_attempts_exhausted_reports_failure(self, get_current_time): + get_current_time.return_value = self.mocked_now + job = self.mock_job + job.attempts = self.worker.max_attempts + job.set_error_unlock.return_value = True + reporter = MagicMock() + self.worker.reporter = reporter + + self.worker.handle_job(job) + + reporter.record_exception.assert_called_once() + reporter.report.assert_any_call(job_failure=True) + reporter.report_raw.assert_any_call(error=True) + + def test_worker_handle_job_when_attempts_left_runs_job(self): + job = self.mock_job + job.attempts = self.worker.max_attempts - 1 + + self.worker.handle_job(job) + + job.run.assert_called_once() + job.remove.assert_called_once() + job.set_error_unlock.assert_not_called() + + def assert_instrument_context_reports_custom_attributes(self, job, reporter): reporter.recorder.assert_called_once() reporter.report.assert_any_call(