Merge "Add mw-ui-icon-after"
[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 an array of Title objects, or a TitleArray object
56 *
57 * @param array $titles
58 * @param array $urlArr
59 * @return SquidUpdate
60 */
61 public static function newFromTitles( $titles, $urlArr = array() ) {
62 global $wgMaxSquidPurgeTitles;
63 $i = 0;
64 /** @var Title $title */
65 foreach ( $titles as $title ) {
66 $urlArr[] = $title->getInternalURL();
67 if ( $i++ > $wgMaxSquidPurgeTitles ) {
68 break;
69 }
70 }
71
72 return new SquidUpdate( $urlArr );
73 }
74
75 /**
76 * @param Title $title
77 * @return SquidUpdate
78 */
79 public static function newSimplePurge( Title $title ) {
80 $urlArr = $title->getSquidURLs();
81
82 return new SquidUpdate( $urlArr );
83 }
84
85 /**
86 * Purges the list of URLs passed to the constructor.
87 */
88 public function doUpdate() {
89 self::purge( $this->urlArr );
90 }
91
92 /**
93 * Purges a list of Squids defined in $wgSquidServers.
94 * $urlArr should contain the full URLs to purge as values
95 * (example: $urlArr[] = 'http://my.host/something')
96 * XXX report broken Squids per mail or log
97 *
98 * @param array $urlArr List of full URLs to purge
99 */
100 public static function purge( $urlArr ) {
101 global $wgSquidServers, $wgHTCPRouting;
102
103 if ( !$urlArr ) {
104 return;
105 }
106
107 wfDebugLog( 'squid', __METHOD__ . ': ' . implode( ' ', $urlArr ) );
108
109 if ( $wgHTCPRouting ) {
110 self::HTCPPurge( $urlArr );
111 }
112
113 wfProfileIn( __METHOD__ );
114
115 // Remove duplicate URLs
116 $urlArr = array_unique( $urlArr );
117 // Maximum number of parallel connections per squid
118 $maxSocketsPerSquid = 8;
119 // Number of requests to send per socket
120 // 400 seems to be a good tradeoff, opening a socket takes a while
121 $urlsPerSocket = 400;
122 $socketsPerSquid = ceil( count( $urlArr ) / $urlsPerSocket );
123 if ( $socketsPerSquid > $maxSocketsPerSquid ) {
124 $socketsPerSquid = $maxSocketsPerSquid;
125 }
126
127 $pool = new SquidPurgeClientPool;
128 $chunks = array_chunk( $urlArr, ceil( count( $urlArr ) / $socketsPerSquid ) );
129 foreach ( $wgSquidServers as $server ) {
130 foreach ( $chunks as $chunk ) {
131 $client = new SquidPurgeClient( $server );
132 foreach ( $chunk as $url ) {
133 $client->queuePurge( $url );
134 }
135 $pool->addClient( $client );
136 }
137 }
138 $pool->run();
139
140 wfProfileOut( __METHOD__ );
141 }
142
143 /**
144 * Send Hyper Text Caching Protocol (HTCP) CLR requests.
145 *
146 * @throws MWException
147 * @param array $urlArr Collection of URLs to purge
148 */
149 public static function HTCPPurge( $urlArr ) {
150 global $wgHTCPRouting, $wgHTCPMulticastTTL;
151 wfProfileIn( __METHOD__ );
152
153 // HTCP CLR operation
154 $htcpOpCLR = 4;
155
156 // @todo FIXME: PHP doesn't support these socket constants (include/linux/in.h)
157 if ( !defined( "IPPROTO_IP" ) ) {
158 define( "IPPROTO_IP", 0 );
159 define( "IP_MULTICAST_LOOP", 34 );
160 define( "IP_MULTICAST_TTL", 33 );
161 }
162
163 // pfsockopen doesn't work because we need set_sock_opt
164 $conn = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
165 if ( !$conn ) {
166 $errstr = socket_strerror( socket_last_error() );
167 wfDebugLog( 'squid', __METHOD__ .
168 ": Error opening UDP socket: $errstr" );
169 wfProfileOut( __METHOD__ );
170
171 return;
172 }
173
174 // Set socket options
175 socket_set_option( $conn, IPPROTO_IP, IP_MULTICAST_LOOP, 0 );
176 if ( $wgHTCPMulticastTTL != 1 ) {
177 // Set multicast time to live (hop count) option on socket
178 socket_set_option( $conn, IPPROTO_IP, IP_MULTICAST_TTL,
179 $wgHTCPMulticastTTL );
180 }
181
182 // Remove duplicate URLs from collection
183 $urlArr = array_unique( $urlArr );
184 // Get sequential trx IDs for packet loss counting
185 $ids = UIDGenerator::newSequentialPerNodeIDs(
186 'squidhtcppurge', 32, count( $urlArr ), UIDGenerator::QUICK_VOLATILE
187 );
188
189 foreach ( $urlArr as $url ) {
190 if ( !is_string( $url ) ) {
191 wfProfileOut( __METHOD__ );
192 throw new MWException( 'Bad purge URL' );
193 }
194 $url = self::expand( $url );
195 $conf = self::getRuleForURL( $url, $wgHTCPRouting );
196 if ( !$conf ) {
197 wfDebugLog( 'squid', __METHOD__ .
198 "No HTCP rule configured for URL {$url} , skipping" );
199 continue;
200 }
201
202 if ( isset( $conf['host'] ) && isset( $conf['port'] ) ) {
203 // Normalize single entries
204 $conf = array( $conf );
205 }
206 foreach ( $conf as $subconf ) {
207 if ( !isset( $subconf['host'] ) || !isset( $subconf['port'] ) ) {
208 wfProfileOut( __METHOD__ );
209 throw new MWException( "Invalid HTCP rule for URL $url\n" );
210 }
211 }
212
213 // Construct a minimal HTCP request diagram
214 // as per RFC 2756
215 // Opcode 'CLR', no response desired, no auth
216 $htcpTransID = current( $ids );
217 next( $ids );
218
219 $htcpSpecifier = pack( 'na4na*na8n',
220 4, 'HEAD', strlen( $url ), $url,
221 8, 'HTTP/1.0', 0 );
222
223 $htcpDataLen = 8 + 2 + strlen( $htcpSpecifier );
224 $htcpLen = 4 + $htcpDataLen + 2;
225
226 // Note! Squid gets the bit order of the first
227 // word wrong, wrt the RFC. Apparently no other
228 // implementation exists, so adapt to Squid
229 $htcpPacket = pack( 'nxxnCxNxxa*n',
230 $htcpLen, $htcpDataLen, $htcpOpCLR,
231 $htcpTransID, $htcpSpecifier, 2 );
232
233 wfDebugLog( 'squid', __METHOD__ .
234 "Purging URL $url via HTCP" );
235 foreach ( $conf as $subconf ) {
236 socket_sendto( $conn, $htcpPacket, $htcpLen, 0,
237 $subconf['host'], $subconf['port'] );
238 }
239 }
240 wfProfileOut( __METHOD__ );
241 }
242
243 /**
244 * Expand local URLs to fully-qualified URLs using the internal protocol
245 * and host defined in $wgInternalServer. Input that's already fully-
246 * qualified will be passed through unchanged.
247 *
248 * This is used to generate purge URLs that may be either local to the
249 * main wiki or include a non-native host, such as images hosted on a
250 * second internal server.
251 *
252 * Client functions should not need to call this.
253 *
254 * @param string $url
255 * @return string
256 */
257 public static function expand( $url ) {
258 return wfExpandUrl( $url, PROTO_INTERNAL );
259 }
260
261 /**
262 * Find the HTCP routing rule to use for a given URL.
263 * @param string $url URL to match
264 * @param array $rules Array of rules, see $wgHTCPRouting for format and behavior
265 * @return mixed Element of $rules that matched, or false if nothing matched
266 */
267 private static function getRuleForURL( $url, $rules ) {
268 foreach ( $rules as $regex => $routing ) {
269 if ( $regex === '' || preg_match( $regex, $url ) ) {
270 return $routing;
271 }
272 }
273
274 return false;
275 }
276 }