Skip to content

Commit

Permalink
Merge branch 'MDL-59594-SIGINT' of https://github.com/brendanheywood/…
Browse files Browse the repository at this point in the history
  • Loading branch information
abgreeve committed Jan 20, 2020
2 parents d29c986 + b15c53f commit c282319
Show file tree
Hide file tree
Showing 7 changed files with 142 additions and 20 deletions.
2 changes: 2 additions & 0 deletions admin/cli/cron.php
Expand Up @@ -74,4 +74,6 @@
die;
}

\core\local\cli\shutdown::script_supports_graceful_exit();

cron_run();
2 changes: 2 additions & 0 deletions admin/tool/task/cli/adhoc_task.php
Expand Up @@ -115,5 +115,7 @@
$humantimenow = date('r', time());
$keepalive = (int)$options['keep-alive'];

\core\local\cli\shutdown::script_supports_graceful_exit();

mtrace("Server Time: {$humantimenow}\n");
cron_run_adhoc_tasks(time(), $keepalive, $checklimits);
2 changes: 2 additions & 0 deletions lang/en/admin.php
Expand Up @@ -120,6 +120,8 @@
$string['cleanup'] = 'Cleanup';
$string['clianswerno'] = 'n';
$string['cliansweryes'] = 'y';
$string['cliexitgraceful'] = 'Exiting gracefully, please wait ...';
$string['cliexitnow'] = 'Exiting right NOW';
$string['cliincorrectvalueerror'] = 'Error, incorrect value "{$a->value}" for "{$a->option}"';
$string['cliincorrectvalueretry'] = 'Incorrect value, please retry';
$string['clistatusdisabled'] = 'Status: disabled';
Expand Down
81 changes: 81 additions & 0 deletions lib/classes/local/cli/shutdown.php
@@ -0,0 +1,81 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

/**
* CLI script shutdown helper class.
*
* @package core
* @copyright 2019 Brendan Heywood <brendan@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

namespace core\local\cli;

defined('MOODLE_INTERNAL') || die();

/**
* CLI script shutdown helper class.
*
* @package core
* @copyright 2019 Brendan Heywood <brendan@catalyst-au.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class shutdown {

/** @var bool Should we exit gracefully at the next opportunity? */
protected static $cligracefulexit = false;

/**
* Declares that this CLI script can gracefully handle signals
*
* @return void
*/
public static function script_supports_graceful_exit(): void {
\core_shutdown_manager::register_signal_handler('\core\local\cli\shutdown::signal_handler');
}

/**
* Should we gracefully exit?
*
* @return bool true if we should gracefully exit
*/
public static function should_gracefully_exit(): bool {
return self::$cligracefulexit;
}

/**
* Handle the signal
*
* The first signal flags a graceful exit. If a second signal is received
* then it immediately exits.
*
* @param int $signo The signal number
* @return bool true if we should exit
*/
public static function signal_handler(int $signo): bool {

if (self::$cligracefulexit) {
cli_heading(get_string('cliexitnow', 'admin'));
return true;
}

cli_heading(get_string('cliexitgraceful', 'admin'));
self::$cligracefulexit = true;
return false;
}

}

67 changes: 50 additions & 17 deletions lib/classes/shutdown_manager.php
Expand Up @@ -33,7 +33,9 @@
*/
class core_shutdown_manager {
/** @var array list of custom callbacks */
protected static $callbacks = array();
protected static $callbacks = [];
/** @var array list of custom signal callbacks */
protected static $signalcallbacks = [];
/** @var bool is this manager already registered? */
protected static $registered = false;

Expand Down Expand Up @@ -66,7 +68,7 @@ public static function initialize() {
*
* @param int $signo The signal being handled
*/
public static function signal_handler($signo) {
public static function signal_handler(int $signo) {
// Note: There is no need to manually call the shutdown handler.
// The fact that we are calling exit() in this script means that the standard shutdown handling is performed
// anyway.
Expand All @@ -92,17 +94,57 @@ public static function signal_handler($signo) {
$exitcode = 1;
}

exit ($exitcode);
// Normally we should exit unless a callback tells us to wait.
$shouldexit = true;
foreach (self::$signalcallbacks as $data) {
list($callback, $params) = $data;
try {
array_unshift($params, $signo);
$shouldexit = call_user_func_array($callback, $params) && $shouldexit;
} catch (Throwable $e) {
// @codingStandardsIgnoreStart
error_log('Exception ignored in signal function ' . get_callable_name($callback) . ': ' . $e->getMessage());
// @codingStandardsIgnoreEnd
}
}

if ($shouldexit) {
exit ($exitcode);
}
}

/**
* Register custom signal handler function.
*
* If a handler returns false the signal will be ignored.
*
* @param callable $callback
* @param array $params
* @return void
*/
public static function register_signal_handler($callback, array $params = null): void {
if (!is_callable($callback)) {
// @codingStandardsIgnoreStart
error_log('Invalid custom signal function detected ' . var_export($callback, true));
// @codingStandardsIgnoreEnd
}
self::$signalcallbacks[] = [$callback, $params ?? []];
}

/**
* Register custom shutdown function.
*
* @param callable $callback
* @param array $params
* @return void
*/
public static function register_function($callback, array $params = null) {
self::$callbacks[] = array($callback, $params);
public static function register_function($callback, array $params = null): void {
if (!is_callable($callback)) {
// @codingStandardsIgnoreStart
error_log('Invalid custom shutdown function detected '.var_export($callback, true));
// @codingStandardsIgnoreEnd
}
self::$callbacks[] = [$callback, $params ?? []];
}

/**
Expand All @@ -115,20 +157,11 @@ public static function shutdown_handler() {
foreach (self::$callbacks as $data) {
list($callback, $params) = $data;
try {
if (!is_callable($callback)) {
error_log('Invalid custom shutdown function detected '.var_export($callback, true));
continue;
}
if ($params === null) {
call_user_func($callback);
} else {
call_user_func_array($callback, $params);
}
} catch (Exception $e) {
error_log('Exception ignored in shutdown function '.get_callable_name($callback).': '.$e->getMessage());
call_user_func_array($callback, $params);
} catch (Throwable $e) {
// Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
// @codingStandardsIgnoreStart
error_log('Exception ignored in shutdown function '.get_callable_name($callback).': '.$e->getMessage());
// @codingStandardsIgnoreEnd
}
}

Expand Down
6 changes: 4 additions & 2 deletions lib/cronlib.php
Expand Up @@ -114,7 +114,8 @@ function cron_run_scheduled_tasks(int $timenow) {

// Run all scheduled tasks.
try {
while (!\core\task\manager::static_caches_cleared_since($timenow) &&
while (!\core\local\cli\shutdown::should_gracefully_exit() &&
!\core\task\manager::static_caches_cleared_since($timenow) &&
$task = \core\task\manager::get_next_scheduled_task($timenow)) {
cron_run_inner_scheduled_task($task);
unset($task);
Expand Down Expand Up @@ -167,7 +168,8 @@ function cron_run_adhoc_tasks(int $timenow, $keepalive = 0, $checklimits = true)
$taskcount = 0;

// Run all adhoc tasks.
while (!\core\task\manager::static_caches_cleared_since($timenow)) {
while (!\core\local\cli\shutdown::should_gracefully_exit() &&
!\core\task\manager::static_caches_cleared_since($timenow)) {

if ($checklimits && (time() - $timenow) >= $maxruntime) {
if ($waiting) {
Expand Down
2 changes: 1 addition & 1 deletion version.php
Expand Up @@ -29,7 +29,7 @@

defined('MOODLE_INTERNAL') || die();

$version = 2020011700.00; // YYYYMMDD = weekly release date of this DEV branch.
$version = 2020011700.01; // YYYYMMDD = weekly release date of this DEV branch.
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.
$release = '3.9dev (Build: 20200117)'; // Human-friendly version name
Expand Down

0 comments on commit c282319

Please sign in to comment.