Merge "Add DROP INDEX support to DatabaseSqlite::replaceVars method"
[lhc/web/wiklou.git] / includes / deferred / SquidUpdate.php
1 <?php
2 /**
3 * Squid cache purging.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Cache
22 */
23
24 /**
25 * Handles purging appropriate Squid URLs given a title (or titles)
26 * @ingroup Cache
27 */
28 class SquidUpdate {
29
30 /**
31 * Collection of URLs to purge.
32 * @var array
33 */
34 protected $urlArr;
35
36 /**
37 * @param array $urlArr Collection of URLs to purge
38 * @param bool|int $maxTitles Maximum number of unique URLs to purge
39 */
40 public function __construct( $urlArr = array(), $maxTitles = false ) {
41 global $wgMaxSquidPurgeTitles;
42 if ( $maxTitles === false ) {
43 $maxTitles = $wgMaxSquidPurgeTitles;
44 }
45
46 // Remove duplicate URLs from list
47 $urlArr = array_unique( $urlArr );
48 if ( count( $urlArr ) > $maxTitles ) {
49 // Truncate to desired maximum URL count
50 $urlArr = array_slice( $urlArr, 0, $maxTitles );
51 }
52 $this->urlArr = $urlArr;
53 }
54
55 /**
56 * Create a SquidUpdate from the given Title object.
57 *
58 * The resulting SquidUpdate will purge the given Title's URLs as well as
59 * the pages that link to it. Capped at $wgMaxSquidPurgeTitles total URLs.
60 *
61 * @param Title $title
62 * @return SquidUpdate
63 */
64 public static function newFromLinksTo( Title $title ) {
65 global $wgMaxSquidPurgeTitles;
66 wfProfileIn( __METHOD__ );
67
68 # Get a list of URLs linking to this page
69 $dbr = wfGetDB( DB_SLAVE );
70 $res = $dbr->select( array( 'links', 'page' ),
71 array( 'page_namespace', 'page_title' ),
72 array(
73 'pl_namespace' => $title->getNamespace(),
74 'pl_title' => $title->getDBkey(),
75 'pl_from=page_id' ),
76 __METHOD__ );
77 $blurlArr = $title->getSquidURLs();
78 if ( $res->numRows() <= $wgMaxSquidPurgeTitles ) {
79 foreach ( $res as $BL ) {
80 $tobj = Title::makeTitle( $BL->page_namespace, $BL->page_title );
81 $blurlArr[] = $tobj->getInternalURL();
82 }
83 }
84
85 wfProfileOut( __METHOD__ );
86 return new SquidUpdate( $blurlArr );
87 }
88
89 /**
90 * Create a SquidUpdate from an array of Title objects, or a TitleArray object
91 *
92 * @param array $titles
93 * @param array $urlArr
94 * @return SquidUpdate
95 */
96 public static function newFromTitles( $titles, $urlArr = array() ) {
97 global $wgMaxSquidPurgeTitles;
98 $i = 0;
99 foreach ( $titles as $title ) {
100 $urlArr[] = $title->getInternalURL();
101 if ( $i++ > $wgMaxSquidPurgeTitles ) {
102 break;
103 }
104 }
105 return new SquidUpdate( $urlArr );
106 }
107
108 /**
109 * @param Title $title
110 * @return SquidUpdate
111 */
112 public static function newSimplePurge( Title $title ) {
113 $urlArr = $title->getSquidURLs();
114 return new SquidUpdate( $urlArr );
115 }
116
117 /**
118 * Purges the list of URLs passed to the constructor.
119 */
120 public function doUpdate() {
121 self::purge( $this->urlArr );
122 }
123
124 /**
125 * Purges a list of Squids defined in $wgSquidServers.
126 * $urlArr should contain the full URLs to purge as values
127 * (example: $urlArr[] = 'http://my.host/something')
128 * XXX report broken Squids per mail or log
129 *
130 * @param array $urlArr List of full URLs to purge
131 */
132 public static function purge( $urlArr ) {
133 global $wgSquidServers, $wgHTCPRouting;
134
135 if ( !$urlArr ) {
136 return;
137 }
138
139 wfDebugLog( 'squid', __METHOD__ . ': ' . implode( ' ', $urlArr ) . "\n" );
140
141 if ( $wgHTCPRouting ) {
142 self::HTCPPurge( $urlArr );
143 }
144
145 wfProfileIn( __METHOD__ );
146
147 // Remove duplicate URLs
148 $urlArr = array_unique( $urlArr );
149 // Maximum number of parallel connections per squid
150 $maxSocketsPerSquid = 8;
151 // Number of requests to send per socket
152 // 400 seems to be a good tradeoff, opening a socket takes a while
153 $urlsPerSocket = 400;
154 $socketsPerSquid = ceil( count( $urlArr ) / $urlsPerSocket );
155 if ( $socketsPerSquid > $maxSocketsPerSquid ) {
156 $socketsPerSquid = $maxSocketsPerSquid;
157 }
158
159 $pool = new SquidPurgeClientPool;
160 $chunks = array_chunk( $urlArr, ceil( count( $urlArr ) / $socketsPerSquid ) );
161 foreach ( $wgSquidServers as $server ) {
162 foreach ( $chunks as $chunk ) {
163 $client = new SquidPurgeClient( $server );
164 foreach ( $chunk as $url ) {
165 $client->queuePurge( $url );
166 }
167 $pool->addClient( $client );
168 }
169 }
170 $pool->run();
171
172 wfProfileOut( __METHOD__ );
173 }
174
175 /**
176 * Send Hyper Text Caching Protocol (HTCP) CLR requests.
177 *
178 * @throws MWException
179 * @param array $urlArr Collection of URLs to purge
180 */
181 public static function HTCPPurge( $urlArr ) {
182 global $wgHTCPRouting, $wgHTCPMulticastTTL;
183 wfProfileIn( __METHOD__ );
184
185 // HTCP CLR operation
186 $htcpOpCLR = 4;
187
188 // @todo FIXME: PHP doesn't support these socket constants (include/linux/in.h)
189 if ( !defined( "IPPROTO_IP" ) ) {
190 define( "IPPROTO_IP", 0 );
191 define( "IP_MULTICAST_LOOP", 34 );
192 define( "IP_MULTICAST_TTL", 33 );
193 }
194
195 // pfsockopen doesn't work because we need set_sock_opt
196 $conn = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
197 if ( ! $conn ) {
198 $errstr = socket_strerror( socket_last_error() );
199 wfDebugLog( 'squid', __METHOD__ .
200 ": Error opening UDP socket: $errstr\n" );
201 wfProfileOut( __METHOD__ );
202 return;
203 }
204
205 // Set socket options
206 socket_set_option( $conn, IPPROTO_IP, IP_MULTICAST_LOOP, 0 );
207 if ( $wgHTCPMulticastTTL != 1 ) {
208 // Set multicast time to live (hop count) option on socket
209 socket_set_option( $conn, IPPROTO_IP, IP_MULTICAST_TTL,
210 $wgHTCPMulticastTTL );
211 }
212
213 // Remove duplicate URLs from collection
214 $urlArr = array_unique( $urlArr );
215 foreach ( $urlArr as $url ) {
216 if ( !is_string( $url ) ) {
217 wfProfileOut( __METHOD__ );
218 throw new MWException( 'Bad purge URL' );
219 }
220 $url = self::expand( $url );
221 $conf = self::getRuleForURL( $url, $wgHTCPRouting );
222 if ( !$conf ) {
223 wfDebugLog( 'squid', __METHOD__ .
224 "No HTCP rule configured for URL {$url} , skipping\n" );
225 continue;
226 }
227
228 if ( isset( $conf['host'] ) && isset( $conf['port'] ) ) {
229 // Normalize single entries
230 $conf = array( $conf );
231 }
232 foreach ( $conf as $subconf ) {
233 if ( !isset( $subconf['host'] ) || !isset( $subconf['port'] ) ) {
234 wfProfileOut( __METHOD__ );
235 throw new MWException( "Invalid HTCP rule for URL $url\n" );
236 }
237 }
238
239 // Construct a minimal HTCP request diagram
240 // as per RFC 2756
241 // Opcode 'CLR', no response desired, no auth
242 $htcpTransID = rand();
243
244 $htcpSpecifier = pack( 'na4na*na8n',
245 4, 'HEAD', strlen( $url ), $url,
246 8, 'HTTP/1.0', 0 );
247
248 $htcpDataLen = 8 + 2 + strlen( $htcpSpecifier );
249 $htcpLen = 4 + $htcpDataLen + 2;
250
251 // Note! Squid gets the bit order of the first
252 // word wrong, wrt the RFC. Apparently no other
253 // implementation exists, so adapt to Squid
254 $htcpPacket = pack( 'nxxnCxNxxa*n',
255 $htcpLen, $htcpDataLen, $htcpOpCLR,
256 $htcpTransID, $htcpSpecifier, 2 );
257
258 wfDebugLog( 'squid', __METHOD__ .
259 "Purging URL $url via HTCP\n" );
260 foreach ( $conf as $subconf ) {
261 socket_sendto( $conn, $htcpPacket, $htcpLen, 0,
262 $subconf['host'], $subconf['port'] );
263 }
264 }
265 wfProfileOut( __METHOD__ );
266 }
267
268 /**
269 * Expand local URLs to fully-qualified URLs using the internal protocol
270 * and host defined in $wgInternalServer. Input that's already fully-
271 * qualified will be passed through unchanged.
272 *
273 * This is used to generate purge URLs that may be either local to the
274 * main wiki or include a non-native host, such as images hosted on a
275 * second internal server.
276 *
277 * Client functions should not need to call this.
278 *
279 * @param string $url
280 * @return string
281 */
282 public static function expand( $url ) {
283 return wfExpandUrl( $url, PROTO_INTERNAL );
284 }
285
286 /**
287 * Find the HTCP routing rule to use for a given URL.
288 * @param string $url URL to match
289 * @param array $rules Array of rules, see $wgHTCPRouting for format and behavior
290 * @return mixed Element of $rules that matched, or false if nothing matched
291 */
292 private static function getRuleForURL( $url, $rules ) {
293 foreach ( $rules as $regex => $routing ) {
294 if ( $regex === '' || preg_match( $regex, $url ) ) {
295 return $routing;
296 }
297 }
298 return false;
299 }
300 }