Skip to content

Instantly share code, notes, and snippets.

@asp24
Last active October 18, 2019 20:34
Show Gist options
  • Save asp24/7767888 to your computer and use it in GitHub Desktop.
Save asp24/7767888 to your computer and use it in GitHub Desktop.
Script for flushing bytecode cache
<?php
/**
* Script for flushing bytecode cache
*
* usage:
* php flush_cache.php unix:///var/run/php5-fpm.sock
* php flush_cache.php 127.0.0.1 9000
*
* Change SECRET bellow before use!
* Latest version https://gist.github.com/asp24/7767888
*/
define('SECRET', 'changeme');
error_reporting(E_ALL);
/**
* FCGI Request client
* @see https://github.com/adoy/PHP-FastCGI-Client
*/
class Client
{
const VERSION_1 = 1;
const BEGIN_REQUEST = 1;
const ABORT_REQUEST = 2;
const END_REQUEST = 3;
const PARAMS = 4;
const STDIN = 5;
const STDOUT = 6;
const STDERR = 7;
const DATA = 8;
const GET_VALUES = 9;
const GET_VALUES_RESULT = 10;
const UNKNOWN_TYPE = 11;
const MAXTYPE = self::UNKNOWN_TYPE;
const RESPONDER = 1;
const AUTHORIZER = 2;
const FILTER = 3;
const REQUEST_COMPLETE = 0;
const CANT_MPX_CONN = 1;
const OVERLOADED = 2;
const UNKNOWN_ROLE = 3;
const MAX_CONNS = 'MAX_CONNS';
const MAX_REQS = 'MAX_REQS';
const MPXS_CONNS = 'MPXS_CONNS';
const HEADER_LEN = 8;
/**
* Socket
* @var Resource
*/
private $_sock = null;
/**
* Host
* @var String
*/
private $_host = null;
/**
* Port
* @var Integer
*/
private $_port = null;
/**
* Keep Alive
* @var Boolean
*/
private $_keepAlive = false;
/**
* Constructor
*
* @param String $host Host of the FastCGI application
* @param Integer $port Port of the FastCGI application
*/
public function __construct($host, $port)
{
$this->_host = $host;
$this->_port = $port;
}
/**
* Define whether or not the FastCGI application should keep the connection
* alive at the end of a request
*
* @param Boolean $b true if the connection should stay alive, false otherwise
*/
public function setKeepAlive($b)
{
$this->_keepAlive = (boolean)$b;
if (!$this->_keepAlive && $this->_sock) {
fclose($this->_sock);
}
}
/**
* Get the keep alive status
*
* @return Boolean true if the connection should stay alive, false otherwise
*/
public function getKeepAlive()
{
return $this->_keepAlive;
}
/**
* Create a connection to the FastCGI application
*/
private function connect()
{
if (!$this->_sock) {
$this->_sock = fsockopen($this->_host, $this->_port, $errno, $errstr, 5);
if (!$this->_sock) {
throw new \Exception('Unable to connect to FastCGI application');
}
}
}
/**
* Build a FastCGI packet
*
* @param Integer $type Type of the packet
* @param String $content Content of the packet
* @param Integer $requestId RequestId
*
* @return string
*/
private function buildPacket($type, $content, $requestId = 1)
{
$clen = strlen($content);
return chr(self::VERSION_1) /* version */
. chr($type) /* type */
. chr(($requestId >> 8) & 0xFF) /* requestIdB1 */
. chr($requestId & 0xFF) /* requestIdB0 */
. chr(($clen >> 8) & 0xFF) /* contentLengthB1 */
. chr($clen & 0xFF) /* contentLengthB0 */
. chr(0) /* paddingLength */
. chr(0) /* reserved */
. $content; /* content */
}
/**
* Build an FastCGI Name value pair
*
* @param String $name Name
* @param String $value Value
* @return String FastCGI Name value pair
*/
private function buildNvpair($name, $value)
{
$nLen = strlen($name);
$vLen = strlen($value);
if ($nLen < 128) {
/* nameLengthB0 */
$nvPair = chr($nLen);
} else {
/* nameLengthB3 & nameLengthB2 & nameLengthB1 & nameLengthB0 */
$nvPair =
chr(($nLen >> 24) | 0x80) .
chr(($nLen >> 16) & 0xFF) .
chr(($nLen >> 8) & 0xFF) .
chr($nLen & 0xFF);
}
if ($vLen < 128) {
/* valueLengthB0 */
$nvPair .= chr($vLen);
} else {
/* valueLengthB3 & valueLengthB2 & valueLengthB1 & valueLengthB0 */
$nvPair .=
chr(($vLen >> 24) | 0x80) .
chr(($vLen >> 16) & 0xFF) .
chr(($vLen >> 8) & 0xFF) .
chr($vLen & 0xFF);
}
/* nameData & valueData */
return $nvPair . $name . $value;
}
/**
* Read a set of FastCGI Name value pairs
*
* @param string $data Data containing the set of FastCGI NVPair
* @param int|null $length Data length
*
* @return string[] array of NVPair
*/
private function readNvPair($data, $length = null)
{
$array = array();
if ($length === null) {
$length = strlen($data);
}
$p = 0;
while ($p != $length) {
$nLen = ord($data{$p++});
if ($nLen >= 128) {
$nLen = ($nLen & 0x7F << 24);
$nLen |= (ord($data{$p++}) << 16);
$nLen |= (ord($data{$p++}) << 8);
$nLen |= (ord($data{$p++}));
}
$vLen = ord($data{$p++});
if ($vLen >= 128) {
$vLen = ($nLen & 0x7F << 24);
$vLen |= (ord($data{$p++}) << 16);
$vLen |= (ord($data{$p++}) << 8);
$vLen |= (ord($data{$p++}));
}
$array[substr($data, $p, $nLen)] = substr($data, $p + $nLen, $vLen);
$p += ($nLen + $vLen);
}
return $array;
}
/**
* Decode a FastCGI Packet
*
* @param string $data String containing all the packet
*
* @return array
*/
private function decodePacketHeader($data)
{
$ret = array();
$ret['version'] = ord($data{0});
$ret['type'] = ord($data{1});
$ret['requestId'] = (ord($data{2}) << 8) + ord($data{3});
$ret['contentLength'] = (ord($data{4}) << 8) + ord($data{5});
$ret['paddingLength'] = ord($data{6});
$ret['reserved'] = ord($data{7});
return $ret;
}
/**
* Read a FastCGI Packet
*
* @return array
*/
private function readPacket()
{
if ($packet = fread($this->_sock, self::HEADER_LEN)) {
$resp = $this->decodePacketHeader($packet);
$resp['content'] = '';
if ($resp['contentLength']) {
$len = $resp['contentLength'];
while ($len && $buf = fread($this->_sock, $len)) {
$len -= strlen($buf);
$resp['content'] .= $buf;
}
}
if ($resp['paddingLength']) {
$buf = fread($this->_sock, $resp['paddingLength']);
}
return $resp;
} else {
return false;
}
}
/**
* Get Informations on the FastCGI application
*
* @param array $requestedInfo information to retrieve
*
* @return array
* @throws Exception
*/
public function getValues(array $requestedInfo)
{
$this->connect();
$request = '';
foreach ($requestedInfo as $info) {
$request .= $this->buildNvpair($info, '');
}
fwrite($this->_sock, $this->buildPacket(self::GET_VALUES, $request, 0));
$resp = $this->readPacket();
if ($resp['type'] == self::GET_VALUES_RESULT) {
return $this->readNvPair($resp['content'], $resp['length']);
} else {
throw new Exception('Unexpected response type, expecting GET_VALUES_RESULT');
}
}
/**
* Execute a request to the FastCGI application
*
* @param array $params Array of parameters
* @param string $stdin Content
*
* @return string
* @throws Exception
*/
public function request(array $params, $stdin)
{
$response = '';
$this->connect();
$request = $this->buildPacket(
self::BEGIN_REQUEST,
chr(0) . chr(self::RESPONDER) . chr((int)$this->_keepAlive) . str_repeat(chr(0), 5)
);
$paramsRequest = '';
foreach ($params as $key => $value) {
$paramsRequest .= $this->buildNvpair($key, $value);
}
if ($paramsRequest) {
$request .= $this->buildPacket(self::PARAMS, $paramsRequest);
}
$request .= $this->buildPacket(self::PARAMS, '');
if ($stdin) {
$request .= $this->buildPacket(self::STDIN, $stdin);
}
$request .= $this->buildPacket(self::STDIN, '');
fwrite($this->_sock, $request);
do {
$resp = $this->readPacket();
if ($resp['type'] == self::STDOUT || $resp['type'] == self::STDERR) {
$response .= $resp['content'];
}
} while ($resp && $resp['type'] != self::END_REQUEST);
if (!is_array($resp)) {
throw new Exception('Bad request');
}
switch (ord($resp['content']{4})) {
case self::CANT_MPX_CONN:
throw new \Exception('This app can\'t multiplex [CANT_MPX_CONN]');
break;
case self::OVERLOADED:
throw new \Exception('New request rejected; too busy [OVERLOADED]');
break;
case self::UNKNOWN_ROLE:
throw new \Exception('Role value not known [UNKNOWN_ROLE]');
break;
case self::REQUEST_COMPLETE:
return $response;
}
}
}
class CacheFlusher
{
const APC = 'APC';
const XCACHE = 'xcache';
const OP_CACHE = 'opcache';
protected function parseBoolIniSettings($varName)
{
$val = ini_get($varName);
return filter_var($val, FILTER_VALIDATE_BOOLEAN);
}
protected function getEnabledCache()
{
$result = array();
if (extension_loaded('xcache') && $this->parseBoolIniSettings('xcache.cacher')) {
$result[] = self::XCACHE;
}
if ((extension_loaded('opcache') || extension_loaded('Zend OPcache')) &&
$this->parseBoolIniSettings('opcache.enable')
) {
$result[] = self::OP_CACHE;
}
if (extension_loaded('apc') && $this->parseBoolIniSettings('apc.enabled')) {
$result[] = self::APC;
}
return $result;
}
protected function flushXCache()
{
xcache_clear_cache(XC_TYPE_PHP);
}
protected function flushOpCache()
{
opcache_reset();
}
protected function flushAPCCache()
{
apc_clear_cache();
}
protected function flushCacheForExtension($extension)
{
switch ($extension) {
case self::APC:
$this->flushAPCCache();
break;
case self::OP_CACHE:
$this->flushOpCache();
break;
case self::XCACHE:
$this->flushXCache();
break;
}
}
public function flush()
{
clearstatcache(true);
foreach ($this->getEnabledCache() as $cache) {
$this->flushCacheForExtension($cache);
}
}
}
function make_request($argc, $argv)
{
if ($argc < 2) {
echo basename(__FILE__), ': Path to fcgi server not defined', PHP_EOL;
return 1;
}
$host = $argv[1];
$port = isset($argv[2]) ? intval($argv[2]) : null;
$content = '';
$client = new Client($host, $port);
$response = $client->request(
array(
'GATEWAY_INTERFACE' => 'FastCGI/1.0',
'REQUEST_METHOD' => 'POST',
'SCRIPT_NAME' => basename(__FILE__),
'SCRIPT_FILENAME' => __FILE__,
'REMOTE_ADDR' => '127.0.0.1',
'SERVER_ADDR' => '127.0.0.1',
'SERVER_PROTOCOL' => 'HTTP/1.0',
'SERVER_SECRET' => SECRET,
'CONTENT_TYPE' => 'text/html',
'CONTENT_LENGTH' => strlen($content),
), $content
);
if (preg_match('/status\:\s?(\d+)/i', $response, $m) === 0) {
return 0;
}
return $m[1] == '200' ? 0 : 1;
}
if (PHP_SAPI === 'cli') {
exit(make_request($argc, $argv));
} else {
if (
$_SERVER['SERVER_SECRET'] !== SECRET ||
$_SERVER['SERVER_ADDR'] !== '127.0.0.1' ||
$_SERVER['REMOTE_ADDR'] !== '127.0.0.1'
) {
http_response_code(403);
exit();
}
if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST') {
http_response_code(405);
exit();
}
(new CacheFlusher())->flush();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment