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