Defer calling ChronologyProtector::initLB() until connecting
[lhc/web/wiklou.git] / includes / libs / rdbms / lbfactory / LBFactoryMulti.php
1 <?php
2 /**
3 * Advanced generator of database load balancing objects for database farms.
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
24 namespace Wikimedia\Rdbms;
25
26 use IDatabase;
27 use InvalidArgumentException;
28
29 /**
30 * A multi-database, multi-master factory for Wikimedia and similar installations.
31 * Ignores the old configuration globals.
32 *
33 * @ingroup Database
34 */
35 class LBFactoryMulti extends LBFactory {
36 /** @var array A map of database names to section names */
37 private $sectionsByDB;
38
39 /**
40 * @var array A 2-d map. For each section, gives a map of server names to
41 * load ratios
42 */
43 private $sectionLoads;
44
45 /**
46 * @var array[] Server info associative array
47 * @note The host, hostName and load entries will be overridden
48 */
49 private $serverTemplate;
50
51 // Optional settings
52
53 /** @var array A 3-d map giving server load ratios for each section and group */
54 private $groupLoadsBySection = [];
55
56 /** @var array A 3-d map giving server load ratios by DB name */
57 private $groupLoadsByDB = [];
58
59 /** @var array A map of hostname to IP address */
60 private $hostsByName = [];
61
62 /** @var array A map of external storage cluster name to server load map */
63 private $externalLoads = [];
64
65 /**
66 * @var array A set of server info keys overriding serverTemplate for
67 * external storage
68 */
69 private $externalTemplateOverrides;
70
71 /**
72 * @var array A 2-d map overriding serverTemplate and
73 * externalTemplateOverrides on a server-by-server basis. Applies to both
74 * core and external storage
75 */
76 private $templateOverridesByServer;
77
78 /** @var array A 2-d map overriding the server info by section */
79 private $templateOverridesBySection;
80
81 /** @var array A 2-d map overriding the server info by external storage cluster */
82 private $templateOverridesByCluster;
83
84 /** @var array An override array for all master servers */
85 private $masterTemplateOverrides;
86
87 /**
88 * @var array|bool A map of section name to read-only message. Missing or
89 * false for read/write
90 */
91 private $readOnlyBySection = [];
92
93 /** @var array Load balancer factory configuration */
94 private $conf;
95
96 /** @var LoadBalancer[] */
97 private $mainLBs = [];
98
99 /** @var LoadBalancer[] */
100 private $extLBs = [];
101
102 /** @var string */
103 private $loadMonitorClass = 'LoadMonitor';
104
105 /** @var string */
106 private $lastDomain;
107
108 /** @var string */
109 private $lastSection;
110
111 /**
112 * @see LBFactory::__construct()
113 *
114 * Template override precedence (highest => lowest):
115 * - templateOverridesByServer
116 * - masterTemplateOverrides
117 * - templateOverridesBySection/templateOverridesByCluster
118 * - externalTemplateOverrides
119 * - serverTemplate
120 * Overrides only work on top level keys (so nested values will not be merged).
121 *
122 * Server configuration maps should be of the format Database::factory() requires.
123 * Additionally, a 'max lag' key should also be set on server maps, indicating how stale the
124 * data can be before the load balancer tries to avoid using it. The map can have 'is static'
125 * set to disable blocking replication sync checks (intended for archive servers with
126 * unchanging data).
127 *
128 * @param array $conf Parameters of LBFactory::__construct() as well as:
129 * - sectionsByDB Map of database names to section names.
130 * - sectionLoads 2-d map. For each section, gives a map of server names to
131 * load ratios. For example:
132 * [
133 * 'section1' => [
134 * 'db1' => 100,
135 * 'db2' => 100
136 * ]
137 * ]
138 * - serverTemplate Server configuration map intended for Database::factory().
139 * Note that "host", "hostName" and "load" entries will be
140 * overridden by "sectionLoads" and "hostsByName".
141 * - groupLoadsBySection 3-d map giving server load ratios for each section/group.
142 * For example:
143 * [
144 * 'section1' => [
145 * 'group1' => [
146 * 'db1' => 100,
147 * 'db2' => 100
148 * ]
149 * ]
150 * ]
151 * - groupLoadsByDB 3-d map giving server load ratios by DB name.
152 * - hostsByName Map of hostname to IP address.
153 * - externalLoads Map of external storage cluster name to server load map.
154 * - externalTemplateOverrides Set of server configuration maps overriding
155 * "serverTemplate" for external storage.
156 * - templateOverridesByServer 2-d map overriding "serverTemplate" and
157 * "externalTemplateOverrides" on a server-by-server basis.
158 * Applies to both core and external storage.
159 * - templateOverridesBySection 2-d map overriding the server configuration maps by section.
160 * - templateOverridesByCluster 2-d map overriding the server configuration maps by external
161 * storage cluster.
162 * - masterTemplateOverrides Server configuration map overrides for all master servers.
163 * - loadMonitorClass Name of the LoadMonitor class to always use.
164 * - readOnlyBySection A map of section name to read-only message.
165 * Missing or false for read/write.
166 */
167 public function __construct( array $conf ) {
168 parent::__construct( $conf );
169
170 $this->conf = $conf;
171 $required = [ 'sectionsByDB', 'sectionLoads', 'serverTemplate' ];
172 $optional = [ 'groupLoadsBySection', 'groupLoadsByDB', 'hostsByName',
173 'externalLoads', 'externalTemplateOverrides', 'templateOverridesByServer',
174 'templateOverridesByCluster', 'templateOverridesBySection', 'masterTemplateOverrides',
175 'readOnlyBySection', 'loadMonitorClass' ];
176
177 foreach ( $required as $key ) {
178 if ( !isset( $conf[$key] ) ) {
179 throw new InvalidArgumentException( __CLASS__ . ": $key is required." );
180 }
181 $this->$key = $conf[$key];
182 }
183
184 foreach ( $optional as $key ) {
185 if ( isset( $conf[$key] ) ) {
186 $this->$key = $conf[$key];
187 }
188 }
189 }
190
191 /**
192 * @param bool|string $domain
193 * @return string
194 */
195 private function getSectionForDomain( $domain = false ) {
196 if ( $this->lastDomain === $domain ) {
197 return $this->lastSection;
198 }
199 list( $dbName, ) = $this->getDBNameAndPrefix( $domain );
200 if ( isset( $this->sectionsByDB[$dbName] ) ) {
201 $section = $this->sectionsByDB[$dbName];
202 } else {
203 $section = 'DEFAULT';
204 }
205 $this->lastSection = $section;
206 $this->lastDomain = $domain;
207
208 return $section;
209 }
210
211 /**
212 * @param bool|string $domain
213 * @return LoadBalancer
214 */
215 public function newMainLB( $domain = false ) {
216 list( $dbName, ) = $this->getDBNameAndPrefix( $domain );
217 $section = $this->getSectionForDomain( $domain );
218 if ( isset( $this->groupLoadsByDB[$dbName] ) ) {
219 $groupLoads = $this->groupLoadsByDB[$dbName];
220 } else {
221 $groupLoads = [];
222 }
223
224 if ( isset( $this->groupLoadsBySection[$section] ) ) {
225 $groupLoads = array_merge_recursive(
226 $groupLoads, $this->groupLoadsBySection[$section] );
227 }
228
229 $readOnlyReason = $this->readOnlyReason;
230 // Use the LB-specific read-only reason if everything isn't already read-only
231 if ( $readOnlyReason === false && isset( $this->readOnlyBySection[$section] ) ) {
232 $readOnlyReason = $this->readOnlyBySection[$section];
233 }
234
235 $template = $this->serverTemplate;
236 if ( isset( $this->templateOverridesBySection[$section] ) ) {
237 $template = $this->templateOverridesBySection[$section] + $template;
238 }
239
240 return $this->newLoadBalancer(
241 $template,
242 $this->sectionLoads[$section],
243 $groupLoads,
244 $readOnlyReason
245 );
246 }
247
248 /**
249 * @param DatabaseDomain|string|bool $domain Domain ID, or false for the current domain
250 * @return LoadBalancer
251 */
252 public function getMainLB( $domain = false ) {
253 $section = $this->getSectionForDomain( $domain );
254 if ( !isset( $this->mainLBs[$section] ) ) {
255 $this->mainLBs[$section] = $this->newMainLB( $domain );
256 }
257
258 return $this->mainLBs[$section];
259 }
260
261 public function newExternalLB( $cluster ) {
262 if ( !isset( $this->externalLoads[$cluster] ) ) {
263 throw new InvalidArgumentException( __METHOD__ . ": Unknown cluster \"$cluster\"" );
264 }
265 $template = $this->serverTemplate;
266 if ( $this->externalTemplateOverrides ) {
267 $template = $this->externalTemplateOverrides + $template;
268 }
269 if ( isset( $this->templateOverridesByCluster[$cluster] ) ) {
270 $template = $this->templateOverridesByCluster[$cluster] + $template;
271 }
272
273 return $this->newLoadBalancer(
274 $template,
275 $this->externalLoads[$cluster],
276 [],
277 $this->readOnlyReason
278 );
279 }
280
281 public function getExternalLB( $cluster ) {
282 if ( !isset( $this->extLBs[$cluster] ) ) {
283 $this->extLBs[$cluster] = $this->newExternalLB( $cluster );
284 }
285
286 return $this->extLBs[$cluster];
287 }
288
289 public function getAllMainLBs() {
290 $lbs = [];
291 foreach ( $this->sectionsByDB as $db => $section ) {
292 if ( !isset( $lbs[$section] ) ) {
293 $lbs[$section] = $this->getMainLB( $db );
294 }
295 }
296
297 return $lbs;
298 }
299
300 public function getAllExternalLBs() {
301 $lbs = [];
302 foreach ( $this->externalLoads as $cluster => $unused ) {
303 $lbs[$cluster] = $this->getExternalLB( $cluster );
304 }
305
306 return $lbs;
307 }
308
309 /**
310 * Make a new load balancer object based on template and load array
311 *
312 * @param array $template
313 * @param array $loads
314 * @param array $groupLoads
315 * @param string|bool $readOnlyReason
316 * @return LoadBalancer
317 */
318 private function newLoadBalancer( $template, $loads, $groupLoads, $readOnlyReason ) {
319 $lb = new LoadBalancer( array_merge(
320 $this->baseLoadBalancerParams(),
321 [
322 'servers' => $this->makeServerArray( $template, $loads, $groupLoads ),
323 'loadMonitor' => [ 'class' => $this->loadMonitorClass ],
324 'readOnlyReason' => $readOnlyReason
325 ]
326 ) );
327 $this->initLoadBalancer( $lb );
328
329 return $lb;
330 }
331
332 /**
333 * Make a server array as expected by LoadBalancer::__construct, using a template and load array
334 *
335 * @param array $template
336 * @param array $loads
337 * @param array $groupLoads
338 * @return array
339 */
340 private function makeServerArray( $template, $loads, $groupLoads ) {
341 $servers = [];
342 $master = true;
343 $groupLoadsByServer = $this->reindexGroupLoads( $groupLoads );
344 foreach ( $groupLoadsByServer as $server => $stuff ) {
345 if ( !isset( $loads[$server] ) ) {
346 $loads[$server] = 0;
347 }
348 }
349 foreach ( $loads as $serverName => $load ) {
350 $serverInfo = $template;
351 if ( $master ) {
352 $serverInfo['master'] = true;
353 if ( $this->masterTemplateOverrides ) {
354 $serverInfo = $this->masterTemplateOverrides + $serverInfo;
355 }
356 $master = false;
357 } else {
358 $serverInfo['replica'] = true;
359 }
360 if ( isset( $this->templateOverridesByServer[$serverName] ) ) {
361 $serverInfo = $this->templateOverridesByServer[$serverName] + $serverInfo;
362 }
363 if ( isset( $groupLoadsByServer[$serverName] ) ) {
364 $serverInfo['groupLoads'] = $groupLoadsByServer[$serverName];
365 }
366 if ( isset( $this->hostsByName[$serverName] ) ) {
367 $serverInfo['host'] = $this->hostsByName[$serverName];
368 } else {
369 $serverInfo['host'] = $serverName;
370 }
371 $serverInfo['hostName'] = $serverName;
372 $serverInfo['load'] = $load;
373 $serverInfo += [ 'flags' => IDatabase::DBO_DEFAULT ];
374
375 $servers[] = $serverInfo;
376 }
377
378 return $servers;
379 }
380
381 /**
382 * Take a group load array indexed by group then server, and reindex it by server then group
383 * @param array $groupLoads
384 * @return array
385 */
386 private function reindexGroupLoads( $groupLoads ) {
387 $reindexed = [];
388 foreach ( $groupLoads as $group => $loads ) {
389 foreach ( $loads as $server => $load ) {
390 $reindexed[$server][$group] = $load;
391 }
392 }
393
394 return $reindexed;
395 }
396
397 /**
398 * @param DatabaseDomain|string|bool $domain Domain ID, or false for the current domain
399 * @return array [database name, table prefix]
400 */
401 private function getDBNameAndPrefix( $domain = false ) {
402 $domain = ( $domain === false )
403 ? $this->localDomain
404 : DatabaseDomain::newFromId( $domain );
405
406 return [ $domain->getDatabase(), $domain->getTablePrefix() ];
407 }
408
409 /**
410 * Execute a function for each tracked load balancer
411 * The callback is called with the load balancer as the first parameter,
412 * and $params passed as the subsequent parameters.
413 * @param callable $callback
414 * @param array $params
415 */
416 public function forEachLB( $callback, array $params = [] ) {
417 foreach ( $this->mainLBs as $lb ) {
418 call_user_func_array( $callback, array_merge( [ $lb ], $params ) );
419 }
420 foreach ( $this->extLBs as $lb ) {
421 call_user_func_array( $callback, array_merge( [ $lb ], $params ) );
422 }
423 }
424 }