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