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 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 CdnCacheUpdate( $urlArr );
66 * Purges the list of URLs passed to the constructor.
68 public function doUpdate() {
69 global $wgCdnReboundPurgeDelay;
71 self
::purge( $this->urls
);
73 if ( $wgCdnReboundPurgeDelay > 0 ) {
74 JobQueueGroup
::singleton()->lazyPush( new CdnPurgeJob( [
75 'urls' => $this->urls
,
76 'jobReleaseTimestamp' => time() +
$wgCdnReboundPurgeDelay
82 * Purges a list of CDN nodes defined in $wgSquidServers.
83 * $urlArr should contain the full URLs to purge as values
84 * (example: $urlArr[] = 'http://my.host/something')
86 * @param string[] $urlArr List of full URLs to purge
88 public static function purge( array $urlArr ) {
89 global $wgSquidServers, $wgHTCPRouting;
95 // Remove duplicate URLs from list
96 $urlArr = array_unique( $urlArr );
98 wfDebugLog( 'squid', __METHOD__
. ': ' . implode( ' ', $urlArr ) );
100 // Reliably broadcast the purge to all edge nodes
101 $relayer = MediaWikiServices
::getInstance()->getEventRelayerGroup()
102 ->getRelayer( 'cdn-url-purges' );
103 $ts = microtime( true );
104 $relayer->notifyMulti(
107 function ( $url ) use ( $ts ) {
117 // Send lossy UDP broadcasting if enabled
118 if ( $wgHTCPRouting ) {
119 self
::HTCPPurge( $urlArr );
122 // Do direct server purges if enabled (this does not scale very well)
123 if ( $wgSquidServers ) {
124 // Maximum number of parallel connections per squid
125 $maxSocketsPerSquid = 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 $socketsPerSquid = ceil( count( $urlArr ) / $urlsPerSocket );
130 if ( $socketsPerSquid > $maxSocketsPerSquid ) {
131 $socketsPerSquid = $maxSocketsPerSquid;
134 $pool = new SquidPurgeClientPool
;
135 $chunks = array_chunk( $urlArr, ceil( count( $urlArr ) / $socketsPerSquid ) );
136 foreach ( $wgSquidServers as $server ) {
137 foreach ( $chunks as $chunk ) {
138 $client = new SquidPurgeClient( $server );
139 foreach ( $chunk as $url ) {
140 $client->queuePurge( $url );
142 $pool->addClient( $client );
151 * Send Hyper Text Caching Protocol (HTCP) CLR requests.
153 * @throws MWException
154 * @param string[] $urlArr Collection of URLs to purge
156 private static function HTCPPurge( array $urlArr ) {
157 global $wgHTCPRouting, $wgHTCPMulticastTTL;
159 // HTCP CLR operation
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 );
169 // pfsockopen doesn't work because we need set_sock_opt
170 $conn = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
172 $errstr = socket_strerror( socket_last_error() );
173 wfDebugLog( 'squid', __METHOD__
.
174 ": Error opening UDP socket: $errstr" );
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 );
187 // Get sequential trx IDs for packet loss counting
188 $ids = UIDGenerator
::newSequentialPerNodeIDs(
189 'squidhtcppurge', 32, count( $urlArr ), UIDGenerator
::QUICK_VOLATILE
192 foreach ( $urlArr as $url ) {
193 if ( !is_string( $url ) ) {
194 throw new MWException( 'Bad purge URL' );
196 $url = self
::expand( $url );
197 $conf = self
::getRuleForURL( $url, $wgHTCPRouting );
199 wfDebugLog( 'squid', __METHOD__
.
200 "No HTCP rule configured for URL {$url} , skipping" );
204 if ( isset( $conf['host'] ) && isset( $conf['port'] ) ) {
205 // Normalize single entries
208 foreach ( $conf as $subconf ) {
209 if ( !isset( $subconf['host'] ) ||
!isset( $subconf['port'] ) ) {
210 throw new MWException( "Invalid HTCP rule for URL $url\n" );
214 // Construct a minimal HTCP request diagram
216 // Opcode 'CLR', no response desired, no auth
217 $htcpTransID = current( $ids );
220 $htcpSpecifier = pack( 'na4na*na8n',
221 4, 'HEAD', strlen( $url ), $url,
224 $htcpDataLen = 8 +
2 +
strlen( $htcpSpecifier );
225 $htcpLen = 4 +
$htcpDataLen +
2;
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 );
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'] );
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.
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.
252 * Client functions should not need to call this.
257 public static function expand( $url ) {
258 return wfExpandUrl( $url, PROTO_INTERNAL
);
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
267 private static function getRuleForURL( $url, $rules ) {
268 foreach ( $rules as $regex => $routing ) {
269 if ( $regex === '' ||
preg_match( $regex, $url ) ) {