Merge "Convert Special:DeletedContributions to use OOUI."
[lhc/web/wiklou.git] / includes / libs / rdbms / ChronologyProtector.php
1 <?php
2 /**
3 * Generator of database load balancing objects.
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 Database
22 */
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\LoggerInterface;
25 use Wikimedia\WaitConditionLoop;
26
27 /**
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]].
30 */
31 class ChronologyProtector implements LoggerAwareInterface {
32 /** @var BagOStuff */
33 protected $store;
34 /** @var LoggerInterface */
35 protected $logger;
36
37 /** @var string Storage key name */
38 protected $key;
39 /** @var string Hash of client parameters */
40 protected $clientId;
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;
49
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 = [];
58
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;
63
64 /**
65 * @param BagOStuff $store
66 * @param array $client Map of (ip: <IP>, agent: <user-agent>)
67 * @param float $posTime UNIX timestamp
68 * @since 1.27
69 */
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();
76 }
77
78 public function setLogger( LoggerInterface $logger ) {
79 $this->logger = $logger;
80 }
81
82 /**
83 * @param bool $enabled Whether to no-op all method calls
84 * @since 1.27
85 */
86 public function setEnabled( $enabled ) {
87 $this->enabled = $enabled;
88 }
89
90 /**
91 * @param bool $enabled Whether to check and wait on positions
92 * @since 1.27
93 */
94 public function setWaitEnabled( $enabled ) {
95 $this->wait = $enabled;
96 }
97
98 /**
99 * Initialise a ILoadBalancer to give it appropriate chronology protection.
100 *
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.
105 *
106 * @param ILoadBalancer $lb
107 * @return void
108 */
109 public function initLB( ILoadBalancer $lb ) {
110 if ( !$this->enabled || $lb->getServerCount() <= 1 ) {
111 return; // non-replicated setup or disabled
112 }
113
114 $this->initPositions();
115
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 );
121 }
122 }
123
124 /**
125 * Notify the ChronologyProtector that the ILoadBalancer is about to shut
126 * down. Saves replication positions.
127 *
128 * @param ILoadBalancer $lb
129 * @return void
130 */
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
136 return;
137 }
138
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;
144 } else {
145 $this->logger->info( __METHOD__ . ": DB '$masterName' touched\n" );
146 }
147 $this->shutdownTouchDBs[$masterName] = 1;
148 }
149
150 /**
151 * Notify the ChronologyProtector that the LBFactory is done calling shutdownLB() for now.
152 * May commit chronology data to persistent storage.
153 *
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
157 */
158 public function shutdown( callable $workCallback = null, $mode = 'sync' ) {
159 if ( !$this->enabled ) {
160 return [];
161 }
162
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 ) {
167 $store->set(
168 $this->getTouchedKey( $this->store, $dbName ),
169 microtime( true ),
170 $store::TTL_DAY
171 );
172 }
173
174 if ( !count( $this->shutdownPositions ) ) {
175 return []; // nothing to save
176 }
177
178 $this->logger->info( __METHOD__ . ": saving master pos for " .
179 implode( ', ', array_keys( $this->shutdownPositions ) ) . "\n"
180 );
181
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 );
190 }
191 $ok = $store->set(
192 $this->key,
193 self::mergePositions( $store->get( $this->key ), $this->shutdownPositions ),
194 self::POSITION_TTL,
195 ( $mode === 'sync' ) ? $store::WRITE_SYNC : 0
196 );
197 $store->unlock( $this->key );
198 } else {
199 $ok = false;
200 }
201
202 if ( !$ok ) {
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"
207 );
208 } elseif ( $mode === 'sync' &&
209 $store->getQoS( $store::ATTR_SYNCWRITES ) < $store::QOS_SYNCWRITES_BE
210 ) {
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;
214 } else {
215 $bouncedPositions = [];
216 }
217
218 return $bouncedPositions;
219 }
220
221 /**
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
224 * @since 1.28
225 */
226 public function getTouched( $dbName ) {
227 return $this->store->get( $this->getTouchedKey( $this->store, $dbName ) );
228 }
229
230 /**
231 * @param BagOStuff $store
232 * @param string $dbName
233 * @return string
234 */
235 private function getTouchedKey( BagOStuff $store, $dbName ) {
236 return $store->makeGlobalKey( __CLASS__, 'mtime', $this->clientId, $dbName );
237 }
238
239 /**
240 * Load in previous master positions for the client
241 */
242 protected function initPositions() {
243 if ( $this->initialized ) {
244 return;
245 }
246
247 $this->initialized = true;
248 if ( $this->wait ) {
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 ) {
252 $data = null;
253 $loop = new WaitConditionLoop(
254 function () use ( &$data ) {
255 $data = $this->store->get( $this->key );
256
257 return ( self::minPosTime( $data ) >= $this->waitForPosTime )
258 ? WaitConditionLoop::CONDITION_REACHED
259 : WaitConditionLoop::CONDITION_CONTINUE;
260 },
261 $this->waitForPosTimeout
262 );
263 $result = $loop->invoke();
264 $waitedMs = $loop->getLastWaitTime() * 1e3;
265
266 if ( $result == $loop::CONDITION_REACHED ) {
267 $msg = "expected and found pos time {$this->waitForPosTime} ({$waitedMs}ms)";
268 $this->logger->debug( $msg );
269 } else {
270 $msg = "expected but missed pos time {$this->waitForPosTime} ({$waitedMs}ms)";
271 $this->logger->info( $msg );
272 }
273 } else {
274 $data = $this->store->get( $this->key );
275 }
276
277 $this->startupPositions = $data ? $data['positions'] : [];
278 $this->logger->info( __METHOD__ . ": key is {$this->key} (read)\n" );
279 } else {
280 $this->startupPositions = [];
281 $this->logger->info( __METHOD__ . ": key is {$this->key} (unread)\n" );
282 }
283 }
284
285 /**
286 * @param array|bool $data
287 * @return float|null
288 */
289 private static function minPosTime( $data ) {
290 if ( !isset( $data['positions'] ) ) {
291 return null;
292 }
293
294 $min = null;
295 foreach ( $data['positions'] as $pos ) {
296 /** @var DBMasterPos $pos */
297 $min = $min ? min( $pos->asOfTime(), $min ) : $pos->asOfTime();
298 }
299
300 return $min;
301 }
302
303 /**
304 * @param array|bool $curValue
305 * @param DBMasterPos[] $shutdownPositions
306 * @return array
307 */
308 private static function mergePositions( $curValue, array $shutdownPositions ) {
309 /** @var $curPositions DBMasterPos[] */
310 if ( $curValue === false ) {
311 $curPositions = $shutdownPositions;
312 } else {
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()
318 ) {
319 $curPositions[$db] = $pos;
320 }
321 }
322 }
323
324 return [ 'positions' => $curPositions ];
325 }
326 }