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