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