home *** CD-ROM | disk | FTP | other *** search
/ Internet Magazine 2003 Autumn / INTERNET109.ISO / pc / software / windows / building / mysql / data1.cab / Development / scripts / mysqlhotcopy.sh < prev    next >
Encoding:
Text File  |  2003-08-03  |  28.2 KB  |  1,027 lines

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