Debian Codegraph @

includes/libs/rdbms/database/position/MySQLPrimaryPos.php

raw symbols SCIP
1 <?php
2
3 namespace Wikimedia\Rdbms;
4
5 use InvalidArgumentException;
6 use Stringable;
7
8 /**
9 * DBPrimaryPos implementation for MySQL and MariaDB.
10 *
11 * Note that primary positions and sync logic here make some assumptions:
12 *
13 * - Binlog-based usage assumes single-source replication and non-hierarchical replication.
14 * - GTID-based usage allows getting/syncing with multi-source replication. It is assumed
15 * that GTID sets are complete (e.g. include all domains on the server).
16 *
17 * @see https://mariadb.com/kb/en/library/gtid/
18 * @see https://dev.mysql.com/doc/refman/5.6/en/replication-gtids-concepts.html
19 * @internal
20 */
21 class MySQLPrimaryPos implements Stringable, DBPrimaryPos {
22 /** @var string One of (BINARY_LOG, GTID_MYSQL, GTID_MARIA) */
23 private $style;
24 /** @var string|null Base name of all Binary Log files */
25 private $binLog;
26 /** @var array<int,int|string>|null Binary Log position tuple (index number, event number) */
27 private $logPos;
28 /** @var string[] Map of (server_uuid/gtid_domain_id => GTID) */
29 private $gtids = [];
30 /** @var string|null Active GTID domain ID */
31 private $activeDomain;
32 /** @var string|null ID of the server were DB writes originate */
33 private $activeServerId;
34 /** @var string|null UUID of the server were DB writes originate */
35 private $activeServerUUID;
36 /** @var float UNIX timestamp */
37 private $asOfTime = 0.0;
38
39 private const BINARY_LOG = 'binary-log';
40 private const GTID_MARIA = 'gtid-maria';
41 private const GTID_MYSQL = 'gtid-mysql';
42
43 /** Key name of the 6 digit binary log index number of a position tuple */
44 public const CORD_INDEX = 0;
45 /** Key name of the 64 bit binary log event number of a position tuple */
46 public const CORD_EVENT = 1;
47
48 /**
49 * @param string $position One of (comma separated GTID list, <binlog file>/<64 bit integer>)
50 * @param float $asOfTime UNIX timestamp
51 */
52 public function __construct( $position, $asOfTime ) {
53 $this->init( $position, $asOfTime );
54 }
55
56 /**
57 * @param string $position
58 * @param float $asOfTime
59 */
60 protected function init( $position, $asOfTime ) {
61 $m = [];
62 if ( preg_match( '!^(.+)\.(\d+)/(\d+)$!', $position, $m ) ) {
63 $this->binLog = $m[1]; // ideally something like host name
64 $this->logPos = [ self::CORD_INDEX => (int)$m[2], self::CORD_EVENT => $m[3] ];
65 $this->style = self::BINARY_LOG;
66 } else {
67 $gtids = array_filter( array_map( 'trim', explode( ',', $position ) ) );
68 foreach ( $gtids as $gtid ) {
69 $components = self::parseGTID( $gtid );
70 if ( !$components ) {
71 throw new InvalidArgumentException( "Invalid GTID '$gtid'." );
72 }
73
74 [ $domain, $eventNumber, , $this->style ] = $components;
75 if ( isset( $this->gtids[$domain] ) ) {
76 // For MySQL, handle the case where some past issue caused a gap in the
77 // executed GTID set, e.g. [last_purged+1,N-1] and [N+1,N+2+K]. Ignore the
78 // gap by using the GTID with the highest ending event number.
79 [ , $otherEventNumber ] = self::parseGTID( $this->gtids[$domain] );
80 if ( $eventNumber > $otherEventNumber ) {
81 $this->gtids[$domain] = $gtid;
82 }
83 } else {
84 $this->gtids[$domain] = $gtid;
85 }
86 }
87 if ( !$this->gtids ) {
88 throw new InvalidArgumentException( "GTID set cannot be empty." );
89 }
90 }
91
92 $this->asOfTime = $asOfTime;
93 }
94
95 public function asOfTime() {
96 return $this->asOfTime;
97 }
98
99 public function hasReached( DBPrimaryPos $pos ) {
100 if ( !( $pos instanceof self ) ) {
101 throw new InvalidArgumentException( "Position not an instance of " . __CLASS__ );
102 }
103
104 // Prefer GTID comparisons, which work with multi-tier replication
105 $thisPosByDomain = $this->getActiveGtidCoordinates();
106 $thatPosByDomain = $pos->getActiveGtidCoordinates();
107 if ( $thisPosByDomain && $thatPosByDomain ) {
108 $comparisons = [];
109 // Check that this has positions reaching those in $pos for all domains in common
110 foreach ( $thatPosByDomain as $domain => $thatPos ) {
111 if ( isset( $thisPosByDomain[$domain] ) ) {
112 $comparisons[] = ( $thatPos <= $thisPosByDomain[$domain] );
113 }
114 }
115 // Check that $this has a GTID for at least one domain also in $pos; due to MariaDB
116 // quirks, prior primary switch-overs may result in inactive garbage GTIDs that cannot
117 // be cleaned up. Assume that the domains in both this and $pos cover the relevant
118 // active channels.
119 return ( $comparisons && !in_array( false, $comparisons, true ) );
120 }
121
122 // Fallback to the binlog file comparisons
123 $thisBinPos = $this->getBinlogCoordinates();
124 $thatBinPos = $pos->getBinlogCoordinates();
125 if ( $thisBinPos && $thatBinPos && $thisBinPos['binlog'] === $thatBinPos['binlog'] ) {
126 return ( $thisBinPos['pos'] >= $thatBinPos['pos'] );
127 }
128
129 // Comparing totally different binlogs does not make sense
130 return false;
131 }
132
133 /**
134 * @return array<int,int|string>|null Tuple of (binary log file number, 64 bit event number)
135 * @since 1.31
136 */
137 public function getLogPosition() {
138 return $this->gtids ? null : $this->logPos;
139 }
140
141 /**
142 * @return string|null Name of the binary log file for this position
143 * @since 1.31
144 */
145 public function getLogFile() {
146 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
147 return $this->gtids ? null : "{$this->binLog}.{$this->logPos[self::CORD_INDEX]}";
148 }
149
150 /**
151 * @return array<string,string> Map of (server_uuid/gtid_domain_id => GTID)
152 * @since 1.31
153 */
154 public function getGTIDs() {
155 return $this->gtids;
156 }
157
158 /**
159 * Set the GTID domain known to be used in new commits on a replication stream of interest
160 *
161 * This makes getRelevantActiveGTIDs() filter out GTIDs from other domains
162 *
163 * @see MySQLPrimaryPos::getRelevantActiveGTIDs()
164 * @see https://mariadb.com/kb/en/library/gtid/#gtid_domain_id
165 *
166 * @param string|int|null $id @@gtid_domain_id of the active replication stream
167 * @return MySQLPrimaryPos This instance (since 1.34)
168 * @since 1.31
169 */
170 public function setActiveDomain( $id ) {
171 $this->activeDomain = (string)$id;
172
173 return $this;
174 }
175
176 /**
177 * Set the server ID known to be used in new commits on a replication stream of interest
178 *
179 * This makes getRelevantActiveGTIDs() filter out GTIDs from other origin servers
180 *
181 * @see MySQLPrimaryPos::getRelevantActiveGTIDs()
182 *
183 * @param string|int|null $id @@server_id of the server were writes originate
184 * @return MySQLPrimaryPos This instance (since 1.34)
185 * @since 1.31
186 */
187 public function setActiveOriginServerId( $id ) {
188 $this->activeServerId = (string)$id;
189
190 return $this;
191 }
192
193 /**
194 * Set the server UUID known to be used in new commits on a replication stream of interest
195 *
196 * This makes getRelevantActiveGTIDs() filter out GTIDs from other origin servers
197 *
198 * @see MySQLPrimaryPos::getRelevantActiveGTIDs()
199 *
200 * @param string|null $id @@server_uuid of the server were writes originate
201 * @return MySQLPrimaryPos This instance (since 1.34)
202 * @since 1.31
203 */
204 public function setActiveOriginServerUUID( $id ) {
205 $this->activeServerUUID = $id;
206
207 return $this;
208 }
209
210 /**
211 * @param MySQLPrimaryPos $pos
212 * @param MySQLPrimaryPos $refPos
213 * @return string[] List of active GTIDs from $pos that have domains in $refPos
214 * @since 1.34
215 */
216 public static function getRelevantActiveGTIDs( MySQLPrimaryPos $pos, MySQLPrimaryPos $refPos ) {
217 return array_values( array_intersect_key(
218 $pos->gtids,
219 $pos->getActiveGtidCoordinates(),
220 $refPos->gtids
221 ) );
222 }
223
224 /**
225 * @see https://mariadb.com/kb/en/mariadb/gtid
226 * @see https://dev.mysql.com/doc/refman/5.6/en/replication-gtids-concepts.html
227 * @return array<string,int> Map of (server_uuid/gtid_domain_id => integer position)
228 */
229 protected function getActiveGtidCoordinates() {
230 $gtidInfos = [];
231
232 foreach ( $this->gtids as $gtid ) {
233 [ $domain, $pos, $server ] = self::parseGTID( $gtid );
234
235 $ignore = false;
236 // Filter out GTIDs from non-active replication domains
237 if ( $this->style === self::GTID_MARIA && $this->activeDomain !== null ) {
238 $ignore = $ignore || ( $domain !== $this->activeDomain );
239 }
240 // Likewise for GTIDs from non-active replication origin servers
241 if ( $this->style === self::GTID_MARIA && $this->activeServerId !== null ) {
242 $ignore = $ignore || ( $server !== $this->activeServerId );
243 } elseif ( $this->style === self::GTID_MYSQL && $this->activeServerUUID !== null ) {
244 $ignore = $ignore || ( $server !== $this->activeServerUUID );
245 }
246
247 if ( !$ignore ) {
248 $gtidInfos[$domain] = $pos;
249 }
250 }
251
252 return $gtidInfos;
253 }
254
255 /**
256 * @param string $id GTID
257 * @return string[]|null (domain ID, event number, source server ID, style) for MariaDB,
258 * (source server UUID, event number, source server UUID, style) for MySQL, or null
259 */
260 protected static function parseGTID( $id ) {
261 $m = [];
262 if ( preg_match( '!^(\d+)-(\d+)-(\d+)$!', $id, $m ) ) {
263 // MariaDB style: "<32 bit domain ID>-<32 bit server id>-<64 bit event number>"
264 $channelId = $m[1];
265 $originServerId = $m[2];
266 $eventNumber = $m[3];
267 $style = self::GTID_MARIA;
268 } elseif ( preg_match( '!^(\w{8}-\w{4}-\w{4}-\w{4}-\w{12}):(?:\d+-|)(\d+)$!', $id, $m ) ) {
269 // MySQL style: "<server UUID>:<64 bit event number>[-<64 bit event number>]".
270 // Normally, the first number should reflect the point (gtid_purged) where older
271 // binary logs where purged to save space. When doing comparisons, it may as well
272 // be 1 in that case. Assume that this is generally the situation.
273 $channelId = $m[1];
274 $originServerId = $m[1];
275 $eventNumber = $m[2];
276 $style = self::GTID_MYSQL;
277 } else {
278 return null;
279 }
280
281 return [ $channelId, $eventNumber, $originServerId, $style ];
282 }
283
284 /**
285 * @see https://dev.mysql.com/doc/refman/5.7/en/show-master-status.html
286 * @see https://dev.mysql.com/doc/refman/5.7/en/show-slave-status.html
287 * @return array|false Map of (binlog:<string>, pos:(<integer>, <integer>)) or false
288 */
289 protected function getBinlogCoordinates() {
290 return ( $this->binLog !== null && $this->logPos !== null )
291 ? [ 'binlog' => $this->binLog, 'pos' => $this->logPos ]
292 : false;
293 }
294
295 public static function newFromArray( array $data ) {
296 $pos = new self( $data['position'], $data['asOfTime'] );
297
298 if ( isset( $data['activeDomain'] ) ) {
299 $pos->setActiveDomain( $data['activeDomain'] );
300 }
301 if ( isset( $data['activeServerId'] ) ) {
302 $pos->setActiveOriginServerId( $data['activeServerId'] );
303 }
304 if ( isset( $data['activeServerUUID'] ) ) {
305 $pos->setActiveOriginServerUUID( $data['activeServerUUID'] );
306 }
307 return $pos;
308 }
309
310 public function toArray(): array {
311 return [
312 '_type_' => get_class( $this ),
313 'position' => $this->__toString(),
314 'activeDomain' => $this->activeDomain,
315 'activeServerId' => $this->activeServerId,
316 'activeServerUUID' => $this->activeServerUUID,
317 'asOfTime' => $this->asOfTime
318 ];
319 }
320
321 /**
322 * @return string GTID set or <binary log file>/<position> (e.g db1034-bin.000976/843431247)
323 */
324 public function __toString() {
325 return $this->gtids
326 ? implode( ',', $this->gtids )
327 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
328 : $this->getLogFile() . "/{$this->logPos[self::CORD_EVENT]}";
329 }
330
331 }