Merge "Add .pipeline/ with dev image variant"
[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 the appropriate CDN objects given a list of URLs or Title instances
28 * @ingroup Cache
29 */
30 class CdnCacheUpdate implements DeferrableUpdate, MergeableUpdate {
31 /** @var string[] Collection of URLs to purge */
32 private $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 $ts = microtime( true );
103 $relayerGroup = MediaWikiServices::getInstance()->getEventRelayerGroup();
104 $relayerGroup->getRelayer( 'cdn-url-purges' )->notifyMulti(
105 'cdn-url-purges',
106 array_map(
107 function ( $url ) use ( $ts ) {
108 return [
109 'url' => $url,
110 'timestamp' => $ts,
111 ];
112 },
113 $urlArr
114 )
115 );
116
117 // Send lossy UDP broadcasting if enabled
118 if ( $wgHTCPRouting ) {
119 self::HTCPPurge( $urlArr );
120 }
121
122 // Do direct server purges if enabled (this does not scale very well)
123 if ( $wgCdnServers ) {
124 // Maximum number of parallel connections per CDN
125 $maxSocketsPerCdn = 8;
126 // Number of requests to send per socket
127 // 400 seems to be a good tradeoff, opening a socket takes a while
128 $urlsPerSocket = 400;
129 $socketsPerCdn = ceil( count( $urlArr ) / $urlsPerSocket );
130 if ( $socketsPerCdn > $maxSocketsPerCdn ) {
131 $socketsPerCdn = $maxSocketsPerCdn;
132 }
133
134 $pool = new SquidPurgeClientPool;
135 $chunks = array_chunk( $urlArr, ceil( count( $urlArr ) / $socketsPerCdn ) );
136 foreach ( $wgCdnServers as $server ) {
137 foreach ( $chunks as $chunk ) {
138 $client = new SquidPurgeClient( $server );
139 foreach ( $chunk as $url ) {
140 $client->queuePurge( self::expand( $url ) );
141 }
142 $pool->addClient( $client );
143 }
144 }
145
146 $pool->run();
147 }
148 }
149
150 /**
151 * Send Hyper Text Caching Protocol (HTCP) CLR requests.
152 *
153 * @throws MWException
154 * @param string[] $urlArr Collection of URLs to purge
155 */
156 private static function HTCPPurge( array $urlArr ) {
157 global $wgHTCPRouting, $wgHTCPMulticastTTL;
158
159 // HTCP CLR operation
160 $htcpOpCLR = 4;
161
162 // @todo FIXME: PHP doesn't support these socket constants (include/linux/in.h)
163 if ( !defined( "IPPROTO_IP" ) ) {
164 define( "IPPROTO_IP", 0 );
165 define( "IP_MULTICAST_LOOP", 34 );
166 define( "IP_MULTICAST_TTL", 33 );
167 }
168
169 // pfsockopen doesn't work because we need set_sock_opt
170 $conn = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
171 if ( !$conn ) {
172 $errstr = socket_strerror( socket_last_error() );
173 wfDebugLog( 'squid', __METHOD__ .
174 ": Error opening UDP socket: $errstr" );
175
176 return;
177 }
178
179 // Set socket options
180 socket_set_option( $conn, IPPROTO_IP, IP_MULTICAST_LOOP, 0 );
181 if ( $wgHTCPMulticastTTL != 1 ) {
182 // Set multicast time to live (hop count) option on socket
183 socket_set_option( $conn, IPPROTO_IP, IP_MULTICAST_TTL,
184 $wgHTCPMulticastTTL );
185 }
186
187 // Get sequential trx IDs for packet loss counting
188 $ids = UIDGenerator::newSequentialPerNodeIDs(
189 'squidhtcppurge', 32, count( $urlArr ), UIDGenerator::QUICK_VOLATILE
190 );
191
192 foreach ( $urlArr as $url ) {
193 if ( !is_string( $url ) ) {
194 throw new MWException( 'Bad purge URL' );
195 }
196 $url = self::expand( $url );
197 $conf = self::getRuleForURL( $url, $wgHTCPRouting );
198 if ( !$conf ) {
199 wfDebugLog( 'squid', __METHOD__ .
200 "No HTCP rule configured for URL {$url} , skipping" );
201 continue;
202 }
203
204 if ( isset( $conf['host'] ) && isset( $conf['port'] ) ) {
205 // Normalize single entries
206 $conf = [ $conf ];
207 }
208 foreach ( $conf as $subconf ) {
209 if ( !isset( $subconf['host'] ) || !isset( $subconf['port'] ) ) {
210 throw new MWException( "Invalid HTCP rule for URL $url\n" );
211 }
212 }
213
214 // Construct a minimal HTCP request diagram
215 // as per RFC 2756
216 // Opcode 'CLR', no response desired, no auth
217 $htcpTransID = current( $ids );
218 next( $ids );
219
220 $htcpSpecifier = pack( 'na4na*na8n',
221 4, 'HEAD', strlen( $url ), $url,
222 8, 'HTTP/1.0', 0 );
223
224 $htcpDataLen = 8 + 2 + strlen( $htcpSpecifier );
225 $htcpLen = 4 + $htcpDataLen + 2;
226
227 // Note! Squid gets the bit order of the first
228 // word wrong, wrt the RFC. Apparently no other
229 // implementation exists, so adapt to Squid
230 $htcpPacket = pack( 'nxxnCxNxxa*n',
231 $htcpLen, $htcpDataLen, $htcpOpCLR,
232 $htcpTransID, $htcpSpecifier, 2 );
233
234 wfDebugLog( 'squid', __METHOD__ .
235 "Purging URL $url via HTCP" );
236 foreach ( $conf as $subconf ) {
237 socket_sendto( $conn, $htcpPacket, $htcpLen, 0,
238 $subconf['host'], $subconf['port'] );
239 }
240 }
241 }
242
243 /**
244 * Expand local URLs to fully-qualified URLs using the internal protocol
245 * and host defined in $wgInternalServer. Input that's already fully-
246 * qualified will be passed through unchanged.
247 *
248 * This is used to generate purge URLs that may be either local to the
249 * main wiki or include a non-native host, such as images hosted on a
250 * second internal server.
251 *
252 * Client functions should not need to call this.
253 *
254 * @param string $url
255 * @return string
256 */
257 private static function expand( $url ) {
258 return wfExpandUrl( $url, PROTO_INTERNAL );
259 }
260
261 /**
262 * Find the HTCP routing rule to use for a given URL.
263 * @param string $url URL to match
264 * @param array $rules Array of rules, see $wgHTCPRouting for format and behavior
265 * @return mixed Element of $rules that matched, or false if nothing matched
266 */
267 private static function getRuleForURL( $url, $rules ) {
268 foreach ( $rules as $regex => $routing ) {
269 if ( $regex === '' || preg_match( $regex, $url ) ) {
270 return $routing;
271 }
272 }
273
274 return false;
275 }
276 }