mysqlhotcopy.sh
上传用户:dzyhzl
上传日期:2019-04-29
资源大小:56270k
文件大小:28k
源码类别:

模拟服务器

开发平台:

C/C++

  1. #!@PERL@ -w
  2. use strict;
  3. use Getopt::Long;
  4. use Data::Dumper;
  5. use File::Basename;
  6. use File::Path;
  7. use DBI;
  8. use Sys::Hostname;
  9. =head1 NAME
  10. mysqlhotcopy - fast on-line hot-backup utility for local MySQL databases and tables
  11. =head1 SYNOPSIS
  12.   mysqlhotcopy db_name
  13.   mysqlhotcopy --suffix=_copy db_name_1 ... db_name_n
  14.   mysqlhotcopy db_name_1 ... db_name_n /path/to/new_directory
  15.   mysqlhotcopy db_name./regex/
  16.   mysqlhotcopy db_name./^(foo|bar)/
  17.   mysqlhotcopy db_name./~regex/
  18.   mysqlhotcopy db_name_1./regex_1/ db_name_1./regex_2/ ... db_name_n./regex_n/ /path/to/new_directory
  19.   mysqlhotcopy --method='scp -Bq -i /usr/home/foo/.ssh/identity' --user=root --password=secretpassword 
  20.          db_1./^nice_table/ user@some.system.dom:~/path/to/new_directory
  21. WARNING: THIS PROGRAM IS STILL IN BETA. Comments/patches welcome.
  22. =cut
  23. # Documentation continued at end of file
  24. my $VERSION = "1.17";
  25. my $opt_tmpdir = $ENV{TMPDIR} || "/tmp";
  26. my $OPTIONS = <<"_OPTIONS";
  27. $0 Ver $VERSION
  28. Usage: $0 db_name[./table_regex/] [new_db_name | directory]
  29.   -?, --help           display this helpscreen and exit
  30.   -u, --user=#         user for database login if not current user
  31.   -p, --password=#     password to use when connecting to server
  32.   -h, --host=#        Hostname for local server when connecting over TCP/IP
  33.   -P, --port=#         port to use when connecting to local server with TCP/IP
  34.   -S, --socket=#       socket to use when connecting to local server
  35.   --allowold           don't abort if target already exists (rename it _old)
  36.   --keepold            don't delete previous (now renamed) target when done
  37.   --noindices          don't include full index files in copy
  38.   --method=#           method for copy (only "cp" currently supported)
  39.   -q, --quiet          be silent except for errors
  40.   --debug              enable debug
  41.   -n, --dryrun         report actions without doing them
  42.   --regexp=#           copy all databases with names matching regexp
  43.   --suffix=#           suffix for names of copied databases
  44.   --checkpoint=#       insert checkpoint entry into specified db.table
  45.   --flushlog           flush logs once all tables are locked 
  46.   --resetmaster        reset the binlog once all tables are locked
  47.   --resetslave         reset the master.info once all tables are locked
  48.   --tmpdir=#        temporary directory (instead of $opt_tmpdir)
  49.   --record_log_pos=#   record slave and master status in specified db.table
  50.   Try 'perldoc $0 for more complete documentation'
  51. _OPTIONS
  52. sub usage {
  53.     die @_, $OPTIONS;
  54. }
  55. my %opt = (
  56.     user => scalar getpwuid($>),
  57.     noindices => 0,
  58.     allowold => 0, # for safety
  59.     keepold => 0,
  60.     method => "cp",
  61.     flushlog    => 0,
  62. );
  63. Getopt::Long::Configure(qw(no_ignore_case)); # disambuguate -p and -P
  64. GetOptions( %opt,
  65.     "help",
  66.     "host|h=s",
  67.     "user|u=s",
  68.     "password|p=s",
  69.     "port|P=s",
  70.     "socket|S=s",
  71.     "allowold!",
  72.     "keepold!",
  73.     "noindices!",
  74.     "method=s",
  75.     "debug",
  76.     "quiet|q",
  77.     "mv!",
  78.     "regexp=s",
  79.     "suffix=s",
  80.     "checkpoint=s",
  81.     "record_log_pos=s",
  82.     "flushlog",
  83.     "resetmaster",
  84.     "resetslave",
  85.     "tmpdir|t=s",
  86.     "dryrun|n",
  87. ) or usage("Invalid option");
  88. # @db_desc
  89. # ==========
  90. # a list of hash-refs containing:
  91. #
  92. #   'src'     - name of the db to copy
  93. #   't_regex' - regex describing tables in src
  94. #   'target'  - destination directory of the copy
  95. #   'tables'  - array-ref to list of tables in the db
  96. #   'files'   - array-ref to list of files to be copied
  97. #               (RAID files look like 'nn/name.MYD')
  98. #   'index'   - array-ref to list of indexes to be copied
  99. #
  100. my @db_desc = ();
  101. my $tgt_name = undef;
  102. usage("") if ($opt{help});
  103. if ( $opt{regexp} || $opt{suffix} || @ARGV > 2 ) {
  104.     $tgt_name   = pop @ARGV unless ( exists $opt{suffix} );
  105.     @db_desc = map { s{^([^.]+)./(.+)/$}{$1}; { 'src' => $_, 't_regex' => ( $2 ? $2 : '.*' ) } } @ARGV;
  106. }
  107. else {
  108.     usage("Database name to hotcopy not specified") unless ( @ARGV );
  109.     $ARGV[0] =~ s{^([^.]+)./(.+)/$}{$1};
  110.     @db_desc = ( { 'src' => $ARGV[0], 't_regex' => ( $2 ? $2 : '.*' ) } );
  111.     if ( @ARGV == 2 ) {
  112. $tgt_name   = $ARGV[1];
  113.     }
  114.     else {
  115. $opt{suffix} = "_copy";
  116.     }
  117. }
  118. my %mysqld_vars;
  119. my $start_time = time;
  120. $opt_tmpdir= $opt{tmpdir} if $opt{tmpdir};
  121. $0 = $1 if $0 =~ m:/([^/]+)$:;
  122. $opt{quiet} = 0 if $opt{debug};
  123. $opt{allowold} = 1 if $opt{keepold};
  124. # --- connect to the database ---
  125. my $dsn;
  126. $dsn  = ";host=" . (defined($opt{host}) ? $opt{host} : "localhost");
  127. $dsn .= ";port=$opt{port}" if $opt{port};
  128. $dsn .= ";mysql_socket=$opt{socket}" if $opt{socket};
  129. my $dbh = DBI->connect("dbi:mysql:$dsn;mysql_read_default_group=mysqlhotcopy",
  130.                         $opt{user}, $opt{password},
  131. {
  132.     RaiseError => 1,
  133.     PrintError => 0,
  134.     AutoCommit => 1,
  135. });
  136. # --- check that checkpoint table exists if specified ---
  137. if ( $opt{checkpoint} ) {
  138.     eval { $dbh->do( qq{ select time_stamp, src, dest, msg 
  139.  from $opt{checkpoint} where 1 != 1} );
  140.        };
  141.     die "Error accessing Checkpoint table ($opt{checkpoint}): $@"
  142.       if ( $@ );
  143. }
  144. # --- check that log_pos table exists if specified ---
  145. if ( $opt{record_log_pos} ) {
  146.     eval { $dbh->do( qq{ select host, time_stamp, log_file, log_pos, master_host, master_log_file, master_log_pos
  147.  from $opt{record_log_pos} where 1 != 1} );
  148.        };
  149.     die "Error accessing log_pos table ($opt{record_log_pos}): $@"
  150.       if ( $@ );
  151. }
  152. # --- get variables from database ---
  153. my $sth_vars = $dbh->prepare("show variables like 'datadir'");
  154. $sth_vars->execute;
  155. while ( my ($var,$value) = $sth_vars->fetchrow_array ) {
  156.     $mysqld_vars{ $var } = $value;
  157. }
  158. my $datadir = $mysqld_vars{'datadir'}
  159.     || die "datadir not in mysqld variables";
  160. $datadir =~ s:/$::;
  161. # --- get target path ---
  162. my ($tgt_dirname, $to_other_database);
  163. $to_other_database=0;
  164. if (defined($tgt_name) && $tgt_name =~ m:^w+$: && @db_desc <= 1)
  165. {
  166.     $tgt_dirname = "$datadir/$tgt_name";
  167.     $to_other_database=1;
  168. }
  169. elsif (defined($tgt_name) && ($tgt_name =~ m:/: || $tgt_name eq '.')) {
  170.     $tgt_dirname = $tgt_name;
  171. }
  172. elsif ( $opt{suffix} ) {
  173.     print "Using copy suffix '$opt{suffix}'n" unless $opt{quiet};
  174. }
  175. else
  176. {
  177.   $tgt_name="" if (!defined($tgt_name));
  178.   die "Target '$tgt_name' doesn't look like a database name or directory path.n";
  179. }
  180. # --- resolve database names from regexp ---
  181. if ( defined $opt{regexp} ) {
  182.     my $sth_dbs = $dbh->prepare("show databases");
  183.     $sth_dbs->execute;
  184.     while ( my ($db_name) = $sth_dbs->fetchrow_array ) {
  185. push @db_desc, { 'src' => $db_name } if ( $db_name =~ m/$opt{regexp}/o );
  186.     }
  187. }
  188. # --- get list of tables to hotcopy ---
  189. my $hc_locks = "";
  190. my $hc_tables = "";
  191. my $num_tables = 0;
  192. my $num_files = 0;
  193. foreach my $rdb ( @db_desc ) {
  194.     my $db = $rdb->{src};
  195.     my @dbh_tables = get_list_of_tables( $db );
  196.     ## generate regex for tables/files
  197.     my $t_regex;
  198.     my $negated;
  199.     if ($rdb->{t_regex}) {
  200.         $t_regex = $rdb->{t_regex};        ## assign temporary regex
  201.         $negated = $t_regex =~ tr/~//d;    ## remove and count
  202.                                            ## negation operator: we
  203.                                            ## don't allow ~ in table
  204.                                            ## names
  205.         $t_regex = qr/$t_regex/;           ## make regex string from
  206.                                            ## user regex
  207.         ## filter (out) tables specified in t_regex
  208.         print "Filtering tables with '$t_regex'n" if $opt{debug};
  209.         @dbh_tables = ( $negated 
  210.                         ? grep { $_ !~ $t_regex } @dbh_tables
  211.                         : grep { $_ =~ $t_regex } @dbh_tables );
  212.     }
  213.     ## get list of files to copy
  214.     my $db_dir = "$datadir/$db";
  215.     opendir(DBDIR, $db_dir ) 
  216.       or die "Cannot open dir '$db_dir': $!";
  217.     my %db_files;
  218.     my @raid_dir = ();
  219.     while ( defined( my $name = readdir DBDIR ) ) {
  220. if ( $name =~ /^dd$/ && -d "$db_dir/$name" ) {
  221.     push @raid_dir, $name;
  222. }
  223. else {
  224.     $db_files{$name} = $1 if ( $name =~ /(.+).w+$/ );
  225.         }
  226.     }
  227.     closedir( DBDIR );
  228.     scan_raid_dir( %db_files, $db_dir, @raid_dir );
  229.     unless( keys %db_files ) {
  230. warn "'$db' is an empty databasen";
  231.     }
  232.     ## filter (out) files specified in t_regex
  233.     my @db_files;
  234.     if ($rdb->{t_regex}) {
  235.         @db_files = ($negated
  236.                      ? grep { $db_files{$_} !~ $t_regex } keys %db_files
  237.                      : grep { $db_files{$_} =~ $t_regex } keys %db_files );
  238.     }
  239.     else {
  240.         @db_files = keys %db_files;
  241.     }
  242.     @db_files = sort @db_files;
  243.     my @index_files=();
  244.     ## remove indices unless we're told to keep them
  245.     if ($opt{noindices}) {
  246.         @index_files= grep { /.(ISM|MYI)$/ } @db_files;
  247. @db_files = grep { not /.(ISM|MYI)$/ } @db_files;
  248.     }
  249.     $rdb->{files}  = [ @db_files ];
  250.     $rdb->{index}  = [ @index_files ];
  251.     my @hc_tables = map { "`$db`.`$_`" } @dbh_tables;
  252.     $rdb->{tables} = [ @hc_tables ];
  253.     $rdb->{raid_dirs} = [ get_raid_dirs( $rdb->{files} ) ];
  254.     $hc_locks .= ", "  if ( length $hc_locks && @hc_tables );
  255.     $hc_locks .= join ", ", map { "$_ READ" } @hc_tables;
  256.     $hc_tables .= ", "  if ( length $hc_tables && @hc_tables );
  257.     $hc_tables .= join ", ", @hc_tables;
  258.     $num_tables += scalar @hc_tables;
  259.     $num_files  += scalar @{$rdb->{files}};
  260. }
  261. # --- resolve targets for copies ---
  262. if (defined($tgt_name) && length $tgt_name ) {
  263.     # explicit destination directory specified
  264.     # GNU `cp -r` error message
  265.     die "copying multiple databases, but last argument ($tgt_dirname) is not a directoryn"
  266.       if ( @db_desc > 1 && !(-e $tgt_dirname && -d $tgt_dirname ) );
  267.     if ($to_other_database)
  268.     {
  269.       foreach my $rdb ( @db_desc ) {
  270. $rdb->{target} = "$tgt_dirname";
  271.       }
  272.     }
  273.     elsif ($opt{method} =~ /^scpb/) 
  274.     {   # we have to trust scp to hit the target
  275. foreach my $rdb ( @db_desc ) {
  276.     $rdb->{target} = "$tgt_dirname/$rdb->{src}";
  277. }
  278.     }
  279.     else
  280.     {
  281.       die "Last argument ($tgt_dirname) is not a directoryn"
  282. if (!(-e $tgt_dirname && -d $tgt_dirname ) );
  283.       foreach my $rdb ( @db_desc ) {
  284. $rdb->{target} = "$tgt_dirname/$rdb->{src}";
  285.       }
  286.     }
  287.   }
  288. else {
  289.   die "Error: expected $opt{suffix} to exist" unless ( exists $opt{suffix} );
  290.   foreach my $rdb ( @db_desc ) {
  291.     $rdb->{target} = "$datadir/$rdb->{src}$opt{suffix}";
  292.   }
  293. }
  294. print Dumper( @db_desc ) if ( $opt{debug} );
  295. # --- bail out if all specified databases are empty ---
  296. die "No tables to hot-copy" unless ( length $hc_locks );
  297. # --- create target directories if we are using 'cp' ---
  298. my @existing = ();
  299. if ($opt{method} =~ /^cpb/)
  300. {
  301.   foreach my $rdb ( @db_desc ) {
  302.     push @existing, $rdb->{target} if ( -d  $rdb->{target} );
  303.   }
  304.   if ( @existing && !$opt{allowold} )
  305.   {
  306.     $dbh->disconnect();
  307.     die "Can't hotcopy to '", join( "','", @existing ), "' because directorynalready exist and the --allowold option was not given.n"
  308.   }
  309. }
  310. retire_directory( @existing ) if ( @existing );
  311. foreach my $rdb ( @db_desc ) {
  312.     foreach my $td ( '', @{$rdb->{raid_dirs}} ) {
  313. my $tgt_dirpath = "$rdb->{target}/$td";
  314. # Remove trailing slashes (needed for Mac OS X)
  315.      substr($tgt_dirpath, 1) =~ s|/+$||;
  316. if ( $opt{dryrun} ) {
  317.     print "mkdir $tgt_dirpath, 0750n";
  318. }
  319. elsif ($opt{method} =~ /^scpb/) {
  320.     ## assume it's there?
  321.     ## ...
  322. }
  323. else {
  324.     mkdir($tgt_dirpath, 0750)
  325. or die "Can't create '$tgt_dirpath': $!n";
  326. }
  327.     }
  328. }
  329. ##############################
  330. # --- PERFORM THE HOT-COPY ---
  331. #
  332. # Note that we try to keep the time between the LOCK and the UNLOCK
  333. # as short as possible, and only start when we know that we should
  334. # be able to complete without error.
  335. # read lock all the tables we'll be copying
  336. # in order to get a consistent snapshot of the database
  337. if ( $opt{checkpoint} || $opt{record_log_pos} ) {
  338.   # convert existing READ lock on checkpoint and/or log_pos table into WRITE lock
  339.   foreach my $table ( grep { defined } ( $opt{checkpoint}, $opt{record_log_pos} ) ) {
  340.     $hc_locks .= ", $table WRITE" 
  341. unless ( $hc_locks =~ s/$tables+READ/$table WRITE/ );
  342.   }
  343. }
  344. my $hc_started = time; # count from time lock is granted
  345. if ( $opt{dryrun} ) {
  346.     print "LOCK TABLES $hc_locksn";
  347.     print "FLUSH TABLES /*!32323 $hc_tables */n";
  348.     print "FLUSH LOGSn" if ( $opt{flushlog} );
  349.     print "RESET MASTERn" if ( $opt{resetmaster} );
  350.     print "RESET SLAVEn" if ( $opt{resetslave} );
  351. }
  352. else {
  353.     my $start = time;
  354.     $dbh->do("LOCK TABLES $hc_locks");
  355.     printf "Locked $num_tables tables in %d seconds.n", time-$start unless $opt{quiet};
  356.     $hc_started = time; # count from time lock is granted
  357.     # flush tables to make on-disk copy uptodate
  358.     $start = time;
  359.     $dbh->do("FLUSH TABLES /*!32323 $hc_tables */");
  360.     printf "Flushed tables ($hc_tables) in %d seconds.n", time-$start unless $opt{quiet};
  361.     $dbh->do( "FLUSH LOGS" ) if ( $opt{flushlog} );
  362.     $dbh->do( "RESET MASTER" ) if ( $opt{resetmaster} );
  363.     $dbh->do( "RESET SLAVE" ) if ( $opt{resetslave} );
  364.     if ( $opt{record_log_pos} ) {
  365. record_log_pos( $dbh, $opt{record_log_pos} );
  366. $dbh->do("FLUSH TABLES /*!32323 $hc_tables */");
  367.     }
  368. }
  369. my @failed = ();
  370. foreach my $rdb ( @db_desc )
  371. {
  372.   my @files = map { "$datadir/$rdb->{src}/$_" } @{$rdb->{files}};
  373.   next unless @files;
  374.   
  375.   eval { copy_files($opt{method}, @files, $rdb->{target}, $rdb->{raid_dirs} ); };
  376.   push @failed, "$rdb->{src} -> $rdb->{target} failed: $@"
  377.     if ( $@ );
  378.   
  379.   @files = @{$rdb->{index}};
  380.   if ($rdb->{index})
  381.   {
  382.     copy_index($opt{method}, @files,
  383.        "$datadir/$rdb->{src}", $rdb->{target} );
  384.   }
  385.   
  386.   if ( $opt{checkpoint} ) {
  387.     my $msg = ( $@ ) ? "Failed: $@" : "Succeeded";
  388.     
  389.     eval {
  390.       $dbh->do( qq{ insert into $opt{checkpoint} (src, dest, msg) 
  391.       VALUES ( '$rdb->{src}', '$rdb->{target}', '$msg' )
  392.     } ); 
  393.     };
  394.     
  395.     if ( $@ ) {
  396.       warn "Failed to update checkpoint table: $@n";
  397.     }
  398.   }
  399. }
  400. if ( $opt{dryrun} ) {
  401.     print "UNLOCK TABLESn";
  402.     if ( @existing && !$opt{keepold} ) {
  403. my @oldies = map { $_ . '_old' } @existing;
  404. print "rm -rf @oldiesn" 
  405.     }
  406.     $dbh->disconnect();
  407.     exit(0);
  408. }
  409. else {
  410.     $dbh->do("UNLOCK TABLES");
  411. }
  412. my $hc_dur = time - $hc_started;
  413. printf "Unlocked tables.n" unless $opt{quiet};
  414. #
  415. # --- HOT-COPY COMPLETE ---
  416. ###########################
  417. $dbh->disconnect;
  418. if ( @failed ) {
  419.     # hotcopy failed - cleanup
  420.     # delete any @targets 
  421.     # rename _old copy back to original
  422.     my @targets = ();
  423.     foreach my $rdb ( @db_desc ) {
  424.         push @targets, $rdb->{target} if ( -d  $rdb->{target} );
  425.     }
  426.     print "Deleting @targets n" if $opt{debug};
  427.     print "Deleting @targets n" if $opt{debug};
  428.     rmtree([@targets]);
  429.     if (@existing) {
  430. print "Restoring @existing from back-upn" if $opt{debug};
  431.         foreach my $dir ( @existing ) {
  432.     rename("${dir}_old", $dir )
  433.       or warn "Can't rename ${dir}_old to $dir: $!n";
  434. }
  435.     }
  436.     die join( "n", @failed );
  437. }
  438. else {
  439.     # hotcopy worked
  440.     # delete _old unless $opt{keepold}
  441.     if ( @existing && !$opt{keepold} ) {
  442. my @oldies = map { $_ . '_old' } @existing;
  443. print "Deleting previous copy in @oldiesn" if $opt{debug};
  444. rmtree([@oldies]);
  445.     }
  446.     printf "$0 copied %d tables (%d files) in %d second%s (%d seconds overall).n",
  447.     $num_tables, $num_files,
  448.     $hc_dur, ($hc_dur==1)?"":"s", time - $start_time
  449. unless $opt{quiet};
  450. }
  451. exit 0;
  452. # ---
  453. sub copy_files {
  454.     my ($method, $files, $target, $raid_dirs) = @_;
  455.     my @cmd;
  456.     print "Copying ".@$files." files...n" unless $opt{quiet};
  457.     if ($method =~ /^s?cpb/) { # cp or scp with optional flags
  458. my @cp = ($method);
  459. # add option to preserve mod time etc of copied files
  460. # not critical, but nice to have
  461. push @cp, "-p" if $^O =~ m/^(solaris|linux|freebsd|darwin)$/;
  462. # add recursive option for scp
  463. push @cp, "-r" if $^O =~ /m^(solaris|linux|freebsd|darwin)$/ && $method =~ /^scpb/;
  464. my @non_raid = map { "'$_'" } grep { ! m:/d{2}/[^/]+$: } @$files;
  465. # add files to copy and the destination directory
  466. safe_system( @cp, @non_raid, "'$target'" );
  467. foreach my $rd ( @$raid_dirs ) {
  468.     my @raid = map { "'$_'" } grep { m:$rd/: } @$files;
  469.     safe_system( @cp, @raid, "'$target'/$rd" ) if ( @raid );
  470. }
  471.     }
  472.     else
  473.     {
  474. die "Can't use unsupported method '$method'n";
  475.     }
  476. }
  477. #
  478. # Copy only the header of the index file
  479. #
  480. sub copy_index
  481. {
  482.   my ($method, $files, $source, $target) = @_;
  483.   my $tmpfile="$opt_tmpdir/mysqlhotcopy$$";
  484.   
  485.   print "Copying indices for ".@$files." files...n" unless $opt{quiet};  
  486.   foreach my $file (@$files)
  487.   {
  488.     my $from="$source/$file";
  489.     my $to="$target/$file";
  490.     my $buff;
  491.     open(INPUT, "<$from") || die "Can't open file $from: $!n";
  492.     my $length=read INPUT, $buff, 2048;
  493.     die "Can't read index header from $fromn" if ($length < 1024);
  494.     close INPUT;
  495.     
  496.     if ( $opt{dryrun} )
  497.     {
  498.       print "$opt{method}-header $from $ton";
  499.     }
  500.     elsif ($opt{method} eq 'cp')
  501.     {
  502.       open(OUTPUT,">$to")   || die "Can't create file $to: $!n";
  503.       if (syswrite(OUTPUT,$buff) != length($buff))
  504.       {
  505. die "Error when writing data to $to: $!n";
  506.       }
  507.       close OUTPUT    || die "Error on close of $to: $!n";
  508.     }
  509.     elsif ($opt{method} eq 'scp')
  510.     {
  511.       my $tmp=$tmpfile;
  512.       open(OUTPUT,">$tmp") || die "Can't create file $tmp: $!n";
  513.       if (syswrite(OUTPUT,$buff) != length($buff))
  514.       {
  515. die "Error when writing data to $tmp: $!n";
  516.       }
  517.       close OUTPUT      || die "Error on close of $tmp: $!n";
  518.       safe_system("scp $tmp $to");
  519.     }
  520.     else
  521.     {
  522.       die "Can't use unsupported method '$opt{method}'n";
  523.     }
  524.   }
  525.   unlink "$tmpfile" if  ($opt{method} eq 'scp');
  526. }
  527. sub safe_system
  528. {
  529.   my @cmd= @_;
  530.   if ( $opt{dryrun} )
  531.   {
  532.     print "@cmdn";
  533.     return;
  534.   }
  535.   ## for some reason system fails but backticks works ok for scp...
  536.   print "Executing '@cmd'n" if $opt{debug};
  537.   my $cp_status = system "@cmd > /dev/null";
  538.   if ($cp_status != 0) {
  539.     warn "Burp ('scuse me). Trying backtick execution...n" if $opt{debug}; #'
  540.     ## try something else
  541.     `@cmd` && die "Error: @cmd failed ($cp_status) while copying files.n";
  542.   }
  543. }
  544. sub retire_directory {
  545.     my ( @dir ) = @_;
  546.     foreach my $dir ( @dir ) {
  547. my $tgt_oldpath = $dir . '_old';
  548. if ( $opt{dryrun} ) {
  549.     print "rmtree $tgt_oldpathn" if ( -d $tgt_oldpath );
  550.     print "rename $dir, $tgt_oldpathn";
  551.     next;
  552. }
  553. if ( -d $tgt_oldpath ) {
  554.     print "Deleting previous 'old' hotcopy directory ('$tgt_oldpath')n" unless $opt{quiet};
  555.     rmtree([$tgt_oldpath])
  556. }
  557. rename($dir, $tgt_oldpath)
  558.   or die "Can't rename $dir=>$tgt_oldpath: $!n";
  559. print "Existing hotcopy directory renamed to '$tgt_oldpath'n" unless $opt{quiet};
  560.     }
  561. }
  562. sub record_log_pos {
  563.     my ( $dbh, $table_name ) = @_;
  564.     eval {
  565. my ($file,$position) = get_row( $dbh, "show master status" );
  566. die "master status is undefined" if !defined $file || !defined $position;
  567. my ($master_host, undef, undef, undef, $log_file, $log_pos ) 
  568.     = get_row( $dbh, "show slave status" );
  569. my $hostname = hostname();
  570. $dbh->do( qq{ replace into $table_name 
  571.   set host=?, log_file=?, log_pos=?, 
  572.                           master_host=?, master_log_file=?, master_log_pos=? }, 
  573.   undef, 
  574.   $hostname, $file, $position, 
  575.   $master_host, $log_file, $log_pos  );
  576.     };
  577.     
  578.     if ( $@ ) {
  579. warn "Failed to store master position: $@n";
  580.     }
  581. }
  582. sub get_row {
  583.   my ( $dbh, $sql ) = @_;
  584.   my $sth = $dbh->prepare($sql);
  585.   $sth->execute;
  586.   return $sth->fetchrow_array();
  587. }
  588. sub scan_raid_dir {
  589.     my ( $r_db_files, $data_dir, @raid_dir ) = @_;
  590.     local(*RAID_DIR);
  591.     
  592.     foreach my $rd ( @raid_dir ) {
  593. opendir(RAID_DIR, "$data_dir/$rd" ) 
  594.     or die "Cannot open dir '$data_dir/$rd': $!";
  595. while ( defined( my $name = readdir RAID_DIR ) ) {
  596.     $r_db_files->{"$rd/$name"} = $1 if ( $name =~ /(.+).w+$/ );
  597. }
  598. closedir( RAID_DIR );
  599.     }
  600. }
  601. sub get_raid_dirs {
  602.     my ( $r_files ) = @_;
  603.     my %dirs = ();
  604.     foreach my $f ( @$r_files ) {
  605. if ( $f =~ m:^(dd)/: ) {
  606.     $dirs{$1} = 1;
  607. }
  608.     }
  609.     return sort keys %dirs;
  610. }
  611. sub get_list_of_tables {
  612.     my ( $db ) = @_;
  613.     # "use database" cannot cope with database names containing spaces
  614.     # so create a new connection 
  615.     my $dbh = DBI->connect("dbi:mysql:${db}${dsn};mysql_read_default_group=mysqlhotcopy",
  616.     $opt{user}, $opt{password},
  617.     {
  618. RaiseError => 1,
  619. PrintError => 0,
  620. AutoCommit => 1,
  621.     });
  622.     my @dbh_tables = eval { $dbh->tables() };
  623.     $dbh->disconnect();
  624.     return @dbh_tables;
  625. }
  626. __END__
  627. =head1 DESCRIPTION
  628. mysqlhotcopy is designed to make stable copies of live MySQL databases.
  629. Here "live" means that the database server is running and the database
  630. may be in active use. And "stable" means that the copy will not have
  631. any corruptions that could occur if the table files were simply copied
  632. without first being locked and flushed from within the server.
  633. =head1 OPTIONS
  634. =over 4
  635. =item --checkpoint checkpoint-table
  636. As each database is copied, an entry is written to the specified
  637. checkpoint-table.  This has the happy side-effect of updating the
  638. MySQL update-log (if it is switched on) giving a good indication of
  639. where roll-forward should begin for backup+rollforward schemes.
  640. The name of the checkpoint table should be supplied in database.table format.
  641. The checkpoint-table must contain at least the following fields:
  642. =over 4
  643.   time_stamp timestamp not null
  644.   src varchar(32)
  645.   dest varchar(60)
  646.   msg varchar(255)
  647. =back
  648. =item --record_log_pos log-pos-table
  649. Just before the database files are copied, update the record in the
  650. log-pos-table from the values returned from "show master status" and
  651. "show slave status". The master status values are stored in the
  652. log_file and log_pos columns, and establish the position in the binary
  653. logs that any slaves of this host should adopt if initialised from
  654. this dump.  The slave status values are stored in master_host,
  655. master_log_file, and master_log_pos, and these are useful if the host
  656. performing the dump is a slave and other sibling slaves are to be
  657. initialised from this dump.
  658. The name of the log-pos table should be supplied in database.table format.
  659. A sample log-pos table definition:
  660. =over 4
  661. CREATE TABLE log_pos (
  662.   host            varchar(60) NOT null,
  663.   time_stamp      timestamp(14) NOT NULL,
  664.   log_file        varchar(32) default NULL,
  665.   log_pos         int(11)     default NULL,
  666.   master_host     varchar(60) NULL,
  667.   master_log_file varchar(32) NULL,
  668.   master_log_pos  int NULL,
  669.   PRIMARY KEY  (host) 
  670. );
  671. =back
  672. =item --suffix suffix
  673. Each database is copied back into the originating datadir under
  674. a new name. The new name is the original name with the suffix
  675. appended. 
  676. If only a single db_name is supplied and the --suffix flag is not
  677. supplied, then "--suffix=_copy" is assumed.
  678. =item --allowold
  679. Move any existing version of the destination to a backup directory for
  680. the duration of the copy. If the copy successfully completes, the backup 
  681. directory is deleted - unless the --keepold flag is set.  If the copy fails,
  682. the backup directory is restored.
  683. The backup directory name is the original name with "_old" appended.
  684. Any existing versions of the backup directory are deleted.
  685. =item --keepold
  686. Behaves as for the --allowold, with the additional feature 
  687. of keeping the backup directory after the copy successfully completes.
  688. =item --flushlog
  689. Rotate the log files by executing "FLUSH LOGS" after all tables are
  690. locked, and before they are copied.
  691. =item --resetmaster
  692. Reset the bin-log by executing "RESET MASTER" after all tables are
  693. locked, and before they are copied. Usefull if you are recovering a
  694. slave in a replication setup.
  695. =item --resetslave
  696. Reset the master.info by executing "RESET SLAVE" after all tables are
  697. locked, and before they are copied. Usefull if you are recovering a
  698. server in a mutual replication setup.
  699. =item --regexp pattern
  700. Copy all databases with names matching the pattern
  701. =item db_name./pattern/
  702. Copy only tables matching pattern. Shell metacharacters ( (, ), |, !,
  703. etc.) have to be escaped (e.g. ). For example, to select all tables
  704. in database db1 whose names begin with 'foo' or 'bar':
  705.     mysqlhotcopy --indices --method=cp db1./^(foo|bar)/
  706. =item db_name./~pattern/
  707. Copy only tables not matching pattern. For example, to copy tables
  708. that do not begin with foo nor bar:
  709.     mysqlhotcopy --indices --method=cp db1./~^(foo|bar)/
  710. =item -?, --help
  711. Display helpscreen and exit
  712. =item -u, --user=#         
  713. user for database login if not current user
  714. =item -p, --password=#     
  715. password to use when connecting to server
  716. =item -h, -h, --host=#
  717. Hostname for local server when connecting over TCP/IP.  By specifying this
  718. different from 'localhost' will trigger mysqlhotcopy to use TCP/IP connection.
  719. =item -P, --port=#         
  720. port to use when connecting to MySQL server with TCP/IP.  This is only used
  721. when using the --host option.
  722. =item -S, --socket=#         
  723. UNIX domain socket to use when connecting to local server
  724. =item  --noindices          
  725. Don't include index files in copy. Only up to the first 2048 bytes
  726. are copied;  You can restore the indexes with isamchk -r or myisamchk -r
  727. on the backup.
  728. =item  --method=#           
  729. method for copy (only "cp" currently supported). Alpha support for
  730. "scp" was added in November 2000. Your experience with the scp method
  731. will vary with your ability to understand how scp works. 'man scp'
  732. and 'man ssh' are your friends.
  733. The destination directory _must exist_ on the target machine using the
  734. scp method. --keepold and --allowold are meeningless with scp.
  735. Liberal use of the --debug option will help you figure out what's
  736. really going on when you do an scp.
  737. Note that using scp will lock your tables for a _long_ time unless
  738. your network connection is _fast_. If this is unacceptable to you,
  739. use the 'cp' method to copy the tables to some temporary area and then
  740. scp or rsync the files at your leisure.
  741. =item -q, --quiet              
  742. be silent except for errors
  743. =item  --debug
  744. Debug messages are displayed 
  745. =item -n, --dryrun
  746. Display commands without actually doing them
  747. =back
  748. =head1 WARRANTY
  749. This software is free and comes without warranty of any kind. You
  750. should never trust backup software without studying the code yourself.
  751. Study the code inside this script and only rely on it if I<you> believe
  752. that it does the right thing for you.
  753. Patches adding bug fixes, documentation and new features are welcome.
  754. Please send these to internals@lists.mysql.com.
  755. =head1 TO DO
  756. Extend the individual table copy to allow multiple subsets of tables
  757. to be specified on the command line:
  758.   mysqlhotcopy db newdb  t1 t2 /^foo_/ : t3 /^bar_/ : +
  759. where ":" delimits the subsets, the /^foo_/ indicates all tables
  760. with names begining with "foo_" and the "+" indicates all tables
  761. not copied by the previous subsets.
  762. newdb is either another not existing database or a full path to a directory
  763. where we can create a directory 'db'
  764. Add option to lock each table in turn for people who don't need
  765. cross-table integrity.
  766. Add option to FLUSH STATUS just before UNLOCK TABLES.
  767. Add support for other copy methods (eg tar to single file?).
  768. Add support for forthcoming MySQL ``RAID'' table subdirectory layouts.
  769. =head1 AUTHOR
  770. Tim Bunce
  771. Martin Waite - added checkpoint, flushlog, regexp and dryrun options
  772.                Fixed cleanup of targets when hotcopy fails. 
  773.        Added --record_log_pos.
  774.                RAID tables are now copied (don't know if this works over scp).
  775. Ralph Corderoy - added synonyms for commands
  776. Scott Wiersdorf - added table regex and scp support
  777. Monty - working --noindex (copy only first 2048 bytes of index file)
  778.         Fixes for --method=scp
  779. Ask Bjoern Hansen - Cleanup code to fix a few bugs and enable -w again.
  780. Emil S. Hansen - Added resetslave and resetmaster.
  781. Jeremy D. Zawodny - Removed depricated DBI calls.  Fixed bug which
  782. resulted in nothing being copied when a regexp was specified but no
  783. database name(s).
  784. Martin Waite - Fix to handle database name that contains space.
  785. Paul DuBois - Remove end '/' from directory names