* Document a bit
[lhc/web/wiklou.git] / includes / SquidUpdate.php
1 <?php
2 /**
3 * See deferred.txt
4 * @file
5 * @ingroup Cache
6 */
7
8 /**
9 * Handles purging appropriate Squid URLs given a title (or titles)
10 * @ingroup Cache
11 */
12 class SquidUpdate {
13 var $urlArr, $mMaxTitles;
14
15 function __construct( $urlArr = Array(), $maxTitles = false ) {
16 global $wgMaxSquidPurgeTitles;
17 if ( $maxTitles === false ) {
18 $this->mMaxTitles = $wgMaxSquidPurgeTitles;
19 } else {
20 $this->mMaxTitles = $maxTitles;
21 }
22 if ( count( $urlArr ) > $this->mMaxTitles ) {
23 $urlArr = array_slice( $urlArr, 0, $this->mMaxTitles );
24 }
25 $this->urlArr = $urlArr;
26 }
27
28 static function newFromLinksTo( &$title ) {
29 wfProfileIn( __METHOD__ );
30
31 # Get a list of URLs linking to this page
32 $dbr = wfGetDB( DB_SLAVE );
33 $res = $dbr->select( array( 'links', 'page' ),
34 array( 'page_namespace', 'page_title' ),
35 array(
36 'pl_namespace' => $title->getNamespace(),
37 'pl_title' => $title->getDBkey(),
38 'pl_from=page_id' ),
39 __METHOD__ );
40 $blurlArr = $title->getSquidURLs();
41 if ( $dbr->numRows( $res ) <= $this->mMaxTitles ) {
42 while ( $BL = $dbr->fetchObject ( $res ) )
43 {
44 $tobj = Title::makeTitle( $BL->page_namespace, $BL->page_title ) ;
45 $blurlArr[] = $tobj->getInternalURL();
46 }
47 }
48 $dbr->freeResult ( $res ) ;
49
50 wfProfileOut( __METHOD__ );
51 return new SquidUpdate( $blurlArr );
52 }
53
54 /**
55 * Create a SquidUpdate from an array of Title objects, or a TitleArray object
56 */
57 static function newFromTitles( $titles, $urlArr = array() ) {
58 global $wgMaxSquidPurgeTitles;
59 $i = 0;
60 foreach ( $titles as $title ) {
61 $urlArr[] = $title->getInternalURL();
62 if ( $i++ > $wgMaxSquidPurgeTitles ) {
63 break;
64 }
65 }
66 return new SquidUpdate( $urlArr );
67 }
68
69 static function newSimplePurge( &$title ) {
70 $urlArr = $title->getSquidURLs();
71 return new SquidUpdate( $urlArr );
72 }
73
74 function doUpdate() {
75 SquidUpdate::purge( $this->urlArr );
76 }
77
78 /* Purges a list of Squids defined in $wgSquidServers.
79 $urlArr should contain the full URLs to purge as values
80 (example: $urlArr[] = 'http://my.host/something')
81 XXX report broken Squids per mail or log */
82
83 static function purge( $urlArr ) {
84 global $wgSquidServers, $wgHTCPMulticastAddress, $wgHTCPPort, $wgSquidResponseLimit;
85
86 /*if ( (@$wgSquidServers[0]) == 'echo' ) {
87 echo implode("<br />\n", $urlArr) . "<br />\n";
88 return;
89 }*/
90
91 if( empty( $urlArr ) ) {
92 return;
93 }
94
95 if ( $wgHTCPMulticastAddress && $wgHTCPPort ) {
96 return SquidUpdate::HTCPPurge( $urlArr );
97 }
98
99 wfProfileIn( __METHOD__ );
100
101 $maxsocketspersquid = 8; // socket cap per Squid
102 $urlspersocket = 400; // 400 seems to be a good tradeoff, opening a socket takes a while
103 $firsturl = SquidUpdate::expand( $urlArr[0] );
104 unset($urlArr[0]);
105 $urlArr = array_values($urlArr);
106 $sockspersq = max(ceil(count($urlArr) / $urlspersocket ),1);
107 if ($sockspersq == 1) {
108 /* the most common case */
109 $urlspersocket = count($urlArr);
110 } else if ($sockspersq > $maxsocketspersquid ) {
111 $urlspersocket = ceil(count($urlArr) / $maxsocketspersquid);
112 $sockspersq = $maxsocketspersquid;
113 }
114 $totalsockets = count($wgSquidServers) * $sockspersq;
115 $sockets = Array();
116
117 /* this sets up the sockets and tests the first socket for each server. */
118 for ($ss=0;$ss < count($wgSquidServers);$ss++) {
119 $failed = false;
120 $so = 0;
121 while ($so < $sockspersq && !$failed) {
122 if ($so == 0) {
123 /* first socket for this server, do the tests */
124 @list($server, $port) = explode(':', $wgSquidServers[$ss]);
125 if(!isset($port)) $port = 80;
126 #$this->debug("Opening socket to $server:$port");
127 $error = $errstr = false;
128 $socket = @fsockopen($server, $port, $error, $errstr, 3);
129 #$this->debug("\n");
130 if (!$socket) {
131 $failed = true;
132 $totalsockets -= $sockspersq;
133 } else {
134 $msg = 'PURGE ' . $firsturl . " HTTP/1.0\r\n".
135 "Connection: Keep-Alive\r\n\r\n";
136 #$this->debug($msg);
137 @fputs($socket,$msg);
138 #$this->debug("...");
139 $res = @fread($socket,512);
140 #$this->debug("\n");
141 /* Squid only returns http headers with 200 or 404 status,
142 if there's more returned something's wrong */
143 if (strlen($res) > $wgSquidResponseLimit) {
144 fclose($socket);
145 $failed = true;
146 $totalsockets -= $sockspersq;
147 } else {
148 @stream_set_blocking($socket,false);
149 $sockets[] = $socket;
150 }
151 }
152 } else {
153 /* open the remaining sockets for this server */
154 list($server, $port) = explode(':', $wgSquidServers[$ss]);
155 if(!isset($port)) $port = 80;
156 $socket = @fsockopen($server, $port, $error, $errstr, 2);
157 @stream_set_blocking($socket,false);
158 $sockets[] = $socket;
159 }
160 $so++;
161 }
162 }
163
164 if ($urlspersocket > 0) {
165 /* now do the heavy lifting. The fread() relies on Squid returning only the headers */
166 for ($r=0;$r < $urlspersocket;$r++) {
167 for ($s=0;$s < $totalsockets;$s++) {
168 if($r != 0) {
169 $res = '';
170 $esc = 0;
171 while (strlen($res) < 100 && $esc < 200 ) {
172 $res .= @fread($sockets[$s],512);
173 $esc++;
174 usleep(20);
175 }
176 }
177 $urindex = $r + $urlspersocket * ($s - $sockspersq * floor($s / $sockspersq));
178 $url = SquidUpdate::expand( $urlArr[$urindex] );
179 $msg = 'PURGE ' . $url . " HTTP/1.0\r\n".
180 "Connection: Keep-Alive\r\n\r\n";
181 #$this->debug($msg);
182 @fputs($sockets[$s],$msg);
183 #$this->debug("\n");
184 }
185 }
186 }
187 #$this->debug("Reading response...");
188 foreach ($sockets as $socket) {
189 $res = '';
190 $esc = 0;
191 while (strlen($res) < 100 && $esc < 200 ) {
192 $res .= @fread($socket,1024);
193 $esc++;
194 usleep(20);
195 }
196
197 @fclose($socket);
198 }
199 #$this->debug("\n");
200 wfProfileOut( __METHOD__ );
201 }
202
203 static function HTCPPurge( $urlArr ) {
204 global $wgHTCPMulticastAddress, $wgHTCPMulticastTTL, $wgHTCPPort;
205 wfProfileIn( __METHOD__ );
206
207 $htcpOpCLR = 4; // HTCP CLR
208
209 // FIXME PHP doesn't support these socket constants (include/linux/in.h)
210 if( !defined( "IPPROTO_IP" ) ) {
211 define( "IPPROTO_IP", 0 );
212 define( "IP_MULTICAST_LOOP", 34 );
213 define( "IP_MULTICAST_TTL", 33 );
214 }
215
216 // pfsockopen doesn't work because we need set_sock_opt
217 $conn = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
218 if ( $conn ) {
219 // Set socket options
220 socket_set_option( $conn, IPPROTO_IP, IP_MULTICAST_LOOP, 0 );
221 if ( $wgHTCPMulticastTTL != 1 )
222 socket_set_option( $conn, IPPROTO_IP, IP_MULTICAST_TTL,
223 $wgHTCPMulticastTTL );
224
225 foreach ( $urlArr as $url ) {
226 if( !is_string( $url ) ) {
227 throw new MWException( 'Bad purge URL' );
228 }
229 $url = SquidUpdate::expand( $url );
230
231 // Construct a minimal HTCP request diagram
232 // as per RFC 2756
233 // Opcode 'CLR', no response desired, no auth
234 $htcpTransID = rand();
235
236 $htcpSpecifier = pack( 'na4na*na8n',
237 4, 'HEAD', strlen( $url ), $url,
238 8, 'HTTP/1.0', 0 );
239
240 $htcpDataLen = 8 + 2 + strlen( $htcpSpecifier );
241 $htcpLen = 4 + $htcpDataLen + 2;
242
243 // Note! Squid gets the bit order of the first
244 // word wrong, wrt the RFC. Apparently no other
245 // implementation exists, so adapt to Squid
246 $htcpPacket = pack( 'nxxnCxNxxa*n',
247 $htcpLen, $htcpDataLen, $htcpOpCLR,
248 $htcpTransID, $htcpSpecifier, 2);
249
250 // Send out
251 wfDebug( "Purging URL $url via HTCP\n" );
252 socket_sendto( $conn, $htcpPacket, $htcpLen, 0,
253 $wgHTCPMulticastAddress, $wgHTCPPort );
254 }
255 } else {
256 $errstr = socket_strerror( socket_last_error() );
257 wfDebug( __METHOD__ . "(): Error opening UDP socket: $errstr\n" );
258 }
259 wfProfileOut( __METHOD__ );
260 }
261
262 function debug( $text ) {
263 global $wgDebugSquid;
264 if ( $wgDebugSquid ) {
265 wfDebug( $text );
266 }
267 }
268
269 /**
270 * Expand local URLs to fully-qualified URLs using the internal protocol
271 * and host defined in $wgInternalServer. Input that's already fully-
272 * qualified will be passed through unchanged.
273 *
274 * This is used to generate purge URLs that may be either local to the
275 * main wiki or include a non-native host, such as images hosted on a
276 * second internal server.
277 *
278 * Client functions should not need to call this.
279 *
280 * @return string
281 */
282 static function expand( $url ) {
283 global $wgInternalServer;
284 if( $url != '' && $url{0} == '/' ) {
285 return $wgInternalServer . $url;
286 }
287 return $url;
288 }
289 }