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
24 use Wikimedia\Assert\Assert
;
25 use MediaWiki\MediaWikiServices
;
28 * Handles purging appropriate CDN URLs given a title (or titles)
31 class CdnCacheUpdate
implements DeferrableUpdate
, MergeableUpdate
{
32 /** @var string[] Collection of URLs to purge */
36 * @param string[] $urlArr Collection of URLs to purge
38 public function __construct( array $urlArr ) {
39 $this->urls
= $urlArr;
42 public function merge( MergeableUpdate
$update ) {
43 /** @var CdnCacheUpdate $update */
44 Assert
::parameterType( __CLASS__
, $update, '$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 );
68 * @return CdnCacheUpdate
69 * @deprecated since 1.27
71 public static function newSimplePurge( Title
$title ) {
72 return new CdnCacheUpdate( $title->getCdnUrls() );
76 * Purges the list of URLs passed to the constructor.
78 public function doUpdate() {
79 global $wgCdnReboundPurgeDelay;
81 self
::purge( $this->urls
);
83 if ( $wgCdnReboundPurgeDelay > 0 ) {
84 JobQueueGroup
::singleton()->lazyPush( new CdnPurgeJob(
85 Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __CLASS__
),
87 'urls' => $this->urls
,
88 'jobReleaseTimestamp' => time() +
$wgCdnReboundPurgeDelay
95 * Purges a list of CDN nodes defined in $wgSquidServers.
96 * $urlArr should contain the full URLs to purge as values
97 * (example: $urlArr[] = 'http://my.host/something')
99 * @param string[] $urlArr List of full URLs to purge
101 public static function purge( array $urlArr ) {
102 global $wgSquidServers, $wgHTCPRouting;
108 // Remove duplicate URLs from list
109 $urlArr = array_unique( $urlArr );
111 wfDebugLog( 'squid', __METHOD__
. ': ' . implode( ' ', $urlArr ) );
113 // Reliably broadcast the purge to all edge nodes
114 $relayer = MediaWikiServices
::getInstance()->getEventRelayerGroup()
115 ->getRelayer( 'cdn-url-purges' );
116 $ts = microtime( true );
117 $relayer->notifyMulti(
120 function ( $url ) use ( $ts ) {
130 // Send lossy UDP broadcasting if enabled
131 if ( $wgHTCPRouting ) {
132 self
::HTCPPurge( $urlArr );
135 // Do direct server purges if enabled (this does not scale very well)
136 if ( $wgSquidServers ) {
137 // Maximum number of parallel connections per squid
138 $maxSocketsPerSquid = 8;
139 // Number of requests to send per socket
140 // 400 seems to be a good tradeoff, opening a socket takes a while
141 $urlsPerSocket = 400;
142 $socketsPerSquid = ceil( count( $urlArr ) / $urlsPerSocket );
143 if ( $socketsPerSquid > $maxSocketsPerSquid ) {
144 $socketsPerSquid = $maxSocketsPerSquid;
147 $pool = new SquidPurgeClientPool
;
148 $chunks = array_chunk( $urlArr, ceil( count( $urlArr ) / $socketsPerSquid ) );
149 foreach ( $wgSquidServers as $server ) {
150 foreach ( $chunks as $chunk ) {
151 $client = new SquidPurgeClient( $server );
152 foreach ( $chunk as $url ) {
153 $client->queuePurge( $url );
155 $pool->addClient( $client );
164 * Send Hyper Text Caching Protocol (HTCP) CLR requests.
166 * @throws MWException
167 * @param string[] $urlArr Collection of URLs to purge
169 private static function HTCPPurge( array $urlArr ) {
170 global $wgHTCPRouting, $wgHTCPMulticastTTL;
172 // HTCP CLR operation
175 // @todo FIXME: PHP doesn't support these socket constants (include/linux/in.h)
176 if ( !defined( "IPPROTO_IP" ) ) {
177 define( "IPPROTO_IP", 0 );
178 define( "IP_MULTICAST_LOOP", 34 );
179 define( "IP_MULTICAST_TTL", 33 );
182 // pfsockopen doesn't work because we need set_sock_opt
183 $conn = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
185 $errstr = socket_strerror( socket_last_error() );
186 wfDebugLog( 'squid', __METHOD__
.
187 ": Error opening UDP socket: $errstr" );
192 // Set socket options
193 socket_set_option( $conn, IPPROTO_IP
, IP_MULTICAST_LOOP
, 0 );
194 if ( $wgHTCPMulticastTTL != 1 ) {
195 // Set multicast time to live (hop count) option on socket
196 socket_set_option( $conn, IPPROTO_IP
, IP_MULTICAST_TTL
,
197 $wgHTCPMulticastTTL );
200 // Get sequential trx IDs for packet loss counting
201 $ids = UIDGenerator
::newSequentialPerNodeIDs(
202 'squidhtcppurge', 32, count( $urlArr ), UIDGenerator
::QUICK_VOLATILE
205 foreach ( $urlArr as $url ) {
206 if ( !is_string( $url ) ) {
207 throw new MWException( 'Bad purge URL' );
209 $url = self
::expand( $url );
210 $conf = self
::getRuleForURL( $url, $wgHTCPRouting );
212 wfDebugLog( 'squid', __METHOD__
.
213 "No HTCP rule configured for URL {$url} , skipping" );
217 if ( isset( $conf['host'] ) && isset( $conf['port'] ) ) {
218 // Normalize single entries
221 foreach ( $conf as $subconf ) {
222 if ( !isset( $subconf['host'] ) ||
!isset( $subconf['port'] ) ) {
223 throw new MWException( "Invalid HTCP rule for URL $url\n" );
227 // Construct a minimal HTCP request diagram
229 // Opcode 'CLR', no response desired, no auth
230 $htcpTransID = current( $ids );
233 $htcpSpecifier = pack( 'na4na*na8n',
234 4, 'HEAD', strlen( $url ), $url,
237 $htcpDataLen = 8 +
2 +
strlen( $htcpSpecifier );
238 $htcpLen = 4 +
$htcpDataLen +
2;
240 // Note! Squid gets the bit order of the first
241 // word wrong, wrt the RFC. Apparently no other
242 // implementation exists, so adapt to Squid
243 $htcpPacket = pack( 'nxxnCxNxxa*n',
244 $htcpLen, $htcpDataLen, $htcpOpCLR,
245 $htcpTransID, $htcpSpecifier, 2 );
247 wfDebugLog( 'squid', __METHOD__
.
248 "Purging URL $url via HTCP" );
249 foreach ( $conf as $subconf ) {
250 socket_sendto( $conn, $htcpPacket, $htcpLen, 0,
251 $subconf['host'], $subconf['port'] );
257 * Expand local URLs to fully-qualified URLs using the internal protocol
258 * and host defined in $wgInternalServer. Input that's already fully-
259 * qualified will be passed through unchanged.
261 * This is used to generate purge URLs that may be either local to the
262 * main wiki or include a non-native host, such as images hosted on a
263 * second internal server.
265 * Client functions should not need to call this.
270 public static function expand( $url ) {
271 return wfExpandUrl( $url, PROTO_INTERNAL
);
275 * Find the HTCP routing rule to use for a given URL.
276 * @param string $url URL to match
277 * @param array $rules Array of rules, see $wgHTCPRouting for format and behavior
278 * @return mixed Element of $rules that matched, or false if nothing matched
280 private static function getRuleForURL( $url, $rules ) {
281 foreach ( $rules as $regex => $routing ) {
282 if ( $regex === '' ||
preg_match( $regex, $url ) ) {
292 * @deprecated since 1.27
294 class SquidUpdate
extends CdnCacheUpdate
{
295 // Keep class name for b/c