<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[14665] twext/trunk/twext/enterprise</title>
</head>
<body>
<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; }
#msg dl a { font-weight: bold}
#msg dl a:link { color:#fc3; }
#msg dl a:active { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.calendarserver.org//changeset/14665">14665</a></dd>
<dt>Author</dt> <dd>cdaboo@apple.com</dd>
<dt>Date</dt> <dd>2015-04-08 06:51:33 -0700 (Wed, 08 Apr 2015)</dd>
</dl>
<h3>Log Message</h3>
<pre>Support temporary failures for job queue items.</pre>
<h3>Modified Paths</h3>
<ul>
<li><a href="#twexttrunktwextenterprisejobqueuepy">twext/trunk/twext/enterprise/jobqueue.py</a></li>
<li><a href="#twexttrunktwextenterprisetesttest_jobqueuepy">twext/trunk/twext/enterprise/test/test_jobqueue.py</a></li>
</ul>
</div>
<div id="patch">
<h3>Diff</h3>
<a id="twexttrunktwextenterprisejobqueuepy"></a>
<div class="modfile"><h4>Modified: twext/trunk/twext/enterprise/jobqueue.py (14664 => 14665)</h4>
<pre class="diff"><span>
<span class="info">--- twext/trunk/twext/enterprise/jobqueue.py        2015-04-08 13:50:32 UTC (rev 14664)
+++ twext/trunk/twext/enterprise/jobqueue.py        2015-04-08 13:51:33 UTC (rev 14665)
</span><span class="lines">@@ -326,6 +326,21 @@
</span><span class="cx">
</span><span class="cx">
</span><span class="cx">
</span><ins>+class JobTemporaryError(Exception):
+ """
+ A job failed to run due to a temporary failure. We will get the job to run again after the specified
+ interval (with a built-in back-off based on the number of failures also applied).
+ """
+
+ def __init__(self, delay):
+ """
+ @param delay: amount of time in seconds before it should run again
+ @type delay: L{int}
+ """
+ self.delay = delay
+
+
+
</ins><span class="cx"> class JobRunningError(Exception):
</span><span class="cx"> """
</span><span class="cx"> A job is already running.
</span><span class="lines">@@ -452,6 +467,28 @@
</span><span class="cx"> def _overtm(nb):
</span><span class="cx"> return "{:.0f}".format(1000 * (t - astimestamp(nb)))
</span><span class="cx">
</span><ins>+ # Failed job clean-up
+ def _failureCleanUp(delay=None):
+ @inlineCallbacks
+ def _cleanUp2(txn2):
+ try:
+ job = yield cls.load(txn2, jobID)
+ except NoSuchRecord:
+ log.debug(
+ "JobItem: {jobid} disappeared t={tm}",
+ jobid=jobID,
+ tm=_tm(),
+ )
+ else:
+ log.debug(
+ "JobItem: {jobid} marking as failed {count} t={tm}",
+ jobid=jobID,
+ count=job.failed + 1,
+ tm=_tm(),
+ )
+ yield job.failedToRun(locked=isinstance(e, JobRunningError), delay=delay)
+ return inTransaction(txnFactory, _cleanUp2, "ultimatelyPerform._failureCleanUp")
+
</ins><span class="cx"> log.debug("JobItem: {jobid} starting to run", jobid=jobID)
</span><span class="cx"> txn = txnFactory(label="ultimatelyPerform: {}".format(jobID))
</span><span class="cx"> try:
</span><span class="lines">@@ -475,28 +512,24 @@
</span><span class="cx"> tm=_tm(),
</span><span class="cx"> )
</span><span class="cx">
</span><ins>+ except JobTemporaryError as e:
+
+ # Temporary failure delay with back-off
+ def _temporaryFailure():
+ return _failureCleanUp(delay=e.delay * (job.failed + 1))
+ log.debug(
+ "JobItem: {jobid} {desc} {work} t={tm}",
+ jobid=jobID,
+ desc="temporary failure #{}".format(job.failed + 1),
+ work=job.workType,
+ tm=_tm(),
+ )
+ txn.postAbort(_temporaryFailure)
+ yield txn.abort()
+
</ins><span class="cx"> except (JobFailedError, JobRunningError) as e:
</span><del>- # Job failed: abort with cleanup, but pretend this method succeeded
- def _cleanUp():
- @inlineCallbacks
- def _cleanUp2(txn2):
- try:
- job = yield cls.load(txn2, jobID)
- except NoSuchRecord:
- log.debug(
- "JobItem: {jobid} disappeared t={tm}",
- jobid=jobID,
- tm=_tm(),
- )
- else:
- log.debug(
- "JobItem: {jobid} marking as failed {count} t={tm}",
- jobid=jobID,
- count=job.failed + 1,
- tm=_tm(),
- )
- yield job.failedToRun(locked=isinstance(e, JobRunningError))
- return inTransaction(txnFactory, _cleanUp2, "ultimatelyPerform._cleanUp")
</del><ins>+
+ # Permanent failure
</ins><span class="cx"> log.debug(
</span><span class="cx"> "JobItem: {jobid} {desc} {work} t={tm}",
</span><span class="cx"> jobid=jobID,
</span><span class="lines">@@ -504,7 +537,7 @@
</span><span class="cx"> work=job.workType,
</span><span class="cx"> tm=_tm(),
</span><span class="cx"> )
</span><del>- txn.postAbort(_cleanUp)
</del><ins>+ txn.postAbort(_failureCleanUp)
</ins><span class="cx"> yield txn.abort()
</span><span class="cx">
</span><span class="cx"> except:
</span><span class="lines">@@ -645,7 +678,10 @@
</span><span class="cx"> workid=workItem.workID,
</span><span class="cx"> exc=f,
</span><span class="cx"> )
</span><del>- raise JobFailedError(e)
</del><ins>+ if isinstance(e, JobTemporaryError):
+ raise
+ else:
+ raise JobFailedError(e)
</ins><span class="cx">
</span><span class="cx"> try:
</span><span class="cx"> # Once the work is done we delete ourselves - NB this must be the last thing done
</span></span></pre></div>
<a id="twexttrunktwextenterprisetesttest_jobqueuepy"></a>
<div class="modfile"><h4>Modified: twext/trunk/twext/enterprise/test/test_jobqueue.py (14664 => 14665)</h4>
<pre class="diff"><span>
<span class="info">--- twext/trunk/twext/enterprise/test/test_jobqueue.py        2015-04-08 13:50:32 UTC (rev 14664)
+++ twext/trunk/twext/enterprise/test/test_jobqueue.py        2015-04-08 13:51:33 UTC (rev 14665)
</span><span class="lines">@@ -38,14 +38,13 @@
</span><span class="cx"> from twext.enterprise.dal.test.test_parseschema import SchemaTestHelper
</span><span class="cx"> from twext.enterprise.fixtures import buildConnectionPool
</span><span class="cx"> from twext.enterprise.fixtures import SteppablePoolHelper
</span><del>-from twext.enterprise.jobqueue import (
- inTransaction, PeerConnectionPool, astimestamp,
- LocalPerformer, _IJobPerformer, WorkItem, WorkerConnectionPool,
- ConnectionFromPeerNode,
- _BaseQueuer, NonPerformingQueuer, JobItem,
- WORK_PRIORITY_LOW, WORK_PRIORITY_HIGH, WORK_PRIORITY_MEDIUM,
- JobDescriptor, SingletonWorkItem, JobFailedError
-)
</del><ins>+from twext.enterprise.jobqueue import \
+ inTransaction, PeerConnectionPool, astimestamp, \
+ LocalPerformer, _IJobPerformer, WorkItem, WorkerConnectionPool, \
+ ConnectionFromPeerNode, \
+ _BaseQueuer, NonPerformingQueuer, JobItem, \
+ WORK_PRIORITY_LOW, WORK_PRIORITY_HIGH, WORK_PRIORITY_MEDIUM, \
+ JobDescriptor, SingletonWorkItem, JobFailedError, JobTemporaryError
</ins><span class="cx"> import twext.enterprise.jobqueue
</span><span class="cx">
</span><span class="cx"> # TODO: There should be a store-building utility within twext.enterprise.
</span><span class="lines">@@ -280,6 +279,8 @@
</span><span class="cx"> def doWork(self):
</span><span class="cx"> if self.a == -1:
</span><span class="cx"> raise ValueError("Ooops")
</span><ins>+ elif self.a == -2:
+ raise JobTemporaryError(120)
</ins><span class="cx"> self.results[self.jobID] = self.a + self.b
</span><span class="cx"> return succeed(None)
</span><span class="cx">
</span><span class="lines">@@ -1000,30 +1001,23 @@
</span><span class="cx"> @transactionally(dbpool.pool.connection)
</span><span class="cx"> @inlineCallbacks
</span><span class="cx"> def setup(txn):
</span><del>- # First, one that's right now.
</del><ins>+ # OK
</ins><span class="cx"> yield DummyWorkItem.makeJob(
</span><span class="cx"> txn, a=1, b=0, notBefore=fakeNow - datetime.timedelta(20 * 60)
</span><span class="cx"> )
</span><span class="cx">
</span><del>- # Next, create one that's actually far enough into the past to run.
</del><ins>+ # Error
</ins><span class="cx"> yield DummyWorkItem.makeJob(
</span><span class="cx"> txn, a=-1, b=1, notBefore=fakeNow - datetime.timedelta(20 * 60)
</span><span class="cx"> )
</span><span class="cx">
</span><del>- # Finally, one that's actually scheduled for the future.
</del><ins>+ # OK
</ins><span class="cx"> yield DummyWorkItem.makeJob(
</span><span class="cx"> txn, a=2, b=0, notBefore=fakeNow - datetime.timedelta(20 * 60)
</span><span class="cx"> )
</span><span class="cx"> yield setup
</span><span class="cx"> clock.advance(20 - 12)
</span><span class="cx">
</span><del>- # Wait for job
-# while True:
-# jobs = yield inTransaction(dbpool.pool.connection, lambda txn: JobItem.all(txn))
-# if all([job.a == -1 for job in jobs]):
-# break
-# clock.advance(1)
-
</del><span class="cx"> # Work item complete
</span><span class="cx"> self.assertTrue(DummyWorkItem.results == {1: 1, 3: 2})
</span><span class="cx">
</span><span class="lines">@@ -1062,7 +1056,41 @@
</span><span class="cx"> self.assertTrue(jobs[0].notBefore > datetime.datetime.utcnow())
</span><span class="cx">
</span><span class="cx">
</span><ins>+ @inlineCallbacks
+ def test_temporaryFailure(self):
+ """
+ When a work item temporARILY fails it should appear as unassigned in the JOB
+ table and have the failure count bumped, and a notBefore set to the temporary delay.
+ """
+ dbpool, _ignore_qpool, clock, _ignore_performerChosen = self._setupPools()
+ fakeNow = datetime.datetime(2012, 12, 12, 12, 12, 12)
</ins><span class="cx">
</span><ins>+ # Let's create a couple of work items directly, not via the enqueue
+ # method, so that they exist but nobody will try to immediately execute
+ # them.
+
+ @transactionally(dbpool.pool.connection)
+ @inlineCallbacks
+ def setup(txn):
+ # Next, create failing work that's actually far enough into the past to run.
+ yield DummyWorkItem.makeJob(
+ txn, a=-2, b=1, notBefore=fakeNow - datetime.timedelta(20 * 60)
+ )
+ yield setup
+ clock.advance(20 - 12)
+
+ @transactionally(dbpool.pool.connection)
+ def check(txn):
+ return JobItem.all(txn)
+
+ jobs = yield check
+ self.assertTrue(len(jobs) == 1)
+ self.assertTrue(jobs[0].assigned is None)
+ self.assertTrue(jobs[0].failed == 1)
+ self.assertTrue(jobs[0].notBefore > datetime.datetime.utcnow() + datetime.timedelta(seconds=90))
+
+
+
</ins><span class="cx"> class HalfConnection(object):
</span><span class="cx"> def __init__(self, protocol):
</span><span class="cx"> self.protocol = protocol
</span></span></pre>
</div>
</div>
</body>
</html>