MediaWiki  master
MultiWriteBagOStuff.php
Go to the documentation of this file.
1 <?php
24 
37  protected $caches;
39  protected $asyncWrites = false;
41  protected $cacheIndexes = [];
42 
43  const UPGRADE_TTL = 3600; // TTL when a key is copied to a higher cache tier
44 
65  public function __construct( $params ) {
66  parent::__construct( $params );
67 
68  if ( empty( $params['caches'] ) || !is_array( $params['caches'] ) ) {
69  throw new InvalidArgumentException(
70  __METHOD__ . ': "caches" parameter must be an array of caches'
71  );
72  }
73 
74  $this->caches = [];
75  foreach ( $params['caches'] as $cacheInfo ) {
76  if ( $cacheInfo instanceof BagOStuff ) {
77  $this->caches[] = $cacheInfo;
78  } else {
79  if ( !isset( $cacheInfo['args'] ) ) {
80  // B/C for when $cacheInfo was for ObjectCache::newFromParams().
81  // Callers intenting this to be for ObjectFactory::getObjectFromSpec
82  // should have set "args" per the docs above. Doings so avoids extra
83  // (likely harmless) params (factory/class/calls) ending up in "args".
84  $cacheInfo['args'] = [ $cacheInfo ];
85  }
86  $this->caches[] = ObjectFactory::getObjectFromSpec( $cacheInfo );
87  }
88  }
89  $this->mergeFlagMaps( $this->caches );
90 
91  $this->asyncWrites = (
92  isset( $params['replication'] ) &&
93  $params['replication'] === 'async' &&
94  is_callable( $this->asyncHandler )
95  );
96 
97  $this->cacheIndexes = array_keys( $this->caches );
98  }
99 
100  public function setDebug( $debug ) {
101  foreach ( $this->caches as $cache ) {
102  $cache->setDebug( $debug );
103  }
104  }
105 
106  public function get( $key, $flags = 0 ) {
107  if ( ( $flags & self::READ_LATEST ) == self::READ_LATEST ) {
108  // If the latest write was a delete(), we do NOT want to fallback
109  // to the other tiers and possibly see the old value. Also, this
110  // is used by merge(), which only needs to hit the primary.
111  return $this->caches[0]->get( $key, $flags );
112  }
113 
114  $value = false;
115  $missIndexes = []; // backends checked
116  foreach ( $this->caches as $i => $cache ) {
117  $value = $cache->get( $key, $flags );
118  if ( $value !== false ) {
119  break;
120  }
121  $missIndexes[] = $i;
122  }
123 
124  if ( $value !== false
125  && $missIndexes
126  && ( $flags & self::READ_VERIFIED ) == self::READ_VERIFIED
127  ) {
128  // Backfill the value to the higher (and often faster/smaller) cache tiers
129  $this->doWrite(
130  $missIndexes,
131  $this->asyncWrites,
132  'set',
133  [ $key, $value, self::UPGRADE_TTL ]
134  );
135  }
136 
137  return $value;
138  }
139  public function set( $key, $value, $exptime = 0, $flags = 0 ) {
140  return $this->doWrite(
141  $this->cacheIndexes,
142  $this->usesAsyncWritesGivenFlags( $flags ),
143  __FUNCTION__,
144  func_get_args()
145  );
146  }
147 
148  public function delete( $key, $flags = 0 ) {
149  return $this->doWrite(
150  $this->cacheIndexes,
151  $this->usesAsyncWritesGivenFlags( $flags ),
152  __FUNCTION__,
153  func_get_args()
154  );
155  }
156 
157  public function add( $key, $value, $exptime = 0, $flags = 0 ) {
158  // Try the write to the top-tier cache
159  $ok = $this->doWrite(
160  [ 0 ],
161  $this->usesAsyncWritesGivenFlags( $flags ),
162  __FUNCTION__,
163  func_get_args()
164  );
165 
166  if ( $ok ) {
167  // Relay the add() using set() if it succeeded. This is meant to handle certain
168  // migration scenarios where the same store might get written to twice for certain
169  // keys. In that case, it does not make sense to return false due to "self-conflicts".
170  return $this->doWrite(
171  array_slice( $this->cacheIndexes, 1 ),
172  $this->usesAsyncWritesGivenFlags( $flags ),
173  'set',
174  [ $key, $value, $exptime, $flags ]
175  );
176  }
177 
178  return false;
179  }
180 
181  public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
182  return $this->doWrite(
183  $this->cacheIndexes,
184  $this->usesAsyncWritesGivenFlags( $flags ),
185  __FUNCTION__,
186  func_get_args()
187  );
188  }
189 
190  public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
191  return $this->doWrite(
192  $this->cacheIndexes,
193  $this->usesAsyncWritesGivenFlags( $flags ),
194  __FUNCTION__,
195  func_get_args()
196  );
197  }
198 
199  public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
200  // Only need to lock the first cache; also avoids deadlocks
201  return $this->caches[0]->lock( $key, $timeout, $expiry, $rclass );
202  }
203 
204  public function unlock( $key ) {
205  // Only the first cache is locked
206  return $this->caches[0]->unlock( $key );
207  }
216  public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
217  $ret = false;
218  foreach ( $this->caches as $cache ) {
219  if ( $cache->deleteObjectsExpiringBefore( $date, $progressCallback ) ) {
220  $ret = true;
221  }
222  }
223 
224  return $ret;
225  }
226 
227  public function getMulti( array $keys, $flags = 0 ) {
228  // Just iterate over each key in order to handle all the backfill logic
229  $res = [];
230  foreach ( $keys as $key ) {
231  $val = $this->get( $key, $flags );
232  if ( $val !== false ) {
233  $res[$key] = $val;
234  }
235  }
236 
237  return $res;
238  }
239 
240  public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
241  return $this->doWrite(
242  $this->cacheIndexes,
243  $this->usesAsyncWritesGivenFlags( $flags ),
244  __FUNCTION__,
245  func_get_args()
246  );
247  }
248 
249  public function deleteMulti( array $data, $flags = 0 ) {
250  return $this->doWrite(
251  $this->cacheIndexes,
252  $this->usesAsyncWritesGivenFlags( $flags ),
253  __FUNCTION__,
254  func_get_args()
255  );
256  }
257 
258  public function incr( $key, $value = 1 ) {
259  return $this->doWrite(
260  $this->cacheIndexes,
261  $this->asyncWrites,
262  __FUNCTION__,
263  func_get_args()
264  );
265  }
266 
267  public function decr( $key, $value = 1 ) {
268  return $this->doWrite(
269  $this->cacheIndexes,
270  $this->asyncWrites,
271  __FUNCTION__,
272  func_get_args()
273  );
274  }
275 
276  public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
277  return $this->doWrite(
278  $this->cacheIndexes,
279  $this->asyncWrites,
280  __FUNCTION__,
281  func_get_args()
282  );
283  }
284 
285  public function getLastError() {
286  return $this->caches[0]->getLastError();
287  }
288 
289  public function clearLastError() {
290  $this->caches[0]->clearLastError();
291  }
301  protected function doWrite( $indexes, $asyncWrites, $method, array $args ) {
302  $ret = true;
303 
304  if ( array_diff( $indexes, [ 0 ] ) && $asyncWrites && $method !== 'merge' ) {
305  // Deep-clone $args to prevent misbehavior when something writes an
306  // object to the BagOStuff then modifies it afterwards, e.g. T168040.
307  $args = unserialize( serialize( $args ) );
308  }
309 
310  foreach ( $indexes as $i ) {
311  $cache = $this->caches[$i];
312  if ( $i == 0 || !$asyncWrites ) {
313  // First store or in sync mode: write now and get result
314  if ( !$cache->$method( ...$args ) ) {
315  $ret = false;
316  }
317  } else {
318  // Secondary write in async mode: do not block this HTTP request
321  function () use ( $cache, $method, $args, $logger ) {
322  if ( !$cache->$method( ...$args ) ) {
323  $logger->warning( "Async $method op failed" );
324  }
325  }
326  );
327  }
328  }
329 
330  return $ret;
331  }
332 
337  protected function usesAsyncWritesGivenFlags( $flags ) {
338  return ( ( $flags & self::WRITE_SYNC ) == self::WRITE_SYNC ) ? false : $this->asyncWrites;
339  }
340 
341  public function makeKeyInternal( $keyspace, $args ) {
342  return $this->caches[0]->makeKeyInternal( ...func_get_args() );
343  }
344 
345  public function makeKey( $class, $component = null ) {
346  return $this->caches[0]->makeKey( ...func_get_args() );
347  }
348 
349  public function makeGlobalKey( $class, $component = null ) {
350  return $this->caches[0]->makeGlobalKey( ...func_get_args() );
351  }
352 
353  protected function doGet( $key, $flags = 0, &$casToken = null ) {
354  throw new LogicException( __METHOD__ . ': proxy class does not need this method.' );
355  }
356 }
makeGlobalKey( $class, $component=null)
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
add( $key, $value, $exptime=0, $flags=0)
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
serialize()
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1982
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$value
string $keyspace
Definition: BagOStuff.php:64
makeKeyInternal( $keyspace, $args)
incrWithInit( $key, $ttl, $value=1, $init=1)
if( $line===false) $args
Definition: cdb.php:64
lock( $key, $timeout=6, $expiry=6, $rclass='')
getMulti(array $keys, $flags=0)
doWrite( $indexes, $asyncWrites, $method, array $args)
Apply a write method to the backing caches specified by $indexes (in order)
deleteObjectsExpiringBefore( $date, $progressCallback=false)
Delete objects expiring before a certain date.
A cache class that replicates all writes to multiple child caches.
changeTTL( $key, $exptime=0, $flags=0)
bool $asyncWrites
Use async secondary writes.
$res
Definition: database.txt:21
__construct( $params)
$params include:
$cache
Definition: mcc.php:33
$params
unserialize( $serialized)
mergeFlagMaps(array $bags)
Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map...
Definition: BagOStuff.php:793
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
merge( $key, callable $callback, $exptime=0, $attempts=10, $flags=0)
doGet( $key, $flags=0, &$casToken=null)
setMulti(array $data, $exptime=0, $flags=0)
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
int [] $cacheIndexes
List of all backing cache indexes.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
LoggerInterface $logger
Definition: BagOStuff.php:66
makeKey( $class, $component=null)
$debug
Definition: mcc.php:31
deleteMulti(array $data, $flags=0)
callable null $asyncHandler
Definition: BagOStuff.php:68