home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Resources / Developers / XAMPP 1.5.4 / Windows installer / xampp-win32-1.5.4-installer.exe / xampp / mysql / scripts / mysqlhotcopy < prev   
Encoding:
Text File  |  2006-04-26  |  32.1 KB  |  1,140 lines

  1. #!/usr/bin/perl -w
  2.  
  3. use strict;
  4. use Getopt::Long;
  5. use Data::Dumper;
  6. use File::Basename;
  7. use File::Path;
  8. use DBI;
  9. use Sys::Hostname;
  10. use File::Copy;
  11. use File::Temp qw(tempfile);
  12.  
  13. =head1 NAME
  14.  
  15. mysqlhotcopy - fast on-line hot-backup utility for local MySQL databases and tables
  16.  
  17. =head1 SYNOPSIS
  18.  
  19.   mysqlhotcopy db_name
  20.  
  21.   mysqlhotcopy --suffix=_copy db_name_1 ... db_name_n
  22.  
  23.   mysqlhotcopy db_name_1 ... db_name_n /path/to/new_directory
  24.  
  25.   mysqlhotcopy db_name./regex/
  26.  
  27.   mysqlhotcopy db_name./^\(foo\|bar\)/
  28.  
  29.   mysqlhotcopy db_name./~regex/
  30.  
  31.   mysqlhotcopy db_name_1./regex_1/ db_name_1./regex_2/ ... db_name_n./regex_n/ /path/to/new_directory
  32.  
  33.   mysqlhotcopy --method='scp -Bq -i /usr/home/foo/.ssh/identity' --user=root --password=secretpassword \
  34.          db_1./^nice_table/ user@some.system.dom:~/path/to/new_directory
  35.  
  36. WARNING: THIS PROGRAM IS STILL IN BETA. Comments/patches welcome.
  37.  
  38. =cut
  39.  
  40. # Documentation continued at end of file
  41.  
  42. my $VERSION = "1.22";
  43.  
  44. my $opt_tmpdir = $ENV{TMPDIR} || "/tmp";
  45.  
  46. my $OPTIONS = <<"_OPTIONS";
  47.  
  48. $0 Ver $VERSION
  49.  
  50. Usage: $0 db_name[./table_regex/] [new_db_name | directory]
  51.  
  52.   -?, --help           display this helpscreen and exit
  53.   -u, --user=#         user for database login if not current user
  54.   -p, --password=#     password to use when connecting to server (if not set
  55.                        in my.cnf, which is recommended)
  56.   -h, --host=#         Hostname for local server when connecting over TCP/IP
  57.   -P, --port=#         port to use when connecting to local server with TCP/IP
  58.   -S, --socket=#       socket to use when connecting to local server
  59.  
  60.   --allowold           don\'t abort if target dir already exists (rename it _old)
  61.   --addtodest          don\'t rename target dir if it exists, just add files to it
  62.   --keepold            don\'t delete previous (now renamed) target when done
  63.   --noindices          don\'t include full index files in copy
  64.   --method=#           method for copy (only "cp" currently supported)
  65.  
  66.   -q, --quiet          be silent except for errors
  67.   --debug              enable debug
  68.   -n, --dryrun         report actions without doing them
  69.  
  70.   --regexp=#           copy all databases with names matching regexp
  71.   --suffix=#           suffix for names of copied databases
  72.   --checkpoint=#       insert checkpoint entry into specified db.table
  73.   --flushlog           flush logs once all tables are locked 
  74.   --resetmaster        reset the binlog once all tables are locked
  75.   --resetslave         reset the master.info once all tables are locked
  76.   --tmpdir=#           temporary directory (instead of $opt_tmpdir)
  77.   --record_log_pos=#   record slave and master status in specified db.table
  78.   --chroot=#           base directory of chroot jail in which mysqld operates
  79.  
  80.   Try \'perldoc $0\' for more complete documentation
  81. _OPTIONS
  82.  
  83. sub usage {
  84.     die @_, $OPTIONS;
  85. }
  86.  
  87. # Do not initialize user or password options; that way, any user/password
  88. # options specified in option files will be used.  If no values are specified
  89. # all, the defaults will be used (login name, no password).
  90.  
  91. my %opt = (
  92.     noindices    => 0,
  93.     allowold    => 0,    # for safety
  94.     keepold    => 0,
  95.     method    => "cp",
  96.     flushlog    => 0,
  97. );
  98. Getopt::Long::Configure(qw(no_ignore_case)); # disambuguate -p and -P
  99. GetOptions( \%opt,
  100.     "help",
  101.     "host|h=s",
  102.     "user|u=s",
  103.     "password|p=s",
  104.     "port|P=s",
  105.     "socket|S=s",
  106.     "allowold!",
  107.     "keepold!",
  108.     "addtodest!",
  109.     "noindices!",
  110.     "method=s",
  111.     "debug",
  112.     "quiet|q",
  113.     "mv!",
  114.     "regexp=s",
  115.     "suffix=s",
  116.     "checkpoint=s",
  117.     "record_log_pos=s",
  118.     "flushlog",
  119.     "resetmaster",
  120.     "resetslave",
  121.     "tmpdir|t=s",
  122.     "dryrun|n",
  123.     "chroot=s",
  124. ) or usage("Invalid option");
  125.  
  126. # @db_desc
  127. # ==========
  128. # a list of hash-refs containing:
  129. #
  130. #   'src'     - name of the db to copy
  131. #   't_regex' - regex describing tables in src
  132. #   'target'  - destination directory of the copy
  133. #   'tables'  - array-ref to list of tables in the db
  134. #   'files'   - array-ref to list of files to be copied
  135. #               (RAID files look like 'nn/name.MYD')
  136. #   'index'   - array-ref to list of indexes to be copied
  137. #
  138.  
  139. my @db_desc = ();
  140. my $tgt_name = undef;
  141.  
  142. usage("") if ($opt{help});
  143.  
  144. if ( $opt{regexp} || $opt{suffix} || @ARGV > 2 ) {
  145.     $tgt_name   = pop @ARGV unless ( exists $opt{suffix} );
  146.     @db_desc = map { s{^([^\.]+)\./(.+)/$}{$1}; { 'src' => $_, 't_regex' => ( $2 ? $2 : '.*' ) } } @ARGV;
  147. }
  148. else {
  149.     usage("Database name to hotcopy not specified") unless ( @ARGV );
  150.  
  151.     $ARGV[0] =~ s{^([^\.]+)\./(.+)/$}{$1};
  152.     @db_desc = ( { 'src' => $ARGV[0], 't_regex' => ( $2 ? $2 : '.*' ) } );
  153.  
  154.     if ( @ARGV == 2 ) {
  155.     $tgt_name   = $ARGV[1];
  156.     }
  157.     else {
  158.     $opt{suffix} = "_copy";
  159.     }
  160. }
  161.  
  162. my %mysqld_vars;
  163. my $start_time = time;
  164. $opt_tmpdir= $opt{tmpdir} if $opt{tmpdir};
  165. $0 = $1 if $0 =~ m:/([^/]+)$:;
  166. $opt{quiet} = 0 if $opt{debug};
  167. $opt{allowold} = 1 if $opt{keepold};
  168.  
  169. # --- connect to the database ---
  170. my $dsn;
  171. $dsn  = ";host=" . (defined($opt{host}) ? $opt{host} : "localhost");
  172. $dsn .= ";port=$opt{port}" if $opt{port};
  173. $dsn .= ";mysql_socket=$opt{socket}" if $opt{socket};
  174.  
  175. # use mysql_read_default_group=mysqlhotcopy so that [client] and
  176. # [mysqlhotcopy] groups will be read from standard options files.
  177.  
  178. my $dbh = DBI->connect("dbi:mysql:$dsn;mysql_read_default_group=mysqlhotcopy",
  179.                         $opt{user}, $opt{password},
  180. {
  181.     RaiseError => 1,
  182.     PrintError => 0,
  183.     AutoCommit => 1,
  184. });
  185.  
  186. # --- check that checkpoint table exists if specified ---
  187. if ( $opt{checkpoint} ) {
  188.     $opt{checkpoint} = quote_names( $opt{checkpoint} );
  189.     eval { $dbh->do( qq{ select time_stamp, src, dest, msg 
  190.              from $opt{checkpoint} where 1 != 1} );
  191.        };
  192.  
  193.     die "Error accessing Checkpoint table ($opt{checkpoint}): $@"
  194.       if ( $@ );
  195. }
  196.  
  197. # --- check that log_pos table exists if specified ---
  198. if ( $opt{record_log_pos} ) {
  199.     $opt{record_log_pos} = quote_names( $opt{record_log_pos} );
  200.  
  201.     eval { $dbh->do( qq{ select host, time_stamp, log_file, log_pos, master_host, master_log_file, master_log_pos
  202.              from $opt{record_log_pos} where 1 != 1} );
  203.        };
  204.  
  205.     die "Error accessing log_pos table ($opt{record_log_pos}): $@"
  206.       if ( $@ );
  207. }
  208.  
  209. # --- get variables from database ---
  210. my $sth_vars = $dbh->prepare("show variables like 'datadir'");
  211. $sth_vars->execute;
  212. while ( my ($var,$value) = $sth_vars->fetchrow_array ) {
  213.     $mysqld_vars{ $var } = $value;
  214. }
  215. my $datadir = $mysqld_vars{'datadir'}
  216.     || die "datadir not in mysqld variables";
  217.     $datadir= $opt{chroot}.$datadir if ($opt{chroot});
  218. $datadir =~ s:/$::;
  219.  
  220.  
  221. # --- get target path ---
  222. my ($tgt_dirname, $to_other_database);
  223. $to_other_database=0;
  224. if (defined($tgt_name) && $tgt_name =~ m:^\w+$: && @db_desc <= 1)
  225. {
  226.     $tgt_dirname = "$datadir/$tgt_name";
  227.     $to_other_database=1;
  228. }
  229. elsif (defined($tgt_name) && ($tgt_name =~ m:/: || $tgt_name eq '.')) {
  230.     $tgt_dirname = $tgt_name;
  231. }
  232. elsif ( $opt{suffix} ) {
  233.     print "Using copy suffix '$opt{suffix}'\n" unless $opt{quiet};
  234. }
  235. elsif ( ($^O =~ m/^(NetWare)$/) && defined($tgt_name) && ($tgt_name =~ m:\\: || $tgt_name eq '.'))  
  236. {
  237.     $tgt_dirname = $tgt_name;
  238. }
  239. else
  240. {
  241.   $tgt_name="" if (!defined($tgt_name));
  242.   die "Target '$tgt_name' doesn't look like a database name or directory path.\n";
  243. }
  244.  
  245. # --- resolve database names from regexp ---
  246. if ( defined $opt{regexp} ) {
  247.     my $t_regex = '.*';
  248.     if ( $opt{regexp} =~ s{^/(.+)/\./(.+)/$}{$1} ) {
  249.         $t_regex = $2;
  250.     }
  251.  
  252.     my $sth_dbs = $dbh->prepare("show databases");
  253.     $sth_dbs->execute;
  254.     while ( my ($db_name) = $sth_dbs->fetchrow_array ) {
  255.     next if $db_name =~ m/^information_schema$/i;
  256.     push @db_desc, { 'src' => $db_name, 't_regex' => $t_regex } if ( $db_name =~ m/$opt{regexp}/o );
  257.     }
  258. }
  259.  
  260. # --- get list of tables to hotcopy ---
  261.  
  262. my $hc_locks = "";
  263. my $hc_tables = "";
  264. my $num_tables = 0;
  265. my $num_files = 0;
  266.  
  267. foreach my $rdb ( @db_desc ) {
  268.     my $db = $rdb->{src};
  269.     my @dbh_tables = get_list_of_tables( $db );
  270.  
  271.     ## generate regex for tables/files
  272.     my $t_regex;
  273.     my $negated;
  274.     if ($rdb->{t_regex}) {
  275.         $t_regex = $rdb->{t_regex};        ## assign temporary regex
  276.         $negated = $t_regex =~ s/^~//;     ## note and remove negation operator
  277.  
  278.         $t_regex = qr/$t_regex/;           ## make regex string from
  279.                                            ## user regex
  280.  
  281.         ## filter (out) tables specified in t_regex
  282.         print "Filtering tables with '$t_regex'\n" if $opt{debug};
  283.         @dbh_tables = ( $negated 
  284.                         ? grep { $_ !~ $t_regex } @dbh_tables
  285.                         : grep { $_ =~ $t_regex } @dbh_tables );
  286.     }
  287.  
  288.     ## get list of files to copy
  289.     my $db_dir = "$datadir/$db";
  290.     opendir(DBDIR, $db_dir ) 
  291.       or die "Cannot open dir '$db_dir': $!";
  292.  
  293.     my %db_files;
  294.     my @raid_dir = ();
  295.  
  296.     while ( defined( my $name = readdir DBDIR ) ) {
  297.     if ( $name =~ /^\d\d$/ && -d "$db_dir/$name" ) {
  298.         push @raid_dir, $name;
  299.     }
  300.     else {
  301.         $db_files{$name} = $1 if ( $name =~ /(.+)\.\w+$/ );
  302.         }
  303.     }
  304.     closedir( DBDIR );
  305.  
  306.     scan_raid_dir( \%db_files, $db_dir, @raid_dir );
  307.  
  308.     unless( keys %db_files ) {
  309.     warn "'$db' is an empty database\n";
  310.     }
  311.  
  312.     ## filter (out) files specified in t_regex
  313.     my @db_files;
  314.     if ($rdb->{t_regex}) {
  315.         @db_files = ($negated
  316.                      ? grep { $db_files{$_} !~ $t_regex } keys %db_files
  317.                      : grep { $db_files{$_} =~ $t_regex } keys %db_files );
  318.     }
  319.     else {
  320.         @db_files = keys %db_files;
  321.     }
  322.  
  323.     @db_files = sort @db_files;
  324.  
  325.     my @index_files=();
  326.  
  327.     ## remove indices unless we're told to keep them
  328.     if ($opt{noindices}) {
  329.         @index_files= grep { /\.(ISM|MYI)$/ } @db_files;
  330.     @db_files = grep { not /\.(ISM|MYI)$/ } @db_files;
  331.     }
  332.  
  333.     $rdb->{files}  = [ @db_files ];
  334.     $rdb->{index}  = [ @index_files ];
  335.     my @hc_tables = map { quote_names("$db.$_") } @dbh_tables;
  336.     $rdb->{tables} = [ @hc_tables ];
  337.  
  338.     $rdb->{raid_dirs} = [ get_raid_dirs( $rdb->{files} ) ];
  339.  
  340.     $hc_locks .= ", "  if ( length $hc_locks && @hc_tables );
  341.     $hc_locks .= join ", ", map { "$_ READ" } @hc_tables;
  342.     $hc_tables .= ", "  if ( length $hc_tables && @hc_tables );
  343.     $hc_tables .= join ", ", @hc_tables;
  344.  
  345.     $num_tables += scalar @hc_tables;
  346.     $num_files  += scalar @{$rdb->{files}};
  347. }
  348.  
  349. # --- resolve targets for copies ---
  350.  
  351. if (defined($tgt_name) && length $tgt_name ) {
  352.     # explicit destination directory specified
  353.  
  354.     # GNU `cp -r` error message
  355.     die "copying multiple databases, but last argument ($tgt_dirname) is not a directory\n"
  356.       if ( @db_desc > 1 && !(-e $tgt_dirname && -d $tgt_dirname ) );
  357.  
  358.     if ($to_other_database)
  359.     {
  360.       foreach my $rdb ( @db_desc ) {
  361.     $rdb->{target} = "$tgt_dirname";
  362.       }
  363.     }
  364.     elsif ($opt{method} =~ /^scp\b/) 
  365.     {   # we have to trust scp to hit the target
  366.     foreach my $rdb ( @db_desc ) {
  367.         $rdb->{target} = "$tgt_dirname/$rdb->{src}";
  368.     }
  369.     }
  370.     else
  371.     {
  372.       die "Last argument ($tgt_dirname) is not a directory\n"
  373.     if (!(-e $tgt_dirname && -d $tgt_dirname ) );
  374.       foreach my $rdb ( @db_desc ) {
  375.     $rdb->{target} = "$tgt_dirname/$rdb->{src}";
  376.       }
  377.     }
  378.   }
  379. else {
  380.   die "Error: expected \$opt{suffix} to exist" unless ( exists $opt{suffix} );
  381.  
  382.   foreach my $rdb ( @db_desc ) {
  383.     $rdb->{target} = "$datadir/$rdb->{src}$opt{suffix}";
  384.   }
  385. }
  386.  
  387. print Dumper( \@db_desc ) if ( $opt{debug} );
  388.  
  389. # --- bail out if all specified databases are empty ---
  390.  
  391. die "No tables to hot-copy" unless ( length $hc_locks );
  392.  
  393. # --- create target directories if we are using 'cp' ---
  394.  
  395. my @existing = ();
  396.  
  397. if ($opt{method} =~ /^cp\b/)
  398. {
  399.   foreach my $rdb ( @db_desc ) {
  400.     push @existing, $rdb->{target} if ( -d  $rdb->{target} );
  401.   }
  402.  
  403.   if ( @existing && !($opt{allowold} || $opt{addtodest}) )
  404.   {
  405.     $dbh->disconnect();
  406.     die "Can't hotcopy to '", join( "','", @existing ), "' because directory\nalready exist and the --allowold or --addtodest options were not given.\n"
  407.   }
  408. }
  409.  
  410. retire_directory( @existing ) if @existing && !$opt{addtodest};
  411.  
  412. foreach my $rdb ( @db_desc ) {
  413.     foreach my $td ( '', @{$rdb->{raid_dirs}} ) {
  414.  
  415.     my $tgt_dirpath = "$rdb->{target}/$td";
  416.     # Remove trailing slashes (needed for Mac OS X)
  417.         substr($tgt_dirpath, 1) =~ s|/+$||;
  418.     if ( $opt{dryrun} ) {
  419.         print "mkdir $tgt_dirpath, 0750\n";
  420.     }
  421.     elsif ($opt{method} =~ /^scp\b/) {
  422.         ## assume it's there?
  423.         ## ...
  424.     }
  425.     else {
  426.         mkdir($tgt_dirpath, 0750) or die "Can't create '$tgt_dirpath': $!\n"
  427.         unless -d $tgt_dirpath;
  428.          if ($^O !~ m/^(NetWare)$/)  
  429.             {
  430.         my @f_info= stat "$datadir/$rdb->{src}";
  431.         chown $f_info[4], $f_info[5], $tgt_dirpath;
  432.             }
  433.     }
  434.     }
  435. }
  436.  
  437. ##############################
  438. # --- PERFORM THE HOT-COPY ---
  439. #
  440. # Note that we try to keep the time between the LOCK and the UNLOCK
  441. # as short as possible, and only start when we know that we should
  442. # be able to complete without error.
  443.  
  444. # read lock all the tables we'll be copying
  445. # in order to get a consistent snapshot of the database
  446.  
  447. if ( $opt{checkpoint} || $opt{record_log_pos} ) {
  448.   # convert existing READ lock on checkpoint and/or log_pos table into WRITE lock
  449.   foreach my $table ( grep { defined } ( $opt{checkpoint}, $opt{record_log_pos} ) ) {
  450.     $hc_locks .= ", $table WRITE" 
  451.     unless ( $hc_locks =~ s/$table\s+READ/$table WRITE/ );
  452.   }
  453. }
  454.  
  455. my $hc_started = time;    # count from time lock is granted
  456.  
  457. if ( $opt{dryrun} ) {
  458.     print "LOCK TABLES $hc_locks\n";
  459.     print "FLUSH TABLES /*!32323 $hc_tables */\n";
  460.     print "FLUSH LOGS\n" if ( $opt{flushlog} );
  461.     print "RESET MASTER\n" if ( $opt{resetmaster} );
  462.     print "RESET SLAVE\n" if ( $opt{resetslave} );
  463. }
  464. else {
  465.     my $start = time;
  466.     $dbh->do("LOCK TABLES $hc_locks");
  467.     printf "Locked $num_tables tables in %d seconds.\n", time-$start unless $opt{quiet};
  468.     $hc_started = time;    # count from time lock is granted
  469.  
  470.     # flush tables to make on-disk copy uptodate
  471.     $start = time;
  472.     $dbh->do("FLUSH TABLES /*!32323 $hc_tables */");
  473.     printf "Flushed tables ($hc_tables) in %d seconds.\n", time-$start unless $opt{quiet};
  474.     $dbh->do( "FLUSH LOGS" ) if ( $opt{flushlog} );
  475.     $dbh->do( "RESET MASTER" ) if ( $opt{resetmaster} );
  476.     $dbh->do( "RESET SLAVE" ) if ( $opt{resetslave} );
  477.  
  478.     if ( $opt{record_log_pos} ) {
  479.     record_log_pos( $dbh, $opt{record_log_pos} );
  480.     $dbh->do("FLUSH TABLES /*!32323 $hc_tables */");
  481.     }
  482. }
  483.  
  484. my @failed = ();
  485.  
  486. foreach my $rdb ( @db_desc )
  487. {
  488.   my @files = map { "$datadir/$rdb->{src}/$_" } @{$rdb->{files}};
  489.   next unless @files;
  490.   
  491.   eval { copy_files($opt{method}, \@files, $rdb->{target}, $rdb->{raid_dirs} ); };
  492.   push @failed, "$rdb->{src} -> $rdb->{target} failed: $@"
  493.     if ( $@ );
  494.   
  495.   @files = @{$rdb->{index}};
  496.   if ($rdb->{index})
  497.   {
  498.     copy_index($opt{method}, \@files,
  499.            "$datadir/$rdb->{src}", $rdb->{target} );
  500.   }
  501.   
  502.   if ( $opt{checkpoint} ) {
  503.     my $msg = ( $@ ) ? "Failed: $@" : "Succeeded";
  504.     
  505.     eval {
  506.       $dbh->do( qq{ insert into $opt{checkpoint} (src, dest, msg) 
  507.               VALUES ( '$rdb->{src}', '$rdb->{target}', '$msg' )
  508.             } ); 
  509.     };
  510.     
  511.     if ( $@ ) {
  512.       warn "Failed to update checkpoint table: $@\n";
  513.     }
  514.   }
  515. }
  516.  
  517. if ( $opt{dryrun} ) {
  518.     print "UNLOCK TABLES\n";
  519.     if ( @existing && !$opt{keepold} ) {
  520.     my @oldies = map { $_ . '_old' } @existing;
  521.     print "rm -rf @oldies\n" 
  522.     }
  523.     $dbh->disconnect();
  524.     exit(0);
  525. }
  526. else {
  527.     $dbh->do("UNLOCK TABLES");
  528. }
  529.  
  530. my $hc_dur = time - $hc_started;
  531. printf "Unlocked tables.\n" unless $opt{quiet};
  532.  
  533. #
  534. # --- HOT-COPY COMPLETE ---
  535. ###########################
  536.  
  537. $dbh->disconnect;
  538.  
  539. if ( @failed ) {
  540.     # hotcopy failed - cleanup
  541.     # delete any @targets 
  542.     # rename _old copy back to original
  543.  
  544.     my @targets = ();
  545.     foreach my $rdb ( @db_desc ) {
  546.         push @targets, $rdb->{target} if ( -d  $rdb->{target} );
  547.     }
  548.     print "Deleting @targets \n" if $opt{debug};
  549.  
  550.     print "Deleting @targets \n" if $opt{debug};
  551.     rmtree([@targets]);
  552.     if (@existing) {
  553.     print "Restoring @existing from back-up\n" if $opt{debug};
  554.         foreach my $dir ( @existing ) {
  555.         rename("${dir}_old", $dir )
  556.           or warn "Can't rename ${dir}_old to $dir: $!\n";
  557.     }
  558.     }
  559.  
  560.     die join( "\n", @failed );
  561. }
  562. else {
  563.     # hotcopy worked
  564.     # delete _old unless $opt{keepold}
  565.  
  566.     if ( @existing && !$opt{keepold} ) {
  567.     my @oldies = map { $_ . '_old' } @existing;
  568.     print "Deleting previous copy in @oldies\n" if $opt{debug};
  569.     rmtree([@oldies]);
  570.     }
  571.  
  572.     printf "$0 copied %d tables (%d files) in %d second%s (%d seconds overall).\n",
  573.         $num_tables, $num_files,
  574.         $hc_dur, ($hc_dur==1)?"":"s", time - $start_time
  575.     unless $opt{quiet};
  576. }
  577.  
  578. exit 0;
  579.  
  580.  
  581. # ---
  582.  
  583. sub copy_files {
  584.     my ($method, $files, $target, $raid_dirs) = @_;
  585.     my @cmd;
  586.     print "Copying ".@$files." files...\n" unless $opt{quiet};
  587.  
  588.     if ($^O =~ m/^(NetWare)$/)  # on NetWare call PERL copy (slower)
  589.     {
  590.       foreach my $file ( @$files )
  591.       {
  592.         copy($file, $target."/".basename($file));
  593.       }
  594.     }
  595.     elsif ($method =~ /^s?cp\b/)  # cp or scp with optional flags
  596.     {
  597.     my $cp = $method;
  598.     # add option to preserve mod time etc of copied files
  599.     # not critical, but nice to have
  600.     $cp.= " -p" if $^O =~ m/^(solaris|linux|freebsd|darwin)$/;
  601.  
  602.     # add recursive option for scp
  603.     $cp.= " -r" if $^O =~ /m^(solaris|linux|freebsd|darwin)$/ && $method =~ /^scp\b/;
  604.  
  605.     my @non_raid = map { "'$_'" } grep { ! m:/\d{2}/[^/]+$: } @$files;
  606.  
  607.     # add files to copy and the destination directory
  608.     safe_system( $cp, @non_raid, "'$target'" ) if (@non_raid);
  609.     
  610.     foreach my $rd ( @$raid_dirs ) {
  611.         my @raid = map { "'$_'" } grep { m:$rd/: } @$files;
  612.         safe_system( $cp, @raid, "'$target'/$rd" ) if ( @raid );
  613.     }
  614.     }
  615.     else
  616.     {
  617.     die "Can't use unsupported method '$method'\n";
  618.     }
  619. }
  620.  
  621. #
  622. # Copy only the header of the index file
  623. #
  624.  
  625. sub copy_index
  626. {
  627.   my ($method, $files, $source, $target) = @_;
  628.   
  629.   print "Copying indices for ".@$files." files...\n" unless $opt{quiet};  
  630.   foreach my $file (@$files)
  631.   {
  632.     my $from="$source/$file";
  633.     my $to="$target/$file";
  634.     my $buff;
  635.     open(INPUT, "<$from") || die "Can't open file $from: $!\n";
  636.     binmode(INPUT, ":raw");
  637.     my $length=read INPUT, $buff, 2048;
  638.     die "Can't read index header from $from\n" if ($length < 1024);
  639.     close INPUT;
  640.     
  641.     if ( $opt{dryrun} )
  642.     {
  643.       print "$opt{method}-header $from $to\n";
  644.     }
  645.     elsif ($opt{method} eq 'cp')
  646.     {
  647.       open(OUTPUT,">$to")   || die "Can\'t create file $to: $!\n";
  648.       if (syswrite(OUTPUT,$buff) != length($buff))
  649.       {
  650.     die "Error when writing data to $to: $!\n";
  651.       }
  652.       close OUTPUT       || die "Error on close of $to: $!\n";
  653.     }
  654.     elsif ($opt{method} =~ /^scp\b/)
  655.     {
  656.       my ($fh, $tmp)= tempfile('mysqlhotcopy-XXXXXX', DIR => $opt_tmpdir) or
  657.     die "Can\'t create/open file in $opt_tmpdir\n";
  658.       if (syswrite($fh,$buff) != length($buff))
  659.       {
  660.     die "Error when writing data to $tmp: $!\n";
  661.       }
  662.       close $fh || die "Error on close of $tmp: $!\n";
  663.       safe_system("$opt{method} $tmp $to");
  664.       unlink $tmp;
  665.     }
  666.     else
  667.     {
  668.       die "Can't use unsupported method '$opt{method}'\n";
  669.     }
  670.   }
  671. }
  672.  
  673.  
  674. sub safe_system {
  675.   my @sources= @_;
  676.   my $method= shift @sources;
  677.   my $target= pop @sources;
  678.   ## @sources = list of source file names
  679.  
  680.   ## We have to deal with very long command lines, otherwise they may generate 
  681.   ## "Argument list too long".
  682.   ## With 10000 tables the command line can be around 1MB, much more than 128kB
  683.   ## which is the common limit on Linux (can be read from
  684.   ## /usr/src/linux/include/linux/binfmts.h
  685.   ## see http://www.linuxjournal.com/article.php?sid=6060).
  686.  
  687.   my $chunk_limit= 100 * 1024; # 100 kB
  688.   my @chunk= (); 
  689.   my $chunk_length= 0;
  690.   foreach (@sources) {
  691.       push @chunk, $_;
  692.       $chunk_length+= length($_);
  693.       if ($chunk_length > $chunk_limit) {
  694.           safe_simple_system($method, @chunk, $target);
  695.           @chunk=();
  696.           $chunk_length= 0;
  697.       }
  698.   }
  699.   if ($chunk_length > 0) { # do not forget last small chunk
  700.       safe_simple_system($method, @chunk, $target); 
  701.   }
  702. }
  703.  
  704. sub safe_simple_system {
  705.     my @cmd= @_;
  706.  
  707.     if ( $opt{dryrun} ) {
  708.         print "@cmd\n";
  709.     }
  710.     else {
  711.         ## for some reason system fails but backticks works ok for scp...
  712.         print "Executing '@cmd'\n" if $opt{debug};
  713.         my $cp_status = system "@cmd > /dev/null";
  714.         if ($cp_status != 0) {
  715.             warn "Executing command failed ($cp_status). Trying backtick execution...\n";
  716.             ## try something else
  717.             `@cmd` || die "Error: @cmd failed ($?) while copying files.\n";
  718.         }
  719.     }
  720. }
  721.  
  722. sub retire_directory {
  723.     my ( @dir ) = @_;
  724.  
  725.     foreach my $dir ( @dir ) {
  726.     my $tgt_oldpath = $dir . '_old';
  727.     if ( $opt{dryrun} ) {
  728.         print "rmtree $tgt_oldpath\n" if ( -d $tgt_oldpath );
  729.         print "rename $dir, $tgt_oldpath\n";
  730.         next;
  731.     }
  732.  
  733.     if ( -d $tgt_oldpath ) {
  734.         print "Deleting previous 'old' hotcopy directory ('$tgt_oldpath')\n" unless $opt{quiet};
  735.         rmtree([$tgt_oldpath],0,1);
  736.     }
  737.     rename($dir, $tgt_oldpath)
  738.       or die "Can't rename $dir=>$tgt_oldpath: $!\n";
  739.     print "Existing hotcopy directory renamed to '$tgt_oldpath'\n" unless $opt{quiet};
  740.     }
  741. }
  742.  
  743. sub record_log_pos {
  744.     my ( $dbh, $table_name ) = @_;
  745.  
  746.     eval {
  747.     my ($file,$position) = get_row( $dbh, "show master status" );
  748.     die "master status is undefined" if !defined $file || !defined $position;
  749.     
  750.     my $row_hash = get_row_hash( $dbh, "show slave status" );
  751.     my ($master_host, $log_file, $log_pos ); 
  752.     if ( $dbh->{mysql_serverinfo} =~ /^3\.23/ ) {
  753.         ($master_host, $log_file, $log_pos ) 
  754.           = @{$row_hash}{ qw / Master_Host Log_File Pos / };
  755.     } else {
  756.         ($master_host, $log_file, $log_pos ) 
  757.           = @{$row_hash}{ qw / Master_Host Master_Log_File Read_Master_Log_Pos / };
  758.     }
  759.     my $hostname = hostname();
  760.     
  761.     $dbh->do( qq{ replace into $table_name 
  762.               set host=?, log_file=?, log_pos=?, 
  763.                           master_host=?, master_log_file=?, master_log_pos=? }, 
  764.           undef, 
  765.           $hostname, $file, $position, 
  766.           $master_host, $log_file, $log_pos  );
  767.     
  768.     };
  769.     
  770.     if ( $@ ) {
  771.     warn "Failed to store master position: $@\n";
  772.     }
  773. }
  774.  
  775. sub get_row {
  776.   my ( $dbh, $sql ) = @_;
  777.  
  778.   my $sth = $dbh->prepare($sql);
  779.   $sth->execute;
  780.   return $sth->fetchrow_array();
  781. }
  782.  
  783. sub get_row_hash {
  784.   my ( $dbh, $sql ) = @_;
  785.  
  786.   my $sth = $dbh->prepare($sql);
  787.   $sth->execute;
  788.   return $sth->fetchrow_hashref();
  789. }
  790.  
  791. sub scan_raid_dir {
  792.     my ( $r_db_files, $data_dir, @raid_dir ) = @_;
  793.  
  794.     local(*RAID_DIR);
  795.     
  796.     foreach my $rd ( @raid_dir ) {
  797.  
  798.     opendir(RAID_DIR, "$data_dir/$rd" ) 
  799.         or die "Cannot open dir '$data_dir/$rd': $!";
  800.  
  801.     while ( defined( my $name = readdir RAID_DIR ) ) {
  802.         $r_db_files->{"$rd/$name"} = $1 if ( $name =~ /(.+)\.\w+$/ );
  803.     }
  804.     closedir( RAID_DIR );
  805.     }
  806. }
  807.  
  808. sub get_raid_dirs {
  809.     my ( $r_files ) = @_;
  810.  
  811.     my %dirs = ();
  812.     foreach my $f ( @$r_files ) {
  813.     if ( $f =~ m:^(\d\d)/: ) {
  814.         $dirs{$1} = 1;
  815.     }
  816.     }
  817.     return sort keys %dirs;
  818. }
  819.  
  820. sub get_list_of_tables {
  821.     my ( $db ) = @_;
  822.  
  823.     # "use database" cannot cope with database names containing spaces
  824.     # so create a new connection 
  825.  
  826.     my $dbh = DBI->connect("dbi:mysql:${db}${dsn};mysql_read_default_group=mysqlhotcopy",
  827.                 $opt{user}, $opt{password},
  828.     {
  829.     RaiseError => 1,
  830.     PrintError => 0,
  831.     AutoCommit => 1,
  832.     });
  833.  
  834.     my @dbh_tables = eval { $dbh->tables() };
  835.  
  836.     ## Remove quotes around table names
  837.     my $quote = $dbh->get_info(29); # SQL_IDENTIFIER_QUOTE_CHAR
  838.     if ($quote) {
  839.       foreach (@dbh_tables) {
  840.         s/^$quote(.*)$quote$/$1/;
  841.         s/$quote$quote/$quote/g;
  842.       }
  843.     }
  844.  
  845.     $dbh->disconnect();
  846.     return @dbh_tables;
  847. }
  848.  
  849. sub quote_names {
  850.   my ( $name ) = @_;
  851.   # given a db.table name, add quotes
  852.  
  853.   my ($db, $table, @cruft) = split( /\./, $name );
  854.   die "Invalid db.table name '$name'" if (@cruft || !defined $db || !defined $table );
  855.  
  856.   # Earlier versions of DBD return table name non-quoted,
  857.   # such as DBD-2.1012 and the newer ones, such as DBD-2.9002
  858.   # returns it quoted. Let's have a support for both.
  859.   $table=~ s/\`//g;
  860.   return "`$db`.`$table`";
  861. }
  862.  
  863. __END__
  864.  
  865. =head1 DESCRIPTION
  866.  
  867. mysqlhotcopy is designed to make stable copies of live MySQL databases.
  868.  
  869. Here "live" means that the database server is running and the database
  870. may be in active use. And "stable" means that the copy will not have
  871. any corruptions that could occur if the table files were simply copied
  872. without first being locked and flushed from within the server.
  873.  
  874. =head1 OPTIONS
  875.  
  876. =over 4
  877.  
  878. =item --checkpoint checkpoint-table
  879.  
  880. As each database is copied, an entry is written to the specified
  881. checkpoint-table.  This has the happy side-effect of updating the
  882. MySQL update-log (if it is switched on) giving a good indication of
  883. where roll-forward should begin for backup+rollforward schemes.
  884.  
  885. The name of the checkpoint table should be supplied in database.table format.
  886. The checkpoint-table must contain at least the following fields:
  887.  
  888. =over 4
  889.  
  890.   time_stamp timestamp not null
  891.   src varchar(32)
  892.   dest varchar(60)
  893.   msg varchar(255)
  894.  
  895. =back
  896.  
  897. =item --record_log_pos log-pos-table
  898.  
  899. Just before the database files are copied, update the record in the
  900. log-pos-table from the values returned from "show master status" and
  901. "show slave status". The master status values are stored in the
  902. log_file and log_pos columns, and establish the position in the binary
  903. logs that any slaves of this host should adopt if initialised from
  904. this dump.  The slave status values are stored in master_host,
  905. master_log_file, and master_log_pos, and these are useful if the host
  906. performing the dump is a slave and other sibling slaves are to be
  907. initialised from this dump.
  908.  
  909. The name of the log-pos table should be supplied in database.table format.
  910. A sample log-pos table definition:
  911.  
  912. =over 4
  913.  
  914. CREATE TABLE log_pos (
  915.   host            varchar(60) NOT null,
  916.   time_stamp      timestamp(14) NOT NULL,
  917.   log_file        varchar(32) default NULL,
  918.   log_pos         int(11)     default NULL,
  919.   master_host     varchar(60) NULL,
  920.   master_log_file varchar(32) NULL,
  921.   master_log_pos  int NULL,
  922.  
  923.   PRIMARY KEY  (host) 
  924. );
  925.  
  926. =back
  927.  
  928.  
  929. =item --suffix suffix
  930.  
  931. Each database is copied back into the originating datadir under
  932. a new name. The new name is the original name with the suffix
  933. appended. 
  934.  
  935. If only a single db_name is supplied and the --suffix flag is not
  936. supplied, then "--suffix=_copy" is assumed.
  937.  
  938. =item --allowold
  939.  
  940. Move any existing version of the destination to a backup directory for
  941. the duration of the copy. If the copy successfully completes, the backup 
  942. directory is deleted - unless the --keepold flag is set.  If the copy fails,
  943. the backup directory is restored.
  944.  
  945. The backup directory name is the original name with "_old" appended.
  946. Any existing versions of the backup directory are deleted.
  947.  
  948. =item --keepold
  949.  
  950. Behaves as for the --allowold, with the additional feature 
  951. of keeping the backup directory after the copy successfully completes.
  952.  
  953. =item --addtodest
  954.  
  955. Don't rename target directory if it already exists, just add the
  956. copied files into it.
  957.  
  958. This is most useful when backing up a database with many large
  959. tables and you don't want to have all the tables locked for the
  960. whole duration.
  961.  
  962. In this situation, I<if> you are happy for groups of tables to be
  963. backed up separately (and thus possibly not be logically consistant
  964. with one another) then you can run mysqlhotcopy several times on
  965. the same database each with different db_name./table_regex/.
  966. All but the first should use the --addtodest option so the tables
  967. all end up in the same directory.
  968.  
  969. =item --flushlog
  970.  
  971. Rotate the log files by executing "FLUSH LOGS" after all tables are
  972. locked, and before they are copied.
  973.  
  974. =item --resetmaster
  975.  
  976. Reset the bin-log by executing "RESET MASTER" after all tables are
  977. locked, and before they are copied. Useful if you are recovering a
  978. slave in a replication setup.
  979.  
  980. =item --resetslave
  981.  
  982. Reset the master.info by executing "RESET SLAVE" after all tables are
  983. locked, and before they are copied. Useful if you are recovering a
  984. server in a mutual replication setup.
  985.  
  986. =item --regexp pattern
  987.  
  988. Copy all databases with names matching the pattern
  989.  
  990. =item --regexp /pattern1/./pattern2/
  991.  
  992. Copy all tables with names matching pattern2 from all databases with
  993. names matching pattern1. For example, to select all tables which
  994. names begin with 'bar' from all databases which names end with 'foo':
  995.  
  996.    mysqlhotcopy --indices --method=cp --regexp /foo$/./^bar/
  997.  
  998. =item db_name./pattern/
  999.  
  1000. Copy only tables matching pattern. Shell metacharacters ( (, ), |, !,
  1001. etc.) have to be escaped (e.g. \). For example, to select all tables
  1002. in database db1 whose names begin with 'foo' or 'bar':
  1003.  
  1004.     mysqlhotcopy --indices --method=cp db1./^\(foo\|bar\)/
  1005.  
  1006. =item db_name./~pattern/
  1007.  
  1008. Copy only tables not matching pattern. For example, to copy tables
  1009. that do not begin with foo nor bar:
  1010.  
  1011.     mysqlhotcopy --indices --method=cp db1./~^\(foo\|bar\)/
  1012.  
  1013. =item -?, --help
  1014.  
  1015. Display helpscreen and exit
  1016.  
  1017. =item -u, --user=#         
  1018.  
  1019. user for database login if not current user
  1020.  
  1021. =item -p, --password=#     
  1022.  
  1023. password to use when connecting to the server. Note that you are strongly
  1024. encouraged *not* to use this option as every user would be able to see the
  1025. password in the process list. Instead use the '[mysqlhotcopy]' section in
  1026. one of the config files, normally /etc/my.cnf or your personal ~/.my.cnf.
  1027. (See the chapter 'my.cnf Option Files' in the manual)
  1028.  
  1029. =item -h, -h, --host=#
  1030.  
  1031. Hostname for local server when connecting over TCP/IP.  By specifying this
  1032. different from 'localhost' will trigger mysqlhotcopy to use TCP/IP connection.
  1033.  
  1034. =item -P, --port=#         
  1035.  
  1036. port to use when connecting to MySQL server with TCP/IP.  This is only used
  1037. when using the --host option.
  1038.  
  1039. =item -S, --socket=#         
  1040.  
  1041. UNIX domain socket to use when connecting to local server
  1042.  
  1043. =item  --noindices          
  1044.  
  1045. Don\'t include index files in copy. Only up to the first 2048 bytes
  1046. are copied;  You can restore the indexes with isamchk -r or myisamchk -r
  1047. on the backup.
  1048.  
  1049. =item  --method=#           
  1050.  
  1051. method for copy (only "cp" currently supported). Alpha support for
  1052. "scp" was added in November 2000. Your experience with the scp method
  1053. will vary with your ability to understand how scp works. 'man scp'
  1054. and 'man ssh' are your friends.
  1055.  
  1056. The destination directory _must exist_ on the target machine using the
  1057. scp method. --keepold and --allowold are meaningless with scp.
  1058. Liberal use of the --debug option will help you figure out what\'s
  1059. really going on when you do an scp.
  1060.  
  1061. Note that using scp will lock your tables for a _long_ time unless
  1062. your network connection is _fast_. If this is unacceptable to you,
  1063. use the 'cp' method to copy the tables to some temporary area and then
  1064. scp or rsync the files at your leisure.
  1065.  
  1066. =item -q, --quiet              
  1067.  
  1068. be silent except for errors
  1069.  
  1070. =item  --debug
  1071.  
  1072. Debug messages are displayed 
  1073.  
  1074. =item -n, --dryrun
  1075.  
  1076. Display commands without actually doing them
  1077.  
  1078. =back
  1079.  
  1080. =head1 WARRANTY
  1081.  
  1082. This software is free and comes without warranty of any kind. You
  1083. should never trust backup software without studying the code yourself.
  1084. Study the code inside this script and only rely on it if I<you> believe
  1085. that it does the right thing for you.
  1086.  
  1087. Patches adding bug fixes, documentation and new features are welcome.
  1088. Please send these to internals@lists.mysql.com.
  1089.  
  1090. =head1 TO DO
  1091.  
  1092. Extend the individual table copy to allow multiple subsets of tables
  1093. to be specified on the command line:
  1094.  
  1095.   mysqlhotcopy db newdb  t1 t2 /^foo_/ : t3 /^bar_/ : +
  1096.  
  1097. where ":" delimits the subsets, the /^foo_/ indicates all tables
  1098. with names begining with "foo_" and the "+" indicates all tables
  1099. not copied by the previous subsets.
  1100.  
  1101. newdb is either another not existing database or a full path to a directory
  1102. where we can create a directory 'db'
  1103.  
  1104. Add option to lock each table in turn for people who don\'t need
  1105. cross-table integrity.
  1106.  
  1107. Add option to FLUSH STATUS just before UNLOCK TABLES.
  1108.  
  1109. Add support for other copy methods (eg tar to single file?).
  1110.  
  1111. Add support for forthcoming MySQL ``RAID'' table subdirectory layouts.
  1112.  
  1113. =head1 AUTHOR
  1114.  
  1115. Tim Bunce
  1116.  
  1117. Martin Waite - added checkpoint, flushlog, regexp and dryrun options
  1118.                Fixed cleanup of targets when hotcopy fails. 
  1119.            Added --record_log_pos.
  1120.                RAID tables are now copied (don't know if this works over scp).
  1121.  
  1122. Ralph Corderoy - added synonyms for commands
  1123.  
  1124. Scott Wiersdorf - added table regex and scp support
  1125.  
  1126. Monty - working --noindex (copy only first 2048 bytes of index file)
  1127.         Fixes for --method=scp
  1128.  
  1129. Ask Bjoern Hansen - Cleanup code to fix a few bugs and enable -w again.
  1130.  
  1131. Emil S. Hansen - Added resetslave and resetmaster.
  1132.  
  1133. Jeremy D. Zawodny - Removed depricated DBI calls.  Fixed bug which
  1134. resulted in nothing being copied when a regexp was specified but no
  1135. database name(s).
  1136.  
  1137. Martin Waite - Fix to handle database name that contains space.
  1138.  
  1139. Paul DuBois - Remove end '/' from directory names
  1140.