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
23 use Psr\Log\LoggerAwareInterface
;
24 use Psr\Log\LoggerInterface
;
25 use Wikimedia\WaitConditionLoop
;
28 * Class for ensuring a consistent ordering of events as seen by the user, despite replication.
29 * Kind of like Hawking's [[Chronology Protection Agency]].
31 class ChronologyProtector
implements LoggerAwareInterface
{
34 /** @var LoggerInterface */
37 /** @var string Storage key name */
39 /** @var string Hash of client parameters */
41 /** @var float|null Minimum UNIX timestamp of 1+ expected startup positions */
42 protected $waitForPosTime;
43 /** @var int Max seconds to wait on positions to appear */
44 protected $waitForPosTimeout = self
::POS_WAIT_TIMEOUT
;
45 /** @var bool Whether to no-op all method calls */
46 protected $enabled = true;
47 /** @var bool Whether to check and wait on positions */
48 protected $wait = true;
50 /** @var bool Whether the client data was loaded */
51 protected $initialized = false;
52 /** @var DBMasterPos[] Map of (DB master name => position) */
53 protected $startupPositions = [];
54 /** @var DBMasterPos[] Map of (DB master name => position) */
55 protected $shutdownPositions = [];
56 /** @var float[] Map of (DB master name => 1) */
57 protected $shutdownTouchDBs = [];
59 /** @var integer Seconds to store positions */
60 const POSITION_TTL
= 60;
61 /** @var integer Max time to wait for positions to appear */
62 const POS_WAIT_TIMEOUT
= 5;
65 * @param BagOStuff $store
66 * @param array $client Map of (ip: <IP>, agent: <user-agent>)
67 * @param float $posTime UNIX timestamp
70 public function __construct( BagOStuff
$store, array $client, $posTime = null ) {
71 $this->store
= $store;
72 $this->clientId
= md5( $client['ip'] . "\n" . $client['agent'] );
73 $this->key
= $store->makeGlobalKey( __CLASS__
, $this->clientId
);
74 $this->waitForPosTime
= $posTime;
75 $this->logger
= new \Psr\Log\
NullLogger();
78 public function setLogger( LoggerInterface
$logger ) {
79 $this->logger
= $logger;
83 * @param bool $enabled Whether to no-op all method calls
86 public function setEnabled( $enabled ) {
87 $this->enabled
= $enabled;
91 * @param bool $enabled Whether to check and wait on positions
94 public function setWaitEnabled( $enabled ) {
95 $this->wait
= $enabled;
99 * Initialise a ILoadBalancer to give it appropriate chronology protection.
101 * If the stash has a previous master position recorded, this will try to
102 * make sure that the next query to a replica DB of that master will see changes up
103 * to that position by delaying execution. The delay may timeout and allow stale
104 * data if no non-lagged replica DBs are available.
106 * @param ILoadBalancer $lb
109 public function initLB( ILoadBalancer
$lb ) {
110 if ( !$this->enabled ||
$lb->getServerCount() <= 1 ) {
111 return; // non-replicated setup or disabled
114 $this->initPositions();
116 $masterName = $lb->getServerName( $lb->getWriterIndex() );
117 if ( !empty( $this->startupPositions
[$masterName] ) ) {
118 $pos = $this->startupPositions
[$masterName];
119 $this->logger
->info( __METHOD__
. ": LB for '$masterName' set to pos $pos\n" );
120 $lb->waitFor( $pos );
125 * Notify the ChronologyProtector that the ILoadBalancer is about to shut
126 * down. Saves replication positions.
128 * @param ILoadBalancer $lb
131 public function shutdownLB( ILoadBalancer
$lb ) {
132 if ( !$this->enabled
) {
133 return; // not enabled
134 } elseif ( !$lb->hasOrMadeRecentMasterChanges( INF
) ) {
135 // Only save the position if writes have been done on the connection
139 $masterName = $lb->getServerName( $lb->getWriterIndex() );
140 if ( $lb->getServerCount() > 1 ) {
141 $pos = $lb->getMasterPos();
142 $this->logger
->info( __METHOD__
. ": LB for '$masterName' has pos $pos\n" );
143 $this->shutdownPositions
[$masterName] = $pos;
145 $this->logger
->info( __METHOD__
. ": DB '$masterName' touched\n" );
147 $this->shutdownTouchDBs
[$masterName] = 1;
151 * Notify the ChronologyProtector that the LBFactory is done calling shutdownLB() for now.
152 * May commit chronology data to persistent storage.
154 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
155 * @param string $mode One of (sync, async); whether to wait on remote datacenters
156 * @return DBMasterPos[] Empty on success; returns the (db name => position) map on failure
158 public function shutdown( callable
$workCallback = null, $mode = 'sync' ) {
159 if ( !$this->enabled
) {
163 $store = $this->store
;
164 // Some callers might want to know if a user recently touched a DB.
165 // These writes do not need to block on all datacenters receiving them.
166 foreach ( $this->shutdownTouchDBs
as $dbName => $unused ) {
168 $this->getTouchedKey( $this->store
, $dbName ),
174 if ( !count( $this->shutdownPositions
) ) {
175 return []; // nothing to save
178 $this->logger
->info( __METHOD__
. ": saving master pos for " .
179 implode( ', ', array_keys( $this->shutdownPositions
) ) . "\n"
182 // CP-protected writes should overwhemingly go to the master datacenter, so get DC-local
183 // lock to merge the values. Use a DC-local get() and a synchronous all-DC set(). This
184 // makes it possible for the BagOStuff class to write in parallel to all DCs with one RTT.
185 if ( $store->lock( $this->key
, 3 ) ) {
186 if ( $workCallback ) {
187 // Let the store run the work before blocking on a replication sync barrier. By the
188 // time it's done with the work, the barrier should be fast if replication caught up.
189 $store->addBusyCallback( $workCallback );
193 self
::mergePositions( $store->get( $this->key
), $this->shutdownPositions
),
195 ( $mode === 'sync' ) ?
$store::WRITE_SYNC
: 0
197 $store->unlock( $this->key
);
203 $bouncedPositions = $this->shutdownPositions
;
204 // Raced out too many times or stash is down
205 $this->logger
->warning( __METHOD__
. ": failed to save master pos for " .
206 implode( ', ', array_keys( $this->shutdownPositions
) ) . "\n"
208 } elseif ( $mode === 'sync' &&
209 $store->getQoS( $store::ATTR_SYNCWRITES
) < $store::QOS_SYNCWRITES_BE
211 // Positions may not be in all datacenters, force LBFactory to play it safe
212 $this->logger
->info( __METHOD__
. ": store may not support synchronous writes." );
213 $bouncedPositions = $this->shutdownPositions
;
215 $bouncedPositions = [];
218 return $bouncedPositions;
222 * @param string $dbName DB master name (e.g. "db1052")
223 * @return float|bool UNIX timestamp when client last touched the DB; false if not on record
226 public function getTouched( $dbName ) {
227 return $this->store
->get( $this->getTouchedKey( $this->store
, $dbName ) );
231 * @param BagOStuff $store
232 * @param string $dbName
235 private function getTouchedKey( BagOStuff
$store, $dbName ) {
236 return $store->makeGlobalKey( __CLASS__
, 'mtime', $this->clientId
, $dbName );
240 * Load in previous master positions for the client
242 protected function initPositions() {
243 if ( $this->initialized
) {
247 $this->initialized
= true;
249 // If there is an expectation to see master positions with a certain min
250 // timestamp, then block until they appear, or until a timeout is reached.
251 if ( $this->waitForPosTime
> 0.0 ) {
253 $loop = new WaitConditionLoop(
254 function () use ( &$data ) {
255 $data = $this->store
->get( $this->key
);
257 return ( self
::minPosTime( $data ) >= $this->waitForPosTime
)
258 ? WaitConditionLoop
::CONDITION_REACHED
259 : WaitConditionLoop
::CONDITION_CONTINUE
;
261 $this->waitForPosTimeout
263 $result = $loop->invoke();
264 $waitedMs = $loop->getLastWaitTime() * 1e3
;
266 if ( $result == $loop::CONDITION_REACHED
) {
267 $msg = "expected and found pos time {$this->waitForPosTime} ({$waitedMs}ms)";
268 $this->logger
->debug( $msg );
270 $msg = "expected but missed pos time {$this->waitForPosTime} ({$waitedMs}ms)";
271 $this->logger
->info( $msg );
274 $data = $this->store
->get( $this->key
);
277 $this->startupPositions
= $data ?
$data['positions'] : [];
278 $this->logger
->info( __METHOD__
. ": key is {$this->key} (read)\n" );
280 $this->startupPositions
= [];
281 $this->logger
->info( __METHOD__
. ": key is {$this->key} (unread)\n" );
286 * @param array|bool $data
289 private static function minPosTime( $data ) {
290 if ( !isset( $data['positions'] ) ) {
295 foreach ( $data['positions'] as $pos ) {
296 /** @var DBMasterPos $pos */
297 $min = $min ?
min( $pos->asOfTime(), $min ) : $pos->asOfTime();
304 * @param array|bool $curValue
305 * @param DBMasterPos[] $shutdownPositions
308 private static function mergePositions( $curValue, array $shutdownPositions ) {
309 /** @var $curPositions DBMasterPos[] */
310 if ( $curValue === false ) {
311 $curPositions = $shutdownPositions;
313 $curPositions = $curValue['positions'];
314 // Use the newest positions for each DB master
315 foreach ( $shutdownPositions as $db => $pos ) {
316 if ( !isset( $curPositions[$db] )
317 ||
$pos->asOfTime() > $curPositions[$db]->asOfTime()
319 $curPositions[$db] = $pos;
324 return [ 'positions' => $curPositions ];