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