3 * Advanced generator of database load balancing objects for database farms.
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
;
27 use InvalidArgumentException
;
30 * A multi-database, multi-master factory for Wikimedia and similar installations.
31 * Ignores the old configuration globals.
35 class LBFactoryMulti
extends LBFactory
{
36 /** @var array A map of database names to section names */
37 private $sectionsByDB;
40 * @var array A 2-d map. For each section, gives a map of server names to
43 private $sectionLoads;
46 * @var array[] Server info associative array
47 * @note The host, hostName and load entries will be overridden
49 private $serverTemplate;
53 /** @var array A 3-d map giving server load ratios for each section and group */
54 private $groupLoadsBySection = [];
56 /** @var array A 3-d map giving server load ratios by DB name */
57 private $groupLoadsByDB = [];
59 /** @var array A map of hostname to IP address */
60 private $hostsByName = [];
62 /** @var array A map of external storage cluster name to server load map */
63 private $externalLoads = [];
66 * @var array A set of server info keys overriding serverTemplate for
69 private $externalTemplateOverrides;
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
76 private $templateOverridesByServer;
78 /** @var array A 2-d map overriding the server info by section */
79 private $templateOverridesBySection;
81 /** @var array A 2-d map overriding the server info by external storage cluster */
82 private $templateOverridesByCluster;
84 /** @var array An override array for all master servers */
85 private $masterTemplateOverrides;
88 * @var array|bool A map of section name to read-only message. Missing or
89 * false for read/write
91 private $readOnlyBySection = [];
93 /** @var array Load balancer factory configuration */
96 /** @var LoadBalancer[] */
97 private $mainLBs = [];
99 /** @var LoadBalancer[] */
100 private $extLBs = [];
103 private $loadMonitorClass = 'LoadMonitor';
109 private $lastSection;
112 * @see LBFactory::__construct()
114 * Template override precedence (highest => lowest):
115 * - templateOverridesByServer
116 * - masterTemplateOverrides
117 * - templateOverridesBySection/templateOverridesByCluster
118 * - externalTemplateOverrides
120 * Overrides only work on top level keys (so nested values will not be merged).
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
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:
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.
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
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.
167 public function __construct( array $conf ) {
168 parent
::__construct( $conf );
171 $required = [ 'sectionsByDB', 'sectionLoads', 'serverTemplate' ];
172 $optional = [ 'groupLoadsBySection', 'groupLoadsByDB', 'hostsByName',
173 'externalLoads', 'externalTemplateOverrides', 'templateOverridesByServer',
174 'templateOverridesByCluster', 'templateOverridesBySection', 'masterTemplateOverrides',
175 'readOnlyBySection', 'loadMonitorClass' ];
177 foreach ( $required as $key ) {
178 if ( !isset( $conf[$key] ) ) {
179 throw new InvalidArgumentException( __CLASS__
. ": $key is required." );
181 $this->$key = $conf[$key];
184 foreach ( $optional as $key ) {
185 if ( isset( $conf[$key] ) ) {
186 $this->$key = $conf[$key];
192 * @param bool|string $domain
195 private function getSectionForDomain( $domain = false ) {
196 if ( $this->lastDomain
=== $domain ) {
197 return $this->lastSection
;
199 list( $dbName, ) = $this->getDBNameAndPrefix( $domain );
200 if ( isset( $this->sectionsByDB
[$dbName] ) ) {
201 $section = $this->sectionsByDB
[$dbName];
203 $section = 'DEFAULT';
205 $this->lastSection
= $section;
206 $this->lastDomain
= $domain;
212 * @param bool|string $domain
213 * @return LoadBalancer
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];
224 if ( isset( $this->groupLoadsBySection
[$section] ) ) {
225 $groupLoads = array_merge_recursive(
226 $groupLoads, $this->groupLoadsBySection
[$section] );
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];
235 $template = $this->serverTemplate
;
236 if ( isset( $this->templateOverridesBySection
[$section] ) ) {
237 $template = $this->templateOverridesBySection
[$section] +
$template;
240 return $this->newLoadBalancer(
242 $this->sectionLoads
[$section],
249 * @param DatabaseDomain|string|bool $domain Domain ID, or false for the current domain
250 * @return LoadBalancer
252 public function getMainLB( $domain = false ) {
253 $section = $this->getSectionForDomain( $domain );
254 if ( !isset( $this->mainLBs
[$section] ) ) {
255 $lb = $this->newMainLB( $domain );
256 $this->getChronologyProtector()->initLB( $lb );
257 $this->mainLBs
[$section] = $lb;
260 return $this->mainLBs
[$section];
263 public function newExternalLB( $cluster ) {
264 if ( !isset( $this->externalLoads
[$cluster] ) ) {
265 throw new InvalidArgumentException( __METHOD__
. ": Unknown cluster \"$cluster\"" );
267 $template = $this->serverTemplate
;
268 if ( $this->externalTemplateOverrides
) {
269 $template = $this->externalTemplateOverrides +
$template;
271 if ( isset( $this->templateOverridesByCluster
[$cluster] ) ) {
272 $template = $this->templateOverridesByCluster
[$cluster] +
$template;
275 return $this->newLoadBalancer(
277 $this->externalLoads
[$cluster],
279 $this->readOnlyReason
283 public function getExternalLB( $cluster ) {
284 if ( !isset( $this->extLBs
[$cluster] ) ) {
285 $this->extLBs
[$cluster] = $this->newExternalLB( $cluster );
286 $this->getChronologyProtector()->initLB( $this->extLBs
[$cluster] );
289 return $this->extLBs
[$cluster];
292 public function getAllMainLBs() {
294 foreach ( $this->sectionsByDB
as $db => $section ) {
295 if ( !isset( $lbs[$section] ) ) {
296 $lbs[$section] = $this->getMainLB( $db );
303 public function getAllExternalLBs() {
305 foreach ( $this->externalLoads
as $cluster => $unused ) {
306 $lbs[$cluster] = $this->getExternalLB( $cluster );
313 * Make a new load balancer object based on template and load array
315 * @param array $template
316 * @param array $loads
317 * @param array $groupLoads
318 * @param string|bool $readOnlyReason
319 * @return LoadBalancer
321 private function newLoadBalancer( $template, $loads, $groupLoads, $readOnlyReason ) {
322 $lb = new LoadBalancer( array_merge(
323 $this->baseLoadBalancerParams(),
325 'servers' => $this->makeServerArray( $template, $loads, $groupLoads ),
326 'loadMonitor' => [ 'class' => $this->loadMonitorClass
],
327 'readOnlyReason' => $readOnlyReason
330 $this->initLoadBalancer( $lb );
336 * Make a server array as expected by LoadBalancer::__construct, using a template and load array
338 * @param array $template
339 * @param array $loads
340 * @param array $groupLoads
343 private function makeServerArray( $template, $loads, $groupLoads ) {
346 $groupLoadsByServer = $this->reindexGroupLoads( $groupLoads );
347 foreach ( $groupLoadsByServer as $server => $stuff ) {
348 if ( !isset( $loads[$server] ) ) {
352 foreach ( $loads as $serverName => $load ) {
353 $serverInfo = $template;
355 $serverInfo['master'] = true;
356 if ( $this->masterTemplateOverrides
) {
357 $serverInfo = $this->masterTemplateOverrides +
$serverInfo;
361 $serverInfo['replica'] = true;
363 if ( isset( $this->templateOverridesByServer
[$serverName] ) ) {
364 $serverInfo = $this->templateOverridesByServer
[$serverName] +
$serverInfo;
366 if ( isset( $groupLoadsByServer[$serverName] ) ) {
367 $serverInfo['groupLoads'] = $groupLoadsByServer[$serverName];
369 if ( isset( $this->hostsByName
[$serverName] ) ) {
370 $serverInfo['host'] = $this->hostsByName
[$serverName];
372 $serverInfo['host'] = $serverName;
374 $serverInfo['hostName'] = $serverName;
375 $serverInfo['load'] = $load;
376 $serverInfo +
= [ 'flags' => IDatabase
::DBO_DEFAULT
];
378 $servers[] = $serverInfo;
385 * Take a group load array indexed by group then server, and reindex it by server then group
386 * @param array $groupLoads
389 private function reindexGroupLoads( $groupLoads ) {
391 foreach ( $groupLoads as $group => $loads ) {
392 foreach ( $loads as $server => $load ) {
393 $reindexed[$server][$group] = $load;
401 * @param DatabaseDomain|string|bool $domain Domain ID, or false for the current domain
402 * @return array [database name, table prefix]
404 private function getDBNameAndPrefix( $domain = false ) {
405 $domain = ( $domain === false )
407 : DatabaseDomain
::newFromId( $domain );
409 return [ $domain->getDatabase(), $domain->getTablePrefix() ];
413 * Execute a function for each tracked load balancer
414 * The callback is called with the load balancer as the first parameter,
415 * and $params passed as the subsequent parameters.
416 * @param callable $callback
417 * @param array $params
419 public function forEachLB( $callback, array $params = [] ) {
420 foreach ( $this->mainLBs
as $lb ) {
421 call_user_func_array( $callback, array_merge( [ $lb ], $params ) );
423 foreach ( $this->extLBs
as $lb ) {
424 call_user_func_array( $callback, array_merge( [ $lb ], $params ) );