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