script/MySQLReplicationClient.pl untested

filter: Statementstmt 0.0% 0 / 83 Branchbran 0.0% 0 / 22 Conditioncond 0.0% 0 / 28 MC/DCmcdc 0.0% 0 / 15 Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 162 CC 12 SCAR 32.5
CC
12
Cov
0%
InitEnvironment
56.0
GetStats
30.0
RunReplicationClient
6.0
CRAP 25.9
1 #!/usr/local/bin/perl
2  
3 use strict;
4 use warnings;
5  
6 use DBI;
7 use Pod::Usage;
8 use Getopt::Long;
9 use Sys::Syslog qw{ :standard :macros };
10 use MySQL::Replication::Client;
11  
12 my ( %Options, $Dbh, $ReplicationClient );
13  
14 InitEnvironment();
15 RunReplicationClient();
16  
17 sub InitEnvironment {
18 %Options = (
19 SrcPort => 2603,
20 DestHost => 'localhost',
21 DestPort => 3306,
22 DestDB => 'Replication',
23 RelayPort => 2600,
24 LogLevel => 'LOG_ERR',
25 );
26  
27 GetOptions(
28 'srchost=s' => \$Options{SrcHost},
29 'srcport=s' => \$Options{SrcPort},
30 'srcbinlog=s' => \$Options{SrcBinlog},
31 'desthost=s' => \$Options{DestHost},
32 'destport=s' => \$Options{DestPort},
33 'destdb=s' => \$Options{DestDB},
34 'destuser=s' => \$Options{DestUser},
35 'destpass=s' => \$Options{DestPass},
36 'relayhost=s' => \$Options{RelayHost},
37 'relayport=s' => \$Options{RelayPort},
38 'loglevel=s' => \$Options{LogLevel},
39 'pidfile=s' => \$Options{PidFile},
40 'getstats' => \$Options{GetStats},
41 ) or pod2usage( 1 );
42  
43 my @RequiredParameters = qw{
44 SrcHost
45 SrcBinlog
46 DestUser
47 DestPass
48 };
49  
50 foreach my $Required ( @RequiredParameters ) {
51 next if $Options{$Required};
52 print STDERR "Required argument '\L$Required' missing\n\n";
53 pod2usage( 1 );
54 }
55  
56 if ( not $Options{PidFile} ) {
57 $Options{PidFile} = "/var/run/mysql_replication_client_$Options{SrcHost}_$Options{SrcBinlog}.pid";
58 }
59  
60 $0 = "MySQLReplicationClient.pl: --pidfile $Options{PidFile}";
61  
62 $Dbh = DBI->connect(
63 sprintf( 'dbi:mysql:database=%s;host=%s;port=%s', $Options{DestDB}, $Options{DestHost}, $Options{DestPort} ),
64 $Options{DestUser},
65 $Options{DestPass}
66 ) or die "Error connecting to database ($DBI::errstr)";
67  
68 if ( $Options{GetStats} ) {
69 GetStats();
70 exit;
71 }
72  
73 if ( -e $Options{PidFile} ) {
74 open my $PidFh, '<', $Options{PidFile}
75 or die "Error opening pid file $Options{PidFile} ($!)";
76  
77 chomp( my $Pid = <$PidFh> );
78 close $PidFh;
79  
80 die 'Already running' if kill 0, $Pid;
81 }
82  
83 open my $PidFh, '>', $Options{PidFile}
84 or die "Error creating pid file $Options{PidFile} ($!)";
85  
86 print $PidFh "$$\n";
87 close $PidFh;
88  
89 openlog( 'MySQLReplicationClient.pl', 'pid,nofatal' )
90 or die 'Error opening syslog';
91  
92 eval "setlogmask( LOG_UPTO($Options{LogLevel}) )"
93 or die "Error setting log level to $Options{LogLevel}";
94  
95 $SIG{__DIE__} = sub {
96 syslog( LOG_ERR, "Aborting: @_" );
97 exit 1;
98 };
99  
100 syslog( LOG_ERR, sprintf( "Starting: Source(%s:%s), Destination(%s:%s:%s), Relay(%s)",
101 $Options{SrcHost},
102 $Options{SrcBinlog},
103 $Options{DestHost},
104 $Options{DestPort},
105 $Options{DestDB},
106 ( $Options{RelayHost} || 'NONE' ),
107 ));
108  
109 if ( not $Options{RelayHost} ) {
110 $Options{RelayHost} = $Options{SrcHost},
111 $Options{RelayPort} = $Options{SrcPort},
112 }
113  
114 my $RelaySocket = IO::Socket::INET->new(
115 PeerAddr => $Options{RelayHost},
116 PeerPort => $Options{RelayPort},
117 Proto => 'tcp',
118 ) or die sprintf( "Error connecting to '%s:%s' ($!)", $Options{RelayHost}, $Options{RelayPort} );
119  
120 $ReplicationClient = MySQL::Replication::Client->new(
121 Dbh => $Dbh,
122 DBName => $Options{DestDB},
123 RelaySocket => $RelaySocket,
124 Host => $Options{SrcHost},
125 Binlog => $Options{SrcBinlog},
126 );
127 }
128  
129 sub RunReplicationClient{
130 $ReplicationClient->RequestQueries();
131  
132 while ( 1 ) {
133 my @Queries = $ReplicationClient->GetQueries();
134  
135 if ( $Options{LogLevel} eq 'LOG_DEBUG' ) {
136 foreach my $Query ( @Queries ) {
137 syslog( LOG_DEBUG, $Query->Stringify() );
138 }
139 }
140  
141 $ReplicationClient->ExecuteQueries( @Queries );
142 }
143 }
144  
145 sub GetStats {
146 my $ServerSocket = IO::Socket::INET->new(
147 PeerAddr => $Options{SrcHost},
148 PeerPort => $Options{SrcPort},
149 Proto => 'tcp',
150 ) or die sprintf( "Error connecting to '%s:%s' ($!)", $Options{SrcHost}, $Options{SrcPort} );
151  
152 my $Request = MySQL::Replication::Command->new(
153 Command => 'POLL',
154 Headers => {
155 Binlog => $Options{SrcBinlog},
156 },
157 ) or die "Error creating POLL request ($MySQL::Replication::Command::Errstr)";
158  
159 $Request->SendToSocket( $ServerSocket )
160 or die "Error sending POLL request ($MySQL::Replication::Command::Errstr)";
161  
162 my $Response = MySQL::Replication::Command->NewFromSocket(
163 Socket => $ServerSocket,
164 Buffer => \my $Buffer,
165 ) or die "Error reading response ($MySQL::Replication::Command::Errstr)";
166  
167 if ( $Response->Command() ne 'STATS' ) {
168 die sprintf( "Invalid response '%s' for POLL", $Response->Command() );
169 }
170  
171 foreach my $Required ( qw{ Log Pos BinlogSize } ) {
172 next if defined $Response->Headers()->{$Required};
173 die "Required header '$Required' missing";
174 }
175  
176 my ( $Log, $Pos ) = $Dbh->selectrow_array( sprintf( q{
177 SELECT Log, Pos
178 FROM %s.SourcePosition
179 WHERE Host = ?
180 AND Binlog = ?
181 }, $Options{DestDB} ),
182 undef,
183 $Options{SrcHost},
184 $Options{SrcBinlog},
185 );
186  
187 if ( not $Log or not $Pos ) {
188 die "Error reading local source position ($DBI::errstr)" if $DBI::errstr;
189 die 'No local source position';
190 }
191  
192 use bigint;
193 my $BytesBehind
194 = ( $Response->Headers()->{BinlogSize} * $Response->Headers()->{Log} + $Response->Headers()->{Pos} )
195 - ( $Response->Headers()->{BinlogSize} * $Log + $Pos );
196  
197 print join( "\n",
198 "LocalLog: $Log",
199 "LocalPos: $Pos",
200 (
201 map { "Remote$_: " . $Response->Headers()->{$_} }
202 qw{ Log Pos }
203 ),
204 "BytesBehind: $BytesBehind",
205 ) . "\n";
206 }
207  
208 =pod
209  
210 =head1 NAME
211  
212 MySQLReplicationClient.pl - Replicates a remote host's binlogs to a local database
213  
214 =head1 SYNOPSIS
215  
216 MySQLReplicationClient.pl
217 --srchost <srchost>
218 --srcport <srcport>
219 --srcbinlog <srcbinlog>
220 --desthost <desthost>
221 --destport <destport>
222 --destdb <destdb>
223 --destuser <destuser>
224 --destpass <destpass>
225 --relayhost <relayhost>
226 --relayport <relayport>
227 --loglevel <loglevel>
228 --getstats
229  
230 =head1 DESCRIPTION
231  
232 This script will:
233  
234 =over
235  
236 =item *
237  
238 Connect to the replication server running on the source host (or a relay)
239  
240 =item *
241  
242 Request binlog queries starting from the local binlog position
243  
244 =item *
245  
246 Read query responses and execute them on the local database
247  
248 =item *
249  
250 Update the local binlog position after each query has been executed
251  
252 =back
253  
254 A running instance will replicate from a single source i.e.:
255  
256 +----------------+ +-----------------+
257 | local database |<------| source database |
258 +----------------+ +-----------------+
259  
260 To replicate from multiple sources, simply run it multiple times i.e.:
261  
262 +----------------+ +------------------+
263 | |<------| source database1 |
264 | | +------------------+
265 | |
266 | | +------------------+
267 | local database |<------| source database2 |
268 | | +------------------+
269 | |
270 | | +------------------+
271 | |<------| source database3 |
272 +----------------+ +------------------+
273  
274 =head2 First Time Setup
275  
276 =head3 Stop MySQL's Built-In Replication
277  
278 MySQL's built-in replication must be stopped between the source host and the
279 local database before continuing. Otherwise MySQL's built-in replication and
280 this script will execute the same queries leading to incorrect data.
281  
282 On the slave host:
283  
284 SLAVE STOP
285  
286 =head3 Create the Replication Schema
287  
288 The replication schema is where internal replication data will be stored.
289 Before running the replication client for the first time, this schema will need
290 to be created on the local database:
291  
292 SET SQL_LOG_BIN=0;
293  
294 CREATE DATABASE IF NOT EXISTS Replication;
295 USE Replication;
296  
297 CREATE TABLE IF NOT EXISTS SourcePosition (
298 Host VARCHAR(255) NOT NULL,
299 Binlog VARCHAR(255) NOT NULL,
300 Log MEDIUMINT NOT NULL,
301 Pos INT NOT NULL,
302 PRIMARY KEY ( Host, Binlog )
303 ) ENGINE=InnoDB;
304  
305 By default the 'Replication' schema name is used.
306  
307 =head3 Grant Permissions
308  
309 Since all queries from the replication server will be executed on the local
310 database, appropriate permissions must be granted to the provided credentials.
311  
312 Note that the C<SUPER> privilege will also need to be granted since it will be
313 modifying the system variable C<SQL_LOG_BIN>.
314  
315 =head3 Setting the Local Binlog Position
316  
317 Before running the replication client for the first time, it will need to know
318 where to start replicating from:
319  
320 SET SQL_LOG_BIN=0;
321  
322 INSERT INTO Replication.SourcePosition VALUES
323 ( srchost, srcbinlog, startlog, startpos );
324  
325 B<WARNING: Is is essential that turning off binlogging here is done before the
326 insert. Otherwise all replication clients of this host will see the insert and
327 update their own internal binlog positions.>
328  
329 The value of startlog and startpos will depend on how the local MySQL database
330 was created.
331  
332 To pick up from where MySQL's built-in replication stopped, use the values from
333 C<SHOW SLAVE STATUS>:
334  
335 > SHOW SLAVE STATUS\G
336 ...
337 Relay_Master_Log_File: binlog-filename.<startlog>
338 Exec_Master_Log_Pos: <startpos>
339  
340 To start from a known query within a binlog on the source host:
341  
342 $ mysqlbinlog binlog-filename.<startlog> | less
343 ...
344 # at <startpos>
345 QueryText
346  
347 =head3 Turn off MySQL's Built-In Replication
348  
349 To stop MySQL's built-in replication from resuming on a restart, on the slave
350 host:
351  
352 RESET SLAVE
353 CHANGE MASTER TO MASTER_HOST=''
354  
355 =head2 Confirm it's working
356  
357 To confirm that replication is working:
358  
359 =over
360  
361 =item
362  
363 You can query the replication position directly:
364  
365 SELECT * FROM Replication.SourcePosition
366  
367 =item
368  
369 Use the --getstats option along with all the required options:
370  
371 ./MySQLReplicationClient ... --getstats
372  
373 =back
374  
375 =head1 OPTIONS
376  
377 =over
378  
379 =item srchost (mandatory)
380  
381 The source host of the binlogs to replicate from.
382  
383 =item srcport (default: 2603)
384  
385 The port of the replication server running on the source host.
386  
387 =item srcbinlog (mandatory)
388  
389 The name of the binlog we want to replicate.
390  
391 =item desthost (default: localhost)
392  
393 The host of the local MySQL server to replicate into.
394  
395 This value is usually 'localhost' however MySQL can be configured to bind to
396 a specific IP address instead of all interfaces.
397  
398 =item destport (default: 3306)
399  
400 The port of the local MySQL server.
401  
402 =item destdb (default: Replication)
403  
404 The schema used for internal replication data such as the local binlog positions.
405  
406 =item destuser (mandatory)
407  
408 =item destpass (mandatory)
409  
410 Credentials to the local MySQL server.
411  
412 =item relayhost
413  
414 If not specified, connect directly to the source host to replicate from.
415  
416 If specified, connect instead to a replication relay host to replicate from.
417  
418 A replication relay acts as a proxy cache for multiple replication clients.
419  
420 =item relayport (default: 2600)
421  
422 The port of the replication relay server.
423  
424 =item loglevel (default: LOG_ERR)
425  
426 Logging is via syslog, using the 'daemon' facility (by default to /var/log/messages).
427  
428 The syslog log level. Possible values are:
429  
430 =over
431  
432 =item *
433  
434 LOG_CRIT
435  
436 Since no log messages are at LOG_CRIT or above, this effectively turns off
437 logging.
438  
439 =item *
440  
441 LOG_ERR
442  
443 Log all errors.
444  
445 =item *
446  
447 LOG_DEBUG
448  
449 Log all errors and query responses.
450  
451 =back
452  
453 =item getstats
454  
455 Displays statistics on how replication is proceeding.
456  
457 =back
458  
459 =head1 BUGS
460  
461 =over
462  
463 =item *
464  
465 Currently, row-based replication and LOAD DATA INFILE and related queries
466 aren't supported. If encountered, replication will stop.
467  
468 =item *
469  
470 Since all queries coming over the wire will be in plain text, it is important
471 that traffic be routed through a secure tunnel.
472  
473 =item *
474  
475 The relay isn't complete yet (but it's coming soon)
476  
477 =back
478  
479 =head1 AUTHOR
480  
481 Alfie John, C<alfiej@opera.com>
482  
483 =head1 LICENSE AND COPYRIGHT
484  
485 Copyright (c) 2011, Opera Software Australia Pty. Ltd.
486 All rights reserved.
487  
488 Redistribution and use in source and binary forms, with or without
489 modification, are permitted provided that the following conditions are
490 met:
491  
492 * Redistributions of source code must retain the above copyright notice,
493 this list of conditions and the following disclaimer.
494 * Redistributions in binary form must reproduce the above copyright notice,
495 this list of conditions and the following disclaimer in the documentation
496 and/or other materials provided with the distribution.
497 * Neither the name of the copyright holder nor the names of its contributors
498 may be used to endorse or promote products derived from this software
499 without specific prior written permission.
500  
501 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
502 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
503 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
504 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
505 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
506 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
507 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
508 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
509 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
510 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
511  
512 =cut