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