3 * Squid and Varnish cache purging.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * An HTTP 1.0 client built for the purposes of purging Squid and Varnish.
25 * Uses asynchronous I/O, allowing purges to be done in a highly parallel
28 * Could be replaced by curl_multi_exec() or some such.
30 class SquidPurgeClient
{
31 var $host, $port, $ip;
33 var $readState = 'idle';
34 var $writeBuffer = '';
35 var $requests = array();
36 var $currentRequestIndex;
40 const EINPROGRESS
= 115;
41 const BUFFER_SIZE
= 8192;
44 * The socket resource, or null for unconnected, or false for disabled due to error
53 * @param $server string
54 * @param $options array
56 public function __construct( $server, $options = array() ) {
57 $parts = explode( ':', $server, 2 );
58 $this->host
= $parts[0];
59 $this->port
= isset( $parts[1] ) ?
$parts[1] : 80;
63 * Open a socket if there isn't one open already, return it.
64 * Returns false on error.
66 * @return bool|resource
68 protected function getSocket() {
69 if ( $this->socket
!== null ) {
75 $this->log( "DNS error" );
79 $this->socket
= socket_create( AF_INET
, SOCK_STREAM
, SOL_TCP
);
80 socket_set_nonblock( $this->socket
);
82 $ok = socket_connect( $this->socket
, $ip, $this->port
);
85 $error = socket_last_error( $this->socket
);
86 if ( $error !== self
::EINPROGRESS
) {
87 $this->log( "connection error: " . socket_strerror( $error ) );
97 * Get read socket array for select()
100 public function getReadSocketsForSelect() {
101 if ( $this->readState
== 'idle' ) {
104 $socket = $this->getSocket();
105 if ( $socket === false ) {
108 return array( $socket );
112 * Get write socket array for select()
115 public function getWriteSocketsForSelect() {
116 if ( !strlen( $this->writeBuffer
) ) {
119 $socket = $this->getSocket();
120 if ( $socket === false ) {
123 return array( $socket );
127 * Get the host's IP address.
128 * Does not support IPv6 at present due to the lack of a convenient interface in PHP.
130 protected function getIP() {
131 if ( $this->ip
=== null ) {
132 if ( IP
::isIPv4( $this->host
) ) {
133 $this->ip
= $this->host
;
134 } elseif ( IP
::isIPv6( $this->host
) ) {
135 throw new MWException( '$wgSquidServers does not support IPv6' );
137 wfSuppressWarnings();
138 $this->ip
= gethostbyname( $this->host
);
139 if ( $this->ip
=== $this->host
) {
149 * Close the socket and ignore any future purge requests.
150 * This is called if there is a protocol error.
152 protected function markDown() {
154 $this->socket
= false;
158 * Close the socket but allow it to be reopened for future purge requests
160 public function close() {
161 if ( $this->socket
) {
162 wfSuppressWarnings();
163 socket_set_block( $this->socket
);
164 socket_shutdown( $this->socket
);
165 socket_close( $this->socket
);
168 $this->socket
= null;
169 $this->readBuffer
= '';
170 // Write buffer is kept since it may contain a request for the next socket
174 * Queue a purge operation
178 public function queuePurge( $url ) {
179 $url = SquidUpdate
::expand( str_replace( "\n", '', $url ) );
180 $this->requests
[] = "PURGE $url HTTP/1.0\r\n" .
181 "Connection: Keep-Alive\r\n" .
182 "Proxy-Connection: Keep-Alive\r\n" .
183 "User-Agent: " . Http
::userAgent() . ' ' . __CLASS__
. "\r\n\r\n";
184 if ( $this->currentRequestIndex
=== null ) {
185 $this->nextRequest();
192 public function isIdle() {
193 return strlen( $this->writeBuffer
) == 0 && $this->readState
== 'idle';
197 * Perform pending writes. Call this when socket_select() indicates that writing will not block.
199 public function doWrites() {
200 if ( !strlen( $this->writeBuffer
) ) {
203 $socket = $this->getSocket();
208 if ( strlen( $this->writeBuffer
) <= self
::BUFFER_SIZE
) {
209 $buf = $this->writeBuffer
;
212 $buf = substr( $this->writeBuffer
, 0, self
::BUFFER_SIZE
);
215 wfSuppressWarnings();
216 $bytesSent = socket_send( $socket, $buf, strlen( $buf ), $flags );
219 if ( $bytesSent === false ) {
220 $error = socket_last_error( $socket );
221 if ( $error != self
::EAGAIN
&& $error != self
::EINTR
) {
222 $this->log( 'write error: ' . socket_strerror( $error ) );
228 $this->writeBuffer
= substr( $this->writeBuffer
, $bytesSent );
232 * Read some data. Call this when socket_select() indicates that the read buffer is non-empty.
234 public function doReads() {
235 $socket = $this->getSocket();
241 wfSuppressWarnings();
242 $bytesRead = socket_recv( $socket, $buf, self
::BUFFER_SIZE
, 0 );
244 if ( $bytesRead === false ) {
245 $error = socket_last_error( $socket );
246 if ( $error != self
::EAGAIN
&& $error != self
::EINTR
) {
247 $this->log( 'read error: ' . socket_strerror( $error ) );
251 } elseif ( $bytesRead === 0 ) {
257 $this->readBuffer
.= $buf;
258 while ( $this->socket
&& $this->processReadBuffer() === 'continue' );
262 * @throws MWException
265 protected function processReadBuffer() {
266 switch ( $this->readState
) {
271 $lines = explode( "\r\n", $this->readBuffer
, 2 );
272 if ( count( $lines ) < 2 ) {
275 if ( $this->readState
== 'status' ) {
276 $this->processStatusLine( $lines[0] );
278 $this->processHeaderLine( $lines[0] );
280 $this->readBuffer
= $lines[1];
283 if ( $this->bodyRemaining
!== null ) {
284 if ( $this->bodyRemaining
> strlen( $this->readBuffer
) ) {
285 $this->bodyRemaining
-= strlen( $this->readBuffer
);
286 $this->readBuffer
= '';
289 $this->readBuffer
= substr( $this->readBuffer
, $this->bodyRemaining
);
290 $this->bodyRemaining
= 0;
291 $this->nextRequest();
295 // No content length, read all data to EOF
296 $this->readBuffer
= '';
300 throw new MWException( __METHOD__
.': unexpected state' );
308 protected function processStatusLine( $line ) {
309 if ( !preg_match( '!^HTTP/(\d+)\.(\d+) (\d{3}) (.*)$!', $line, $m ) ) {
310 $this->log( 'invalid status line' );
314 list( , , , $status, $reason ) = $m;
315 $status = intval( $status );
316 if ( $status !== 200 && $status !== 404 ) {
317 $this->log( "unexpected status code: $status $reason" );
321 $this->readState
= 'header';
325 * @param $line string
327 protected function processHeaderLine( $line ) {
328 if ( preg_match( '/^Content-Length: (\d+)$/i', $line, $m ) ) {
329 $this->bodyRemaining
= intval( $m[1] );
330 } elseif ( $line === '' ) {
331 $this->readState
= 'body';
335 protected function nextRequest() {
336 if ( $this->currentRequestIndex
!== null ) {
337 unset( $this->requests
[$this->currentRequestIndex
] );
339 if ( count( $this->requests
) ) {
340 $this->readState
= 'status';
341 $this->currentRequestIndex
= key( $this->requests
);
342 $this->writeBuffer
= $this->requests
[$this->currentRequestIndex
];
344 $this->readState
= 'idle';
345 $this->currentRequestIndex
= null;
346 $this->writeBuffer
= '';
348 $this->bodyRemaining
= null;
354 protected function log( $msg ) {
355 wfDebugLog( 'squid', __CLASS__
." ($this->host): $msg\n" );
359 class SquidPurgeClientPool
{
362 * @var array of SquidPurgeClient
364 var $clients = array();
368 * @param $options array
370 function __construct( $options = array() ) {
371 if ( isset( $options['timeout'] ) ) {
372 $this->timeout
= $options['timeout'];
377 * @param $client SquidPurgeClient
380 public function addClient( $client ) {
381 $this->clients
[] = $client;
384 public function run() {
386 $startTime = microtime( true );
388 $readSockets = $writeSockets = array();
390 * @var $client SquidPurgeClient
392 foreach ( $this->clients
as $clientIndex => $client ) {
393 $sockets = $client->getReadSocketsForSelect();
394 foreach ( $sockets as $i => $socket ) {
395 $readSockets["$clientIndex/$i"] = $socket;
397 $sockets = $client->getWriteSocketsForSelect();
398 foreach ( $sockets as $i => $socket ) {
399 $writeSockets["$clientIndex/$i"] = $socket;
402 if ( !count( $readSockets ) && !count( $writeSockets ) ) {
405 $exceptSockets = null;
406 $timeout = min( $startTime +
$this->timeout
- microtime( true ), 1 );
407 wfSuppressWarnings();
408 $numReady = socket_select( $readSockets, $writeSockets, $exceptSockets, $timeout );
410 if ( $numReady === false ) {
411 wfDebugLog( 'squid', __METHOD__
.': Error in stream_select: ' .
412 socket_strerror( socket_last_error() ) . "\n" );
415 // Check for timeout, use 1% tolerance since we aimed at having socket_select()
416 // exit at precisely the overall timeout
417 if ( microtime( true ) - $startTime > $this->timeout
* 0.99 ) {
418 wfDebugLog( 'squid', __CLASS__
.": timeout ({$this->timeout}s)\n" );
420 } elseif ( !$numReady ) {
424 foreach ( $readSockets as $key => $socket ) {
425 list( $clientIndex, ) = explode( '/', $key );
426 $client = $this->clients
[$clientIndex];
429 foreach ( $writeSockets as $key => $socket ) {
430 list( $clientIndex, ) = explode( '/', $key );
431 $client = $this->clients
[$clientIndex];
436 foreach ( $this->clients
as $client ) {
437 if ( !$client->isIdle() ) {
442 foreach ( $this->clients
as $client ) {