Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/phabricator
Path: blob/master/src/infrastructure/daemon/workers/PhabricatorTriggerDaemon.php
12242 views
1
<?php
2
3
/**
4
* Schedule and execute event triggers, which run code at specific times.
5
*
6
* Also performs garbage collection of old logs, caches, etc.
7
*
8
* @task garbage Garbage Collection
9
*/
10
final class PhabricatorTriggerDaemon
11
extends PhabricatorDaemon {
12
13
const COUNTER_VERSION = 'trigger.version';
14
const COUNTER_CURSOR = 'trigger.cursor';
15
16
private $garbageCollectors;
17
private $nextCollection;
18
19
private $anyNuanceData;
20
private $nuanceSources;
21
private $nuanceCursors;
22
23
private $calendarEngine;
24
25
protected function run() {
26
27
// The trigger daemon is a low-level infrastructure daemon which schedules
28
// and executes chronological events. Examples include a subscription which
29
// generates a bill on the 12th of every month, or a reminder email 15
30
// minutes before a meeting.
31
32
// Only one trigger daemon can run at a time, and very little work should
33
// happen in the daemon process. In general, triggered events should
34
// just schedule a task into the normal daemon worker queue and then
35
// return. This allows the real work to take longer to execute without
36
// disrupting other triggers.
37
38
// The trigger mechanism guarantees that events will execute exactly once,
39
// but does not guarantee that they will execute at precisely the specified
40
// time. Under normal circumstances, they should execute within a minute or
41
// so of the desired time, so this mechanism can be used for things like
42
// meeting reminders.
43
44
// If the trigger queue backs up (for example, because it is overwhelmed by
45
// trigger updates, doesn't run for a while, or a trigger action is written
46
// inefficiently) or the daemon queue backs up (usually for similar
47
// reasons), events may execute an arbitrarily long time after they were
48
// scheduled to execute. In some cases (like billing a subscription) this
49
// may be desirable; in other cases (like sending a meeting reminder) the
50
// action may want to check the current time and see if the event is still
51
// relevant.
52
53
// The trigger daemon works in two phases:
54
//
55
// 1. A scheduling phase processes recently updated triggers and
56
// schedules them for future execution. For example, this phase would
57
// see that a meeting trigger had been changed recently, determine
58
// when the reminder for it should execute, and then schedule the
59
// action to execute at that future date.
60
// 2. An execution phase runs the actions for any scheduled events which
61
// are due to execute.
62
//
63
// The major goal of this design is to deliver on the guarantee that events
64
// will execute exactly once. It prevents race conditions in scheduling
65
// and execution by ensuring there is only one writer for either of these
66
// phases. Without this separation of responsibilities, web processes
67
// trying to reschedule events after an update could race with other web
68
// processes or the daemon.
69
70
// We want to start the first GC cycle right away, not wait 4 hours.
71
$this->nextCollection = PhabricatorTime::getNow();
72
73
do {
74
PhabricatorCaches::destroyRequestCache();
75
76
$lock = PhabricatorGlobalLock::newLock('trigger');
77
78
try {
79
$lock->lock(5);
80
} catch (PhutilLockException $ex) {
81
throw new PhutilProxyException(
82
pht(
83
'Another process is holding the trigger lock. Usually, this '.
84
'means another copy of the trigger daemon is running elsewhere. '.
85
'Multiple processes are not permitted to update triggers '.
86
'simultaneously.'),
87
$ex);
88
}
89
90
// Run the scheduling phase. This finds updated triggers which we have
91
// not scheduled yet and schedules them.
92
$last_version = $this->loadCurrentCursor();
93
$head_version = $this->loadCurrentVersion();
94
95
// The cursor points at the next record to process, so we can only skip
96
// this step if we're ahead of the version number.
97
if ($last_version <= $head_version) {
98
$this->scheduleTriggers($last_version);
99
}
100
101
// Run the execution phase. This finds events which are due to execute
102
// and runs them.
103
$this->executeTriggers();
104
105
$lock->unlock();
106
107
$sleep_duration = $this->getSleepDuration();
108
$sleep_duration = $this->runNuanceImportCursors($sleep_duration);
109
$sleep_duration = $this->runGarbageCollection($sleep_duration);
110
$sleep_duration = $this->runCalendarNotifier($sleep_duration);
111
112
if ($this->shouldHibernate($sleep_duration)) {
113
break;
114
}
115
116
$this->sleep($sleep_duration);
117
} while (!$this->shouldExit());
118
}
119
120
121
/**
122
* Process all of the triggers which have been updated since the last time
123
* the daemon ran, scheduling them into the event table.
124
*
125
* @param int Cursor for the next version update to process.
126
* @return void
127
*/
128
private function scheduleTriggers($cursor) {
129
$limit = 100;
130
131
$query = id(new PhabricatorWorkerTriggerQuery())
132
->setViewer($this->getViewer())
133
->withVersionBetween($cursor, null)
134
->setOrder(PhabricatorWorkerTriggerQuery::ORDER_VERSION)
135
->needEvents(true)
136
->setLimit($limit);
137
while (true) {
138
$triggers = $query->execute();
139
140
foreach ($triggers as $trigger) {
141
$event = $trigger->getEvent();
142
if ($event) {
143
$last_epoch = $event->getLastEventEpoch();
144
} else {
145
$last_epoch = null;
146
}
147
148
$next_epoch = $trigger->getNextEventEpoch(
149
$last_epoch,
150
$is_reschedule = false);
151
152
$new_event = PhabricatorWorkerTriggerEvent::initializeNewEvent($trigger)
153
->setLastEventEpoch($last_epoch)
154
->setNextEventEpoch($next_epoch);
155
156
$new_event->openTransaction();
157
if ($event) {
158
$event->delete();
159
}
160
161
// Always save the new event. Note that we save it even if the next
162
// epoch is `null`, indicating that it will never fire, because we
163
// would lose the last epoch information if we delete it.
164
//
165
// In particular, some events may want to execute exactly once.
166
// Retaining the last epoch allows them to do this, even if the
167
// trigger is updated.
168
$new_event->save();
169
170
// Move the cursor forward to make sure we don't reprocess this
171
// trigger until it is updated again.
172
$this->updateCursor($trigger->getTriggerVersion() + 1);
173
$new_event->saveTransaction();
174
}
175
176
// If we saw fewer than a full page of updated triggers, we're caught
177
// up, so we can move on to the execution phase.
178
if (count($triggers) < $limit) {
179
break;
180
}
181
182
// Otherwise, skip past the stuff we just processed and grab another
183
// page of updated triggers.
184
$min = last($triggers)->getTriggerVersion() + 1;
185
$query->withVersionBetween($min, null);
186
187
$this->stillWorking();
188
}
189
}
190
191
192
/**
193
* Run scheduled event triggers which are due for execution.
194
*
195
* @return void
196
*/
197
private function executeTriggers() {
198
199
// We run only a limited number of triggers before ending the execution
200
// phase. If we ran until exhaustion, we could end up executing very
201
// out-of-date triggers if there was a long backlog: trigger changes
202
// during this phase are not reflected in the event table until we run
203
// another scheduling phase.
204
205
// If we exit this phase with triggers still ready to execute we'll
206
// jump back into the scheduling phase immediately, so this just makes
207
// sure we don't spend an unreasonably long amount of time without
208
// processing trigger updates and doing rescheduling.
209
210
$limit = 100;
211
$now = PhabricatorTime::getNow();
212
213
$triggers = id(new PhabricatorWorkerTriggerQuery())
214
->setViewer($this->getViewer())
215
->setOrder(PhabricatorWorkerTriggerQuery::ORDER_EXECUTION)
216
->withNextEventBetween(null, $now)
217
->needEvents(true)
218
->setLimit($limit)
219
->execute();
220
foreach ($triggers as $trigger) {
221
$event = $trigger->getEvent();
222
223
// Execute the trigger action.
224
$trigger->executeTrigger(
225
$event->getLastEventEpoch(),
226
$event->getNextEventEpoch());
227
228
// Now that we've executed the trigger, the current trigger epoch is
229
// going to become the last epoch.
230
$last_epoch = $event->getNextEventEpoch();
231
232
// If this is a recurring trigger, give it an opportunity to reschedule.
233
$reschedule_epoch = $trigger->getNextEventEpoch(
234
$last_epoch,
235
$is_reschedule = true);
236
237
// Don't reschedule events unless the next occurrence is in the future.
238
if (($reschedule_epoch !== null) &&
239
($last_epoch !== null) &&
240
($reschedule_epoch <= $last_epoch)) {
241
throw new Exception(
242
pht(
243
'Trigger is attempting to perform a routine reschedule where '.
244
'the next event (at %s) does not occur after the previous event '.
245
'(at %s). Routine reschedules must strictly move event triggers '.
246
'forward through time to avoid executing a trigger an infinite '.
247
'number of times instantaneously.',
248
$reschedule_epoch,
249
$last_epoch));
250
}
251
252
$new_event = PhabricatorWorkerTriggerEvent::initializeNewEvent($trigger)
253
->setLastEventEpoch($last_epoch)
254
->setNextEventEpoch($reschedule_epoch);
255
256
$event->openTransaction();
257
// Remove the event we just processed.
258
$event->delete();
259
260
// See note in the scheduling phase about this; we save the new event
261
// even if the next epoch is `null`.
262
$new_event->save();
263
$event->saveTransaction();
264
}
265
}
266
267
268
/**
269
* Get the number of seconds to sleep for before starting the next scheduling
270
* phase.
271
*
272
* If no events are scheduled soon, we'll sleep briefly. Otherwise,
273
* we'll sleep until the next scheduled event.
274
*
275
* @return int Number of seconds to sleep for.
276
*/
277
private function getSleepDuration() {
278
$sleep = phutil_units('3 minutes in seconds');
279
280
$next_triggers = id(new PhabricatorWorkerTriggerQuery())
281
->setViewer($this->getViewer())
282
->setOrder(PhabricatorWorkerTriggerQuery::ORDER_EXECUTION)
283
->withNextEventBetween(0, null)
284
->setLimit(1)
285
->needEvents(true)
286
->execute();
287
if ($next_triggers) {
288
$next_trigger = head($next_triggers);
289
$next_epoch = $next_trigger->getEvent()->getNextEventEpoch();
290
$until = max(0, $next_epoch - PhabricatorTime::getNow());
291
$sleep = min($sleep, $until);
292
}
293
294
return $sleep;
295
}
296
297
298
/* -( Counters )----------------------------------------------------------- */
299
300
301
private function loadCurrentCursor() {
302
return $this->loadCurrentCounter(self::COUNTER_CURSOR);
303
}
304
305
private function loadCurrentVersion() {
306
return $this->loadCurrentCounter(self::COUNTER_VERSION);
307
}
308
309
private function updateCursor($value) {
310
LiskDAO::overwriteCounterValue(
311
id(new PhabricatorWorkerTrigger())->establishConnection('w'),
312
self::COUNTER_CURSOR,
313
$value);
314
}
315
316
private function loadCurrentCounter($counter_name) {
317
return (int)LiskDAO::loadCurrentCounterValue(
318
id(new PhabricatorWorkerTrigger())->establishConnection('w'),
319
$counter_name);
320
}
321
322
323
/* -( Garbage Collection )------------------------------------------------- */
324
325
326
/**
327
* Run the garbage collector for up to a specified number of seconds.
328
*
329
* @param int Number of seconds the GC may run for.
330
* @return int Number of seconds remaining in the time budget.
331
* @task garbage
332
*/
333
private function runGarbageCollection($duration) {
334
$run_until = (PhabricatorTime::getNow() + $duration);
335
336
// NOTE: We always run at least one GC cycle to make sure the GC can make
337
// progress even if the trigger queue is busy.
338
do {
339
$more_garbage = $this->updateGarbageCollection();
340
if (!$more_garbage) {
341
// If we don't have any more collection work to perform, we're all
342
// done.
343
break;
344
}
345
} while (PhabricatorTime::getNow() <= $run_until);
346
347
$remaining = max(0, $run_until - PhabricatorTime::getNow());
348
349
return $remaining;
350
}
351
352
353
/**
354
* Update garbage collection, possibly collecting a small amount of garbage.
355
*
356
* @return bool True if there is more garbage to collect.
357
* @task garbage
358
*/
359
private function updateGarbageCollection() {
360
// If we're ready to start the next collection cycle, load all the
361
// collectors.
362
$next = $this->nextCollection;
363
if ($next && (PhabricatorTime::getNow() >= $next)) {
364
$this->nextCollection = null;
365
366
$all_collectors = PhabricatorGarbageCollector::getAllCollectors();
367
$this->garbageCollectors = $all_collectors;
368
}
369
370
// If we're in a collection cycle, continue collection.
371
if ($this->garbageCollectors) {
372
foreach ($this->garbageCollectors as $key => $collector) {
373
$more_garbage = $collector->runCollector();
374
if (!$more_garbage) {
375
unset($this->garbageCollectors[$key]);
376
}
377
// We only run one collection per call, to prevent triggers from being
378
// thrown too far off schedule if there's a lot of garbage to collect.
379
break;
380
}
381
382
if ($this->garbageCollectors) {
383
// If we have more work to do, return true.
384
return true;
385
}
386
387
// Otherwise, reschedule another cycle in 4 hours.
388
$now = PhabricatorTime::getNow();
389
$wait = phutil_units('4 hours in seconds');
390
$this->nextCollection = $now + $wait;
391
}
392
393
return false;
394
}
395
396
397
/* -( Nuance Importers )--------------------------------------------------- */
398
399
400
private function runNuanceImportCursors($duration) {
401
$run_until = (PhabricatorTime::getNow() + $duration);
402
403
do {
404
$more_data = $this->updateNuanceImportCursors();
405
if (!$more_data) {
406
break;
407
}
408
} while (PhabricatorTime::getNow() <= $run_until);
409
410
$remaining = max(0, $run_until - PhabricatorTime::getNow());
411
412
return $remaining;
413
}
414
415
416
private function updateNuanceImportCursors() {
417
$nuance_app = 'PhabricatorNuanceApplication';
418
if (!PhabricatorApplication::isClassInstalled($nuance_app)) {
419
return false;
420
}
421
422
// If we haven't loaded sources yet, load them first.
423
if (!$this->nuanceSources && !$this->nuanceCursors) {
424
$this->anyNuanceData = false;
425
426
$sources = id(new NuanceSourceQuery())
427
->setViewer($this->getViewer())
428
->withIsDisabled(false)
429
->withHasImportCursors(true)
430
->execute();
431
if (!$sources) {
432
return false;
433
}
434
435
$this->nuanceSources = array_reverse($sources);
436
}
437
438
// If we don't have any cursors, move to the next source and generate its
439
// cursors.
440
if (!$this->nuanceCursors) {
441
$source = array_pop($this->nuanceSources);
442
443
$definition = $source->getDefinition()
444
->setViewer($this->getViewer())
445
->setSource($source);
446
447
$cursors = $definition->getImportCursors();
448
$this->nuanceCursors = array_reverse($cursors);
449
}
450
451
// Update the next cursor.
452
$cursor = array_pop($this->nuanceCursors);
453
if ($cursor) {
454
$more_data = $cursor->importFromSource();
455
if ($more_data) {
456
$this->anyNuanceData = true;
457
}
458
}
459
460
if (!$this->nuanceSources && !$this->nuanceCursors) {
461
return $this->anyNuanceData;
462
}
463
464
return true;
465
}
466
467
468
/* -( Calendar Notifier )-------------------------------------------------- */
469
470
471
private function runCalendarNotifier($duration) {
472
$run_until = (PhabricatorTime::getNow() + $duration);
473
474
if (!$this->calendarEngine) {
475
$this->calendarEngine = new PhabricatorCalendarNotificationEngine();
476
}
477
478
$this->calendarEngine->publishNotifications();
479
480
$remaining = max(0, $run_until - PhabricatorTime::getNow());
481
return $remaining;
482
}
483
484
}
485
486