File: LBFactoryMulti.php

package info (click to toggle)
mediawiki 1%3A1.43.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 417,464 kB
  • sloc: php: 1,062,949; javascript: 664,290; sql: 9,714; python: 5,458; xml: 3,489; sh: 1,131; makefile: 64
file content (392 lines) | stat: -rw-r--r-- 15,854 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */
namespace Wikimedia\Rdbms;

use InvalidArgumentException;
use LogicException;
use UnexpectedValueException;

/**
 * LoadBalancer manager for sites with several "main" database clusters
 *
 * Each database cluster consists of a "primary" server and any number of replica servers,
 * all of which converge, as soon as possible, to contain the same schemas and records. If
 * a replication topology has multiple primaries, then the "primary" is merely the preferred
 * co-primary for the current context (e.g. datacenter).
 *
 * For single-primary topologies, the schemas and records of the primary define the "dataset".
 * For multiple-primary topologies, the "dataset" is the convergent result of applying/merging
 * all committed events (regardless of the co-primary they originated on); it possible that no
 * co-primary has yet converged upon this state at any given time (especially when there are
 * frequent writes and co-primaries are geographically distant).
 *
 * A "main" cluster contain a "main" dataset, which consists of data that is compact, highly
 * relational (e.g. read by JOIN queries), and essential to one or more sites. The "external"
 * clusters each store an "external" dataset, which consists of data that is non-relational
 * (e.g. key/value pairs), self-contained (e.g. JOIN queries and transactions thereof never
 * involve a main dataset), or too bulky to reside in a main dataset (e.g. text blobs).
 *
 * The class allows for large site farms to split up their data in the following ways:
 *   - Vertically shard compact site-specific data by site (e.g. page/comment metadata)
 *   - Vertically shard compact global data by module (e.g. account/notification data)
 *   - Horizontally shard any bulk data by blob key (e.g. page/comment content blobs)
 *
 * @ingroup Database
 */
class LBFactoryMulti extends LBFactory {
	/** @var array<string,LoadBalancer> Map of (main section => tracked LoadBalancer) */
	private $mainLBs = [];
	/** @var array<string,LoadBalancer> Map of (external cluster => tracked LoadBalancer) */
	private $externalLBs = [];

	/** @var string[] Map of (server name => IP address) */
	private $hostsByServerName;
	/** @var string[] Map of (database name => main section) */
	private $sectionsByDB;
	/** @var int[][][] Map of (main section => group => server name => load ratio) */
	private $groupLoadsBySection;
	/** @var int[][] Map of (external cluster => server name => load ratio) */
	private $externalLoadsByCluster;
	/** @var array Server config map ("host", "serverName", "load", and "groupLoads" ignored) */
	private $serverTemplate;
	/** @var array Server config map overriding "serverTemplate" for all external servers */
	private $externalTemplateOverrides;
	/** @var array[] Map of (main section => server config map overrides) */
	private $templateOverridesBySection;
	/** @var array[] Map of (external cluster => server config map overrides) */
	private $templateOverridesByCluster;
	/** @var array Server config override map for all main/external primary DB servers */
	private $masterTemplateOverrides;
	/** @var array[] Map of (server name => server config map overrides) for all servers */
	private $templateOverridesByServer;
	/** @var string[]|bool[] A map of (main section => read-only message) */
	private $readOnlyBySection;
	/** @var array Configuration for the LoadMonitor to use within LoadBalancer instances */
	private $loadMonitorConfig;
	/** @var DatabaseDomain[] Map of (domain ID => domain instance) */
	private $nonLocalDomainCache = [];

	/**
	 * Template override precedence (highest => lowest):
	 *   - templateOverridesByServer
	 *   - masterTemplateOverrides
	 *   - templateOverridesBySection/templateOverridesByCluster
	 *   - externalTemplateOverrides
	 *   - serverTemplate
	 * Overrides only work on top level keys (so nested values will not be merged).
	 *
	 * Server config maps should be of the format Database::factory() requires.
	 * Additionally, a 'max lag' key should also be set on server maps, indicating how stale the
	 * data can be before the load balancer tries to avoid using it. The map can have 'is static'
	 * set to disable blocking  replication sync checks (intended for archive servers with
	 * unchanging data).
	 *
	 * @see LBFactory::__construct()
	 * @param array $conf Additional parameters include:
	 *   - hostsByName: map of (server name => IP address). [optional]
	 *   - sectionsByDB: map of (database => main section). The database name "DEFAULT" is
	 *      interpreted as a catch-all for all databases not otherwise mentioned. If no section
	 *      name is specified for "DEFAULT", then the catch-all section is assumed to be named
	 *      "DEFAULT". [optional]
	 *   - sectionLoads: map of (main section => server name => load ratio); the first host
	 *      listed in each section is the primary DB server for that section. [optional]
	 *   - groupLoadsBySection: map of (main section => group => server name => group load ratio).
	 *      Any ILoadBalancer::GROUP_GENERIC group will be ignored. [optional]
	 *   - externalLoads: map of (cluster => server name => load ratio) map. [optional]
	 *   - serverTemplate: server config map for Database::factory().
	 *      Note that "host", "serverName" and "load" entries will be overridden by
	 *      "groupLoadsBySection" and "hostsByName". [optional]
	 *   - externalTemplateOverrides: server config map overrides for external stores;
	 *      respects the override precedence described above. [optional]
	 *   - templateOverridesBySection: map of (main section => server config map overrides);
	 *      respects the override precedence described above. [optional]
	 *   - templateOverridesByCluster: map of (external cluster => server config map overrides);
	 *      respects the override precedence described above. [optional]
	 *   - masterTemplateOverrides: server config map overrides for masters;
	 *      respects the override precedence described above. [optional]
	 *   - templateOverridesByServer: map of (server name => server config map overrides);
	 *      respects the override precedence described above and applies to both core
	 *      and external storage. [optional]
	 *   - loadMonitor: LoadMonitor::__construct() parameters with "class" field. [optional]
	 *   - readOnlyBySection: map of (main section => message text or false).
	 *      String values make sections read only, whereas anything else does not
	 *      restrict read/write mode. [optional]
	 *   - configCallback: A callback that returns a conf array that can be passed to
	 *      the reconfigure() method. This will be used to autoReconfigure() to load
	 *      any updated configuration.
	 */
	public function __construct( array $conf ) {
		parent::__construct( $conf );

		$this->hostsByServerName = $conf['hostsByName'] ?? [];
		$this->sectionsByDB = $conf['sectionsByDB'];
		$this->sectionsByDB += [ self::CLUSTER_MAIN_DEFAULT => self::CLUSTER_MAIN_DEFAULT ];
		$this->groupLoadsBySection = $conf['groupLoadsBySection'] ?? [];
		foreach ( ( $conf['sectionLoads'] ?? [] ) as $section => $loadsByServerName ) {
			$this->groupLoadsBySection[$section][ILoadBalancer::GROUP_GENERIC] = $loadsByServerName;
		}
		$this->externalLoadsByCluster = $conf['externalLoads'] ?? [];
		$this->serverTemplate = $conf['serverTemplate'] ?? [];
		$this->externalTemplateOverrides = $conf['externalTemplateOverrides'] ?? [];
		$this->templateOverridesBySection = $conf['templateOverridesBySection'] ?? [];
		$this->templateOverridesByCluster = $conf['templateOverridesByCluster'] ?? [];
		$this->masterTemplateOverrides = $conf['masterTemplateOverrides'] ?? [];
		$this->templateOverridesByServer = $conf['templateOverridesByServer'] ?? [];
		$this->readOnlyBySection = $conf['readOnlyBySection'] ?? [];

		if ( isset( $conf['loadMonitor'] ) ) {
			$this->loadMonitorConfig = $conf['loadMonitor'];
		} elseif ( isset( $conf['loadMonitorClass'] ) ) { // b/c
			$this->loadMonitorConfig = [ 'class' => $conf['loadMonitorClass'] ];
		} else {
			$this->loadMonitorConfig = [ 'class' => LoadMonitor::class ];
		}

		foreach ( $this->externalLoadsByCluster as $cluster => $_ ) {
			if ( isset( $this->groupLoadsBySection[$cluster] ) ) {
				throw new LogicException(
					"External cluster '$cluster' has the same name as a main section/cluster"
				);
			}
		}
	}

	public function newMainLB( $domain = false ): ILoadBalancerForOwner {
		$domainInstance = $this->resolveDomainInstance( $domain );
		$database = $domainInstance->getDatabase();
		$section = $this->getSectionFromDatabase( $database );

		if ( !isset( $this->groupLoadsBySection[$section][ILoadBalancer::GROUP_GENERIC] ) ) {
			throw new UnexpectedValueException( "Section '$section' has no hosts defined." );
		}

		return $this->newLoadBalancer(
			$section,
			array_merge(
				$this->serverTemplate,
				$this->templateOverridesBySection[$section] ?? []
			),
			$this->groupLoadsBySection[$section],
			// Use the LB-specific read-only reason if everything isn't already read-only
			is_string( $this->readOnlyReason )
				? $this->readOnlyReason
				: ( $this->readOnlyBySection[$section] ?? false )
		);
	}

	/**
	 * @param DatabaseDomain|string|false $domain
	 * @return DatabaseDomain
	 */
	private function resolveDomainInstance( $domain ) {
		if ( $domain instanceof DatabaseDomain ) {
			return $domain; // already a domain instance
		} elseif ( $domain === false || $domain === $this->localDomain->getId() ) {
			return $this->localDomain;
		} elseif ( isset( $this->domainAliases[$domain] ) ) {
			// This array acts as both the original map and as instance cache.
			// Instances pass-through DatabaseDomain::newFromId as-is.
			$this->domainAliases[$domain] =
				DatabaseDomain::newFromId( $this->domainAliases[$domain] );

			return $this->domainAliases[$domain];
		}

		$cachedDomain = $this->nonLocalDomainCache[$domain] ?? null;
		if ( $cachedDomain === null ) {
			$cachedDomain = DatabaseDomain::newFromId( $domain );
			$this->nonLocalDomainCache = [ $domain => $cachedDomain ];
		}

		return $cachedDomain;
	}

	public function getMainLB( $domain = false ): ILoadBalancer {
		$domainInstance = $this->resolveDomainInstance( $domain );
		$section = $this->getSectionFromDatabase( $domainInstance->getDatabase() );

		if ( !isset( $this->mainLBs[$section] ) ) {
			$this->mainLBs[$section] = $this->newMainLB( $domain );
		}

		return $this->mainLBs[$section];
	}

	public function newExternalLB( $cluster ): ILoadBalancerForOwner {
		if ( !isset( $this->externalLoadsByCluster[$cluster] ) ) {
			throw new InvalidArgumentException( "Unknown cluster '$cluster'" );
		}
		return $this->newLoadBalancer(
			$cluster,
			array_merge(
				$this->serverTemplate,
				$this->externalTemplateOverrides,
				$this->templateOverridesByCluster[$cluster] ?? []
			),
			[ ILoadBalancer::GROUP_GENERIC => $this->externalLoadsByCluster[$cluster] ],
			$this->readOnlyReason
		);
	}

	public function getExternalLB( $cluster ): ILoadBalancer {
		if ( !isset( $this->externalLBs[$cluster] ) ) {
			$this->externalLBs[$cluster] = $this->newExternalLB(
				$cluster
			);
		}

		return $this->externalLBs[$cluster];
	}

	public function getAllMainLBs(): array {
		$lbs = [];
		foreach ( $this->sectionsByDB as $db => $section ) {
			if ( !isset( $lbs[$section] ) ) {
				$lbs[$section] = $this->getMainLB( $db );
			}
		}

		return $lbs;
	}

	public function getAllExternalLBs(): array {
		$lbs = [];
		foreach ( $this->externalLoadsByCluster as $cluster => $unused ) {
			$lbs[$cluster] = $this->getExternalLB( $cluster );
		}

		return $lbs;
	}

	protected function getLBsForOwner() {
		foreach ( $this->mainLBs as $lb ) {
			yield $lb;
		}
		foreach ( $this->externalLBs as $lb ) {
			yield $lb;
		}
	}

	/**
	 * Make a new load balancer object based on template and load array
	 *
	 * @param string $clusterName
	 * @param array $serverTemplate
	 * @param array $groupLoads
	 * @param string|false $readOnlyReason
	 * @return LoadBalancer
	 */
	private function newLoadBalancer(
		string $clusterName,
		array $serverTemplate,
		array $groupLoads,
		$readOnlyReason
	) {
		$lb = new LoadBalancer( array_merge(
			$this->baseLoadBalancerParams(),
			[
				'servers' => $this->makeServerConfigArrays( $serverTemplate, $groupLoads ),
				'loadMonitor' => $this->loadMonitorConfig,
				'readOnlyReason' => $readOnlyReason,
				'clusterName' => $clusterName
			]
		) );
		$this->initLoadBalancer( $lb );

		return $lb;
	}

	/**
	 * Make a server array as expected by LoadBalancer::__construct()
	 *
	 * @param array $serverTemplate Server config map
	 * @param int[][] $groupLoads Map of (group => server name => load)
	 * @return array[] List of server config maps
	 */
	private function makeServerConfigArrays( array $serverTemplate, array $groupLoads ) {
		// The primary DB server is the first host explicitly listed in the generic load group
		if ( !$groupLoads[ILoadBalancer::GROUP_GENERIC] ) {
			throw new UnexpectedValueException( "Empty generic load array; no primary DB defined." );
		}
		$groupLoadsByServerName = [];
		foreach ( $groupLoads as $group => $loadByServerName ) {
			foreach ( $loadByServerName as $serverName => $load ) {
				$groupLoadsByServerName[$serverName][$group] = $load;
			}
		}

		// Get the ordered map of (server name => load); the primary DB server is first
		$genericLoads = $groupLoads[ILoadBalancer::GROUP_GENERIC];
		// Implicitly append any hosts that only appear in custom load groups
		$genericLoads += array_fill_keys( array_keys( $groupLoadsByServerName ), 0 );
		$servers = [];
		foreach ( $genericLoads as $serverName => $load ) {
			$servers[] = array_merge(
				$serverTemplate,
				$servers ? [] : $this->masterTemplateOverrides,
				$this->templateOverridesByServer[$serverName] ?? [],
				[
					'host' => $this->hostsByServerName[$serverName] ?? $serverName,
					'serverName' => $serverName,
					'load' => $load,
					'groupLoads' => $groupLoadsByServerName[$serverName] ?? []
				]
			);
		}

		return $servers;
	}

	/**
	 * @param string $database
	 * @return string Main section name
	 */
	private function getSectionFromDatabase( $database ) {
		return $this->sectionsByDB[$database]
			?? $this->sectionsByDB[self::CLUSTER_MAIN_DEFAULT]
			?? self::CLUSTER_MAIN_DEFAULT;
	}

	public function reconfigure( array $conf ): void {
		if ( !$conf ) {
			return;
		}

		foreach ( $this->mainLBs as $lb ) {
			// Approximate what LBFactoryMulti::__construct does (T346365)
			$groupLoads = $conf['groupLoadsBySection'][$lb->getClusterName()] ?? [];
			$groupLoads[ILoadBalancer::GROUP_GENERIC] = $conf['sectionLoads'][$lb->getClusterName()];
			$config = [
				'servers' => $this->makeServerConfigArrays( $conf['serverTemplate'] ?? [], $groupLoads )
			];
			$lb->reconfigure( $config );

		}
		foreach ( $this->externalLBs as $lb ) {
			$groupLoads = [
				ILoadBalancer::GROUP_GENERIC => $conf['externalLoads'][$lb->getClusterName()]
			];
			$config = [
				'servers' => $this->makeServerConfigArrays( $conf['serverTemplate'] ?? [], $groupLoads )
			];
			$lb->reconfigure( $config );
		}
	}
}