Merge "Override momentjs's digit transform logic with MW's"
[lhc/web/wiklou.git] / includes / deferred / CdnCacheUpdate.php
1 <?php
2 /**
3 * CDN cache purging.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Cache
22 */
23
24 use Wikimedia\Assert\Assert;
25 use MediaWiki\MediaWikiServices;
26
27 /**
28 * Handles purging appropriate CDN URLs given a title (or titles)
29 * @ingroup Cache
30 */
31 class CdnCacheUpdate implements DeferrableUpdate, MergeableUpdate {
32 /** @var string[] Collection of URLs to purge */
33 protected $urls = [];
34
35 /**
36 * @param string[] $urlArr Collection of URLs to purge
37 */
38 public function __construct( array $urlArr ) {
39 $this->urls = $urlArr;
40 }
41
42 public function merge( MergeableUpdate $update ) {
43 /** @var CdnCacheUpdate $update */
44 Assert::parameterType( __CLASS__, $update, '$update' );
45
46 $this->urls = array_merge( $this->urls, $update->urls );
47 }
48
49 /**
50 * Create an update object from an array of Title objects, or a TitleArray object
51 *
52 * @param Traversable|array $titles
53 * @param string[] $urlArr
54 * @return CdnCacheUpdate
55 */
56 public static function newFromTitles( $titles, $urlArr = [] ) {
57 /** @var Title $title */
58 foreach ( $titles as $title ) {
59 $urlArr = array_merge( $urlArr, $title->getCdnUrls() );
60 }
61
62 return new CdnCacheUpdate( $urlArr );
63 }
64
65 /**
66 * @param Title $title
67 * @return CdnCacheUpdate
68 * @deprecated 1.27
69 */
70 public static function newSimplePurge( Title $title ) {
71 return new CdnCacheUpdate( $title->getCdnUrls() );
72 }
73
74 /**
75 * Purges the list of URLs passed to the constructor.
76 */
77 public function doUpdate() {
78 global $wgCdnReboundPurgeDelay;
79
80 self::purge( $this->urls );
81
82 if ( $wgCdnReboundPurgeDelay > 0 ) {
83 JobQueueGroup::singleton()->lazyPush( new CdnPurgeJob(
84 Title::makeTitle( NS_SPECIAL, 'Badtitle/' . __CLASS__ ),
85 [
86 'urls' => $this->urls,
87 'jobReleaseTimestamp' => time() + $wgCdnReboundPurgeDelay
88 ]
89 ) );
90 }
91 }
92
93 /**
94 * Purges a list of CDN nodes defined in $wgSquidServers.
95 * $urlArr should contain the full URLs to purge as values
96 * (example: $urlArr[] = 'http://my.host/something')
97 *
98 * @param string[] $urlArr List of full URLs to purge
99 */
100 public static function purge( array $urlArr ) {
101 global $wgSquidServers, $wgHTCPRouting;
102
103 if ( !$urlArr ) {
104 return;
105 }
106
107 // Remove duplicate URLs from list
108 $urlArr = array_unique( $urlArr );
109
110 wfDebugLog( 'squid', __METHOD__ . ': ' . implode( ' ', $urlArr ) );
111
112 // Reliably broadcast the purge to all edge nodes
113 $relayer = MediaWikiServices::getInstance()->getEventRelayerGroup()
114 ->getRelayer( 'cdn-url-purges' );
115 $relayer->notify(
116 'cdn-url-purges',
117 [
118 'urls' => array_values( $urlArr ), // JSON array
119 'timestamp' => microtime( true )
120 ]
121 );
122
123 // Send lossy UDP broadcasting if enabled
124 if ( $wgHTCPRouting ) {
125 self::HTCPPurge( $urlArr );
126 }
127
128 // Do direct server purges if enabled (this does not scale very well)
129 if ( $wgSquidServers ) {
130 // Maximum number of parallel connections per squid
131 $maxSocketsPerSquid = 8;
132 // Number of requests to send per socket
133 // 400 seems to be a good tradeoff, opening a socket takes a while
134 $urlsPerSocket = 400;
135 $socketsPerSquid = ceil( count( $urlArr ) / $urlsPerSocket );
136 if ( $socketsPerSquid > $maxSocketsPerSquid ) {
137 $socketsPerSquid = $maxSocketsPerSquid;
138 }
139
140 $pool = new SquidPurgeClientPool;
141 $chunks = array_chunk( $urlArr, ceil( count( $urlArr ) / $socketsPerSquid ) );
142 foreach ( $wgSquidServers as $server ) {
143 foreach ( $chunks as $chunk ) {
144 $client = new SquidPurgeClient( $server );
145 foreach ( $chunk as $url ) {
146 $client->queuePurge( $url );
147 }
148 $pool->addClient( $client );
149 }
150 }
151
152 $pool->run();
153 }
154 }
155
156 /**
157 * Send Hyper Text Caching Protocol (HTCP) CLR requests.
158 *
159 * @throws MWException
160 * @param string[] $urlArr Collection of URLs to purge
161 */
162 private static function HTCPPurge( array $urlArr ) {
163 global $wgHTCPRouting, $wgHTCPMulticastTTL;
164
165 // HTCP CLR operation
166 $htcpOpCLR = 4;
167
168 // @todo FIXME: PHP doesn't support these socket constants (include/linux/in.h)
169 if ( !defined( "IPPROTO_IP" ) ) {
170 define( "IPPROTO_IP", 0 );
171 define( "IP_MULTICAST_LOOP", 34 );
172 define( "IP_MULTICAST_TTL", 33 );
173 }
174
175 // pfsockopen doesn't work because we need set_sock_opt
176 $conn = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
177 if ( !$conn ) {
178 $errstr = socket_strerror( socket_last_error() );
179 wfDebugLog( 'squid', __METHOD__ .
180 ": Error opening UDP socket: $errstr" );
181
182 return;
183 }
184
185 // Set socket options
186 socket_set_option( $conn, IPPROTO_IP, IP_MULTICAST_LOOP, 0 );
187 if ( $wgHTCPMulticastTTL != 1 ) {
188 // Set multicast time to live (hop count) option on socket
189 socket_set_option( $conn, IPPROTO_IP, IP_MULTICAST_TTL,
190 $wgHTCPMulticastTTL );
191 }
192
193 // Get sequential trx IDs for packet loss counting
194 $ids = UIDGenerator::newSequentialPerNodeIDs(
195 'squidhtcppurge', 32, count( $urlArr ), UIDGenerator::QUICK_VOLATILE
196 );
197
198 foreach ( $urlArr as $url ) {
199 if ( !is_string( $url ) ) {
200 throw new MWException( 'Bad purge URL' );
201 }
202 $url = self::expand( $url );
203 $conf = self::getRuleForURL( $url, $wgHTCPRouting );
204 if ( !$conf ) {
205 wfDebugLog( 'squid', __METHOD__ .
206 "No HTCP rule configured for URL {$url} , skipping" );
207 continue;
208 }
209
210 if ( isset( $conf['host'] ) && isset( $conf['port'] ) ) {
211 // Normalize single entries
212 $conf = [ $conf ];
213 }
214 foreach ( $conf as $subconf ) {
215 if ( !isset( $subconf['host'] ) || !isset( $subconf['port'] ) ) {
216 throw new MWException( "Invalid HTCP rule for URL $url\n" );
217 }
218 }
219
220 // Construct a minimal HTCP request diagram
221 // as per RFC 2756
222 // Opcode 'CLR', no response desired, no auth
223 $htcpTransID = current( $ids );
224 next( $ids );
225
226 $htcpSpecifier = pack( 'na4na*na8n',
227 4, 'HEAD', strlen( $url ), $url,
228 8, 'HTTP/1.0', 0 );
229
230 $htcpDataLen = 8 + 2 + strlen( $htcpSpecifier );
231 $htcpLen = 4 + $htcpDataLen + 2;
232
233 // Note! Squid gets the bit order of the first
234 // word wrong, wrt the RFC. Apparently no other
235 // implementation exists, so adapt to Squid
236 $htcpPacket = pack( 'nxxnCxNxxa*n',
237 $htcpLen, $htcpDataLen, $htcpOpCLR,
238 $htcpTransID, $htcpSpecifier, 2 );
239
240 wfDebugLog( 'squid', __METHOD__ .
241 "Purging URL $url via HTCP" );
242 foreach ( $conf as $subconf ) {
243 socket_sendto( $conn, $htcpPacket, $htcpLen, 0,
244 $subconf['host'], $subconf['port'] );
245 }
246 }
247 }
248
249 /**
250 * Expand local URLs to fully-qualified URLs using the internal protocol
251 * and host defined in $wgInternalServer. Input that's already fully-
252 * qualified will be passed through unchanged.
253 *
254 * This is used to generate purge URLs that may be either local to the
255 * main wiki or include a non-native host, such as images hosted on a
256 * second internal server.
257 *
258 * Client functions should not need to call this.
259 *
260 * @param string $url
261 * @return string
262 */
263 public static function expand( $url ) {
264 return wfExpandUrl( $url, PROTO_INTERNAL );
265 }
266
267 /**
268 * Find the HTCP routing rule to use for a given URL.
269 * @param string $url URL to match
270 * @param array $rules Array of rules, see $wgHTCPRouting for format and behavior
271 * @return mixed Element of $rules that matched, or false if nothing matched
272 */
273 private static function getRuleForURL( $url, $rules ) {
274 foreach ( $rules as $regex => $routing ) {
275 if ( $regex === '' || preg_match( $regex, $url ) ) {
276 return $routing;
277 }
278 }
279
280 return false;
281 }
282 }
283
284 /**
285 * @deprecated since 1.27
286 */
287 class SquidUpdate extends CdnCacheUpdate {
288 // Keep class name for b/c
289 }