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