Import: Handle uploads with sha1 starting with 0 properly
[mediawiki.git] / includes / deferred / CdnCacheUpdate.php
blob9f7d8caec78e42fbad93c5efca1fbe4cb33fbd84
1 <?php
2 /**
3 * CDN cache purging.
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
20 * @file
21 * @ingroup Cache
24 use Wikimedia\Assert\Assert;
26 /**
27 * Handles purging appropriate CDN URLs given a title (or titles)
28 * @ingroup Cache
30 class CdnCacheUpdate implements DeferrableUpdate, MergeableUpdate {
31 /** @var string[] Collection of URLs to purge */
32 protected $urls = array();
34 /**
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 );
48 /**
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 );
64 /**
65 * @param Title $title
66 * @return CdnCacheUpdate
67 * @deprecated 1.27
69 public static function newSimplePurge( Title $title ) {
70 return new CdnCacheUpdate( $title->getCdnUrls() );
73 /**
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__ ),
84 array(
85 'urls' => $this->urls,
86 'jobReleaseTimestamp' => time() + $wgCdnReboundPurgeDelay
88 ) );
92 /**
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;
102 if ( !$urlArr ) {
103 return;
106 // Remove duplicate URLs from list
107 $urlArr = array_unique( $urlArr );
109 wfDebugLog( 'squid', __METHOD__ . ': ' . implode( ' ', $urlArr ) );
111 if ( $wgHTCPRouting ) {
112 self::HTCPPurge( $urlArr );
115 if ( $wgSquidServers ) {
116 // Maximum number of parallel connections per squid
117 $maxSocketsPerSquid = 8;
118 // Number of requests to send per socket
119 // 400 seems to be a good tradeoff, opening a socket takes a while
120 $urlsPerSocket = 400;
121 $socketsPerSquid = ceil( count( $urlArr ) / $urlsPerSocket );
122 if ( $socketsPerSquid > $maxSocketsPerSquid ) {
123 $socketsPerSquid = $maxSocketsPerSquid;
126 $pool = new SquidPurgeClientPool;
127 $chunks = array_chunk( $urlArr, ceil( count( $urlArr ) / $socketsPerSquid ) );
128 foreach ( $wgSquidServers as $server ) {
129 foreach ( $chunks as $chunk ) {
130 $client = new SquidPurgeClient( $server );
131 foreach ( $chunk as $url ) {
132 $client->queuePurge( $url );
134 $pool->addClient( $client );
138 $pool->run();
143 * Send Hyper Text Caching Protocol (HTCP) CLR requests.
145 * @throws MWException
146 * @param string[] $urlArr Collection of URLs to purge
148 private static function HTCPPurge( array $urlArr ) {
149 global $wgHTCPRouting, $wgHTCPMulticastTTL;
151 // HTCP CLR operation
152 $htcpOpCLR = 4;
154 // @todo FIXME: PHP doesn't support these socket constants (include/linux/in.h)
155 if ( !defined( "IPPROTO_IP" ) ) {
156 define( "IPPROTO_IP", 0 );
157 define( "IP_MULTICAST_LOOP", 34 );
158 define( "IP_MULTICAST_TTL", 33 );
161 // pfsockopen doesn't work because we need set_sock_opt
162 $conn = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
163 if ( !$conn ) {
164 $errstr = socket_strerror( socket_last_error() );
165 wfDebugLog( 'squid', __METHOD__ .
166 ": Error opening UDP socket: $errstr" );
168 return;
171 // Set socket options
172 socket_set_option( $conn, IPPROTO_IP, IP_MULTICAST_LOOP, 0 );
173 if ( $wgHTCPMulticastTTL != 1 ) {
174 // Set multicast time to live (hop count) option on socket
175 socket_set_option( $conn, IPPROTO_IP, IP_MULTICAST_TTL,
176 $wgHTCPMulticastTTL );
179 // Get sequential trx IDs for packet loss counting
180 $ids = UIDGenerator::newSequentialPerNodeIDs(
181 'squidhtcppurge', 32, count( $urlArr ), UIDGenerator::QUICK_VOLATILE
184 foreach ( $urlArr as $url ) {
185 if ( !is_string( $url ) ) {
186 throw new MWException( 'Bad purge URL' );
188 $url = self::expand( $url );
189 $conf = self::getRuleForURL( $url, $wgHTCPRouting );
190 if ( !$conf ) {
191 wfDebugLog( 'squid', __METHOD__ .
192 "No HTCP rule configured for URL {$url} , skipping" );
193 continue;
196 if ( isset( $conf['host'] ) && isset( $conf['port'] ) ) {
197 // Normalize single entries
198 $conf = array( $conf );
200 foreach ( $conf as $subconf ) {
201 if ( !isset( $subconf['host'] ) || !isset( $subconf['port'] ) ) {
202 throw new MWException( "Invalid HTCP rule for URL $url\n" );
206 // Construct a minimal HTCP request diagram
207 // as per RFC 2756
208 // Opcode 'CLR', no response desired, no auth
209 $htcpTransID = current( $ids );
210 next( $ids );
212 $htcpSpecifier = pack( 'na4na*na8n',
213 4, 'HEAD', strlen( $url ), $url,
214 8, 'HTTP/1.0', 0 );
216 $htcpDataLen = 8 + 2 + strlen( $htcpSpecifier );
217 $htcpLen = 4 + $htcpDataLen + 2;
219 // Note! Squid gets the bit order of the first
220 // word wrong, wrt the RFC. Apparently no other
221 // implementation exists, so adapt to Squid
222 $htcpPacket = pack( 'nxxnCxNxxa*n',
223 $htcpLen, $htcpDataLen, $htcpOpCLR,
224 $htcpTransID, $htcpSpecifier, 2 );
226 wfDebugLog( 'squid', __METHOD__ .
227 "Purging URL $url via HTCP" );
228 foreach ( $conf as $subconf ) {
229 socket_sendto( $conn, $htcpPacket, $htcpLen, 0,
230 $subconf['host'], $subconf['port'] );
236 * Expand local URLs to fully-qualified URLs using the internal protocol
237 * and host defined in $wgInternalServer. Input that's already fully-
238 * qualified will be passed through unchanged.
240 * This is used to generate purge URLs that may be either local to the
241 * main wiki or include a non-native host, such as images hosted on a
242 * second internal server.
244 * Client functions should not need to call this.
246 * @param string $url
247 * @return string
249 public static function expand( $url ) {
250 return wfExpandUrl( $url, PROTO_INTERNAL );
254 * Find the HTCP routing rule to use for a given URL.
255 * @param string $url URL to match
256 * @param array $rules Array of rules, see $wgHTCPRouting for format and behavior
257 * @return mixed Element of $rules that matched, or false if nothing matched
259 private static function getRuleForURL( $url, $rules ) {
260 foreach ( $rules as $regex => $routing ) {
261 if ( $regex === '' || preg_match( $regex, $url ) ) {
262 return $routing;
266 return false;
271 * @deprecated since 1.27
273 class SquidUpdate extends CdnCacheUpdate {
274 // Keep class name for b/c