| 1 |
""" |
| 2 |
A cron-like facility to regularly run some functions. |
| 3 |
|
| 4 |
Most of the apparatus in here is not really for user consumption. |
| 5 |
There's a singleton of the queue created below, and the methods of that |
| 6 |
singleton are exposed as module-level functions. |
| 7 |
|
| 8 |
To make the jobs actually execute, the running program has to call |
| 9 |
registerSchedulerFunction(schedulerFunction). Only the first |
| 10 |
registration is relevant. The schedulerFunction has the signature |
| 11 |
sf(delay, callable) and has to arrange for callable to be called delay |
| 12 |
seconds in the future; twisted's reactor.callLater works like this. |
| 13 |
|
| 14 |
However, you should arrange for previous callLaters to be canceled when |
| 15 |
a new one comes in. There is no management to make sure only one |
| 16 |
queue reaper runs at any time (it doesn't hurt much if more than one |
| 17 |
run, but it's a waste of resources). |
| 18 |
""" |
| 19 |
|
| 20 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 21 |
#c |
| 22 |
#c This program is free software, covered by the GNU GPL. See the |
| 23 |
#c COPYING file in the source distribution. |
| 24 |
|
| 25 |
|
| 26 |
import calendar |
| 27 |
import datetime |
| 28 |
import heapq |
| 29 |
import sys |
| 30 |
import time |
| 31 |
import threading |
| 32 |
import traceback |
| 33 |
|
| 34 |
from gavo import utils |
| 35 |
from gavo.base import config |
| 36 |
from gavo.base import osinter |
| 37 |
|
| 38 |
from gavo.utils.dachstypes import ( |
| 39 |
Any, Callable, List, Optional, Sequence, Tuple) |
| 40 |
|
| 41 |
|
| 42 |
def sendMailToAdmin(subject: str, message: str, debug: bool=False): |
| 43 |
"""tries to send a mail to the configured administrator. |
| 44 |
|
| 45 |
This relies on a functional mail infrastructure on the local host. |
| 46 |
""" |
| 47 |
if not config.get("maintainerAddress"): |
| 48 |
utils.sendUIEvent("Error", "Wanted to send mail with subject '%s', but no" |
| 49 |
" maintainerAddress is given"%subject) |
| 50 |
return |
| 51 |
|
| 52 |
if debug: |
| 53 |
rateLimitKey = None |
| 54 |
else: |
| 55 |
rateLimitKey = subject |
| 56 |
|
| 57 |
osinter.sendMail( |
| 58 |
"\n".join(["To: "+config.get("maintainerAddress"), |
| 59 |
"Subject: "+subject, |
| 60 |
"From: DaCHS server <%s>"%config.get("maintainerAddress"), |
| 61 |
"Content-Type: text/plain", |
| 62 |
"", |
| 63 |
utils.safe_str(message)]), rateLimitKey) |
| 64 |
|
| 65 |
|
| 66 |
class AbstractJob: |
| 67 |
"""A job run in a queue. |
| 68 |
|
| 69 |
These have a name and a run() method; use their reportCronFailure(message) |
| 70 |
method to deliver error messages (of course, you can also just log; |
| 71 |
reportCronFailure will in typically send a mail). Concrete jobs |
| 72 |
have to implement a getNextWakeupTime(gmtime) -> gmtime method; |
| 73 |
they probably have to redefine __init__; the must up-call. |
| 74 |
""" |
| 75 |
# here, Queue keeps track of the last (unix) time this job was started. |
| 76 |
lastStarted: Optional[float] = None |
| 77 |
|
| 78 |
def __init__(self, name: str, callable: Callable[[], None]) -> None: |
| 79 |
self.name = name |
| 80 |
self.callable = callable |
| 81 |
|
| 82 |
def __str__(self) -> str: |
| 83 |
return "<%s %s, last run at %s>"%( |
| 84 |
self.__class__.__name__, self.name, self.lastStarted) |
| 85 |
|
| 86 |
def __lt__(self, other: Any) -> bool: |
| 87 |
# these might be compared when the queue is heapified and two jobs |
| 88 |
# are scheduled at the same moment. Order doesn't matter, though. |
| 89 |
return id(self)<id(other) |
| 90 |
|
| 91 |
def reportCronFailure(self, message:str) -> None: |
| 92 |
sendMailToAdmin("DaCHS %s job failed"%self.name, |
| 93 |
"\n".join([ |
| 94 |
"DaCHS job %s failed"%utils.safe_str(self), |
| 95 |
"\nDetails:\n", |
| 96 |
message])) |
| 97 |
|
| 98 |
def run(self) -> None: |
| 99 |
"""runs callable under somewhat reliable circumstances. |
| 100 |
""" |
| 101 |
try: |
| 102 |
self.callable() |
| 103 |
except Exception: |
| 104 |
utils.sendUIEvent("Error", |
| 105 |
"Failure in timed job %s. Trying to send maintainer a mail."% |
| 106 |
utils.safe_str(self)) |
| 107 |
self.reportCronFailure("".join( |
| 108 |
traceback.format_exception(*sys.exc_info()))) |
| 109 |
|
| 110 |
def getNextWakeupTime(self, curTime: float) -> float: |
| 111 |
"""returns the UTC unix epoch seconds when this job is next |
| 112 |
supposed to run, starting from curTime. |
| 113 |
""" |
| 114 |
raise NotImplementedError( |
| 115 |
"You must override AbstractJob.getNextWakeupTime()") |
| 116 |
|
| 117 |
|
| 118 |
def isCensored(job: AbstractJob) -> bool: |
| 119 |
"""a hook to that can return true to suppress jobs. |
| 120 |
|
| 121 |
This is used with serve debug. |
| 122 |
""" |
| 123 |
return False |
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
class IntervalJob(AbstractJob): |
| 128 |
"""A job that's executed roughly every interval seconds. |
| 129 |
|
| 130 |
interval can be negative, in which case the job is scheduled for (almost) |
| 131 |
immediate execution. |
| 132 |
""" |
| 133 |
def __init__(self, |
| 134 |
interval: int, |
| 135 |
name: str, |
| 136 |
callable: Callable[[], None]) -> None: |
| 137 |
self.interval = interval |
| 138 |
AbstractJob.__init__(self, name, callable) |
| 139 |
|
| 140 |
def getNextWakeupTime(self, curTime: float) -> float: |
| 141 |
# special behaviour for the first call with a negative interval: |
| 142 |
# fix the interval and run immediately. |
| 143 |
if self.interval<0: |
| 144 |
self.interval = -self.interval |
| 145 |
return curTime |
| 146 |
|
| 147 |
if self.lastStarted is None: |
| 148 |
return curTime+self.interval/10 |
| 149 |
else: |
| 150 |
return curTime+self.interval |
| 151 |
|
| 152 |
|
| 153 |
class TimedJob(AbstractJob): |
| 154 |
"""A job that's run roughly daily at some wallclock (UTC) times. |
| 155 |
|
| 156 |
times is a list of (day-of-month, day-of-week, hour, minute) tuples. |
| 157 |
day-of-month and/or day-of-week are 1-based and may be None (if both |
| 158 |
are non-none, day-of-week wins). |
| 159 |
""" |
| 160 |
def __init__(self, |
| 161 |
times: List[Tuple[Optional[int], Optional[int], int, int]], |
| 162 |
name: str, |
| 163 |
callable: Callable[[], None]) -> None: |
| 164 |
self.times = times |
| 165 |
AbstractJob.__init__(self, name, callable) |
| 166 |
|
| 167 |
def getNextWakeupTime(self, curTime: float) -> float: |
| 168 |
# dumb strategy: get parts, replace hour and minute, and if it's |
| 169 |
# in the past, add a day; do that for all recurrence times, and use |
| 170 |
# the smallest one. |
| 171 |
nextWakeups = [] |
| 172 |
baseDT = datetime.datetime.utcfromtimestamp(curTime) |
| 173 |
|
| 174 |
for dom, dow, hour, minute in self.times: |
| 175 |
if dow is not None: |
| 176 |
dayDiff = dow-baseDT.isoweekday() |
| 177 |
if dayDiff<0: |
| 178 |
dayDiff += 7 |
| 179 |
curDT = baseDT+datetime.timedelta(days=dayDiff) |
| 180 |
curDT = curDT.replace(hour=hour, minute=minute) |
| 181 |
if curDT<=baseDT: |
| 182 |
curDT = curDT+datetime.timedelta(days=7) |
| 183 |
|
| 184 |
elif dom is not None: |
| 185 |
curDT = baseDT.replace(day=dom, hour=hour, minute=minute) |
| 186 |
if curDT<=baseDT: |
| 187 |
if curDT.month<12: |
| 188 |
curDT = curDT.replace(month=curDT.month+1) |
| 189 |
else: |
| 190 |
curDT = curDT.replace(year=curDT.year+1, month=1) |
| 191 |
|
| 192 |
else: |
| 193 |
curDT = baseDT.replace(hour=hour, minute=minute) |
| 194 |
if curDT<=baseDT: |
| 195 |
curDT = curDT+datetime.timedelta(hours=24) |
| 196 |
|
| 197 |
nextWakeups.append(calendar.timegm(curDT.utctimetuple())) |
| 198 |
|
| 199 |
return min(nextWakeups) |
| 200 |
|
| 201 |
|
| 202 |
class Queue: |
| 203 |
"""A cron-job queue. |
| 204 |
|
| 205 |
This is really a heap sorted by the time the job is next supposed to run. |
| 206 |
""" |
| 207 |
def __init__(self) -> None: |
| 208 |
self.jobs: List[Tuple[float, AbstractJob]] = [] |
| 209 |
self.lock = threading.Lock() |
| 210 |
self.scheduleFunction: Optional[Callable[[float, Callable], None]] = None |
| 211 |
|
| 212 |
def _rescheduleJob(self, |
| 213 |
job: AbstractJob) -> None: |
| 214 |
"""adds job to the queue and reschedules the wakeup if necessary. |
| 215 |
|
| 216 |
Since this method does not check for the presence of like-named jobs, |
| 217 |
it must be used for rescheduling exclusively. To schedule new jobs, |
| 218 |
use _scheduleJob. |
| 219 |
""" |
| 220 |
if isCensored(job): |
| 221 |
return |
| 222 |
|
| 223 |
else: |
| 224 |
with self.lock: |
| 225 |
heapq.heappush(self.jobs, (job.getNextWakeupTime(time.time()), job)) |
| 226 |
|
| 227 |
self._scheduleWakeup() |
| 228 |
|
| 229 |
def _scheduleJob(self, job: AbstractJob) -> None: |
| 230 |
"""adds job to the job list. |
| 231 |
|
| 232 |
This is basically like _rescheduleJob, except that this method makes |
| 233 |
sure that any other job with the same name is removed. |
| 234 |
""" |
| 235 |
lastStarted = self._unscheduleForName(job.name) |
| 236 |
job.lastStarted = lastStarted |
| 237 |
self._rescheduleJob(job) |
| 238 |
|
| 239 |
def _unscheduleForName(self, name: str) -> Optional[float]: |
| 240 |
"""removes all jobs named name from the job queue. |
| 241 |
""" |
| 242 |
toRemove = [] |
| 243 |
with self.lock: |
| 244 |
for index, (_, job) in enumerate(self.jobs): |
| 245 |
if job.name==name: |
| 246 |
toRemove.append(index) |
| 247 |
if not toRemove: |
| 248 |
return None |
| 249 |
|
| 250 |
toRemove.reverse() |
| 251 |
retval = self.jobs[toRemove[0]][1].lastStarted |
| 252 |
for index in toRemove: |
| 253 |
self.jobs.pop(index) |
| 254 |
heapq.heapify(self.jobs) |
| 255 |
return retval |
| 256 |
|
| 257 |
def _runNextJob(self) -> None: |
| 258 |
"""takes the next job off of the job queue and runs it. |
| 259 |
|
| 260 |
If the wakeup time of the next job is too far in the future, |
| 261 |
this does essentially nothing. |
| 262 |
""" |
| 263 |
with self.lock: |
| 264 |
if not self.jobs: |
| 265 |
return |
| 266 |
if self.jobs[0][0]>time.time()+0.1: |
| 267 |
# don't do anything on spurious wakeups |
| 268 |
self._scheduleWakeup() |
| 269 |
return |
| 270 |
|
| 271 |
jobTime, job = heapq.heappop(self.jobs) |
| 272 |
|
| 273 |
job.lastStarted = time.time() |
| 274 |
self._rescheduleJob(job) |
| 275 |
job.run() |
| 276 |
|
| 277 |
def _scheduleWakeup(self) -> None: |
| 278 |
"""makes the toplevel scheduler wake queue processing up when the |
| 279 |
next job is due. |
| 280 |
""" |
| 281 |
if not self.jobs: |
| 282 |
# Nothing to run; we'll be called when someone schedules something |
| 283 |
return |
| 284 |
nextWakeup = self.jobs[0][0] |
| 285 |
if self.scheduleFunction is not None: |
| 286 |
self.scheduleFunction( |
| 287 |
max(1, nextWakeup-time.time()), |
| 288 |
self._runNextJob) |
| 289 |
|
| 290 |
def runEvery(self, |
| 291 |
seconds: int, |
| 292 |
name: str, |
| 293 |
callable: Callable[[], None]) -> IntervalJob: |
| 294 |
"""schedules callable to be run every seconds. |
| 295 |
|
| 296 |
name must be a unique identifier for the "job". jobs with identical |
| 297 |
names overwrite each other. |
| 298 |
|
| 299 |
callable will be run in the main thread, so it must finish quickly |
| 300 |
or it will block the server. |
| 301 |
""" |
| 302 |
job = IntervalJob(seconds, name, callable) |
| 303 |
self._scheduleJob(job) |
| 304 |
return job |
| 305 |
|
| 306 |
def repeatAt(self, times: List[Tuple[Optional[int], Optional[int], int, int]], |
| 307 |
name: str, |
| 308 |
callable: Callable[[], None]) -> TimedJob: |
| 309 |
"""schedules callable to be run every day at times. |
| 310 |
|
| 311 |
times is a list of (day-of-month, day-of-week, hour, minute) tuples. |
| 312 |
day-of-month and/or day-of-week are 1-based and may be None (if both |
| 313 |
are non-None, day-of-week wins). |
| 314 |
|
| 315 |
name must be a unique identifier for the "job". jobs with identical |
| 316 |
names overwrite each other. |
| 317 |
|
| 318 |
callable will be run in the main thread, so it must finish quickly |
| 319 |
or it will block the server. |
| 320 |
""" |
| 321 |
job = TimedJob(times, name, callable) |
| 322 |
self._scheduleJob(job) |
| 323 |
return job |
| 324 |
|
| 325 |
def registerScheduleFunction(self, |
| 326 |
scheduleFunction: Callable[[float, Callable], None]) -> None: |
| 327 |
if self.scheduleFunction is None: |
| 328 |
self.scheduleFunction = scheduleFunction |
| 329 |
self._scheduleWakeup() |
| 330 |
else: |
| 331 |
if self.scheduleFunction is not scheduleFunction: |
| 332 |
raise TypeError("There already is a schedule function. Call" |
| 333 |
" clearScheduleFunction first if you want to override it.") |
| 334 |
|
| 335 |
def clearScheduleFunction(self) -> None: |
| 336 |
self.scheduleFunction = None |
| 337 |
|
| 338 |
def getQueueRepr(self) -> Sequence[Tuple[datetime.datetime, str]]: |
| 339 |
"""returns a sequence of (startDateTime local, job name) pairs. |
| 340 |
|
| 341 |
This is for inspection/debug purposes. |
| 342 |
""" |
| 343 |
with self.lock: |
| 344 |
schedule = self.jobs[:] |
| 345 |
return [(datetime.datetime.fromtimestamp(jobTime), job.name) |
| 346 |
for jobTime, job in schedule] |
| 347 |
|
| 348 |
|
| 349 |
_queue = Queue() |
| 350 |
runEvery = _queue.runEvery |
| 351 |
repeatAt = _queue.repeatAt |
| 352 |
registerScheduleFunction = _queue.registerScheduleFunction |
| 353 |
clearScheduleFunction = _queue.clearScheduleFunction |