PageRenderTime 48ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/deferred/CdnCacheUpdate.php

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