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