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.
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.
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
23 use Wikimedia\Assert\Assert
;
24 use MediaWiki\MediaWikiServices
;
27 * Handles purging appropriate CDN URLs given a title (or titles)
30 class CdnCacheUpdate
implements DeferrableUpdate
, MergeableUpdate
{
31 /** @var string[] Collection of URLs to purge */
35 * @param string[] $urlArr Collection of URLs to purge
37 public function __construct( array $urlArr ) {
38 $this->urls
= $urlArr;
41 public function merge( MergeableUpdate
$update ) {
42 /** @var self $update */
43 Assert
::parameterType( __CLASS__
, $update, '$update' );
44 '@phan-var self $update';
46 $this->urls
= array_merge( $this->urls
, $update->urls
);
50 * Create an update object from an array of Title objects, or a TitleArray object
52 * @param Traversable|Title[] $titles
53 * @param string[] $urlArr
54 * @return CdnCacheUpdate
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() );
63 return new CdnCacheUpdate( $urlArr );
67 * Purges the list of URLs passed to the constructor.
69 public function doUpdate() {
70 global $wgCdnReboundPurgeDelay;
72 self
::purge( $this->urls
);
74 if ( $wgCdnReboundPurgeDelay > 0 ) {
75 JobQueueGroup
::singleton()->lazyPush( new CdnPurgeJob( [
76 'urls' => $this->urls
,
77 'jobReleaseTimestamp' => time() +
$wgCdnReboundPurgeDelay
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')
87 * @param string[] $urlArr List of full URLs to purge
89 public static function purge( array $urlArr ) {
90 global $wgCdnServers, $wgHTCPRouting;
96 // Remove duplicate URLs from list
97 $urlArr = array_unique( $urlArr );
99 wfDebugLog( 'squid', __METHOD__
. ': ' . implode( ' ', $urlArr ) );
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(
108 function ( $url ) use ( $ts ) {
118 // Send lossy UDP broadcasting if enabled
119 if ( $wgHTCPRouting ) {
120 self
::HTCPPurge( $urlArr );
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;
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 );
143 $pool->addClient( $client );
152 * Send Hyper Text Caching Protocol (HTCP) CLR requests.
154 * @throws MWException
155 * @param string[] $urlArr Collection of URLs to purge
157 private static function HTCPPurge( array $urlArr ) {
158 global $wgHTCPRouting, $wgHTCPMulticastTTL;
160 // HTCP CLR operation
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 );
170 // pfsockopen doesn't work because we need set_sock_opt
171 $conn = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
173 $errstr = socket_strerror( socket_last_error() );
174 wfDebugLog( 'squid', __METHOD__
.
175 ": Error opening UDP socket: $errstr" );
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 );
188 // Get sequential trx IDs for packet loss counting
189 $ids = UIDGenerator
::newSequentialPerNodeIDs(
190 'squidhtcppurge', 32, count( $urlArr ), UIDGenerator
::QUICK_VOLATILE
193 foreach ( $urlArr as $url ) {
194 if ( !is_string( $url ) ) {
195 throw new MWException( 'Bad purge URL' );
197 $url = self
::expand( $url );
198 $conf = self
::getRuleForURL( $url, $wgHTCPRouting );
200 wfDebugLog( 'squid', __METHOD__
.
201 "No HTCP rule configured for URL {$url} , skipping" );
205 if ( isset( $conf['host'] ) && isset( $conf['port'] ) ) {
206 // Normalize single entries
209 foreach ( $conf as $subconf ) {
210 if ( !isset( $subconf['host'] ) ||
!isset( $subconf['port'] ) ) {
211 throw new MWException( "Invalid HTCP rule for URL $url\n" );
215 // Construct a minimal HTCP request diagram
217 // Opcode 'CLR', no response desired, no auth
218 $htcpTransID = current( $ids );
221 $htcpSpecifier = pack( 'na4na*na8n',
222 4, 'HEAD', strlen( $url ), $url,
225 $htcpDataLen = 8 +
2 +
strlen( $htcpSpecifier );
226 $htcpLen = 4 +
$htcpDataLen +
2;
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 );
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'] );
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.
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.
253 * Client functions should not need to call this.
258 public static function expand( $url ) {
259 return wfExpandUrl( $url, PROTO_INTERNAL
);
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
268 private static function getRuleForURL( $url, $rules ) {
269 foreach ( $rules as $regex => $routing ) {
270 if ( $regex === '' ||
preg_match( $regex, $url ) ) {