3 * Generator of database load balancing objects.
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
24 namespace Wikimedia\Rdbms
;
26 use Psr\Log\LoggerAwareInterface
;
27 use Psr\Log\LoggerInterface
;
28 use Psr\Log\NullLogger
;
29 use Wikimedia\WaitConditionLoop
;
33 * Class for ensuring a consistent ordering of events as seen by the user, despite replication.
34 * Kind of like Hawking's [[Chronology Protection Agency]].
36 class ChronologyProtector
implements LoggerAwareInterface
{
39 /** @var LoggerInterface */
42 /** @var string Storage key name */
44 /** @var string Hash of client parameters */
46 /** @var int|null Expected minimum index of the last write to the position store */
47 protected $waitForPosIndex;
48 /** @var int Max seconds to wait on positions to appear */
49 protected $waitForPosStoreTimeout = self
::POS_STORE_WAIT_TIMEOUT
;
50 /** @var bool Whether to no-op all method calls */
51 protected $enabled = true;
52 /** @var bool Whether to check and wait on positions */
53 protected $wait = true;
55 /** @var bool Whether the client data was loaded */
56 protected $initialized = false;
57 /** @var DBMasterPos[] Map of (DB master name => position) */
58 protected $startupPositions = [];
59 /** @var DBMasterPos[] Map of (DB master name => position) */
60 protected $shutdownPositions = [];
61 /** @var float[] Map of (DB master name => 1) */
62 protected $shutdownTouchDBs = [];
64 /** @var int Seconds to store positions */
65 const POSITION_TTL
= 60;
66 /** @var int Seconds to store position write index cookies (safely less than POSITION_TTL) */
67 const POSITION_COOKIE_TTL
= 60;
68 /** @var int Max time to wait for positions to appear */
69 const POS_STORE_WAIT_TIMEOUT
= 5;
72 * @param BagOStuff $store
73 * @param array[] $client Map of (ip: <IP>, agent: <user-agent> [, clientId: <hash>] )
74 * @param int|null $posIndex Write counter index [optional]
77 public function __construct( BagOStuff
$store, array $client, $posIndex = null ) {
78 $this->store
= $store;
79 $this->clientId
= isset( $client['clientId'] )
81 : md5( $client['ip'] . "\n" . $client['agent'] );
82 $this->key
= $store->makeGlobalKey( __CLASS__
, $this->clientId
, 'v2' );
83 $this->waitForPosIndex
= $posIndex;
84 $this->logger
= new NullLogger();
87 public function setLogger( LoggerInterface
$logger ) {
88 $this->logger
= $logger;
92 * @return string Client ID hash
95 public function getClientId() {
96 return $this->clientId
;
100 * @param bool $enabled Whether to no-op all method calls
103 public function setEnabled( $enabled ) {
104 $this->enabled
= $enabled;
108 * @param bool $enabled Whether to check and wait on positions
111 public function setWaitEnabled( $enabled ) {
112 $this->wait
= $enabled;
116 * Initialise a ILoadBalancer to give it appropriate chronology protection.
118 * If the stash has a previous master position recorded, this will try to
119 * make sure that the next query to a replica DB of that master will see changes up
120 * to that position by delaying execution. The delay may timeout and allow stale
121 * data if no non-lagged replica DBs are available.
123 * @param ILoadBalancer $lb
126 public function initLB( ILoadBalancer
$lb ) {
127 if ( !$this->enabled ||
$lb->getServerCount() <= 1 ) {
128 return; // non-replicated setup or disabled
131 $this->initPositions();
133 $masterName = $lb->getServerName( $lb->getWriterIndex() );
135 isset( $this->startupPositions
[$masterName] ) &&
136 $this->startupPositions
[$masterName] instanceof DBMasterPos
138 $pos = $this->startupPositions
[$masterName];
139 $this->logger
->debug( __METHOD__
. ": LB for '$masterName' set to pos $pos\n" );
140 $lb->waitFor( $pos );
145 * Notify the ChronologyProtector that the ILoadBalancer is about to shut
146 * down. Saves replication positions.
148 * @param ILoadBalancer $lb
151 public function shutdownLB( ILoadBalancer
$lb ) {
152 if ( !$this->enabled
) {
153 return; // not enabled
154 } elseif ( !$lb->hasOrMadeRecentMasterChanges( INF
) ) {
155 // Only save the position if writes have been done on the connection
159 $masterName = $lb->getServerName( $lb->getWriterIndex() );
160 if ( $lb->getServerCount() > 1 ) {
161 $pos = $lb->getMasterPos();
163 $this->logger
->debug( __METHOD__
. ": LB for '$masterName' has pos $pos\n" );
164 $this->shutdownPositions
[$masterName] = $pos;
167 $this->logger
->debug( __METHOD__
. ": DB '$masterName' touched\n" );
169 $this->shutdownTouchDBs
[$masterName] = 1;
173 * Notify the ChronologyProtector that the LBFactory is done calling shutdownLB() for now.
174 * May commit chronology data to persistent storage.
176 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
177 * @param string $mode One of (sync, async); whether to wait on remote datacenters
178 * @param int|null &$cpIndex DB position key write counter; incremented on update
179 * @return DBMasterPos[] Empty on success; returns the (db name => position) map on failure
181 public function shutdown( callable
$workCallback = null, $mode = 'sync', &$cpIndex = null ) {
182 if ( !$this->enabled
) {
186 $store = $this->store
;
187 // Some callers might want to know if a user recently touched a DB.
188 // These writes do not need to block on all datacenters receiving them.
189 foreach ( $this->shutdownTouchDBs
as $dbName => $unused ) {
191 $this->getTouchedKey( $this->store
, $dbName ),
197 if ( !count( $this->shutdownPositions
) ) {
198 return []; // nothing to save
201 $this->logger
->debug( __METHOD__
. ": saving master pos for " .
202 implode( ', ', array_keys( $this->shutdownPositions
) ) . "\n"
205 // CP-protected writes should overwhelmingly go to the master datacenter, so use a
206 // DC-local lock to merge the values. Use a DC-local get() and a synchronous all-DC
207 // set(). This makes it possible for the BagOStuff class to write in parallel to all
208 // DCs with one RTT. The use of WRITE_SYNC avoids needing READ_LATEST for the get().
209 if ( $store->lock( $this->key
, 3 ) ) {
210 if ( $workCallback ) {
211 // Let the store run the work before blocking on a replication sync barrier.
212 // If replication caught up while the work finished, the barrier will be fast.
213 $store->addBusyCallback( $workCallback );
217 $this->mergePositions(
218 $store->get( $this->key
),
219 $this->shutdownPositions
,
223 ( $mode === 'sync' ) ?
$store::WRITE_SYNC
: 0
225 $store->unlock( $this->key
);
231 $cpIndex = null; // nothing saved
232 $bouncedPositions = $this->shutdownPositions
;
233 // Raced out too many times or stash is down
234 $this->logger
->warning( __METHOD__
. ": failed to save master pos for " .
235 implode( ', ', array_keys( $this->shutdownPositions
) ) . "\n"
237 } elseif ( $mode === 'sync' &&
238 $store->getQoS( $store::ATTR_SYNCWRITES
) < $store::QOS_SYNCWRITES_BE
240 // Positions may not be in all datacenters, force LBFactory to play it safe
241 $this->logger
->info( __METHOD__
. ": store may not support synchronous writes." );
242 $bouncedPositions = $this->shutdownPositions
;
244 $bouncedPositions = [];
247 return $bouncedPositions;
251 * @param string $dbName DB master name (e.g. "db1052")
252 * @return float|bool UNIX timestamp when client last touched the DB; false if not on record
255 public function getTouched( $dbName ) {
256 return $this->store
->get( $this->getTouchedKey( $this->store
, $dbName ) );
260 * @param BagOStuff $store
261 * @param string $dbName
264 private function getTouchedKey( BagOStuff
$store, $dbName ) {
265 return $store->makeGlobalKey( __CLASS__
, 'mtime', $this->clientId
, $dbName );
269 * Load in previous master positions for the client
271 protected function initPositions() {
272 if ( $this->initialized
) {
276 $this->initialized
= true;
278 // If there is an expectation to see master positions from a certain write
279 // index or higher, then block until it appears, or until a timeout is reached.
280 // Since the write index restarts each time the key is created, it is possible that
281 // a lagged store has a matching key write index. However, in that case, it should
282 // already be expired and thus treated as non-existing, maintaining correctness.
283 if ( $this->waitForPosIndex
> 0 ) {
285 $indexReached = null; // highest index reached in the position store
286 $loop = new WaitConditionLoop(
287 function () use ( &$data, &$indexReached ) {
288 $data = $this->store
->get( $this->key
);
289 if ( !is_array( $data ) ) {
290 return WaitConditionLoop
::CONDITION_CONTINUE
; // not found yet
291 } elseif ( !isset( $data['writeIndex'] ) ) {
292 return WaitConditionLoop
::CONDITION_REACHED
; // b/c
294 $indexReached = max( $data['writeIndex'], $indexReached );
296 return ( $data['writeIndex'] >= $this->waitForPosIndex
)
297 ? WaitConditionLoop
::CONDITION_REACHED
298 : WaitConditionLoop
::CONDITION_CONTINUE
;
300 $this->waitForPosStoreTimeout
302 $result = $loop->invoke();
303 $waitedMs = $loop->getLastWaitTime() * 1e3
;
305 if ( $result == $loop::CONDITION_REACHED
) {
306 $this->logger
->debug(
307 __METHOD__
. ": expected and found position index.",
309 'cpPosIndex' => $this->waitForPosIndex
,
310 'waitTimeMs' => $waitedMs
314 $this->logger
->warning(
315 __METHOD__
. ": expected but failed to find position index.",
317 'cpPosIndex' => $this->waitForPosIndex
,
318 'indexReached' => $indexReached,
319 'waitTimeMs' => $waitedMs
324 $data = $this->store
->get( $this->key
);
327 $this->startupPositions
= $data ?
$data['positions'] : [];
328 $this->logger
->debug( __METHOD__
. ": key is {$this->key} (read)\n" );
330 $this->startupPositions
= [];
331 $this->logger
->debug( __METHOD__
. ": key is {$this->key} (unread)\n" );
336 * @param array|bool $curValue
337 * @param DBMasterPos[] $shutdownPositions
338 * @param int|null &$cpIndex
341 protected function mergePositions( $curValue, array $shutdownPositions, &$cpIndex = null ) {
342 /** @var DBMasterPos[] $curPositions */
343 $curPositions = $curValue['positions'] ??
[];
344 // Use the newest positions for each DB master
345 foreach ( $shutdownPositions as $db => $pos ) {
347 !isset( $curPositions[$db] ) ||
348 !( $curPositions[$db] instanceof DBMasterPos
) ||
349 $pos->asOfTime() > $curPositions[$db]->asOfTime()
351 $curPositions[$db] = $pos;
355 $cpIndex = $curValue['writeIndex'] ??
0;
358 'positions' => $curPositions,
359 'writeIndex' => ++
$cpIndex