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