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
;
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 */
32 protected $urls = array();
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|array $titles
52 * @param string[] $urlArr
53 * @return CdnCacheUpdate
55 public static function newFromTitles( $titles, $urlArr = array() ) {
56 /** @var Title $title */
57 foreach ( $titles as $title ) {
58 $urlArr = array_merge( $urlArr, $title->getCdnUrls() );
61 return new CdnCacheUpdate( $urlArr );
66 * @return CdnCacheUpdate
69 public static function newSimplePurge( Title
$title ) {
70 return new CdnCacheUpdate( $title->getCdnUrls() );
74 * Purges the list of URLs passed to the constructor.
76 public function doUpdate() {
77 global $wgCdnReboundPurgeDelay;
79 self
::purge( $this->urls
);
81 if ( $wgCdnReboundPurgeDelay > 0 ) {
82 JobQueueGroup
::singleton()->lazyPush( new CdnPurgeJob(
83 Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __CLASS__
),
85 'urls' => $this->urls
,
86 'jobReleaseTimestamp' => time() +
$wgCdnReboundPurgeDelay
93 * Purges a list of CDN nodes defined in $wgSquidServers.
94 * $urlArr should contain the full URLs to purge as values
95 * (example: $urlArr[] = 'http://my.host/something')
97 * @param string[] $urlArr List of full URLs to purge
99 public static function purge( array $urlArr ) {
100 global $wgSquidServers, $wgHTCPRouting;
106 // Remove duplicate URLs from list
107 $urlArr = array_unique( $urlArr );
109 wfDebugLog( 'squid', __METHOD__
. ': ' . implode( ' ', $urlArr ) );
111 // Reliably broadcast the purge to all edge nodes
112 $relayer = EventRelayerGroup
::singleton()->getRelayer( 'cdn-url-purges' );
116 'urls' => array_values( $urlArr ), // JSON array
117 'timestamp' => microtime( true )
121 // Send lossy UDP broadcasting if enabled
122 if ( $wgHTCPRouting ) {
123 self
::HTCPPurge( $urlArr );
126 // Do direct server purges if enabled (this does not scale very well)
127 if ( $wgSquidServers ) {
128 // Maximum number of parallel connections per squid
129 $maxSocketsPerSquid = 8;
130 // Number of requests to send per socket
131 // 400 seems to be a good tradeoff, opening a socket takes a while
132 $urlsPerSocket = 400;
133 $socketsPerSquid = ceil( count( $urlArr ) / $urlsPerSocket );
134 if ( $socketsPerSquid > $maxSocketsPerSquid ) {
135 $socketsPerSquid = $maxSocketsPerSquid;
138 $pool = new SquidPurgeClientPool
;
139 $chunks = array_chunk( $urlArr, ceil( count( $urlArr ) / $socketsPerSquid ) );
140 foreach ( $wgSquidServers as $server ) {
141 foreach ( $chunks as $chunk ) {
142 $client = new SquidPurgeClient( $server );
143 foreach ( $chunk as $url ) {
144 $client->queuePurge( $url );
146 $pool->addClient( $client );
155 * Send Hyper Text Caching Protocol (HTCP) CLR requests.
157 * @throws MWException
158 * @param string[] $urlArr Collection of URLs to purge
160 private static function HTCPPurge( array $urlArr ) {
161 global $wgHTCPRouting, $wgHTCPMulticastTTL;
163 // HTCP CLR operation
166 // @todo FIXME: PHP doesn't support these socket constants (include/linux/in.h)
167 if ( !defined( "IPPROTO_IP" ) ) {
168 define( "IPPROTO_IP", 0 );
169 define( "IP_MULTICAST_LOOP", 34 );
170 define( "IP_MULTICAST_TTL", 33 );
173 // pfsockopen doesn't work because we need set_sock_opt
174 $conn = socket_create( AF_INET
, SOCK_DGRAM
, SOL_UDP
);
176 $errstr = socket_strerror( socket_last_error() );
177 wfDebugLog( 'squid', __METHOD__
.
178 ": Error opening UDP socket: $errstr" );
183 // Set socket options
184 socket_set_option( $conn, IPPROTO_IP
, IP_MULTICAST_LOOP
, 0 );
185 if ( $wgHTCPMulticastTTL != 1 ) {
186 // Set multicast time to live (hop count) option on socket
187 socket_set_option( $conn, IPPROTO_IP
, IP_MULTICAST_TTL
,
188 $wgHTCPMulticastTTL );
191 // Get sequential trx IDs for packet loss counting
192 $ids = UIDGenerator
::newSequentialPerNodeIDs(
193 'squidhtcppurge', 32, count( $urlArr ), UIDGenerator
::QUICK_VOLATILE
196 foreach ( $urlArr as $url ) {
197 if ( !is_string( $url ) ) {
198 throw new MWException( 'Bad purge URL' );
200 $url = self
::expand( $url );
201 $conf = self
::getRuleForURL( $url, $wgHTCPRouting );
203 wfDebugLog( 'squid', __METHOD__
.
204 "No HTCP rule configured for URL {$url} , skipping" );
208 if ( isset( $conf['host'] ) && isset( $conf['port'] ) ) {
209 // Normalize single entries
210 $conf = array( $conf );
212 foreach ( $conf as $subconf ) {
213 if ( !isset( $subconf['host'] ) ||
!isset( $subconf['port'] ) ) {
214 throw new MWException( "Invalid HTCP rule for URL $url\n" );
218 // Construct a minimal HTCP request diagram
220 // Opcode 'CLR', no response desired, no auth
221 $htcpTransID = current( $ids );
224 $htcpSpecifier = pack( 'na4na*na8n',
225 4, 'HEAD', strlen( $url ), $url,
228 $htcpDataLen = 8 +
2 +
strlen( $htcpSpecifier );
229 $htcpLen = 4 +
$htcpDataLen +
2;
231 // Note! Squid gets the bit order of the first
232 // word wrong, wrt the RFC. Apparently no other
233 // implementation exists, so adapt to Squid
234 $htcpPacket = pack( 'nxxnCxNxxa*n',
235 $htcpLen, $htcpDataLen, $htcpOpCLR,
236 $htcpTransID, $htcpSpecifier, 2 );
238 wfDebugLog( 'squid', __METHOD__
.
239 "Purging URL $url via HTCP" );
240 foreach ( $conf as $subconf ) {
241 socket_sendto( $conn, $htcpPacket, $htcpLen, 0,
242 $subconf['host'], $subconf['port'] );
248 * Expand local URLs to fully-qualified URLs using the internal protocol
249 * and host defined in $wgInternalServer. Input that's already fully-
250 * qualified will be passed through unchanged.
252 * This is used to generate purge URLs that may be either local to the
253 * main wiki or include a non-native host, such as images hosted on a
254 * second internal server.
256 * Client functions should not need to call this.
261 public static function expand( $url ) {
262 return wfExpandUrl( $url, PROTO_INTERNAL
);
266 * Find the HTCP routing rule to use for a given URL.
267 * @param string $url URL to match
268 * @param array $rules Array of rules, see $wgHTCPRouting for format and behavior
269 * @return mixed Element of $rules that matched, or false if nothing matched
271 private static function getRuleForURL( $url, $rules ) {
272 foreach ( $rules as $regex => $routing ) {
273 if ( $regex === '' ||
preg_match( $regex, $url ) ) {
283 * @deprecated since 1.27
285 class SquidUpdate
extends CdnCacheUpdate
{
286 // Keep class name for b/c