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 the appropriate CDN objects given a list of URLs or Title instances
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 CdnCacheUpdate $update */
43 Assert
::parameterType( __CLASS__
, $update, '$update' );
45 $this->urls
= array_merge( $this->urls
, $update->urls
);
49 * Create an update object from an array of Title objects, or a TitleArray object
51 * @param Traversable|Title[] $titles
52 * @param string[] $urlArr
53 * @return CdnCacheUpdate
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() );
62 return new self( $urlArr );
65 public function doUpdate() {
66 global $wgCdnReboundPurgeDelay;
68 self
::purge( $this->urls
);
70 if ( $wgCdnReboundPurgeDelay > 0 ) {
71 JobQueueGroup
::singleton()->lazyPush( new CdnPurgeJob( [
72 'urls' => $this->urls
,
73 'jobReleaseTimestamp' => time() +
$wgCdnReboundPurgeDelay
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')
83 * @param string[] $urlArr List of full URLs to purge
85 public static function purge( array $urlArr ) {
86 global $wgCdnServers, $wgHTCPRouting;
92 // Remove duplicate URLs from list
93 $urlArr = array_unique( $urlArr );
95 wfDebugLog( 'squid', __METHOD__
. ': ' . implode( ' ', $urlArr ) );
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(
103 function ( $url ) use ( $ts ) {
113 // Send lossy UDP broadcasting if enabled
114 if ( $wgHTCPRouting ) {
115 self
::HTCPPurge( $urlArr );
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;
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 );
138 $pool->addClient( $client );
147 * Send Hyper Text Caching Protocol (HTCP) CLR requests.
149 * @throws MWException
150 * @param string[] $urlArr Collection of URLs to purge
152 private static function HTCPPurge( array $urlArr ) {
153 global $wgHTCPRouting, $wgHTCPMulticastTTL;
155 // HTCP CLR operation
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 );
165 // pfsockopen doesn't work because we need set_sock_opt
166 $conn = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
168 $errstr = socket_strerror( socket_last_error() );
169 wfDebugLog( 'squid', __METHOD__
.
170 ": Error opening UDP socket: $errstr" );
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 );
183 // Get sequential trx IDs for packet loss counting
184 $ids = UIDGenerator
::newSequentialPerNodeIDs(
185 'squidhtcppurge', 32, count( $urlArr ), UIDGenerator
::QUICK_VOLATILE
188 foreach ( $urlArr as $url ) {
189 if ( !is_string( $url ) ) {
190 throw new MWException( 'Bad purge URL' );
192 $url = self
::expand( $url );
193 $conf = self
::getRuleForURL( $url, $wgHTCPRouting );
195 wfDebugLog( 'squid', __METHOD__
.
196 "No HTCP rule configured for URL {$url} , skipping" );
200 if ( isset( $conf['host'] ) && isset( $conf['port'] ) ) {
201 // Normalize single entries
204 foreach ( $conf as $subconf ) {
205 if ( !isset( $subconf['host'] ) ||
!isset( $subconf['port'] ) ) {
206 throw new MWException( "Invalid HTCP rule for URL $url\n" );
210 // Construct a minimal HTCP request diagram
212 // Opcode 'CLR', no response desired, no auth
213 $htcpTransID = current( $ids );
216 $htcpSpecifier = pack( 'na4na*na8n',
217 4, 'HEAD', strlen( $url ), $url,
220 $htcpDataLen = 8 +
2 +
strlen( $htcpSpecifier );
221 $htcpLen = 4 +
$htcpDataLen +
2;
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 );
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'] );
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.
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.
248 * Client functions should not need to call this.
253 public static function expand( $url ) {
254 return wfExpandUrl( $url, PROTO_INTERNAL
);
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
263 private static function getRuleForURL( $url, $rules ) {
264 foreach ( $rules as $regex => $routing ) {
265 if ( $regex === '' ||
preg_match( $regex, $url ) ) {