Skip to content

Instantly share code, notes, and snippets.

@dpb587
Created January 14, 2013 17:30
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save dpb587/4531728 to your computer and use it in GitHub Desktop.
Save dpb587/4531728 to your computer and use it in GitHub Desktop.
Terminating Gearman Workers in PHP - locally and remotely stopping workers without interrupting jobs.

Details

Related blog post: dpb587.me/blog/2013/01/14/terminating-gearman-workers-in-php.html

License

MIT License (http://opensource.org/licenses/mit-license.php)

Copyright (c) 2013 Danny Berger <dpb587@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<?php
$gearman = new GearmanClient();
$gearman->addServer();
$gearman->doBackground(
$_SERVER['argv'][1],
isset($_SERVER['argv'][2]) ? $_SERVER['argv'][2] : ''
);
<?php
// connect to gearman
if (false === $sh = fsockopen('127.0.0.1', '4730', $errno, $errstr, 10)) {
fwrite(STDERR, sprintf('Unable to connect to gearman: %s: %s', $errno, $errstr) . "\n");
exit(1);
}
fwrite($sh, "status\n");
$workers = array();
$gearman = new GearmanClient();
$gearman->addServer();
// find running workers and ask them to terminate
while ((!feof($sh)) && (".\n" !== $line = fgets($sh))) {
if (preg_match('/^_worker_([^\s]+)\s+\d+\s+\d+\s+(\d+)/', $line, $match)) {
if ($match[2]) {
fwrite(STDOUT, sprintf('[%s] UP %s', date('H:i:s'), $match[1]) . "\n");
$workers[$match[1]] = $gearman->doHighBackground(
'_worker_' . $match[1],
'terminate',
$match[1]
);
}
}
}
fclose($sh);
// callback to update the list of who is still down
$gearman->setStatusCallback(
function (GearmanTask $task, $context) use (&$workers) {
if (!$task->isKnown()) {
unset($workers[$context]);
fwrite(STDOUT, sprintf('[%s] DOWN %s', date('H:i:s'), $context) . "\n");
}
}
);
$loop = 0;
// poll gearman about the termination jobs
do {
foreach ($workers as $worker => $handle) {
$gearman->addTaskStatus($handle, $worker);
}
$gearman->runTasks();
if ((0 == ++ $loop % 20) && ($workers)) {
// remind who is still down every 10 seconds
fwrite(STDOUT, sprintf('[%s] waiting for: %s', date('H:i:s'), implode(' ', array_keys($workers))) . "\n");
}
usleep(500000);
} while ($workers);
<?php
declare(ticks = 1);
$context = array(
// ought to be unique within the server's workforce
'id' => $_SERVER['argv'][1],
'pid' => getmypid(),
'terminate' => false,
);
pcntl_signal(
SIGTERM,
function () use (&$context) {
fwrite(STDOUT, sprintf('[%s] SIGTERM %s', date('H:i:s'), $context['id']) . "\n");
$context['terminate'] = true;
}
);
$worker = new GearmanWorker();
$worker->addOptions(GEARMAN_WORKER_NON_BLOCKING);
// maximum time that gearman will block from userspace code
$worker->setTimeout(2500);
$worker->addServer();
$worker->addFunction(
'sleep',
function ($job) use ($context) {
fwrite(STDOUT, sprintf('[%s] ASLEEP %s', date('H:i:s'), $context['id']) . "\n");
for ($i = 0; $i < $job->workload(); $i ++) {
// signals interrupt sleep, so loop for one second instead
sleep(1);
}
fwrite(STDOUT, sprintf('[%s] AWAKE %s', date('H:i:s'), $context['id']) . "\n");
}
);
$worker->addFunction(
'_worker_' . $context['id'],
function (GearmanJob $job) use ($context) {
switch ($job->workload()) {
case 'terminate':
posix_kill($context['pid'], SIGTERM); # exec(sprintf('/bin/kill -s TERM %d', $context['pid']));
break;
}
}
);
fwrite(STDOUT, sprintf('[%s] READY %s (%d)', date('H:i:s'), $context['id'], $context['pid']) . "\n");
// work on jobs as they're available
while (
(!$context['terminate'])
&& (
$worker->work()
|| (GEARMAN_IO_WAIT == $worker->returnCode())
|| (GEARMAN_NO_JOBS == $worker->returnCode())
)
) {
if (GEARMAN_SUCCESS == $worker->returnCode()) {
continue;
}
$worker->wait();
}
$worker->unregisterAll();
fwrite(STDOUT, sprintf('[%s] EXIT %s', date('H:i:s'), $context['id']) . "\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment