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