parserTests: Do not check for DjVu support
[lhc/web/wiklou.git] / includes / libs / rdbms / chronologyprotector / 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
26 /**
27 * Class for ensuring a consistent ordering of events as seen by the user, despite replication.
28 * Kind of like Hawking's [[Chronology Protection Agency]].
29 */
30 class ChronologyProtector implements LoggerAwareInterface{
31 /** @var BagOStuff */
32 protected $store;
33 /** @var LoggerInterface */
34 protected $logger;
35
36 /** @var string Storage key name */
37 protected $key;
38 /** @var string Hash of client parameters */
39 protected $clientId;
40 /** @var float|null Minimum UNIX timestamp of 1+ expected startup positions */
41 protected $waitForPosTime;
42 /** @var int Max seconds to wait on positions to appear */
43 protected $waitForPosTimeout = self::POS_WAIT_TIMEOUT;
44 /** @var bool Whether to no-op all method calls */
45 protected $enabled = true;
46 /** @var bool Whether to check and wait on positions */
47 protected $wait = true;
48
49 /** @var bool Whether the client data was loaded */
50 protected $initialized = false;
51 /** @var DBMasterPos[] Map of (DB master name => position) */
52 protected $startupPositions = [];
53 /** @var DBMasterPos[] Map of (DB master name => position) */
54 protected $shutdownPositions = [];
55 /** @var float[] Map of (DB master name => 1) */
56 protected $shutdownTouchDBs = [];
57
58 /** @var integer Seconds to store positions */
59 const POSITION_TTL = 60;
60 /** @var integer Max time to wait for positions to appear */
61 const POS_WAIT_TIMEOUT = 5;
62
63 /**
64 * @param BagOStuff $store
65 * @param array $client Map of (ip: <IP>, agent: <user-agent>)
66 * @param float $posTime UNIX timestamp
67 * @since 1.27
68 */
69 public function __construct( BagOStuff $store, array $client, $posTime = null ) {
70 $this->store = $store;
71 $this->clientId = md5( $client['ip'] . "\n" . $client['agent'] );
72 $this->key = $store->makeGlobalKey( __CLASS__, $this->clientId );
73 $this->waitForPosTime = $posTime;
74 $this->logger = new \Psr\Log\NullLogger();
75 }
76
77 public function setLogger( LoggerInterface $logger ) {
78 $this->logger = $logger;
79 }
80
81 /**
82 * @param bool $enabled Whether to no-op all method calls
83 * @since 1.27
84 */
85 public function setEnabled( $enabled ) {
86 $this->enabled = $enabled;
87 }
88
89 /**
90 * @param bool $enabled Whether to check and wait on positions
91 * @since 1.27
92 */
93 public function setWaitEnabled( $enabled ) {
94 $this->wait = $enabled;
95 }
96
97 /**
98 * Initialise a ILoadBalancer to give it appropriate chronology protection.
99 *
100 * If the stash has a previous master position recorded, this will try to
101 * make sure that the next query to a replica DB of that master will see changes up
102 * to that position by delaying execution. The delay may timeout and allow stale
103 * data if no non-lagged replica DBs are available.
104 *
105 * @param ILoadBalancer $lb
106 * @return void
107 */
108 public function initLB( ILoadBalancer $lb ) {
109 if ( !$this->enabled || $lb->getServerCount() <= 1 ) {
110 return; // non-replicated setup or disabled
111 }
112
113 $this->initPositions();
114
115 $masterName = $lb->getServerName( $lb->getWriterIndex() );
116 if ( !empty( $this->startupPositions[$masterName] ) ) {
117 $pos = $this->startupPositions[$masterName];
118 $this->logger->info( __METHOD__ . ": LB for '$masterName' set to pos $pos\n" );
119 $lb->waitFor( $pos );
120 }
121 }
122
123 /**
124 * Notify the ChronologyProtector that the ILoadBalancer is about to shut
125 * down. Saves replication positions.
126 *
127 * @param ILoadBalancer $lb
128 * @return void
129 */
130 public function shutdownLB( ILoadBalancer $lb ) {
131 if ( !$this->enabled ) {
132 return; // not enabled
133 } elseif ( !$lb->hasOrMadeRecentMasterChanges( INF ) ) {
134 // Only save the position if writes have been done on the connection
135 return;
136 }
137
138 $masterName = $lb->getServerName( $lb->getWriterIndex() );
139 if ( $lb->getServerCount() > 1 ) {
140 $pos = $lb->getMasterPos();
141 $this->logger->info( __METHOD__ . ": LB for '$masterName' has pos $pos\n" );
142 $this->shutdownPositions[$masterName] = $pos;
143 } else {
144 $this->logger->info( __METHOD__ . ": DB '$masterName' touched\n" );
145 }
146 $this->shutdownTouchDBs[$masterName] = 1;
147 }
148
149 /**
150 * Notify the ChronologyProtector that the LBFactory is done calling shutdownLB() for now.
151 * May commit chronology data to persistent storage.
152 *
153 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
154 * @param string $mode One of (sync, async); whether to wait on remote datacenters
155 * @return DBMasterPos[] Empty on success; returns the (db name => position) map on failure
156 */
157 public function shutdown( callable $workCallback = null, $mode = 'sync' ) {
158 if ( !$this->enabled ) {
159 return [];
160 }
161
162 $store = $this->store;
163 // Some callers might want to know if a user recently touched a DB.
164 // These writes do not need to block on all datacenters receiving them.
165 foreach ( $this->shutdownTouchDBs as $dbName => $unused ) {
166 $store->set(
167 $this->getTouchedKey( $this->store, $dbName ),
168 microtime( true ),
169 $store::TTL_DAY
170 );
171 }
172
173 if ( !count( $this->shutdownPositions ) ) {
174 return []; // nothing to save
175 }
176
177 $this->logger->info( __METHOD__ . ": saving master pos for " .
178 implode( ', ', array_keys( $this->shutdownPositions ) ) . "\n"
179 );
180
181 // CP-protected writes should overwhemingly go to the master datacenter, so get DC-local
182 // lock to merge the values. Use a DC-local get() and a synchronous all-DC set(). This
183 // makes it possible for the BagOStuff class to write in parallel to all DCs with one RTT.
184 if ( $store->lock( $this->key, 3 ) ) {
185 if ( $workCallback ) {
186 // Let the store run the work before blocking on a replication sync barrier. By the
187 // time it's done with the work, the barrier should be fast if replication caught up.
188 $store->addBusyCallback( $workCallback );
189 }
190 $ok = $store->set(
191 $this->key,
192 self::mergePositions( $store->get( $this->key ), $this->shutdownPositions ),
193 self::POSITION_TTL,
194 ( $mode === 'sync' ) ? $store::WRITE_SYNC : 0
195 );
196 $store->unlock( $this->key );
197 } else {
198 $ok = false;
199 }
200
201 if ( !$ok ) {
202 $bouncedPositions = $this->shutdownPositions;
203 // Raced out too many times or stash is down
204 $this->logger->warning( __METHOD__ . ": failed to save master pos for " .
205 implode( ', ', array_keys( $this->shutdownPositions ) ) . "\n"
206 );
207 } elseif ( $mode === 'sync' &&
208 $store->getQoS( $store::ATTR_SYNCWRITES ) < $store::QOS_SYNCWRITES_BE
209 ) {
210 // Positions may not be in all datacenters, force LBFactory to play it safe
211 $this->logger->info( __METHOD__ . ": store may not support synchronous writes." );
212 $bouncedPositions = $this->shutdownPositions;
213 } else {
214 $bouncedPositions = [];
215 }
216
217 return $bouncedPositions;
218 }
219
220 /**
221 * @param string $dbName DB master name (e.g. "db1052")
222 * @return float|bool UNIX timestamp when client last touched the DB; false if not on record
223 * @since 1.28
224 */
225 public function getTouched( $dbName ) {
226 return $this->store->get( $this->getTouchedKey( $this->store, $dbName ) );
227 }
228
229 /**
230 * @param BagOStuff $store
231 * @param string $dbName
232 * @return string
233 */
234 private function getTouchedKey( BagOStuff $store, $dbName ) {
235 return $store->makeGlobalKey( __CLASS__, 'mtime', $this->clientId, $dbName );
236 }
237
238 /**
239 * Load in previous master positions for the client
240 */
241 protected function initPositions() {
242 if ( $this->initialized ) {
243 return;
244 }
245
246 $this->initialized = true;
247 if ( $this->wait ) {
248 // If there is an expectation to see master positions with a certain min
249 // timestamp, then block until they appear, or until a timeout is reached.
250 if ( $this->waitForPosTime > 0.0 ) {
251 $data = null;
252 $loop = new WaitConditionLoop(
253 function () use ( &$data ) {
254 $data = $this->store->get( $this->key );
255
256 return ( self::minPosTime( $data ) >= $this->waitForPosTime )
257 ? WaitConditionLoop::CONDITION_REACHED
258 : WaitConditionLoop::CONDITION_CONTINUE;
259 },
260 $this->waitForPosTimeout
261 );
262 $result = $loop->invoke();
263 $waitedMs = $loop->getLastWaitTime() * 1e3;
264
265 if ( $result == $loop::CONDITION_REACHED ) {
266 $msg = "expected and found pos time {$this->waitForPosTime} ({$waitedMs}ms)";
267 $this->logger->debug( $msg );
268 } else {
269 $msg = "expected but missed pos time {$this->waitForPosTime} ({$waitedMs}ms)";
270 $this->logger->info( $msg );
271 }
272 } else {
273 $data = $this->store->get( $this->key );
274 }
275
276 $this->startupPositions = $data ? $data['positions'] : [];
277 $this->logger->info( __METHOD__ . ": key is {$this->key} (read)\n" );
278 } else {
279 $this->startupPositions = [];
280 $this->logger->info( __METHOD__ . ": key is {$this->key} (unread)\n" );
281 }
282 }
283
284 /**
285 * @param array|bool $data
286 * @return float|null
287 */
288 private static function minPosTime( $data ) {
289 if ( !isset( $data['positions'] ) ) {
290 return null;
291 }
292
293 $min = null;
294 foreach ( $data['positions'] as $pos ) {
295 /** @var DBMasterPos $pos */
296 $min = $min ? min( $pos->asOfTime(), $min ) : $pos->asOfTime();
297 }
298
299 return $min;
300 }
301
302 /**
303 * @param array|bool $curValue
304 * @param DBMasterPos[] $shutdownPositions
305 * @return array
306 */
307 private static function mergePositions( $curValue, array $shutdownPositions ) {
308 /** @var $curPositions DBMasterPos[] */
309 if ( $curValue === false ) {
310 $curPositions = $shutdownPositions;
311 } else {
312 $curPositions = $curValue['positions'];
313 // Use the newest positions for each DB master
314 foreach ( $shutdownPositions as $db => $pos ) {
315 if ( !isset( $curPositions[$db] )
316 || $pos->asOfTime() > $curPositions[$db]->asOfTime()
317 ) {
318 $curPositions[$db] = $pos;
319 }
320 }
321 }
322
323 return [ 'positions' => $curPositions ];
324 }
325 }