Merge "Timing::measure(): handle missing marks better"
[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
26 /**
27 * Handles purging appropriate CDN URLs given a title (or titles)
28 * @ingroup Cache
29 */
30 class CdnCacheUpdate implements DeferrableUpdate, MergeableUpdate {
31 /** @var string[] Collection of URLs to purge */
32 protected $urls = array();
33
34 /**
35 * @param string[] $urlArr Collection of URLs to purge
36 */
37 public function __construct( array $urlArr ) {
38 $this->urls = $urlArr;
39 }
40
41 public function merge( MergeableUpdate $update ) {
42 /** @var CdnCacheUpdate $update */
43 Assert::parameterType( __CLASS__, $update, '$update' );
44
45 $this->urls = array_merge( $this->urls, $update->urls );
46 }
47
48 /**
49 * Create an update object from an array of Title objects, or a TitleArray object
50 *
51 * @param Traversable|array $titles
52 * @param string[] $urlArr
53 * @return CdnCacheUpdate
54 */
55 public static function newFromTitles( $titles, $urlArr = array() ) {
56 /** @var Title $title */
57 foreach ( $titles as $title ) {
58 $urlArr = array_merge( $urlArr, $title->getSquidURLs() );
59 }
60
61 return new CdnCacheUpdate( $urlArr );
62 }
63
64 /**
65 * @param Title $title
66 * @return CdnCacheUpdate
67 * @deprecated 1.27
68 */
69 public static function newSimplePurge( Title $title ) {
70 return new CdnCacheUpdate( $title->getSquidURLs() );
71 }
72
73 /**
74 * Purges the list of URLs passed to the constructor.
75 */
76 public function doUpdate() {
77 global $wgCdnReboundPurgeDelay;
78
79 self::purge( $this->urls );
80
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
87 )
88 ) );
89 }
90 }
91
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')
96 *
97 * @param string[] $urlArr List of full URLs to purge
98 */
99 public static function purge( array $urlArr ) {
100 global $wgSquidServers, $wgHTCPRouting;
101
102 if ( !$urlArr ) {
103 return;
104 }
105
106 // Remove duplicate URLs from list
107 $urlArr = array_unique( $urlArr );
108
109 wfDebugLog( 'squid', __METHOD__ . ': ' . implode( ' ', $urlArr ) );
110
111 if ( $wgHTCPRouting ) {
112 self::HTCPPurge( $urlArr );
113 }
114
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;
124 }
125
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 );
133 }
134 $pool->addClient( $client );
135 }
136 }
137
138 $pool->run();
139 }
140 }
141
142 /**
143 * Send Hyper Text Caching Protocol (HTCP) CLR requests.
144 *
145 * @throws MWException
146 * @param string[] $urlArr Collection of URLs to purge
147 */
148 private static function HTCPPurge( array $urlArr ) {
149 global $wgHTCPRouting, $wgHTCPMulticastTTL;
150
151 // HTCP CLR operation
152 $htcpOpCLR = 4;
153
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 );
159 }
160
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" );
167
168 return;
169 }
170
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 );
177 }
178
179 // Get sequential trx IDs for packet loss counting
180 $ids = UIDGenerator::newSequentialPerNodeIDs(
181 'squidhtcppurge', 32, count( $urlArr ), UIDGenerator::QUICK_VOLATILE
182 );
183
184 foreach ( $urlArr as $url ) {
185 if ( !is_string( $url ) ) {
186 throw new MWException( 'Bad purge URL' );
187 }
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;
194 }
195
196 if ( isset( $conf['host'] ) && isset( $conf['port'] ) ) {
197 // Normalize single entries
198 $conf = array( $conf );
199 }
200 foreach ( $conf as $subconf ) {
201 if ( !isset( $subconf['host'] ) || !isset( $subconf['port'] ) ) {
202 throw new MWException( "Invalid HTCP rule for URL $url\n" );
203 }
204 }
205
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 );
211
212 $htcpSpecifier = pack( 'na4na*na8n',
213 4, 'HEAD', strlen( $url ), $url,
214 8, 'HTTP/1.0', 0 );
215
216 $htcpDataLen = 8 + 2 + strlen( $htcpSpecifier );
217 $htcpLen = 4 + $htcpDataLen + 2;
218
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 );
225
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'] );
231 }
232 }
233 }
234
235 /**
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.
239 *
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.
243 *
244 * Client functions should not need to call this.
245 *
246 * @param string $url
247 * @return string
248 */
249 public static function expand( $url ) {
250 return wfExpandUrl( $url, PROTO_INTERNAL );
251 }
252
253 /**
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
258 */
259 private static function getRuleForURL( $url, $rules ) {
260 foreach ( $rules as $regex => $routing ) {
261 if ( $regex === '' || preg_match( $regex, $url ) ) {
262 return $routing;
263 }
264 }
265
266 return false;
267 }
268 }
269
270 /**
271 * @deprecated since 1.27
272 */
273 class SquidUpdate extends CdnCacheUpdate {
274 // Keep class name for b/c
275 }