max_execution_time與request_terminate_timeout
之前一直沒搞清楚這兩個超時設置的關系,今天搞明白了順便記一下。
max_execution_time是PHP執行超時時間,在php.ini中配置,cli下為0(即不生效),觸發時會在phperror日志中輸出如下:
PHP Fatal error: Maximum execution time of 10 seconds exceeded in /usr/local/nginx/html/index.php on line 4
request_terminate_timeout是fpm中的超時選項,在php-fpm.conf中配置,觸發時會在php-fpm.log日志中輸出如下:
WARNING: [pool www] child 64761, script '/usr/local/nginx/html/index.php' (request: "GET /index.php") execution timed out (10.061351 sec), terminating
WARNING: [pool www] child 64761 exited on signal 15 (SIGTERM) after 1547.025796 seconds from start
[pool www] child 66843 started
可以看到,work進程因為超時被殺掉并重啟了新的work進程,同時頁面也會返回502錯誤。
那么這兩個選項到底有什么不同,線上該如何配置?
max_execution_time
搜索PHP源碼,在腳本執行代碼里看到:
PHPAPI int php_execute_script(zend_file_handle *primary_file)
if (PG(max_input_time) != -1) {
#ifdef PHP_WIN32
zend_unset_timeout();
#endif
zend_set_timeout(INI_INT("max_execution_time"), 0);
}
這里設置了定時器,再看zend_set_timeout:
void zend_set_timeout(zend_long seconds, int reset_signals) /* {{{ */
{
EG(timeout_seconds) = seconds;
zend_set_timeout_ex(seconds, reset_signals);
EG(timed_out) = 0;
}
在zend_set_timeout_ex中使用到了setitimer()方法:
# ifdef __CYGWIN__
setitimer(ITIMER_REAL, &t_r, NULL);
}
signo = SIGALRM;
# else
setitimer(ITIMER_PROF, &t_r, NULL);
}
signo = SIGPROF;
# endif
這有個分支,由于我們環境走的是else,先分析setitimer(ITIMER_PROF, &t_r, NULL);
搜索了下setitimer()的定義和說明:
int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue);
參數:
which:間歇計時器類型,有三種選擇
ITIMER_REAL //數值為0,計時器的值實時遞減,發送的信號是SIGALRM。
ITIMER_VIRTUAL //數值為1,進程執行時遞減計時器的值,發送的信號是SIGVTALRM。
ITIMER_PROF //數值為2,進程和系統執行時都遞減計時器的值,發送的信號是SIGPROF。
也就是說這里使用的ITIMER_PROF模式表示的是進程的用戶及系統狀態執行時間(即占用cpu時間),那么像I\O操作及sleep等造成進程阻塞而掛起的時間是不計算在內的。
為了驗證我的結論,試驗了一下
例1
如果sleep超時,index.php:
<?php
$i = 0;
sleep(12);
echo "hello world";
php.ini:
max_execution_time = 10
為不受request_terminate_timeout影響,設置
request_terminate_timeout = 30
請求訪問:
在等待一段時間后,頁面成功顯示hello world
例2
如果改為cpu忙碌超時,index.php:
<?php
$i = 0;
while(1) {
$i = 1;
}
echo "hello world";
請求訪問:
在等待一段時間后,頁面500
phperror.log
Fatal error: Maximum execution time of 10 seconds exceeded in /usr/local/nginx/html/index.php on line 4
這樣證明了ITIMER_PROF確實只是在進程執行的過程才會計時,也就時max_execution_time表示進程執行總超時時間
由于ITIMER_REAL表示實時計時時間,試著把ITIMER_PROF改為ITIMER_REAL,重新編譯PHP,重啟php-fpm,再來測試例1
結果如下:
在等待一段時間后,頁面502
php-fpm.log
[pool www] child 16233 exited on signal 14 (SIGALRM) after 21.457062 seconds from start
[pool www] child 16254 started
可以看到,SIGALRM正是ITIMER_REAL模式超時發送的信號,也就是說把ITIMER_PROF改成ITIMER_REAL,可以使max_execution_time達到和request_terminate_timeout一樣的效果。
request_terminate_timeout
而我們知道,一次請求執行的最大時間,超時就會被殺掉,一般來說,請求執行時長要遠遠大于進程在cpu中實際執行時間。因此,我們經常會看到,request_terminate_timeout首先生效,而max_execution_time卻很難觸發。