~laurynas-biveinis/percona-xtrabackup/BT-28340-1164979-2.0

342 by Alexey Kopytov
Cherrypick of fix for bug #892393.
1
#!/usr/bin/env perl
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2
#
3
# A script for making backups of InnoDB and MyISAM tables, indexes and .frm
4
# files.
5
#
242.62.3 by Alexey Kopytov
s/Percona Inc/Percona Ireland Ltd/g
6
# Copyright 2003, 2009 Innobase Oy and Percona Ireland Ltd 2009-2012.
7
# All Rights Reserved.
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
8
#
9
516.4.1 by Alexey Kopytov
Bug #1116177: Fix warnings reported by "use warnings FATAL => 'all'"
10
use warnings FATAL => 'all';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
11
use strict;
12
use Getopt::Long;
13
use File::Spec;
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
14
use Pod::Usage qw(pod2usage);
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
15
use POSIX "strftime";
16
use POSIX ":sys_wait_h";
17
use FileHandle;
109.1.1 by Aleksandr Kuzminsky
Fixed Bug #434486: Using dirname(), basename() instead of manual parsing of filenames
18
use File::Basename;
340 by Alexey Kopytov
Cherrypick of fix for bug #687544.
19
use File::Temp;
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
20
use File::Find;
21
use File::Copy;
121.1.1 by Daniel Nichter
Get ibbackup/xtrabackup exit code. Exit with same.
22
use English qw(-no_match_vars);
490.5.1 by Sergei Glushchenko
Bug 1095551
23
use Time::HiRes qw(usleep);
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
24
25
# version of this script
26
my $innobackup_version = '1.5.1-xtrabackup';
109.3.1 by Aleksandr Kuzminsky
Fixed Bug #463709: The script outputs its own name
27
my $innobackup_script = basename($0);
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
28
29
# copyright notice
356 by Alexey Kopytov
Cherrypick of (C) string update due to 2012.
30
my $copyright_notice =
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
31
"InnoDB Backup Utility v${innobackup_version}; Copyright 2003, 2009 Innobase Oy
242.62.3 by Alexey Kopytov
s/Percona Inc/Percona Ireland Ltd/g
32
and Percona Ireland Ltd 2009-2012.  All Rights Reserved.
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
33
34
This software is published under
35
the GNU GENERAL PUBLIC LICENSE Version 2, June 1991.
36
37
";
38
39
# required Perl version (5.005)
40
my @required_perl_version = (5, 0, 5);
41
my $required_perl_version_old_style = 5.005;
42
43
# force flush after every write and print
44
$| = 1;
45
434 by Alexey Kopytov
Bug #1003518: innobackupex does not copy back table files in subfolders
46
# disable nlink count optimization, see File::Find documentation for details
47
$File::Find::dont_use_nlink=1;
48
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
49
######################################################################
50
# modifiable parameters
51
######################################################################
52
53
# maximum number of files in a database directory which are
54
# separately printed when a backup is made
55
my $backup_file_print_limit = 9;
56
57
# timeout in seconds for a reply from mysql
58
my $mysql_response_timeout = 900;
59
60
# default compression level (this is an argument to ibbackup)
61
my $default_compression_level = 1;
62
63
# time in seconds after which a dummy query is sent to mysql server
64
# in order to keep the database connection alive
242.25.3 by Alexey Kopytov
Bug #408803: innodbbackupex reaches Servers wait_timeout
65
my $mysql_keep_alive = 5;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
66
67
######################################################################
68
# end of modifiable parameters
69
######################################################################
70
71
72
# command line options
73
my $option_help = '';
74
my $option_version = '';
75
my $option_apply_log = '';
181 by root
added --redo-only option to innobackupex
76
my $option_redo_only = '';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
77
my $option_copy_back = '';
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
78
my $option_move_back = '';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
79
my $option_include = '';
80
my $option_databases = '';
166.1.1 by Daniel Nichter
Add --tables-file to innobackupex.
81
my $option_tables_file = '';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
82
my $option_throttle = '';
83
my $option_sleep = '';
84
my $option_compress = 999;
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
85
my $option_compress_threads = 1;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
86
my $option_uncompress = '';
61 by kinoyasu
innobackupex can pass --export option
87
my $option_export = '';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
88
my $option_use_memory = '';
89
my $option_mysql_password = '';
90
my $option_mysql_user = '';
91
my $option_mysql_port = '';
92
my $option_mysql_socket = '';
116.1.1 by Daniel Nichter
Bug 510965: add --host, remove --host=127.0.0.1 from --port.
93
my $option_mysql_host = '';
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
94
my $option_defaults_group = 'mysqld';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
95
my $option_no_timestamp = '';
96
my $option_slave_info = '';
353 by Alexey Kopytov
Cherrypick of Galera support.
97
my $option_galera_info = '';
100.1.1 by Aleksandr Kuzminsky
--no-lock option is added
98
my $option_no_lock = '';
152 by Aleksandr Kuzminsky
1. innobackupex saves the xtrabackup binary name in a file xtrabackup_binary.
99
my $option_ibbackup_binary = 'autodetect';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
100
36 by kinoyasu
some small fixes of innobackupex: bug 355214, bug 356776, etc
101
my $option_defaults_file = '';
487.3.1 by George O. Lorch III
Incorporated patch for Bug #740489 : Add --defaults-extra-file param to innobackupex
102
my $option_defaults_extra_file = '';
14 by kinoyasu
using rsync for incremental backup
103
my $option_incremental = '';
130 by Vadim Tkachenko
bugfix 546876
104
my $option_incremental_basedir = '';
218 by Vadim Tkachenko
Added option --incremental-dir to innobackupex script
105
my $option_incremental_dir = '';
219 by Vadim Tkachenko
Added option --incremental-lsn to innobackupex script.
106
my $option_incremental_lsn = '';
220 by Vadim Tkachenko
Bugfix #680936
107
my $option_extra_lsndir = '';
14 by kinoyasu
using rsync for incremental backup
108
my $option_remote_host = '';
242.25.4 by Alexey Kopytov
Implementation of
109
my $option_rsync = '';
22 by kinoyasu
"innobackup --stream=tar" is supported
110
my $option_stream = '';
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
111
my $stream_cmd = '';
22 by kinoyasu
"innobackup --stream=tar" is supported
112
my $option_tmpdir = '';
14 by kinoyasu
using rsync for incremental backup
113
68 by kinoyasu
new mode of innobackupex --stream=tar4ibd; new command tar4ibd based on libtar-1.2.11
114
my $option_tar4ibd = '';
70.1.1 by Aleksandr Kuzminsky
Allow configuration of scp options
115
my $option_scp_opt = '-Cp -c arcfour';
371 by Alexey Kopytov
Cherrypick of fix for bug 733658: pass options to both ssh and scp.
116
my $option_ssh_opt = '';
70.1.1 by Aleksandr Kuzminsky
Allow configuration of scp options
117
195 by Alexey Kopytov
Implementation of parallel data files transfer for xtrabackup.
118
my $option_parallel = '';
119
127.1.6 by Daniel Nichter
Add and implement --safe-slave-backup and --safe-slave-backup-timeout.
120
my $option_safe_slave_backup = '';
121
my $option_safe_slave_backup_timeout = 300;
122
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
123
# name of the my.cnf configuration file
124
#my $config_file = '';
125
126
# root of the backup directory
127
my $backup_root = '';
128
129
# backup directory pathname
130
my $backup_dir = '';
131
132
# name of the ibbackup suspend-at-end file
133
my $suspend_file = '';
134
17 by kinoyasu
--remote-host uses scp/ssh, remove using rsync
135
# name of the temporary transaction log file during the backup
136
my $tmp_logfile = '';
137
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
138
# home directory of innoDB log files
139
my $innodb_log_group_home_dir = '';
140
141
# backup my.cnf file
14 by kinoyasu
using rsync for incremental backup
142
my $backup_config_file = '';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
143
471.1.1 by Alexey Kopytov
Bug #1037379: SQL_THREAD left in stopped state of
144
# whether slave SQL thread is running when wait_for_safe_slave() is called
145
my $sql_thread_started = 0;
242.24.1 by Lachlan Mulcahy
Fixed bug 860879 - innobackupex fails if mysql is not a slave, but --safe-slave-backup is specified.
146
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
147
# options from the options file
148
my %config;
149
150
# options from the backup options file
151
#my %backup_config;
152
153
# list of databases to be included in a backup
154
my %databases_list;
155
171 by Daniel Nichter
Filter files copied according to --tables-file.
156
# list of tables to be included in a backup
157
my %table_list;
158
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
159
# prefix for output lines
109.3.1 by Aleksandr Kuzminsky
Fixed Bug #463709: The script outputs its own name
160
my $prefix = "$innobackup_script:";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
161
162
# process id of mysql client program (runs as a child process of this script)
163
my $mysql_pid = '';
164
165
# mysql server version string
166
my $mysql_server_version = '';
167
168
# name of the file where stderr of mysql process is directed
340 by Alexey Kopytov
Cherrypick of fix for bug #687544.
169
my $mysql_stderr_fh = File::Temp->new();
170
my $mysql_stderr = $mysql_stderr_fh->filename;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
171
172
# name of the file where stdout of mysql process is directed
340 by Alexey Kopytov
Cherrypick of fix for bug #687544.
173
my $mysql_stdout_fh = File::Temp->new();
174
my $mysql_stdout = $mysql_stdout_fh->filename;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
175
176
# name of the file where binlog position info is written
177
my $binlog_info;
178
353 by Alexey Kopytov
Cherrypick of Galera support.
179
# name of the file where galera position info is written
180
my $galera_info;
181
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
182
# name of the file where slave info is written
183
my $slave_info;
184
185
# mysql binlog position as given by "SHOW MASTER STATUS" command
186
my $mysql_binlog_position = '';
187
188
# mysql master's binlog position as given by "SHOW SLAVE STATUS" command
189
# run on a slave server
190
my $mysql_slave_position = '';
191
192
# process id of ibbackup program (runs as a child process of this script)
193
my $ibbackup_pid = '';
194
195
# a counter for numbering mysql connection checks
196
my $hello_id = 0;
197
198
# the request which has been sent to mysqld, but to which
199
# mysqld has not yet replied. Empty string denotes that no
200
# request has been sent to mysqld or that mysqld has replied
201
# to all requests.
202
my $current_mysql_request = '';
203
204
# escape sequences for options files
205
my %option_value_escapes = ('b' => "\b",
206
                            't' => "\t",
207
                            'n' => "\n",
208
                            'r' => "\r",
209
                            "\\" => "\\",
210
                            's' => ' ');
211
212
# signal that is sent to child processes when they are killed
213
my $kill_signal = 15;
214
215
# current local time
216
my $now;
217
66 by Vadim Tkachenko
Added incremental option to innobackupex-1.5.1 script
218
# incremental backup base directory
219
my $incremental_basedir = '';
220
108.1.4 by Aleksandr Kuzminsky
escape_path() function is added.
221
my $src_name;
222
my $dst_name;
223
my $win = ($^O eq 'MSWin32' ? 1 : 0);
224
my $CP_CMD = ($win eq 1 ? "copy /Y" : "cp -p");
152 by Aleksandr Kuzminsky
1. innobackupex saves the xtrabackup binary name in a file xtrabackup_binary.
225
my $xtrabackup_binary_file = 'xtrabackup_binary';
353 by Alexey Kopytov
Cherrypick of Galera support.
226
my $xtrabackup_pid_file = 'xtrabackup_pid';
242.25.4 by Alexey Kopytov
Implementation of
227
my %rsync_files_hash;
228
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
229
my $copy_dir_src;
230
my $copy_dir_dst;
231
my $copy_dir_exclude_regexp;
232
my $copy_dir_overwrite;
233
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
234
######################################################################
235
# program execution begins here
236
######################################################################
237
238
# check command-line args
239
check_args();
240
241
# print program version and copyright
242
print_version();
243
244
# initialize global variables and perform some checks
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
245
if ($option_copy_back || $option_move_back) {
242.11.8 by Alexey Kopytov
Bug #817132: innobackupex copy-back doesn't work without ibbackup
246
    $option_ibbackup_binary = 'xtrabackup' if ($option_ibbackup_binary eq 'autodetect');
152 by Aleksandr Kuzminsky
1. innobackupex saves the xtrabackup binary name in a file xtrabackup_binary.
247
} elsif ($option_apply_log) {
248
	# Read XtraBackup version from backup dir
249
	if (-e "$backup_dir/$xtrabackup_binary_file") {
250
		# Read XtraBackup version from file
251
		open XTRABACKUP_BINARY, "$backup_dir/$xtrabackup_binary_file"
252
			or die "Cannot open file $backup_dir/$xtrabackup_binary_file: $!\n";
253
		$option_ibbackup_binary = <XTRABACKUP_BINARY>;
254
		close XTRABACKUP_BINARY;
255
		}
256
257
	else {
258
		if( $option_ibbackup_binary eq "autodetect" ){
259
			# Try to connect MySQL and get the version
242.32.1 by Alexey Kopytov
Bug #514068: Output to STDOUT and STDERR is not conventional
260
			print STDERR "option_ibbackup_binary is autodetect, trying to connect to MySQL\n";
152 by Aleksandr Kuzminsky
1. innobackupex saves the xtrabackup binary name in a file xtrabackup_binary.
261
			my $options = get_mysql_options();
262
			$mysql_pid = open(*MYSQL_WRITER, "| mysql $options >$mysql_stdout 2>$mysql_stderr ");
242.32.1 by Alexey Kopytov
Bug #514068: Output to STDOUT and STDERR is not conventional
263
			print STDERR "Connected to MySQL with pid $mysql_pid\n";
152 by Aleksandr Kuzminsky
1. innobackupex saves the xtrabackup binary name in a file xtrabackup_binary.
264
			sleep 1;
265
			if ($mysql_pid && $mysql_pid == waitpid($mysql_pid, &WNOHANG)) {
266
				my $reason = `cat $mysql_stderr`;
267
				$mysql_pid = '';
268
				# Failed to connect to MySQL
504.10.3 by Alexey Kopytov
Basic 5.6 support:
269
				die "Failed to connect to MySQL server to detect version.\nYou must set xtrabackup version to use with --ibbackup option.\nPossible values are xtrabackup_51 (for MySQL 5.0 and 5.1), xtrabackup_55 (for MySQL 5.5), xtrabackup_56 (for MySQL or Percona Server 5.6,  or xtrabackup (for MySQL 5.1 with InnoDB plugin or Percona Server)\n";
152 by Aleksandr Kuzminsky
1. innobackupex saves the xtrabackup binary name in a file xtrabackup_binary.
270
				}
271
			else{
272
				mysql_close();
242.32.1 by Alexey Kopytov
Bug #514068: Output to STDOUT and STDERR is not conventional
273
				print STDERR "Connected successfully\n";
152 by Aleksandr Kuzminsky
1. innobackupex saves the xtrabackup binary name in a file xtrabackup_binary.
274
				$option_ibbackup_binary = set_xtrabackup_version();
275
				}
276
			}
277
		}
255.2.1 by Stewart Smith
innobackupex ignores --ibbackup and calls set_xtrabackup_version() anyway.
278
} elsif ($option_ibbackup_binary eq 'autodetect') {
152 by Aleksandr Kuzminsky
1. innobackupex saves the xtrabackup binary name in a file xtrabackup_binary.
279
    $option_ibbackup_binary = set_xtrabackup_version();
280
}
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
281
init();
282
121.1.1 by Daniel Nichter
Get ibbackup/xtrabackup exit code. Exit with same.
283
my $ibbackup_exit_code = 0;
284
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
285
if ($option_copy_back) {
286
    # copy files from backup directory back to their original locations
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
287
    copy_back(0);
288
} elsif ($option_move_back) {
289
    # move files from backup directory back to their original locations
290
    copy_back(1);
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
291
} elsif ($option_apply_log) {
292
    # expand data files in backup directory by applying log files to them
293
    apply_log();
294
} else {
295
    # make a backup of InnoDB and MyISAM tables, indexes and .frm files.
121.1.1 by Daniel Nichter
Get ibbackup/xtrabackup exit code. Exit with same.
296
    $ibbackup_exit_code = backup();
259 by Alexey Kopytov
Bug #787988: innobackupex fails with --remote-host when trying to create
297
    if ($option_remote_host) {
298
      open(XTRABACKUP_BINARY,
371 by Alexey Kopytov
Cherrypick of fix for bug 733658: pass options to both ssh and scp.
299
	   "| ssh $option_ssh_opt $option_remote_host 'cat > $backup_dir/$xtrabackup_binary_file'")
259 by Alexey Kopytov
Bug #787988: innobackupex fails with --remote-host when trying to create
300
	|| die "Failed to open file '$option_remote_host:$backup_dir/$xtrabackup_binary_file': $!";
301
    } elsif ($option_stream) {
302
      open XTRABACKUP_BINARY, "> $option_tmpdir/$xtrabackup_binary_file"
303
    	|| die "Cannot open file $option_tmpdir/$xtrabackup_binary_file: $!\n";
304
    } else {
305
      open XTRABACKUP_BINARY, "> $backup_dir/$xtrabackup_binary_file"
306
    	|| die "Cannot open file $backup_dir/$xtrabackup_binary_file: $!\n";
307
    }
152 by Aleksandr Kuzminsky
1. innobackupex saves the xtrabackup binary name in a file xtrabackup_binary.
308
    print XTRABACKUP_BINARY $option_ibbackup_binary;
309
    close XTRABACKUP_BINARY;
259 by Alexey Kopytov
Bug #787988: innobackupex fails with --remote-host when trying to create
310
311
    if ($option_stream) {
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
312
      system("cd $option_tmpdir; $stream_cmd $xtrabackup_binary_file")
259 by Alexey Kopytov
Bug #787988: innobackupex fails with --remote-host when trying to create
313
	&& die "Failed to stream $xtrabackup_binary_file: $!";
314
      unlink "$option_tmpdir/$xtrabackup_binary_file";
315
    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
316
}
317
318
$now = current_time();
22 by kinoyasu
"innobackup --stream=tar" is supported
319
320
if ($option_stream eq 'tar') {
121.1.1 by Daniel Nichter
Get ibbackup/xtrabackup exit code. Exit with same.
321
   print STDERR "$prefix You must use -i (--ignore-zeros) option for extraction of the tar stream.\n";
322
}
323
324
if ( $ibbackup_exit_code == 0 ) {
325
   # program has completed successfully
326
   print STDERR "$now  $prefix completed OK!\n";
327
}
328
else {
329
   print STDERR "$now  $prefix $option_ibbackup_binary failed! (exit code $ibbackup_exit_code)  The backup may not be complete.\n";
330
}
331
332
exit $ibbackup_exit_code;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
333
334
######################################################################
335
# end of program execution
336
######################################################################
337
338
339
#
340
# print_version subroutine prints program version and copyright.
341
#
342
sub print_version {
22 by kinoyasu
"innobackup --stream=tar" is supported
343
    printf(STDERR $copyright_notice);
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
344
}
345
346
347
#
348
# usage subroutine prints instructions of how to use this program to stdout.
349
#
350
sub usage {
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
351
   my $msg = shift || '';
352
   pod2usage({ -msg => $msg, -verbose => 1});
353
   return 0;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
354
}
355
356
357
#
358
# return current local time as string in form "070816 12:23:15"
359
#
360
sub current_time {
361
    return strftime("%y%m%d %H:%M:%S", localtime());
362
}
363
364
365
#
366
# Die subroutine kills all child processes and exits this process.
367
# This subroutine takes the same argument as the built-in die function.
368
#    Parameters:
369
#       message   string which is printed to stdout
370
#
371
sub Die {
372
    my $message = shift;
373
    my $extra_info = '';
374
375
    # kill all child processes of this process
376
    kill_child_processes();
377
378
    if ($current_mysql_request) {
379
        $extra_info = " while waiting for reply to MySQL request:" .
380
            " '$current_mysql_request'";
381
    }
382
    die "$prefix Error: $message$extra_info";
383
}
384
    
385
386
#
387
# backup subroutine makes a backup of InnoDB and MyISAM tables, indexes and 
388
# .frm files. It connects to the database server and runs ibbackup as a child
389
# process.
390
#
391
sub backup {
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
392
    my $orig_datadir = get_option(\%config, $option_defaults_group, 'datadir');
36 by kinoyasu
some small fixes of innobackupex: bug 355214, bug 356776, etc
393
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
394
    # check that we can connect to the database. This done by
395
    # connecting, issuing a query, and closing the connection.
396
    mysql_open();
397
    mysql_close();
398
399
    # start ibbackup as a child process
400
    start_ibbackup();
401
402
    # wait for ibbackup to suspend itself
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
403
    if (!$option_remote_host) {
14 by kinoyasu
using rsync for incremental backup
404
        wait_for_ibbackup_suspend();
405
    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
406
242.22.1 by Lachlan Mulcahy
Fixed bug 857788
407
    # connect to database
408
    mysql_open();
409
242.14.1 by Alexey Kopytov
Bug #834657: --slave-info does not work with --no-lock
410
    if ($option_safe_slave_backup) {
411
      wait_for_safe_slave();
412
    }
413
255.1.1 by Vadim Tkachenko
During incremental backup
414
    # flush tables with read lock
330.1.1 by Alexey Kopytov
Manual merge from 1.6 (conflict in innobackupex).
415
    if (!$option_no_lock) {
242.25.4 by Alexey Kopytov
Implementation of
416
        # make a prep copy before locking tables, if using rsync
417
        backup_files(1);
418
66 by Vadim Tkachenko
Added incremental option to innobackupex-1.5.1 script
419
        # flush tables with read lock
242.25.4 by Alexey Kopytov
Implementation of
420
        mysql_lockall();
66 by Vadim Tkachenko
Added incremental option to innobackupex-1.5.1 script
421
    }
255.1.1 by Vadim Tkachenko
During incremental backup
422
242.22.1 by Lachlan Mulcahy
Fixed bug 857788
423
    if ($option_slave_info) {
424
        write_slave_info();
425
    }
426
242.14.1 by Alexey Kopytov
Bug #834657: --slave-info does not work with --no-lock
427
471.6.1 by Alexey Kopytov
Bug #733665: innobackupex not supporting Maria 5.2
428
    # backup non-InnoDB files and tables
242.25.4 by Alexey Kopytov
Implementation of
429
    # (or finalize the backup by syncing changes if using rsync)
430
    backup_files(0);
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
431
478 by Alexey Kopytov
Bug #1055989: innobackupex waits for streaming temporary log file to
432
    # resume ibbackup and wait till log copying is finished
433
    resume_ibbackup();
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
434
242.61.1 by Alexey Kopytov
Bug #771981: myisam tables are not locked during incremental backup
435
    # release read locks on all tables
436
    mysql_unlockall() if !$option_no_lock;
255.1.1 by Vadim Tkachenko
During incremental backup
437
478 by Alexey Kopytov
Bug #1055989: innobackupex waits for streaming temporary log file to
438
    my $ibbackup_exit_code = wait_for_ibbackup_finish();
439
471.1.1 by Alexey Kopytov
Bug #1037379: SQL_THREAD left in stopped state of
440
    if ( $option_safe_slave_backup && $sql_thread_started) {
242.14.1 by Alexey Kopytov
Bug #834657: --slave-info does not work with --no-lock
441
      print STDERR "$prefix: Starting slave SQL thread\n";
442
      mysql_send('START SLAVE SQL_THREAD;');
443
    }
444
242.22.1 by Lachlan Mulcahy
Fixed bug 857788
445
    # Close the DB connection
446
    mysql_close();
447
380.2.1 by Sergei Glushchenko
Bug 543134.
448
    # copy ib_lru_dump
449
    if (-e "$orig_datadir/ib_lru_dump") {
450
        if ($option_remote_host) {
451
            print STDERR "$prefix Backing up file 'ib_lru_dump'\n";
452
            system("scp $option_scp_opt '$orig_datadir/ib_lru_dump' '$option_remote_host:$backup_dir/ib_lru_dump'")
453
                and Die "Failed to scp file 'ib_lru_dump': $!";
454
        } elsif ($option_stream) {
455
            print STDERR "$prefix Backing up as tar stream 'ib_lru_dump'\n";
419.1.1 by Sergei Glushchenko
Bug #983720: ib_lru_dump and --galera-info fail with --stream=xbstream
456
            system("cd $orig_datadir; $stream_cmd ib_lru_dump")
380.2.1 by Sergei Glushchenko
Bug 543134.
457
                and Die "Failed to stream 'ib_lru_dump': $!";
458
        } elsif (!$option_rsync) {
459
            my $src_name = escape_path("$orig_datadir/ib_lru_dump");
460
            my $dst_name = escape_path("$backup_dir/ib_lru_dump");
461
            system("$CP_CMD \"$src_name\" \"$dst_name\"")
462
                and Die "Failed to copy file 'ib_lru_dump': $!";
463
        }
464
    }
465
17 by kinoyasu
--remote-host uses scp/ssh, remove using rsync
466
    if ($option_remote_host) {
70.1.1 by Aleksandr Kuzminsky
Allow configuration of scp options
467
        system("scp $option_scp_opt '$tmp_logfile' '$option_remote_host:$backup_dir/xtrabackup_logfile'")
17 by kinoyasu
--remote-host uses scp/ssh, remove using rsync
468
            and Die "Failed to scp file '$option_remote_host:$backup_dir/xtrabackup_logfile': $!";
20 by kinoyasu
innobackup --include=REGEXP with --remote
469
        unlink $tmp_logfile || Die "Failed to delete '$tmp_logfile': $!";
36 by kinoyasu
some small fixes of innobackupex: bug 355214, bug 356776, etc
470
374 by Alexey Kopytov
Cherrypick of fix for placement of xtrabackup_suspended and xtrabackup_checkpoint.
471
        system("scp $option_scp_opt '$option_tmpdir/xtrabackup_checkpoints' '$option_remote_host:$backup_dir/xtrabackup_checkpoints'")
36 by kinoyasu
some small fixes of innobackupex: bug 355214, bug 356776, etc
472
            and Die "Failed to scp file '$option_remote_host:$backup_dir/xtrabackup_checkpoints': $!";
374 by Alexey Kopytov
Cherrypick of fix for placement of xtrabackup_suspended and xtrabackup_checkpoint.
473
        unlink "$option_tmpdir/xtrabackup_checkpoints" || Die "Failed to delete '$option_tmpdir/xtrabackup_checkpoints': $!";
17 by kinoyasu
--remote-host uses scp/ssh, remove using rsync
474
    }
475
22 by kinoyasu
"innobackup --stream=tar" is supported
476
    print STDERR "\n$prefix Backup created in directory '$backup_dir'\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
477
    if ($mysql_binlog_position) {
22 by kinoyasu
"innobackup --stream=tar" is supported
478
        print STDERR "$prefix MySQL binlog position: $mysql_binlog_position\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
479
    }
480
    if ($mysql_slave_position && $option_slave_info) {
22 by kinoyasu
"innobackup --stream=tar" is supported
481
        print STDERR "$prefix MySQL slave binlog position: $mysql_slave_position\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
482
    }
121.1.1 by Daniel Nichter
Get ibbackup/xtrabackup exit code. Exit with same.
483
484
    return $ibbackup_exit_code;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
485
}
486
487
488
#
489
# are_equal_innodb_data_file_paths subroutine checks if the given
490
# InnoDB data file option values are equal.
491
#   Parameters:
492
#     str1    InnoDB data file path option value
493
#     str2    InnoDB data file path option value
494
#   Return value:
495
#     1  if values are equal
496
#     0  otherwise
497
#
498
sub are_equal_innodb_data_file_paths {
499
    my $str1 = shift;
500
    my $str2 = shift;
501
    my @array1 = split(/;/, $str1);
502
    my @array2 = split(/;/, $str2);
503
    
504
    if ($#array1 != $#array2) { return 0; }
505
506
    for (my $i = 0; $i <= $#array1; $i++) {
507
        my @def1 = split(/:/, $array1[$i]);
508
        my @def2 = split(/:/, $array2[$i]);
509
        
510
        if ($#def1 != $#def2) { return 0; }
511
512
        for (my $j = 0; $j <= $#def1; $j++) {
513
            if ($def1[$j] ne $def2[$j]) { return 0; }
514
        }
515
    }
516
    return 1;
517
}        
518
519
520
#
242.26.20 by Alexey Kopytov
Fix for bug #924026: innobackupex fails during backup if table is
521
# copy_if_exists subroutin attempt to copy a file from $src to $dst
522
# If the copy fails due to the file not existing, the error is ignored
523
#  Parameters:
524
#    $src    The source file to copy
525
#    $dst    The destination to copy to
526
#  Return value:
527
#    1  if copy was successful, or unsuccessful but the source file didn't exist
528
#    0  otherwise
529
#
530
sub copy_if_exists {
531
    my $src = shift;
532
    my $dst = shift;
533
534
    # Copy the file
535
    if( system("$CP_CMD \"$src\" \"$dst\"") != 0 ) {
536
        # if the copy failed, check if the file exists
537
        if( -e "$src" ) {
538
            # if the file exists, we had a real error
539
            return 0;
540
        }
541
    }
542
    # Success otherwise
543
    return 1;
544
}
545
546
547
#
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
548
# is_in_array subroutine checks if the given string is in the array.
549
#   Parameters:
550
#     str       a string
551
#     array_ref a reference to an array of strings
552
#   Return value:
553
#     1  if string is in the array
554
#     0  otherwise
555
# 
556
sub is_in_array {
557
    my $str = shift;
558
    my $array_ref = shift;
559
560
    if (grep { $str eq $_ } @{$array_ref}) {
561
        return 1;
562
    }
563
    return 0;
564
}
565
242.29.1 by Valentine Gostev
Fix for bug https://bugs.launchpad.net/percona-xtrabackup/+bug/737569
566
#
567
# if_directory_exists_and_empty accepts two arguments:
568
# variable with directory name and comment.
569
# Sub checks that directory exists and is empty
570
# usage: is_directory_exists_and_empty($directory,"Comment");
571
#
572
573
sub if_directory_exists_and_empty {
574
    my $empty_dir = shift;
575
    my $is_directory_empty_comment = shift;
576
    if (! -d $empty_dir) {
487.1.1 by Alexey Kopytov
Backport of the fix for bug #1089375 to 2.0:
577
        die "$is_directory_empty_comment directory '$empty_dir' does not exist!";
242.29.1 by Valentine Gostev
Fix for bug https://bugs.launchpad.net/percona-xtrabackup/+bug/737569
578
    }
487.1.1 by Alexey Kopytov
Backport of the fix for bug #1089375 to 2.0:
579
    opendir (my $dh, $empty_dir) or die "$is_directory_empty_comment directory '$empty_dir': Not a directory";
392.1.1 by Igor Tverdovskiy
my.cnf and master.info are excluded from empty destination dir validator now.
580
    if ( ! scalar( grep { $_ ne "." && $_ ne ".." && $_ ne "my.cnf" && $_ ne "master.info"} readdir($dh)) == 0) {
487.1.1 by Alexey Kopytov
Backport of the fix for bug #1089375 to 2.0:
581
        die "$is_directory_empty_comment directory '$empty_dir' is not empty!";
242.29.1 by Valentine Gostev
Fix for bug https://bugs.launchpad.net/percona-xtrabackup/+bug/737569
582
    }
583
    closedir($dh);
584
}
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
585
586
#
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
587
# copy() wrapper with error handling
588
#
589
sub copy_file {
590
    my $src_path = shift;
591
    my $dst_path = shift;
592
593
    print STDERR "$prefix Copying '$src_path' to '$dst_path'\n";
594
    copy($src_path, $dst_path) or Die "copy failed: $!";
595
}
596
597
#
598
# move() wrapper with error handling
599
#
600
sub move_file {
601
    my $src_path = shift;
602
    my $dst_path = shift;
603
604
    print STDERR "$prefix Moving '$src_path' to '$dst_path'\n";
605
    move($src_path, $dst_path) or Die "move failed: $!";
606
}
607
608
609
#
610
# Auxiliary function called from find() callbacks to copy or move files and create directories
611
# when necessary.
612
#
613
# SYNOPSIS
614
#
615
#     process_file(\&process_func);
616
#
617
#       &process_func is a code reference that does the actual file operation
618
#
619
sub process_file {
620
    my $process_func = shift;
621
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
622
    if (/$copy_dir_exclude_regexp/) {
623
	return;
624
    }
625
    (my $dst_path = $File::Find::name) =~ s/^$copy_dir_src/$copy_dir_dst/;
626
    if (-d "$File::Find::name") {
627
	# Create the directory in the destination if necessary
628
	if (! -e "$dst_path") {
629
	    print STDERR "$prefix Creating directory '$dst_path'\n";
630
	    mkdir "$dst_path" or Die "mkdir failed: $!";
631
	} elsif (! -d "$dst_path") {
632
	    Die "$dst_path exists, but is not a directory";
633
	}
634
    } else {
635
	# Don't overwrite files unless $copy_dir_overwrite is 1
636
	if (!$copy_dir_overwrite && -e "$copy_dir_dst/$_") {
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
637
	    Die "Failed to process file $File::Find::name: " .
638
		"not overwriting file $copy_dir_dst/$_";
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
639
	}
640
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
641
	&$process_func($File::Find::name, $dst_path);
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
642
    }
643
}
644
645
#
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
646
# find() callback to copy files
647
#
648
sub copy_file_callback {
649
    process_file(\&copy_file);
650
}
651
652
#
653
# find() callback to move files
654
#
655
sub move_file_callback {
656
    process_file(\&move_file);
657
}
658
659
#
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
660
# copy_dir_recursively subroutine does a recursive copy of a specified
661
# directory excluding files matching a specifies regexp. If $overwrite
662
# is 1, it overwrites the existing files.
663
#
664
# SYNOPSIS 
665
#
666
#     copy_dir_recursively($src_dir, $dst_dir, $exclude_regexp,
667
#                          $overwrite);
668
#
669
# TODO
670
#
671
#     use rsync when --rsync is specified
672
#
673
sub copy_dir_recursively {
242.55.1 by Alexey Kopytov
Bug #1002688: innobackupex incremental apply-log copies to wrong
674
    # Clean paths and remove trailing slashes if any
675
    $copy_dir_src = File::Spec->canonpath(shift);
676
    $copy_dir_dst = File::Spec->canonpath(shift);
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
677
    $copy_dir_exclude_regexp = shift;
678
    $copy_dir_overwrite = shift;
679
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
680
    find(\&copy_file_callback, $copy_dir_src);
681
}
682
683
#
684
# Similar to copy_dir_recursively, but moves files instead.
685
#
686
# SYNOPSIS
687
#
688
#     move_dir_recursively($src_dir, $dst_dir, $exclude_regexp,
689
#                          $overwrite);
690
#
691
# TODO
692
#
693
#     use rsync when --rsync is specified
694
#
695
sub move_dir_recursively {
696
    # Clean paths and remove trailing slashes if any
697
    $copy_dir_src = File::Spec->canonpath(shift);
698
    $copy_dir_dst = File::Spec->canonpath(shift);
699
    $copy_dir_exclude_regexp = shift;
700
    $copy_dir_overwrite = shift;
701
702
    find(\&move_file_callback, $copy_dir_src);
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
703
}
704
705
#
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
706
# copy_back subroutine copies data and index files from backup directory 
707
# back to their original locations.
708
#
709
sub copy_back {
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
710
    my $move_flag = shift;
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
711
    my $orig_datadir = get_option(\%config, $option_defaults_group, 'datadir');
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
712
    my $orig_ibdata_dir = 
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
713
        get_option(\%config, $option_defaults_group, 'innodb_data_home_dir');
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
714
    my $orig_innodb_data_file_path = 
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
715
        get_option(\%config, $option_defaults_group, 'innodb_data_file_path');
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
716
    my $orig_iblog_dir =
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
717
        get_option(\%config, $option_defaults_group, 'innodb_log_group_home_dir');
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
718
    my $iblog_files = 'ib_logfile.*';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
719
    my $excluded_files = 
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
720
        '\.\.?|backup-my\.cnf|xtrabackup_logfile|' .
441 by Alexey Kopytov
Bug #983695: --copy-back should ignore *.qp files
721
	'xtrabackup_binary|xtrabackup_binlog_info|xtrabackup_checkpoints|' .
722
        '.*\.qp|' .
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
723
	$iblog_files;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
724
    my $compressed_data_file = '.*\.ibz$';
725
    my $file;
726
    my $backup_innodb_data_file_path;
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
727
471.5.1 by Sergei Glushchenko
Bug #1066843: Fix for bug #932623 does not take separate doublewrite
728
    if (has_option(\%config, $option_defaults_group, 'innodb_doublewrite_file')) {
729
        my $doublewrite_file =
730
                get_option(\%config, $option_defaults_group,
731
                            'innodb_doublewrite_file');
732
        $excluded_files = $excluded_files . '|' . $doublewrite_file;
733
    }
734
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
735
    # check whether files should be copied or moved to dest directory
736
    my $move_or_copy_file = $move_flag ? \&move_file : \&copy_file;
737
    my $move_or_copy_dir = $move_flag ?
738
        \&move_dir_recursively : \&copy_dir_recursively;
739
    my $operation = $move_flag ? "move" : "copy";
740
741
242.29.1 by Valentine Gostev
Fix for bug https://bugs.launchpad.net/percona-xtrabackup/+bug/737569
742
    # check that original data directories exist and they are empty
743
    if_directory_exists_and_empty($orig_datadir, "Original data");
744
    if_directory_exists_and_empty($orig_ibdata_dir, "Original InnoDB data");
745
    if_directory_exists_and_empty($orig_iblog_dir, "Original InnoDB log");
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
746
747
    # check that the original options file and the backup options file have
748
    # the same value for "innodb_data_file_path" option
749
    #$backup_innodb_data_file_path = 
750
    #    get_option(\%backup_config, 'mysqld', 'innodb_data_file_path');
751
    #if (!are_equal_innodb_data_file_paths($orig_innodb_data_file_path, 
752
    #                                      $backup_innodb_data_file_path)
753
    #) {
754
    #    Die "The value of 'innodb_data_file_path' option in the original "
755
    #      . "my.cnf file '$config_file' is different from the value "
756
    #      . "in the backup my.cnf file '$backup_config_file'.\n(original: "
757
    #      . "'$orig_innodb_data_file_path')\n"
758
    #      . "(backup:   '$backup_innodb_data_file_path')";
759
    #}
760
761
    # make a list of all ibdata files in the backup directory and all
762
    # directories in the backup directory under which there are ibdata files
763
    foreach my $a (split(/;/, $orig_innodb_data_file_path)) {
764
        my $path = (split(/:/,$a))[0];
42 by kinoyasu
fix bug 357653; remove innobackup-1.5.1.patch
765
        my $filename = (split(/\/+/, $path))[-1];
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
766
767
        # check that the backup data file exists
42 by kinoyasu
fix bug 357653; remove innobackup-1.5.1.patch
768
        if (! -e "$backup_dir/$filename") {
769
            if (-e "$backup_dir/${filename}.ibz") {
770
                Die "Backup data file '$backup_dir/$filename' does not exist, but "
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
771
                  . "its compressed copy '${path}.ibz' exists. Check "
109.3.1 by Aleksandr Kuzminsky
Fixed Bug #463709: The script outputs its own name
772
                  . "that you have run '$innobackup_script --apply-log --uncompress "
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
773
                  . "...' before attempting '$innobackup_script --copy-back ...'  "
774
                  . "or '$innobackup_script --move-back ...' !";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
775
            } else {
42 by kinoyasu
fix bug 357653; remove innobackup-1.5.1.patch
776
                Die "Backup data file '$backup_dir/$filename' does not exist.";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
777
            }
778
        }
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
779
	
780
        $excluded_files .= "|\Q$filename\E";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
781
    }
782
783
    # copy files from backup dir to their original locations
784
785
    # copy files to original data directory
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
786
    my $excluded_regexp = '^(' . $excluded_files . ')$';
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
787
    print STDERR "$prefix Starting to $operation files in '$backup_dir'\n"; 
22 by kinoyasu
"innobackup --stream=tar" is supported
788
    print STDERR "$prefix back to original data directory '$orig_datadir'\n";
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
789
    &$move_or_copy_dir($backup_dir, $orig_datadir, $excluded_regexp, 0);
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
790
791
    # copy InnoDB data files to original InnoDB data directory
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
792
    print STDERR "\n$prefix Starting to $operation InnoDB system tablespace\n";
22 by kinoyasu
"innobackup --stream=tar" is supported
793
    print STDERR "$prefix in '$backup_dir'\n";
794
    print STDERR "$prefix back to original InnoDB data directory '$orig_ibdata_dir'\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
795
    foreach my $a (split(/;/, $orig_innodb_data_file_path)) {
796
        # get the relative pathname of a data file
797
        my $path = (split(/:/,$a))[0];
42 by kinoyasu
fix bug 357653; remove innobackup-1.5.1.patch
798
        my $filename = (split(/\/+/, $path))[-1];
108.1.4 by Aleksandr Kuzminsky
escape_path() function is added.
799
        $src_name = escape_path("$backup_dir/$filename");
800
        $dst_name = escape_path("$orig_ibdata_dir/$path");
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
801
        &$move_or_copy_file($src_name, $dst_name);
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
802
    }
803
804
    # copy InnoDB log files to original InnoDB log directory
805
    opendir(DIR, $backup_dir) 
806
        || Die "Can't open directory '$backup_dir': $!\n";
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
807
    print STDERR "\n$prefix Starting to $operation InnoDB log files\n";
22 by kinoyasu
"innobackup --stream=tar" is supported
808
    print STDERR "$prefix in '$backup_dir'\n";
809
    print STDERR "$prefix back to original InnoDB log directory '$orig_iblog_dir'\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
810
    while (defined($file = readdir(DIR))) {
516.4.1 by Alexey Kopytov
Bug #1116177: Fix warnings reported by "use warnings FATAL => 'all'"
811
        if ($file =~ /^$iblog_files$/ && -f "$backup_dir/$file") {
108.1.4 by Aleksandr Kuzminsky
escape_path() function is added.
812
            $src_name = escape_path("$backup_dir/$file");
813
            $dst_name = escape_path("$orig_iblog_dir");
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
814
            &$move_or_copy_file($src_name, $dst_name);
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
815
        }
816
    }
817
    closedir(DIR);
818
22 by kinoyasu
"innobackup --stream=tar" is supported
819
    print STDERR "$prefix Finished copying back files.\n\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
820
}
821
822
823
#
824
# apply_log subroutine prepares a backup for starting database server
825
# on the backup. It applies InnoDB log files to the InnoDB data files.
826
#
827
sub apply_log {
828
    my $rcode;
829
    my $cmdline = '';
43 by kinoyasu
fix bug 358266, bug 359341
830
    my $options = '';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
831
36 by kinoyasu
some small fixes of innobackupex: bug 355214, bug 356776, etc
832
    if ($option_defaults_file) {
108.1.5 by Aleksandr Kuzminsky
Fixed issue in quoting defaults-file when specified
833
        $options = $options . " --defaults-file=\"$option_defaults_file\" ";
242.47.10 by Sergei Glushchenko
Bug 996493: innobackupex --apply-log doesn't read config from backup-my.cnf
834
    } else {
835
        $options = $options . " --defaults-file=\"${backup_dir}/backup-my.cnf\" ";
36 by kinoyasu
some small fixes of innobackupex: bug 355214, bug 356776, etc
836
    }
43 by kinoyasu
fix bug 358266, bug 359341
837
487.3.1 by George O. Lorch III
Incorporated patch for Bug #740489 : Add --defaults-extra-file param to innobackupex
838
    if ($option_defaults_extra_file) {
839
        $options = $options . " --defaults-extra-file=\"$option_defaults_extra_file\" ";
840
    }
841
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
842
    if ($option_defaults_group) {
843
        $options = $options . " --defaults-group=\"$option_defaults_group\" ";
844
    }
845
43 by kinoyasu
fix bug 358266, bug 359341
846
    $options = $options . "--prepare --target-dir=$backup_dir";
847
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
848
    if ($option_uncompress) {
849
        $options = $options . ' --uncompress';
850
    }
61 by kinoyasu
innobackupex can pass --export option
851
    if ($option_export) {
852
        $options = $options . ' --export';
853
    }
181 by root
added --redo-only option to innobackupex
854
    if ($option_redo_only) {
855
        $options = $options . ' --apply-log-only';
856
    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
857
    if ($option_use_memory) {
858
        $options = $options . " --use-memory=$option_use_memory";
859
    }
860
218 by Vadim Tkachenko
Added option --incremental-dir to innobackupex script
861
    if ($option_incremental_dir) {
862
        $options = $options . " --incremental-dir=$option_incremental_dir";
863
    }
864
504.4.1 by Alexey Kopytov
Bug #1085099: innobackupex does not pass --tmpdir to xtrabackup
865
    if ($option_tmpdir) {
866
        $options .= " --tmpdir=$option_tmpdir";
867
    }
868
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
869
    # run ibbackup as a child process
870
    $cmdline = "$option_ibbackup_binary $options";
871
    $now = current_time();
22 by kinoyasu
"innobackup --stream=tar" is supported
872
    print STDERR "\n$now  $prefix Starting ibbackup with command: $cmdline\n\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
873
    $rcode = system("$cmdline");
874
    if ($rcode) {
875
        # failure
876
        Die "\n$prefix ibbackup failed";
877
    }
878
222 by Vadim Tkachenko
Disabled auto-creating of ib_logfile* when
879
    # We should not create ib_logfile files if we prepare for following incremental applies
880
    # Also we do not prepare ib_logfile if we applied incremental changes
881
    if (!( ($option_redo_only) or ($option_incremental_dir))) { 
345 by Alexey Kopytov
Cherrypick of fix for bug #03984 - When applying deltas from an incremental over a full backup to "roll forward" is completed, update the xtrabackup_slave_info file in the target dir if there is an updated xtraback.
882
        $now = current_time();
883
        print STDERR "\n$now  $prefix Restarting xtrabackup with command: $cmdline\nfor creating ib_logfile*\n\n";
884
        $rcode = system("$cmdline");
885
        if ($rcode) {
886
            # failure
887
            Die "\n$prefix xtrabackup (2nd execution) failed";
888
        }
889
    }
890
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
891
    # If we were applying an incremental change set, we need to make
892
    # sure non-InnoDB files and xtrabackup_* metainfo files are copied
893
    # to the full backup directory.
345 by Alexey Kopytov
Cherrypick of fix for bug #03984 - When applying deltas from an incremental over a full backup to "roll forward" is completed, update the xtrabackup_slave_info file in the target dir if there is an updated xtraback.
894
    if ( $option_incremental_dir ) {
242.42.1 by Alexey Kopytov
Bug #759701: innobackupex does not copy non-InnoDB files when applying
895
	print STDERR "$prefix Starting to copy non-InnoDB files in '$option_incremental_dir'\n"; 
896
	print STDERR "$prefix to the full backup directory '$backup_dir'\n";
897
	copy_dir_recursively($option_incremental_dir, $backup_dir,
898
			     '^(\.\.?|backup-my\.cnf|xtrabackup_logfile|' .
899
			     'xtrabackup_binary|xtrabackup_checkpoints|' .
900
			     '.*\.delta|.*\.meta|ib_logfile.*)$', 1);
901
        # If the latest backup has no file, we need to remove the old
902
        # xtrabackup_slave_info file, because it is out of date
903
        # TODO: this will not be needed when bug #856400 is fixed.
904
        if ( -e "$backup_dir/xtrabackup_slave_info" ) {
345 by Alexey Kopytov
Cherrypick of fix for bug #03984 - When applying deltas from an incremental over a full backup to "roll forward" is completed, update the xtrabackup_slave_info file in the target dir if there is an updated xtraback.
905
            print STDERR "\n$now  $prefix No updated xtrabackup_slave_info found in incremental dir, removing stale xtrabackup_slave_info file from target dir.";
906
            $cmdline = "rm $backup_dir/xtrabackup_slave_info";
907
            $rcode = system("$cmdline");
908
            if ($rcode) {
909
                # failure
910
                Die "\n$prefix Failed to remove stale xtrabackup_slave_info in $backup_dir";
911
            }
912
913
        }
914
    }
915
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
916
}
917
918
919
#
920
# wait_for_ibbackup_suspend subroutine waits until ibbackup has suspended 
921
# itself.
922
#
923
sub wait_for_ibbackup_suspend {
22 by kinoyasu
"innobackup --stream=tar" is supported
924
    print STDERR "$prefix Waiting for ibbackup (pid=$ibbackup_pid) to suspend\n";
925
    print STDERR "$prefix Suspend file '$suspend_file'\n\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
926
    for (;;) {
490.5.1 by Sergei Glushchenko
Bug 1095551
927
        usleep(100000);
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
928
        last if -e $suspend_file;
929
930
        # check that ibbackup child process is still alive
931
        if ($ibbackup_pid == waitpid($ibbackup_pid, &WNOHANG)) {
932
            $ibbackup_pid = '';
933
            Die "ibbackup child process has died";
934
        }
935
    }
936
    $now = current_time();
353 by Alexey Kopytov
Cherrypick of Galera support.
937
    open XTRABACKUP_PID, "> $option_tmpdir/$xtrabackup_pid_file";
938
    print XTRABACKUP_PID $ibbackup_pid;
939
    close XTRABACKUP_PID;
22 by kinoyasu
"innobackup --stream=tar" is supported
940
    print STDERR "\n$now  $prefix Continuing after ibbackup has suspended\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
941
}
942
943
944
#
478 by Alexey Kopytov
Bug #1055989: innobackupex waits for streaming temporary log file to
945
# resume_ibbackup subroutine signals ibbackup to finish log copying by deleting
946
# the 'xtrabackup_suspended' file and waits until log copying is stopped,
947
# i.e. until 'xtrabackup_suspended' is created again.
948
#
949
# If this functions detects that the xtrabackup process has terminated, it also
950
# sets ibbackup_exit_code and resets ibbackup_pid to avoid trying to reap a
951
# non-existing process later
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
952
#
953
sub resume_ibbackup {
478 by Alexey Kopytov
Bug #1055989: innobackupex waits for streaming temporary log file to
954
    my $pid = -1;
955
956
    $now = current_time();
957
    print STDERR "$now  $prefix Waiting for log copying to finish\n\n";
958
    unlink $suspend_file || Die "Failed to delete '$suspend_file': $!";
959
960
    for (;;) {
961
        # check if the xtrabackup process is still alive _before_ checking if
962
        # the file exists to avoid a race condition when the file is created and
963
        # the process terminates right after we do the file check
964
        $pid = waitpid($ibbackup_pid, &WNOHANG);
965
966
        last if -e $suspend_file;
967
968
        if ($ibbackup_pid == $pid) {
969
            # The file doesn't exist, but the process has terminated
970
            Die "ibbackup child process has died";
971
        }
972
973
        sleep 1;
974
    }
975
976
    if ($pid == $ibbackup_pid) {
977
        $ibbackup_exit_code = $CHILD_ERROR >> 8;
978
        $ibbackup_pid = '';
979
    }
980
981
    unlink $suspend_file || Die "Failed to delete '$suspend_file': $!";
982
}
983
984
#
985
# wait for ibbackup to finish and return its exit code
986
#
987
sub wait_for_ibbackup_finish {
988
    if (!$ibbackup_pid) {
989
        # The process has already been reaped.
501 by Alexey Kopytov
Bug #1114955: xtrabackup_pid remains existed after execution
990
        unlink "$option_tmpdir/$xtrabackup_pid_file";
478 by Alexey Kopytov
Bug #1055989: innobackupex waits for streaming temporary log file to
991
        return $ibbackup_exit_code;
992
    }
993
994
    $now = current_time();
995
    print STDERR "$now  $prefix Waiting for ibbackup (pid=$ibbackup_pid) to finish\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
996
997
    # wait for ibbackup to finish
998
    waitpid($ibbackup_pid, 0);
353 by Alexey Kopytov
Cherrypick of Galera support.
999
    unlink "$option_tmpdir/$xtrabackup_pid_file";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1000
    $ibbackup_pid = '';
121.1.1 by Daniel Nichter
Get ibbackup/xtrabackup exit code. Exit with same.
1001
    return $CHILD_ERROR >> 8;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1002
}
1003
    
1004
1005
#
1006
# start_ibbackup subroutine spawns a child process running ibbackup
1007
# program for backing up InnoDB tables and indexes.
1008
#
1009
sub start_ibbackup {
43 by kinoyasu
fix bug 358266, bug 359341
1010
    my $options = '';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1011
    my $cmdline = '';
1012
    my $pid = undef;
1013
43 by kinoyasu
fix bug 358266, bug 359341
1014
    if ($option_defaults_file) {
108.1.5 by Aleksandr Kuzminsky
Fixed issue in quoting defaults-file when specified
1015
        $options = $options . " --defaults-file=\"$option_defaults_file\" ";
43 by kinoyasu
fix bug 358266, bug 359341
1016
    }
1017
487.3.1 by George O. Lorch III
Incorporated patch for Bug #740489 : Add --defaults-extra-file param to innobackupex
1018
    if ($option_defaults_extra_file) {
1019
        $options = $options . " --defaults-extra-file=\"$option_defaults_extra_file\" ";
1020
    }
1021
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
1022
    if ($option_defaults_group) {
1023
        $options = $options . " --defaults-group=\"$option_defaults_group\" ";
1024
    }
1025
43 by kinoyasu
fix bug 358266, bug 359341
1026
    $options = $options . "--backup --suspend-at-end";
1027
22 by kinoyasu
"innobackup --stream=tar" is supported
1028
    if (!$option_remote_host && !$option_stream) {
15 by kinoyasu
trial implementation of --remote-host when --incremental (innobackup)
1029
        $options = $options . " --target-dir=$backup_dir";
1030
    } else {
36 by kinoyasu
some small fixes of innobackupex: bug 355214, bug 356776, etc
1031
        #(datadir) for 'xtrabackup_suspended' and 'xtrabackup_checkpoints'
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1032
        $options = $options . " --target-dir=" . $option_tmpdir;
1033
	if ($option_remote_host) {
1034
	  $options = $options . " --log-stream";
1035
	}
15 by kinoyasu
trial implementation of --remote-host when --incremental (innobackup)
1036
    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1037
504.4.1 by Alexey Kopytov
Bug #1085099: innobackupex does not pass --tmpdir to xtrabackup
1038
    if ($option_tmpdir) {
1039
        $options .= " --tmpdir=$option_tmpdir";
1040
    }
1041
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1042
    # prepare command line for running ibbackup
1043
    if ($option_throttle) {
1044
        $options = $options . " --throttle=$option_throttle";
1045
    }
1046
    if ($option_sleep) {
1047
        $options = $options . " --sleep=$option_sleep";
1048
    }
1049
    if ($option_compress) {
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1050
        $options = $options . " --compress";
1051
        $options = $options . " --compress-threads=$option_compress_threads";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1052
    }
1053
    if ($option_use_memory) {
1054
        $options = $options . " --use-memory=$option_use_memory";
1055
    }
1056
    if ($option_include) {
19 by kinoyasu
xtrabackup --tables=REGEXP, innobackup --index=REGEXP
1057
        $options = $options . " --tables='$option_include'";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1058
    }
220 by Vadim Tkachenko
Bugfix #680936
1059
    if ($option_extra_lsndir) {
1060
        $options = $options . " --extra-lsndir='$option_extra_lsndir'";
1061
    }
1062
66 by Vadim Tkachenko
Added incremental option to innobackupex-1.5.1 script
1063
    if ($option_incremental) {
219 by Vadim Tkachenko
Added option --incremental-lsn to innobackupex script.
1064
        if($option_incremental_lsn) {
1065
          $options = $options . " --incremental-lsn='$option_incremental_lsn'";
242.23.1 by Lachlan Mulcahy
Fixed bug 860133
1066
	    } else {
219 by Vadim Tkachenko
Added option --incremental-lsn to innobackupex script.
1067
          $options = $options . " --incremental-basedir='$incremental_basedir'";
242.23.1 by Lachlan Mulcahy
Fixed bug 860133
1068
	    }
66 by Vadim Tkachenko
Added incremental option to innobackupex-1.5.1 script
1069
    }
220 by Vadim Tkachenko
Bugfix #680936
1070
166.1.1 by Daniel Nichter
Add --tables-file to innobackupex.
1071
    if ($option_tables_file) {
1072
        $options = $options . " --tables_file='$option_tables_file'";
1073
    }
195 by Alexey Kopytov
Implementation of parallel data files transfer for xtrabackup.
1074
    if ($option_parallel) {
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1075
        $options = $options . " --parallel=$option_parallel";
1076
    }
1077
    if ($option_stream) {
1078
	$options = $options . " --stream=$option_stream";
195 by Alexey Kopytov
Implementation of parallel data files transfer for xtrabackup.
1079
    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1080
    $cmdline = "$option_ibbackup_binary $options";
1081
1082
    # run ibbackup as a child process
1083
    $now = current_time();
22 by kinoyasu
"innobackup --stream=tar" is supported
1084
    print STDERR "\n$now  $prefix Starting ibbackup with command: $cmdline\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1085
    if (defined($pid = fork)) {
1086
        if ($pid) {
1087
            # parent process
1088
            $ibbackup_pid = $pid;
14 by kinoyasu
using rsync for incremental backup
1089
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1090
            if($option_remote_host) {
17 by kinoyasu
--remote-host uses scp/ssh, remove using rsync
1091
                #direct copy to remote
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
1092
                my $orig_datadir = get_option(\%config, $option_defaults_group, 'datadir');
14 by kinoyasu
using rsync for incremental backup
1093
                my $orig_ibdata_dir =
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
1094
                    get_option(\%config, $option_defaults_group, 'innodb_data_home_dir');
14 by kinoyasu
using rsync for incremental backup
1095
                my $orig_innodb_data_file_path =
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
1096
                    get_option(\%config, $option_defaults_group, 'innodb_data_file_path');
224 by Alexey Kopytov
Bug #606981: linux + o_direct + stream backup = broken?
1097
                my $innodb_flush_method = 
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
1098
                    get_option(\%config, $option_defaults_group, 'innodb_flush_method');
224 by Alexey Kopytov
Bug #606981: linux + o_direct + stream backup = broken?
1099
                my $innodb_use_odirect;
242.11.13 by Alexey Kopytov
Bug #759225: xtrabackup does not support ALL_O_DIRECT for
1100
                $innodb_use_odirect = 1 if $innodb_flush_method =~ m/^(ALL_)?O_DIRECT$/i;
224 by Alexey Kopytov
Bug #606981: linux + o_direct + stream backup = broken?
1101
14 by kinoyasu
using rsync for incremental backup
1102
                my $subdir;
1103
                my @list;
1104
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1105
                if (system("ssh $option_ssh_opt $option_remote_host test -e $backup_dir/ib_logfile0")
1106
                    == 0) {
1107
                    print STDERR "$prefix Remove $option_remote_host:$backup_dir/ib_logfile*\n";
1108
                    system("ssh $option_ssh_opt $option_remote_host rm $backup_dir/ib_logfile\*")
1109
                        and Die "Failed to rm file '$backup_dir/ib_logfile*': $!";
14 by kinoyasu
using rsync for incremental backup
1110
                }
1111
1112
                wait_for_ibbackup_suspend();
1113
1114
                #InnoDB data files from original InnoDB data directory
22 by kinoyasu
"innobackup --stream=tar" is supported
1115
                print STDERR "\n$prefix Starting to backup InnoDB tables and indexes\n";
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1116
                print STDERR "$prefix to '$backup_dir'\n";
22 by kinoyasu
"innobackup --stream=tar" is supported
1117
                print STDERR "$prefix from original InnoDB data directory '$orig_ibdata_dir'\n";
14 by kinoyasu
using rsync for incremental backup
1118
                foreach my $a (split(/;/, $orig_innodb_data_file_path)) {
1119
                    my $path = (split(/:/,$a))[0];
86.1.1 by akuzminsky
Fixed bug#417178
1120
                    $path=~s/([\$\\\" ])/\\$1/g;
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1121
                    print STDERR "$prefix Backing up file '$orig_ibdata_dir/$path'\n";
1122
                    system("scp $option_scp_opt '$orig_ibdata_dir/$path' '$option_remote_host:$backup_dir/$path'")
1123
                      and Die "Failed to scp file '$path': $!";
14 by kinoyasu
using rsync for incremental backup
1124
                }
1125
1126
                #copy *.ibd files
1127
                opendir(DIR, $orig_datadir)
1128
                    || Die "Can't open directory '$orig_datadir': $!\n";
1129
                while (defined($subdir = readdir(DIR))) {
1130
                    my $print_each_file = 0;
1131
                    my $file_c;
1132
                    my $file;
1133
                    if ($subdir eq '.' || $subdir eq '..') { next; }
1134
                    next unless -d "$orig_datadir/$subdir";
1135
                    next unless check_if_required($subdir);
1136
1137
                    @list = glob("$orig_datadir/$subdir/" . '*.ibd');
1138
1139
                    $file_c = @list;
1140
                    if ($file_c <= $backup_file_print_limit) {
1141
                        $print_each_file = 1;
1142
                    } else {
22 by kinoyasu
"innobackup --stream=tar" is supported
1143
                        print STDERR "$prefix Backing up files " .
14 by kinoyasu
using rsync for incremental backup
1144
                            "'$orig_datadir/$subdir/*.ibd' ($file_c files)\n";
1145
                    }
1146
                    foreach $file (@list) {
174 by Vadim Tkachenko
tables_file option is applied to copy via stream also
1147
			next unless check_if_required($subdir, $file);
20 by kinoyasu
innobackup --include=REGEXP with --remote
1148
                        if($option_include) {
504.6.1 by Alexey Kopytov
Bug #1130627: Can't backup individual partitions
1149
                            my $table = get_table_name($file);
1150
                            my $table_part = get_table_name_with_part_suffix($file);
1151
1152
                            if (!("$subdir.$table_part" =~ /$option_include/ ||
1153
                                  "$subdir.$table" =~ /$option_include/)) {
1154
                                if ($print_each_file) {
1155
                                    print STDERR "'$file' is skipped.\n";
1156
                                }
20 by kinoyasu
innobackup --include=REGEXP with --remote
1157
                                next;
1158
                            }
1159
                        }
1160
14 by kinoyasu
using rsync for incremental backup
1161
                        if ($print_each_file) {
22 by kinoyasu
"innobackup --stream=tar" is supported
1162
                            print STDERR "$prefix Backing up file '$file'\n";
1163
                        }
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1164
                        if (system("ssh $option_ssh_opt $option_remote_host test -e $backup_dir/$subdir")
1165
                            != 0) {
1166
                          system("ssh $option_ssh_opt $option_remote_host mkdir $backup_dir/$subdir");
22 by kinoyasu
"innobackup --stream=tar" is supported
1167
                        }
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1168
                        system("scp $option_scp_opt '$file' '$option_remote_host:$backup_dir/$subdir/'")
1169
                          and Die "Failed to scp file '$file': $!";
1170
		      }
14 by kinoyasu
using rsync for incremental backup
1171
                }
1172
                closedir(DIR);
1173
            }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1174
        } else {
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1175
            if($option_remote_host) {
17 by kinoyasu
--remote-host uses scp/ssh, remove using rsync
1176
                open(STDOUT, "> $tmp_logfile")
1177
                || Die "Failed to open file '$tmp_logfile': $!"
14 by kinoyasu
using rsync for incremental backup
1178
            }
1179
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1180
            # child process
1181
            exec($cmdline) || Die "Failed to exec ibbackup: $!";
1182
        }
1183
    } else {
1184
        Die "failed to fork ibbackup child process: $!";
1185
    }
1186
}
1187
                  
1188
1189
#
1190
# get_mysql_options subroutine returns the options to mysql client program
1191
# as a string. The options are determined from the options given by the
1192
# user to innobackup.
1193
#
1194
sub get_mysql_options {
114.2.1 by Daniel Nichter
Fix bug 510964: innobackupex doesn't pass --defaults-files to mysql child proc
1195
    my $options = '';
1196
1197
    # this option has to be first
1198
    if ($option_defaults_file) {
211.1.2 by Valentine Gostev
Added fix for bug 688211 (additional single quotes)
1199
        $options = "$options --defaults-file='$option_defaults_file'";
114.2.1 by Daniel Nichter
Fix bug 510964: innobackupex doesn't pass --defaults-files to mysql child proc
1200
    }
1201
487.3.1 by George O. Lorch III
Incorporated patch for Bug #740489 : Add --defaults-extra-file param to innobackupex
1202
    if ($option_defaults_extra_file) {
1203
        $options = $options . " --defaults-extra-file=\"$option_defaults_extra_file\" ";
1204
    }
1205
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1206
    if ($option_mysql_password) {
211.1.2 by Valentine Gostev
Added fix for bug 688211 (additional single quotes)
1207
        $options = "$options --password='$option_mysql_password'";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1208
    }
1209
    if ($option_mysql_user) {
211.1.2 by Valentine Gostev
Added fix for bug 688211 (additional single quotes)
1210
        $options = "$options --user='$option_mysql_user'";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1211
    }
116.1.1 by Daniel Nichter
Bug 510965: add --host, remove --host=127.0.0.1 from --port.
1212
    if ($option_mysql_host) {
211.1.2 by Valentine Gostev
Added fix for bug 688211 (additional single quotes)
1213
        $options = "$options --host='$option_mysql_host'";
116.1.1 by Daniel Nichter
Bug 510965: add --host, remove --host=127.0.0.1 from --port.
1214
    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1215
    if ($option_mysql_port) {
211.1.2 by Valentine Gostev
Added fix for bug 688211 (additional single quotes)
1216
        $options = "$options --port='$option_mysql_port'";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1217
    }
1218
    if ($option_mysql_socket) {
211.1.2 by Valentine Gostev
Added fix for bug 688211 (additional single quotes)
1219
        $options = "$options --socket='$option_mysql_socket'";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1220
    }
114.2.1 by Daniel Nichter
Fix bug 510964: innobackupex doesn't pass --defaults-files to mysql child proc
1221
    $options = "$options --unbuffered --";
1222
    return $options;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1223
}
1224
1225
1226
#
242.25.3 by Alexey Kopytov
Bug #408803: innodbbackupex reaches Servers wait_timeout
1227
# Check that the server is responding to queries
1228
#
1229
sub mysql_ping {
242.32.3 by Alexey Kopytov
Don't do file io inside a signal handler as that breaks system() calls.
1230
    my $alarm_handler = shift;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1231
    my $mysql_pid_copy = $mysql_pid;
1232
1233
    # send a dummy query to mysql child process
1234
    $hello_id++;
242.25.3 by Alexey Kopytov
Bug #408803: innodbbackupex reaches Servers wait_timeout
1235
1236
    my $hello_message = "xtrabackup ping $hello_id";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1237
    print MYSQL_WRITER "select '$hello_message';\n" 
1238
        or Die "Connection to mysql child process failed: $!";
1239
242.32.3 by Alexey Kopytov
Don't do file io inside a signal handler as that breaks system() calls.
1240
    # Don't check server's response if running in a signal handler
1241
    # because that breaks system() calls
1242
    if ($alarm_handler)
1243
    {
1244
	return 0;
1245
    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1246
    # wait for reply
1247
    eval {
1248
        local $SIG{ALRM} = sub { die "alarm clock restart" };
1249
        my $stdout = '';
1250
        my $stderr = '';
1251
        alarm $mysql_response_timeout;
1252
        while (index($stdout, $hello_message) < 0) {
1253
            sleep 2;
1254
            if ($mysql_pid && $mysql_pid == waitpid($mysql_pid, &WNOHANG)) {
1255
                my $reason = `cat $mysql_stderr`;
1256
                $mysql_pid = '';
1257
                die "mysql child process has died: $reason";
1258
            }
1259
            $stdout = `cat $mysql_stdout`;
163 by Aleksandr Kuzminsky
suppress warnings in error detecting function
1260
            $stderr = `cat $mysql_stderr | grep -v ^Warning`;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1261
            if ($stderr) {
1262
                # mysql has reported an error, do exit
1263
                die "mysql error: $stderr";
1264
            }
1265
        }
1266
        alarm 0;
1267
    };
1268
    if ($@ =~ /alarm clock restart/) {
1269
        Die "Connection to mysql child process (pid=$mysql_pid_copy) timedout."
1270
            . " (Time limit of $mysql_response_timeout seconds exceeded."
1271
            . " You may adjust time limit by editing the value of parameter"
1272
            . " \"\$mysql_response_timeout\" in this script.)";
1273
    } elsif ($@) { Die $@; }
242.25.3 by Alexey Kopytov
Bug #408803: innodbbackupex reaches Servers wait_timeout
1274
}
1275
1276
1277
#
1278
# SIGALRM handler which sends a keepalive query to the server
1279
#
1280
sub catch_sigalrm {
242.32.3 by Alexey Kopytov
Don't do file io inside a signal handler as that breaks system() calls.
1281
  mysql_ping(1);
242.25.3 by Alexey Kopytov
Bug #408803: innodbbackupex reaches Servers wait_timeout
1282
  # Reschedule SIGALRM
1283
  alarm $mysql_keep_alive;
1284
}
1285
1286
1287
#
1288
# Schedule periodic server pings
1289
#
1290
sub start_keepalives {
1291
  $SIG{ALRM} = \&catch_sigalrm;
1292
  alarm $mysql_keep_alive;
1293
}
1294
1295
#
1296
# Cancel periodic server pings
1297
#
1298
sub stop_keepalives {
1299
  alarm 0;
1300
  $SIG{ALRM} = "DEFAULT";
1301
}
1302
1303
#
1304
# mysql_open subroutine starts mysql as a child process with
1305
# a pipe connection.
1306
#
1307
sub mysql_open {
1308
    my $options = get_mysql_options();
1309
    # run mysql as a child process with a pipe connection
1310
    $now = current_time();
330 by Alexey Kopytov
Manual merge from 1.6.
1311
    (my $prt_options = $options) =~ s/--password=[^ ]+ /--password=xxxxxxxx /g;
1312
    print STDERR "$now  $prefix Starting mysql with options: $prt_options\n";
242.25.3 by Alexey Kopytov
Bug #408803: innodbbackupex reaches Servers wait_timeout
1313
    $mysql_pid = open(*MYSQL_WRITER, "| mysql $options >$mysql_stdout 2>$mysql_stderr ") or Die "Failed to spawn mysql child process: $!";
1314
    MYSQL_WRITER->autoflush(1);
1315
    $now = current_time();
1316
    print STDERR "$now  $prefix Connected to database with mysql child process (pid=$mysql_pid)\n";
330 by Alexey Kopytov
Manual merge from 1.6.
1317
    print MYSQL_WRITER "SET SESSION wait_timeout = 2147000;\n" or die "Connection to mysql child process failed: $!";
242.25.3 by Alexey Kopytov
Bug #408803: innodbbackupex reaches Servers wait_timeout
1318
242.32.3 by Alexey Kopytov
Don't do file io inside a signal handler as that breaks system() calls.
1319
    mysql_ping(0);
242.25.3 by Alexey Kopytov
Bug #408803: innodbbackupex reaches Servers wait_timeout
1320
1321
    start_keepalives();
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1322
}
1323
1324
1325
#
1326
# mysql_send subroutine send a request string to mysql child process.
1327
# This subroutine appends a newline character to the request and checks 
1328
# that mysqld receives the query.
1329
# Parameters:
1330
#    request  request string
1331
#
1332
sub mysql_send {
1333
    my $request = shift;
1334
242.25.3 by Alexey Kopytov
Bug #408803: innodbbackupex reaches Servers wait_timeout
1335
    stop_keepalives();
1336
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1337
    $current_mysql_request = $request;
1338
    print MYSQL_WRITER "$request\n";
242.32.3 by Alexey Kopytov
Don't do file io inside a signal handler as that breaks system() calls.
1339
    mysql_ping(0);
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1340
    $current_mysql_request = '';
242.25.3 by Alexey Kopytov
Bug #408803: innodbbackupex reaches Servers wait_timeout
1341
1342
    start_keepalives();
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1343
}
1344
    
1345
1346
#
1347
# mysql_close subroutine terminates mysql child process gracefully.
1348
# 
1349
sub mysql_close {
242.25.3 by Alexey Kopytov
Bug #408803: innodbbackupex reaches Servers wait_timeout
1350
    stop_keepalives();
1351
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1352
    print MYSQL_WRITER "quit\n";
1353
    $now = current_time();
22 by kinoyasu
"innobackup --stream=tar" is supported
1354
    print STDERR "$now  $prefix Connection to database server closed\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1355
    $mysql_pid = '';
1356
}
1357
1358
1359
#
1360
# write_binlog_info subroutine retrieves MySQL binlog position and
1361
# saves it in a file. It also prints it to stdout.
1362
#
1363
sub write_binlog_info {
1364
    my @lines;
1365
    my $position = '';
1366
    my $filename = '';
1367
1368
    # get binlog position
242.55.4 by Alexey Kopytov
Bug #977101: --safe-slave-backup results in incorrect binlog info
1369
    mysql_send 'SHOW MASTER STATUS\G';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1370
242.55.4 by Alexey Kopytov
Bug #977101: --safe-slave-backup results in incorrect binlog info
1371
    # get the name of the last binlog file and position in it
1372
    # from the SHOW MASTER STATUS output
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1373
    file_to_array($mysql_stdout, \@lines);
242.55.4 by Alexey Kopytov
Bug #977101: --safe-slave-backup results in incorrect binlog info
1374
    foreach (@lines) {
1375
        $filename = $1 if /^\s+File:\s(\S+)\s*$/;
1376
        $position = $1 if /^\s+Position:\s(\d+)\s*$/;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1377
    }
1378
1379
    # write binlog info file
15 by kinoyasu
trial implementation of --remote-host when --incremental (innobackup)
1380
    if (!$option_remote_host) {
1381
        open(FILE, ">$binlog_info") || 
1382
            Die "Failed to open file '$binlog_info': $!";
1383
    } else {
371 by Alexey Kopytov
Cherrypick of fix for bug 733658: pass options to both ssh and scp.
1384
        open(FILE, "| ssh $option_ssh_opt $option_remote_host 'cat > $binlog_info'") ||
15 by kinoyasu
trial implementation of --remote-host when --incremental (innobackup)
1385
            Die "Failed to open file '$option_remote_host:$binlog_info': $!";
1386
    }
242.55.4 by Alexey Kopytov
Bug #977101: --safe-slave-backup results in incorrect binlog info
1387
    print FILE  "$filename\t$position\t\t\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1388
    close(FILE);
1389
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1390
    if ($option_stream) {
1391
        system("cd $option_tmpdir; $stream_cmd xtrabackup_binlog_info")
22 by kinoyasu
"innobackup --stream=tar" is supported
1392
            and Die "Failed to stream 'xtrabackup_binlog_info': $!";
1393
        unlink $binlog_info || Die "Failed to delete '$binlog_info': $!";
1394
    }
1395
242.55.4 by Alexey Kopytov
Bug #977101: --safe-slave-backup results in incorrect binlog info
1396
    $mysql_binlog_position = "filename '$filename', position $position";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1397
}
1398
353 by Alexey Kopytov
Cherrypick of Galera support.
1399
#
1400
# write_galera_info subroutine retrieves MySQL Galera and
1401
# saves it in a file. It also prints it to stdout.
1402
#
1403
sub write_galera_info {
1404
    my @lines;
1405
    my @info_lines = ();
1406
    my $position = '';
1407
    my $filename = '';
1408
1409
    # get binlog position
1410
    mysql_send "SHOW STATUS LIKE 'wsrep_local_state_uuid';";
1411
    mysql_send "SHOW STATUS LIKE 'wsrep_last_committed';";
1412
1413
    # get "show master status" output lines (2) from mysql output
1414
    file_to_array($mysql_stdout, \@lines);
1415
1416
    open(FILE, ">$galera_info") || 
1417
         Die "Failed to open file '$galera_info': $!";
1418
1419
    foreach my $line (@lines) {
1420
        if ($line =~ m/wsrep_local_state_uuid/) {
1421
	    $line =~ s/wsrep_local_state_uuid\s*//g;
1422
            print FILE  "$line:";
1423
        }
1424
    }
1425
1426
    foreach my $line (@lines) {
1427
        if ($line =~ m/wsrep_last_committed/) {
1428
	    $line =~ s/wsrep_last_committed\s*//g;
1429
            print FILE  "$line\n";
1430
        }
1431
    }
1432
1433
    close(FILE);
1434
419.1.1 by Sergei Glushchenko
Bug #983720: ib_lru_dump and --galera-info fail with --stream=xbstream
1435
    if ($option_stream) {
1436
        system("cd $option_tmpdir; $stream_cmd xtrabackup_galera_info")
353 by Alexey Kopytov
Cherrypick of Galera support.
1437
            and Die "Failed to stream 'xtrabackup_galera_info': $!";
1438
        unlink $galera_info || Die "Failed to delete '$galera_info': $!";
1439
    }
1440
1441
}
1442
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1443
1444
# 
1445
# write_slave_info subroutine retrieves MySQL binlog position of the
1446
# master server in a replication setup and saves it in a file. It
1447
# also saves it in $msql_slave_position variable.
1448
#
1449
sub write_slave_info {
1450
    my @lines;
1451
    my @info_lines;
1452
    my $position = '';
1453
    my $filename = '';
1454
    my $master= '';
1455
	
1456
    # get slave status. Use single quotes here, otherwise
1457
    # \G is evaluated as a control character.
242.55.4 by Alexey Kopytov
Bug #977101: --safe-slave-backup results in incorrect binlog info
1458
    mysql_send 'SHOW SLAVE STATUS\G';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1459
1460
    # get output of the "show slave status" command from mysql output
1461
    # and extract binlog position of the master server
1462
    file_to_array($mysql_stdout, \@lines);
1463
    for (@lines) {
1464
        $master = $1 if /Master_Host:\s*(\S*)\s*$/;
1465
        $filename = $1 if /Master_Log_File:\s*(\S*)\s*$/;
1466
        $position = $1 if /Master_Log_Pos:\s*(\S*)\s*$/;
1467
    }
1468
1469
    # print slave status to a file
15 by kinoyasu
trial implementation of --remote-host when --incremental (innobackup)
1470
    if (!$option_remote_host) {
1471
        open(FILE, ">$slave_info") || 
1472
            Die "Failed to open file '$slave_info': $!";
1473
    } else {
371 by Alexey Kopytov
Cherrypick of fix for bug 733658: pass options to both ssh and scp.
1474
        open(FILE, "| ssh $option_ssh_opt $option_remote_host 'cat > $slave_info'") ||
15 by kinoyasu
trial implementation of --remote-host when --incremental (innobackup)
1475
            Die "Failed to open file '$option_remote_host:$slave_info': $!";
1476
    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1477
    print FILE  "CHANGE MASTER TO MASTER_LOG_FILE='$filename', MASTER_LOG_POS=$position\n";
1478
    close(FILE);
1479
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1480
    if ($option_stream) {
1481
        system("cd $option_tmpdir; $stream_cmd xtrabackup_slave_info")
22 by kinoyasu
"innobackup --stream=tar" is supported
1482
            and Die "Failed to stream 'xtrabackup_slave_info': $!";
1483
        unlink $slave_info || Die "Failed to delete '$slave_info': $!";
1484
    }
1485
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1486
    $mysql_slave_position = "master host '$master', filename '$filename', position $position";
1487
}
1488
1489
1490
#
1491
# mysql_lockall subroutine puts a read lock on all tables in all databases.
1492
# 
1493
sub mysql_lockall {
1494
    $now = current_time();
22 by kinoyasu
"innobackup --stream=tar" is supported
1495
    print STDERR "$now  $prefix Starting to lock all tables...\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1496
1497
    mysql_send "USE mysql;";
89 by kinoyasu
fix bug 386535, bug 402884, probability to crash --prepare
1498
#    mysql_send "DROP TABLE IF EXISTS ibbackup_binlog_marker;";
1499
#    if (compare_versions($mysql_server_version, '4.1.0') == -1) {
1500
#        # MySQL server version is 4.0 or older, ENGINE keyword not supported
1501
#        mysql_send "CREATE TABLE ibbackup_binlog_marker(a INT) TYPE=INNODB;";
1502
#    } else {
1503
#        # MySQL server version is 4.1 or newer, use ENGINE keyword
1504
#        mysql_send "CREATE TABLE ibbackup_binlog_marker(a INT) ENGINE=INNODB;";
1505
#    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1506
    mysql_send "SET AUTOCOMMIT=0;";
89 by kinoyasu
fix bug 386535, bug 402884, probability to crash --prepare
1507
#    mysql_send "INSERT INTO ibbackup_binlog_marker VALUES (1);";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1508
    if (compare_versions($mysql_server_version, '4.0.22') == 0
1509
        || compare_versions($mysql_server_version, '4.1.7') == 0) {
1510
        # MySQL server version is 4.0.22 or 4.1.7
1511
        mysql_send "COMMIT;";
1512
        mysql_send "FLUSH TABLES WITH READ LOCK;";
1513
    } else {
1514
        # MySQL server version is other than 4.0.22 or 4.1.7
1515
        mysql_send "FLUSH TABLES WITH READ LOCK;";
1516
        mysql_send "COMMIT;";
1517
    }
1518
    write_binlog_info;
353 by Alexey Kopytov
Cherrypick of Galera support.
1519
    write_galera_info if $option_galera_info;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1520
	
1521
    $now = current_time();
22 by kinoyasu
"innobackup --stream=tar" is supported
1522
    print STDERR "$now  $prefix All tables locked and flushed to disk\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1523
}
1524
1525
1526
#
1527
# mysql_unlockall subroutine releases read locks on all tables in all 
1528
# databases.
1529
# 
1530
sub mysql_unlockall {
1531
    mysql_send "UNLOCK TABLES;";
89 by kinoyasu
fix bug 386535, bug 402884, probability to crash --prepare
1532
#    mysql_send "DROP TABLE IF EXISTS ibbackup_binlog_marker;";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1533
1534
    $now = current_time();
22 by kinoyasu
"innobackup --stream=tar" is supported
1535
    print STDERR "$now  $prefix All tables unlocked\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1536
}
1537
1538
1539
#
1540
# catch_sigpipe subroutine is a signal handler for SIGPIPE.
1541
#
1542
sub catch_sigpipe {
1543
    my $rcode;
1544
1545
    if ($mysql_pid && (-1 == ($rcode = waitpid($mysql_pid, &WNOHANG))
1546
                       || $rcode == $mysql_pid)) {
1547
        my $reason = `cat $mysql_stderr`;
22 by kinoyasu
"innobackup --stream=tar" is supported
1548
        print STDERR "Pipe to mysql child process broken: $reason at";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1549
        system("date +'%H:%M:%S'");
1550
        exit(1);
1551
    } else {
1552
        Die "Broken pipe";
1553
    }
1554
}
1555
1556
1557
#
1558
# kill_child_processes subroutine kills all child processes of this process.
1559
#
1560
sub kill_child_processes {
1561
    if ($ibbackup_pid) {
1562
        kill($kill_signal, $ibbackup_pid);
1563
        $ibbackup_pid = '';
1564
    }
1565
    
1566
    if ($mysql_pid) {
1567
        kill($kill_signal, $mysql_pid);
1568
        $mysql_pid = '';
1569
    }
1570
}
1571
1572
1573
#
1574
# require_external subroutine checks that an external program is runnable
1575
# via the shell. This is tested by calling the program with the
1576
# given arguments. It is checked that the program returns 0 and does 
1577
# not print anything to stderr. If this check fails, this subroutine exits.
1578
#    Parameters:
1579
#       program      pathname of the program file
1580
#       args         arguments to the program
1581
#       pattern      a string containing a regular expression for finding 
1582
#                    the program version.
1583
#                    this pattern should contain a subpattern enclosed
1584
#                    in parentheses which is matched with the version.
1585
#       version_ref  a reference to a variable where the program version
1586
#                    string is returned. Example "2.0-beta2".
1587
#
1588
sub require_external {
1589
    my $program = shift;
1590
    my $args = shift;
1591
    my $pattern = shift;
1592
    my $version_ref = shift;
1593
    my @lines;
1594
    my $tmp_stdout = tmpnam();
1595
    my $tmp_stderr = tmpnam();
1596
    my $rcode;
1597
    my $error;
1598
1599
    $rcode = system("$program $args >$tmp_stdout 2>$tmp_stderr");
1600
    if ($rcode) {
1601
        $error = $!;
1602
    }
163 by Aleksandr Kuzminsky
suppress warnings in error detecting function
1603
    my $stderr = `cat $tmp_stderr | grep -v ^Warning`;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1604
    unlink $tmp_stderr;
1605
    if ($stderr ne '') {
1606
        # failure
1607
        unlink $tmp_stdout;
1608
        Die "Couldn't run $program: $stderr";
1609
    } elsif ($rcode) {
1610
        # failure
1611
        unlink $tmp_stdout;
1612
        Die "Couldn't run $program: $error";
1613
    }
1614
1615
    # success
1616
    my $stdout = `cat $tmp_stdout`;
1617
    unlink $tmp_stdout;
1618
    @lines = split(/\n|;/,$stdout);
22 by kinoyasu
"innobackup --stream=tar" is supported
1619
    print STDERR "$prefix Using $lines[0]\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1620
1621
    # get version string from the first output line of the program
1622
    ${$version_ref} = '';
1623
    if ($lines[0] =~ /$pattern/) {
1624
        ${$version_ref} = $1;
1625
    }
1626
}
1627
1628
1629
# compare_versions subroutine compares two GNU-style version strings.
1630
# A GNU-style version string consists of three decimal numbers delimitted 
1631
# by dots, and optionally followed by extra attributes.
1632
# Examples: "4.0.1", "4.1.1-alpha-debug". 
1633
#    Parameters:
1634
#       str1   a GNU-style version string
1635
#       str2   a GNU-style version string
1636
#    Return value:
1637
#       -1   if str1 < str2
1638
#        0   if str1 == str2
1639
#        1   is str1 > str2
1640
sub compare_versions {
1641
    my $str1 = shift;
1642
    my $str2 = shift;
1643
    my $extra1 = '';
1644
    my $extra2 = '';
1645
    my @array1 = ();
1646
    my @array2 = ();
1647
    my $i;
1648
1649
    # remove possible extra attributes
1650
    ($str1, $extra1) = $str1 =~ /^([0-9.]*)(.*)/;
1651
    ($str2, $extra2) = $str2 =~ /^([0-9.]*)(.*)/;
1652
1653
    # split "dotted" decimal number string into an array
1654
    @array1 = split('\.', $str1);
1655
    @array2 = split('\.', $str2);
1656
1657
    # compare in lexicographic order
1658
    for ($i = 0; $i <= $#array1 && $i <= $#array2; $i++) {
1659
        if ($array1[$i] < $array2[$i]) {
1660
            return -1;
1661
        } elsif ($array1[$i] > $array2[$i]) {
1662
            return 1;
1663
        }
1664
    }
1665
    if ($#array1 < $#array2) {
1666
        return -1;
1667
    } elsif ($#array1 > $#array2) {
1668
        return 1;
1669
    } else {
1670
        return 0;
1671
    }
1672
}
1673
1674
1675
#
1676
# init subroutine initializes global variables and performs some checks on the
1677
# system we are running on.
1678
#
1679
sub init {
1680
    my $mysql_version = '';
1681
    my $ibbackup_version = '';
1682
    my $run = '';
1683
1684
    # print some instructions to the user
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
1685
    if (!$option_apply_log && !$option_copy_back && !$option_move_back) {
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1686
        $run = 'backup';
1687
    } elsif ($option_copy_back) {
1688
        $run = 'copy-back';
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
1689
    } elsif ($option_move_back) {
1690
        $run = 'move-back';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1691
    } else {
1692
        $run = 'apply-log';
1693
    }
22 by kinoyasu
"innobackup --stream=tar" is supported
1694
    print STDERR "IMPORTANT: Please check that the $run run completes successfully.\n";
109.3.1 by Aleksandr Kuzminsky
Fixed Bug #463709: The script outputs its own name
1695
    print STDERR "           At the end of a successful $run run $innobackup_script\n";
1696
    print STDERR "           prints \"completed OK!\".\n\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1697
1698
    # check that MySQL client program and InnoDB Hot Backup program
1699
    # are runnable via shell
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
1700
    if (!$option_copy_back && !$option_move_back) {
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1701
        # we are making a backup or applying log to backup
1702
        if (!$option_apply_log) {
1703
            # we are making a backup, we need mysql server
1704
            my $output = '';
1705
            my @lines = ();
1706
1707
            # check that we have mysql client program
1708
            require_external('mysql', '--version', 'Ver ([^,]+)', 
1709
                             \$mysql_version);
1710
            
1711
            # get mysql server version
1712
            my $options = get_mysql_options();
1713
            @lines = split('\n', 
108.1.1 by Aleksandr Kuzminsky
Fixed number of issues in innobackupex-1.5.1 on windows platform
1714
                           `mysql $options -e "select \@\@version"`);
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1715
            $mysql_server_version = $lines[1];
22 by kinoyasu
"innobackup --stream=tar" is supported
1716
            print STDERR "$prefix Using mysql server version $mysql_server_version\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1717
        }
1718
        #require_external($option_ibbackup_binary, '--license', 
1719
        #                 'version (\S+)', \$ibbackup_version);
22 by kinoyasu
"innobackup --stream=tar" is supported
1720
        print STDERR "\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1721
        
1722
        if ($option_include 
1723
            && $ibbackup_version 
1724
            && $ibbackup_version le "2.0") {
1725
            # --include option was given, but ibbackup is too
1726
            # old to support it
1727
            Die "--include option was given, but ibbackup is too old"
1728
                . " to support it. You must upgrade to InnoDB Hot Backup"
1729
                . " v2.0 in order to use --include option.\n";
1730
        }
1731
    }
1732
    
1733
    # set signal handlers
1734
    $SIG{PIPE} = \&catch_sigpipe;
1735
1736
    # read MySQL options file
1737
    #read_config_file($config_file, \%config);
1738
    read_config_file(\%config);
1739
22 by kinoyasu
"innobackup --stream=tar" is supported
1740
    if(!$option_tmpdir) {
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
1741
        $option_tmpdir = get_option(\%config, $option_defaults_group, 'tmpdir');
22 by kinoyasu
"innobackup --stream=tar" is supported
1742
    }
1743
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1744
    # get innodb log home directory from options file
1745
    #$innodb_log_group_home_dir = 
1746
    #    get_option(\%config, 'mysqld', 'innodb_log_group_home_dir');
1747
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
1748
    if (!$option_apply_log && !$option_copy_back && !$option_move_back) {
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1749
        # we are making a backup, create a new backup directory
17 by kinoyasu
--remote-host uses scp/ssh, remove using rsync
1750
        if (!$option_remote_host) {
14 by kinoyasu
using rsync for incremental backup
1751
            $backup_dir = File::Spec->rel2abs(make_backup_dir());
1752
        } else {
17 by kinoyasu
--remote-host uses scp/ssh, remove using rsync
1753
            $backup_dir = make_backup_dir();
14 by kinoyasu
using rsync for incremental backup
1754
        }
22 by kinoyasu
"innobackup --stream=tar" is supported
1755
        print STDERR "$prefix Created backup directory $backup_dir\n";
1756
        if (!$option_remote_host && !$option_stream) {
14 by kinoyasu
using rsync for incremental backup
1757
        $backup_config_file = $backup_dir . '/backup-my.cnf';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1758
        $suspend_file = $backup_dir . '/xtrabackup_suspended';
1759
        $binlog_info = $backup_dir . '/xtrabackup_binlog_info';
353 by Alexey Kopytov
Cherrypick of Galera support.
1760
        $galera_info = $backup_dir . '/xtrabackup_galera_info';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1761
        $slave_info = $backup_dir . '/xtrabackup_slave_info';
15 by kinoyasu
trial implementation of --remote-host when --incremental (innobackup)
1762
        } else {
374 by Alexey Kopytov
Cherrypick of fix for placement of xtrabackup_suspended and xtrabackup_checkpoint.
1763
        $suspend_file = $option_tmpdir . '/xtrabackup_suspended';
22 by kinoyasu
"innobackup --stream=tar" is supported
1764
        $tmp_logfile = $option_tmpdir . '/xtrabackup_logfile';
1765
        if ($option_stream) {
1766
            $backup_config_file = $option_tmpdir . '/backup-my.cnf';
1767
            $binlog_info = $option_tmpdir . '/xtrabackup_binlog_info';
353 by Alexey Kopytov
Cherrypick of Galera support.
1768
            $galera_info = $option_tmpdir . '/xtrabackup_galera_info';
22 by kinoyasu
"innobackup --stream=tar" is supported
1769
            $slave_info = $option_tmpdir . '/xtrabackup_slave_info';
1770
        } else {
1771
            $backup_config_file = $backup_dir . '/backup-my.cnf';
1772
            $binlog_info = $backup_dir . '/xtrabackup_binlog_info';
353 by Alexey Kopytov
Cherrypick of Galera support.
1773
            $galera_info = $backup_dir . '/xtrabackup_galera_info';
22 by kinoyasu
"innobackup --stream=tar" is supported
1774
            $slave_info = $backup_dir . '/xtrabackup_slave_info';
1775
        }
15 by kinoyasu
trial implementation of --remote-host when --incremental (innobackup)
1776
        }
1777
        write_backup_config_file($backup_config_file);
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
1778
    } elsif ($option_copy_back || $option_move_back) {
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1779
        #$backup_config_file = $backup_dir . '/backup-my.cnf';
1780
        #read_config_file($backup_config_file, \%backup_config);
487.2.1 by George O. Lorch III
Fixed https://bugs.launchpad.net/percona-xtrabackup/+bug/1007446
1781
    }
1782
1783
    if ( -e "$suspend_file" ) {
1784
        print STDERR "WARNING : A left over instance of suspend file '$suspend_file' was found.\n";
1785
        unlink $suspend_file || Die "Failed to delete '$suspend_file': $!";
1786
    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1787
}
1788
1789
1790
#
1791
# write_backup_config_file subroutine creates a backup options file for
1792
# ibbackup program. It writes to the file only those options that
1793
# are required by ibbackup.
1794
#    Parameters:
1795
#       filename  name for the created options file
1796
#
1797
sub write_backup_config_file {
1798
    my $filename = shift;
42 by kinoyasu
fix bug 357653; remove innobackup-1.5.1.patch
1799
15 by kinoyasu
trial implementation of --remote-host when --incremental (innobackup)
1800
    if (!$option_remote_host) {
1801
        open(FILE, "> $filename") || Die "Failed to open file '$filename': $!";
1802
    } else {
371 by Alexey Kopytov
Cherrypick of fix for bug 733658: pass options to both ssh and scp.
1803
        open(FILE, "| ssh $option_ssh_opt $option_remote_host 'cat > $filename'")
15 by kinoyasu
trial implementation of --remote-host when --incremental (innobackup)
1804
            || Die "Failed to open file '$option_remote_host:$filename': $!";
1805
    }
1806
242.44.1 by Sergei Glushchenko
Bug #733651
1807
    my @option_names = (
242.53.1 by Sergei Glushchenko
Bug 983685: innodb_data_file_path is not written to backup-my.cnf
1808
        "innodb_data_file_path",
242.44.1 by Sergei Glushchenko
Bug #733651
1809
        "innodb_log_files_in_group",
1810
        "innodb_log_file_size",
1811
        "innodb_fast_checksum",
1812
        "innodb_page_size",
471.5.1 by Sergei Glushchenko
Bug #1066843: Fix for bug #932623 does not take separate doublewrite
1813
        "innodb_log_block_size"
242.44.1 by Sergei Glushchenko
Bug #733651
1814
        );
1815
1816
    my $options_dump = "# This MySQL options file was generated by $innobackup_script.\n\n" .
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1817
          "# The MySQL server\n" .
242.47.10 by Sergei Glushchenko
Bug 996493: innobackupex --apply-log doesn't read config from backup-my.cnf
1818
          "[mysqld]\n";
242.44.1 by Sergei Glushchenko
Bug #733651
1819
1820
    my $option_name;
1821
    foreach $option_name (@option_names) {
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
1822
        if (has_option(\%config, $option_defaults_group, $option_name)) {
1823
            my $option_value = get_option(\%config, $option_defaults_group, $option_name);
242.44.1 by Sergei Glushchenko
Bug #733651
1824
            $options_dump .= "$option_name=$option_value\n";
1825
        }
1826
    }
471.5.1 by Sergei Glushchenko
Bug #1066843: Fix for bug #932623 does not take separate doublewrite
1827
    if (has_option(\%config,
1828
        $option_defaults_group, "innodb_doublewrite_file")) {
1829
        $options_dump .= "innodb_doublewrite_file=" . (split(/\/+/,
1830
                get_option(\%config, $option_defaults_group,
1831
                            'innodb_doublewrite_file')))[-1] . "\n";
1832
    }
242.44.1 by Sergei Glushchenko
Bug #733651
1833
1834
    print FILE $options_dump;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1835
    close(FILE);
22 by kinoyasu
"innobackup --stream=tar" is supported
1836
1837
    if ($option_stream) {
109.1.1 by Aleksandr Kuzminsky
Fixed Bug #434486: Using dirname(), basename() instead of manual parsing of filenames
1838
        my $filename_dir = dirname($filename);
1839
        my $filename_name = basename($filename);
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1840
	system("cd $filename_dir; $stream_cmd $filename_name")
1841
	  and Die "Failed to stream '$filename_name': $!";
1842
22 by kinoyasu
"innobackup --stream=tar" is supported
1843
        unlink $filename || Die "Failed to delete '$filename': $!";
1844
    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1845
}
1846
1847
1848
#
1849
# check_args subroutine checks command line arguments. If there is a problem,
1850
# this subroutine prints error message and exits.
1851
#
1852
sub check_args {
1853
    my $i;
1854
    my $rcode;
1855
    my $buf;
1856
    my $perl_version;
1857
1858
    # check the version of the perl we are running
1859
    if (!defined $^V) {
1860
        # this perl is prior to 5.6.0 and uses old style version string
1861
        my $required_version = $required_perl_version_old_style;
1862
        if ($] lt $required_version) {
22 by kinoyasu
"innobackup --stream=tar" is supported
1863
            print STDERR "$prefix Warning: " . 
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1864
                "Your perl is too old! Innobackup requires\n";
22 by kinoyasu
"innobackup --stream=tar" is supported
1865
            print STDERR "$prefix Warning: perl $required_version or newer!\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1866
        }
1867
    }
1868
1869
    if (@ARGV == 0) {
1870
        # no command line arguments
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
1871
        print STDERR "$prefix You must specify the backup directory.\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1872
        exit(1);
1873
    }
1874
1875
    # read command line options
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1876
    $rcode = GetOptions('compress' => \$option_compress,
1877
	    		'compress-threads=i' => \$option_compress_threads,
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1878
                        'help' => \$option_help,
1879
                        'version' => \$option_version,
1880
                        'throttle=i' => \$option_throttle,
1881
                        'sleep=i' => \$option_sleep,
1882
                        'apply-log' => \$option_apply_log,
181 by root
added --redo-only option to innobackupex
1883
                        'redo-only' => \$option_redo_only,
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1884
                        'copy-back' => \$option_copy_back,
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
1885
                        'move-back' => \$option_move_back,
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1886
                        'include=s' => \$option_include,
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
1887
                        'databases=s' => \$option_databases,
1888
                        'tables-file=s', => \$option_tables_file,
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1889
                        'use-memory=s' => \$option_use_memory,
1890
                        'uncompress' => \$option_uncompress,
61 by kinoyasu
innobackupex can pass --export option
1891
                        'export' => \$option_export,
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1892
                        'password=s' => \$option_mysql_password,
1893
                        'user=s' => \$option_mysql_user,
116.1.1 by Daniel Nichter
Bug 510965: add --host, remove --host=127.0.0.1 from --port.
1894
                        'host=s' => \$option_mysql_host,
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1895
                        'port=s' => \$option_mysql_port,
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
1896
                        'defaults-group=s' => \$option_defaults_group,
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1897
                        'slave-info' => \$option_slave_info,
353 by Alexey Kopytov
Cherrypick of Galera support.
1898
                        'galera-info' => \$option_galera_info,
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1899
                        'socket=s' => \$option_mysql_socket,
1900
                        'no-timestamp' => \$option_no_timestamp,
36 by kinoyasu
some small fixes of innobackupex: bug 355214, bug 356776, etc
1901
                        'defaults-file=s' => \$option_defaults_file,
487.3.1 by George O. Lorch III
Incorporated patch for Bug #740489 : Add --defaults-extra-file param to innobackupex
1902
                        'defaults-extra-file=s' => \$option_defaults_extra_file,
14 by kinoyasu
using rsync for incremental backup
1903
                        'incremental' => \$option_incremental,
130 by Vadim Tkachenko
bugfix 546876
1904
                        'incremental-basedir=s' => \$option_incremental_basedir,
219 by Vadim Tkachenko
Added option --incremental-lsn to innobackupex script.
1905
                        'incremental-lsn=s' => \$option_incremental_lsn,
218 by Vadim Tkachenko
Added option --incremental-dir to innobackupex script
1906
                        'incremental-dir=s' => \$option_incremental_dir,
220 by Vadim Tkachenko
Bugfix #680936
1907
                        'extra-lsndir=s' => \$option_extra_lsndir,
14 by kinoyasu
using rsync for incremental backup
1908
                        'remote-host=s' => \$option_remote_host,
22 by kinoyasu
"innobackup --stream=tar" is supported
1909
                        'stream=s' => \$option_stream,
242.25.4 by Alexey Kopytov
Implementation of
1910
			'rsync' => \$option_rsync,
22 by kinoyasu
"innobackup --stream=tar" is supported
1911
                        'tmpdir=s' => \$option_tmpdir,
100.1.1 by Aleksandr Kuzminsky
--no-lock option is added
1912
                        'no-lock' => \$option_no_lock,
70.1.1 by Aleksandr Kuzminsky
Allow configuration of scp options
1913
                        'ibbackup=s' => \$option_ibbackup_binary,
119.1.1 by Daniel Nichter
Make --stream=tar use tar4ibd by default unless hidden --force-tar is specified.
1914
                        'scpopt=s' => \$option_scp_opt,
371 by Alexey Kopytov
Cherrypick of fix for bug 733658: pass options to both ssh and scp.
1915
                        'sshopt=s' => \$option_ssh_opt,
211 by Alexey Kopytov
Manual merge from lp:~percona-dev/percona-xtrabackup/safe-slave-backup
1916
                        'parallel=i' => \$option_parallel,
1917
                        'safe-slave-backup' => \$option_safe_slave_backup,
471.1.1 by Alexey Kopytov
Bug #1037379: SQL_THREAD left in stopped state of
1918
                        'safe-slave-backup-timeout=i' => \$option_safe_slave_backup_timeout,
127.1.6 by Daniel Nichter
Add and implement --safe-slave-backup and --safe-slave-backup-timeout.
1919
    );
1920
                        
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1921
    if (!$rcode) {
1922
        # failed to read options
22 by kinoyasu
"innobackup --stream=tar" is supported
1923
        print STDERR "$prefix Bad command line arguments\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1924
        exit(1);
1925
    }
1926
    if ($option_help) {
1927
        # print help text and exit
1928
        usage();
1929
        exit(0);
1930
    }
1931
    if ($option_version) {
1932
        # print program version and copyright
1933
        print_version();
1934
        exit(0);
1935
    }
1936
487.3.1 by George O. Lorch III
Incorporated patch for Bug #740489 : Add --defaults-extra-file param to innobackupex
1937
    if ($option_defaults_file && $option_defaults_extra_file) {
1938
        print STDERR "$prefix --defaults-file and --defaults-extra-file " .
1939
            "options are mutually exclusive";
1940
        exit(1);
1941
    }
1942
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
1943
    if ($option_copy_back && $option_move_back) {
1944
        print STDERR "$prefix --copy-back and --move-back options are " .
1945
            "mutually exclusive";
1946
    }
1947
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1948
    if ($option_compress == 0) {
1949
        # compression level no specified, use default level
1950
        $option_compress = $default_compression_level;
1951
    } 
1952
1953
    if ($option_compress == 999) {
1954
        # compress option not given in the command line
1955
	$option_compress = 0;
1956
    }
1957
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
1958
    if ($option_stream eq 'tar') {
1959
      $stream_cmd = 'tar chf -';
1960
    } elsif ($option_stream eq 'xbstream') {
1961
      $stream_cmd = 'xbstream -c'
1962
    }
1963
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1964
    if (@ARGV < 1) {
22 by kinoyasu
"innobackup --stream=tar" is supported
1965
        print STDERR "$prefix Missing command line argument\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1966
        exit(1);
1967
    } elsif (@ARGV > 1) {
22 by kinoyasu
"innobackup --stream=tar" is supported
1968
        print STDERR "$prefix Too many command line arguments\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1969
        exit(1);
1970
    }
1971
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
1972
    if (!$option_apply_log && !$option_copy_back && !$option_move_back) {
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1973
        # we are making a backup, get backup root directory
1974
        $backup_root = $ARGV[0];
242.23.1 by Lachlan Mulcahy
Fixed bug 860133
1975
        if ($option_incremental && !$option_incremental_lsn) {
130 by Vadim Tkachenko
bugfix 546876
1976
            if ($option_incremental_basedir) {
1977
                $incremental_basedir = $option_incremental_basedir;
1978
            } else {
516.4.1 by Alexey Kopytov
Bug #1116177: Fix warnings reported by "use warnings FATAL => 'all'"
1979
                my @dirs = `ls -t $backup_root`;
1980
                my $inc_dir = $dirs[0];
1981
                chomp($inc_dir);
130 by Vadim Tkachenko
bugfix 546876
1982
                $incremental_basedir = File::Spec->catfile($backup_root, $inc_dir);
1983
            }
14 by kinoyasu
using rsync for incremental backup
1984
        }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
1985
    } else {
1986
        # get backup directory
1987
        $backup_dir = File::Spec->rel2abs($ARGV[0]);
1988
    }        
1989
242.14.1 by Alexey Kopytov
Bug #834657: --slave-info does not work with --no-lock
1990
    if ($option_slave_info) {
301.2.1 by Alexey Kopytov
Manual merge of the fix for bug #834657 from 1.6.
1991
        if ($option_no_lock and !$option_safe_slave_backup) {
1992
	  print STDERR "--slave-info is used with --no-lock but without --safe-slave-backup. The binlog position cannot be consistent with the backup data.\n";
242.14.1 by Alexey Kopytov
Bug #834657: --slave-info does not work with --no-lock
1993
	    exit(1);
1994
	}
1995
    }
1996
242.25.4 by Alexey Kopytov
Implementation of
1997
    if ($option_rsync && ($option_remote_host || $option_stream)) {
1998
        print STDERR "--rsync doesn't work with --remote-host or --stream\n";
1999
	exit(1);
2000
    }
2001
242.48.1 by Stewart Smith
Deprecate --remote-host in favor of streaming backups. We will remove --remote-host in 2.0
2002
    if ($option_remote_host) {
2003
	print STDERR "\nWARNING: --remote-host is DEPRECATED and will be ",
242.47.3 by Stewart Smith
merge deprecation warning for --remote-host, updating version it to be removed in to 2.1
2004
	"removed in Percona XtraBackup 2.1 in favor of streaming backups.\n";
242.48.1 by Stewart Smith
Deprecate --remote-host in favor of streaming backups. We will remove --remote-host in 2.0
2005
    }
2006
22 by kinoyasu
"innobackup --stream=tar" is supported
2007
    print STDERR "\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2008
2009
    parse_databases_option_value();
171 by Daniel Nichter
Filter files copied according to --tables-file.
2010
    parse_tables_file_option_value($option_tables_file);
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2011
}
2012
2013
2014
#
2015
# make_backup_dir subroutine creates a new backup directory and returns
2016
# its name.
2017
#
2018
sub make_backup_dir {
2019
    my $dir;
2020
    my $innodb_data_file_path = 
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
2021
        get_option(\%config, $option_defaults_group, 'innodb_data_file_path');
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2022
2023
    # create backup directory
2024
    $dir = $backup_root;
22 by kinoyasu
"innobackup --stream=tar" is supported
2025
    if ($option_stream) {
2026
        return $dir;
2027
    }
2028
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2029
    $dir .= '/' . strftime("%Y-%m-%d_%H-%M-%S", localtime())
2030
       unless $option_no_timestamp;
17 by kinoyasu
--remote-host uses scp/ssh, remove using rsync
2031
    if (!$option_remote_host) {
2032
        mkdir($dir, 0777) || Die "Failed to create backup directory $dir: $!";
2033
    } else {
371 by Alexey Kopytov
Cherrypick of fix for bug 733658: pass options to both ssh and scp.
2034
        system("ssh $option_ssh_opt $option_remote_host mkdir $dir");
17 by kinoyasu
--remote-host uses scp/ssh, remove using rsync
2035
    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2036
2037
    # create subdirectories for ibdata files if needed
42 by kinoyasu
fix bug 357653; remove innobackup-1.5.1.patch
2038
#    foreach my $a (split(/;/, $innodb_data_file_path)) {
2039
#        my $path = (split(/:/,$a))[0];
2040
#        my @relative_path = split(/\/+/, $path);
2041
#        pop @relative_path;
2042
#        if (@relative_path) {
2043
#            # there is a non-trivial path from the backup directory
2044
#            # to the directory of this backup ibdata file, check
2045
#            # that all the directories in the path exist.
2046
#            create_path_if_needed($dir, \@relative_path);
2047
#        }
2048
#    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2049
2050
    return $dir;
2051
}
2052
2053
2054
#
2055
# create_path_if_needed subroutine checks that all components
2056
# in the given relative path are directories. If the
2057
# directories do not exist, they are created.
2058
#    Parameters:
2059
#       root           a path to the root directory of the relative pathname
2060
#       relative_path  a relative pathname (a reference to an array of 
2061
#                      pathname components) 
2062
#
2063
sub create_path_if_needed {
2064
    my $root = shift;
2065
    my $relative_path = shift;
2066
    my $path;
2067
2068
    $path = $root;
2069
    foreach $a (@{$relative_path}) {
2070
        $path = $path . "/" . $a;
17 by kinoyasu
--remote-host uses scp/ssh, remove using rsync
2071
        if (!$option_remote_host) {
2072
            if (! -d $path) {
2073
                # this directory does not exist, create it !
2074
                mkdir($path, 0777) || Die "Failed to create backup directory: $!";
2075
            }
2076
        } else {
371 by Alexey Kopytov
Cherrypick of fix for bug 733658: pass options to both ssh and scp.
2077
            if (system("ssh $option_ssh_opt $option_remote_host test -d $path") != 0) {
2078
                system("ssh $option_ssh_opt $option_remote_host mkdir $path");
17 by kinoyasu
--remote-host uses scp/ssh, remove using rsync
2079
            }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2080
        }
2081
    }
2082
}
2083
2084
2085
#
2086
# remove_from_array subroutine removes excluded element from the array.
2087
#    Parameters:
2088
#       array_ref   a reference to an array of strings
2089
#       excluded   a string to be excluded from the copy
2090
#  
2091
sub remove_from_array {
2092
    my $array_ref = shift;
2093
    my $excluded = shift;
2094
    my @copy = ();
2095
    my $size = 0;
2096
2097
    foreach my $str (@{$array_ref}) {
2098
        if ($str ne $excluded) {
2099
            $copy[$size] = $str;
2100
            $size = $size + 1;
2101
        }
2102
    }
2103
    @{$array_ref} = @copy;
2104
}
2105
2106
2107
#
2108
# backup_files subroutine copies .frm, .MRG, .MYD and .MYI files to 
2109
# backup directory.
2110
#
2111
sub backup_files {
242.25.4 by Alexey Kopytov
Implementation of
2112
    my $prep_mode = shift;
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
2113
    my $source_dir = get_option(\%config, $option_defaults_group, 'datadir');
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2114
    my @list;
2115
    my $file;
2116
    my $database;
471.6.1 by Alexey Kopytov
Bug #733665: innobackupex not supporting Maria 5.2
2117
    my $wildcard = '*.{frm,MYD,MYI,MAD,MAI,MRG,TRG,TRN,ARM,ARZ,CSM,CSV,opt,par}';
242.25.4 by Alexey Kopytov
Implementation of
2118
    my $rsync_file_list;
2119
    my $operation;
2120
    my $rsync_tmpfile_pass1 = "$option_tmpdir/xtrabackup_rsyncfiles_pass1";
2121
    my $rsync_tmpfile_pass2 = "$option_tmpdir/xtrabackup_rsyncfiles_pass2";
2122
2123
    # prep_mode will pre-copy the data, so that rsync is faster the 2nd time
2124
    # saving time while all tables are locked.
2125
    # currently only rsync mode is supported for prep.
2126
    if ($prep_mode and !$option_rsync) {
2127
        return;
2128
    }
2129
2130
    if ($option_rsync) {
2131
	if ($prep_mode) {
2132
	    $rsync_file_list = $rsync_tmpfile_pass1;
2133
	} else {
2134
	    $rsync_file_list = $rsync_tmpfile_pass2;
2135
	}
2136
	open(RSYNC, ">$rsync_file_list")
2137
	    || Die "Can't open $rsync_file_list for writing: $!\n";
2138
    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2139
2140
    opendir(DIR, $source_dir) 
2141
        || Die "Can't open directory '$source_dir': $!\n";
2142
    $now = current_time();
242.25.4 by Alexey Kopytov
Implementation of
2143
    if ($prep_mode) {
2144
	$operation = "a prep copy of";
2145
    } else {
2146
	$operation = "to backup";
2147
    }
471.6.1 by Alexey Kopytov
Bug #733665: innobackupex not supporting Maria 5.2
2148
    print STDERR "\n$now  $prefix Starting $operation non-InnoDB tables and files\n";
2149
    print STDERR "$prefix in subdirectories of '$source_dir'\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2150
    # loop through all database directories
2151
    while (defined($database = readdir(DIR))) {
2152
        my $print_each_file = 0;
2153
        my $file_c;
83 by Aleksandr Kuzminsky
Fixed bug394464
2154
        my @scp_files;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2155
        # skip files that are not database directories
2156
        if ($database eq '.' || $database eq '..') { next; }
2157
        next unless -d "$source_dir/$database";
171 by Daniel Nichter
Filter files copied according to --tables-file.
2158
	     next unless check_if_required($database);
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2159
        
22 by kinoyasu
"innobackup --stream=tar" is supported
2160
        if (!$option_remote_host && !$option_stream) {
15 by kinoyasu
trial implementation of --remote-host when --incremental (innobackup)
2161
            if (! -e "$backup_dir/$database") {
2162
                # create database directory for the backup
2163
                mkdir("$backup_dir/$database", 0777)
2164
                    || Die "Couldn't create directory '$backup_dir/$database': $!";
2165
            }
22 by kinoyasu
"innobackup --stream=tar" is supported
2166
        } elsif ($option_remote_host) {
371 by Alexey Kopytov
Cherrypick of fix for bug 733658: pass options to both ssh and scp.
2167
            if (system("ssh $option_ssh_opt $option_remote_host test -e $backup_dir/$database")
15 by kinoyasu
trial implementation of --remote-host when --incremental (innobackup)
2168
                    != 0) {
371 by Alexey Kopytov
Cherrypick of fix for bug 733658: pass options to both ssh and scp.
2169
                system("ssh $option_ssh_opt $option_remote_host mkdir $backup_dir/$database");
15 by kinoyasu
trial implementation of --remote-host when --incremental (innobackup)
2170
            }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2171
        }
2172
2173
        # copy files of this database
108.1.1 by Aleksandr Kuzminsky
Fixed number of issues in innobackupex-1.5.1 on windows platform
2174
	opendir(DBDIR, "$source_dir/$database");
471.6.1 by Alexey Kopytov
Bug #733665: innobackupex not supporting Maria 5.2
2175
	@list = grep(/\.(frm|MYD|MYI|MAD|MAI|MRG|TRG|TRN|ARM|ARZ|CSM|CSV|opt|par)$/, readdir(DBDIR));
108.1.1 by Aleksandr Kuzminsky
Fixed number of issues in innobackupex-1.5.1 on windows platform
2176
	closedir DBDIR;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2177
        $file_c = @list;
2178
        if ($file_c <= $backup_file_print_limit) {
2179
            $print_each_file = 1;
2180
        } else {
22 by kinoyasu
"innobackup --stream=tar" is supported
2181
            print STDERR "$prefix Backing up files " . 
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2182
                "'$source_dir/$database/$wildcard' ($file_c files)\n";
2183
        }
2184
        foreach $file (@list) {
2185
            next unless check_if_required($database, $file);
217 by Vadim Tkachenko
Bugfix #597384
2186
2187
	    if($option_include) {
504.6.1 by Alexey Kopytov
Bug #1130627: Can't backup individual partitions
2188
                my $table = get_table_name($file);
2189
                my $table_part = get_table_name_with_part_suffix($file);
2190
2191
                if (!("$database.$table_part" =~ /$option_include/ ||
2192
                      "$database.$table" =~ /$option_include/)) {
2193
2194
                    if ($print_each_file) {
2195
                        print STDERR "$database.$file is skipped because it does not match '$option_include'.\n";
2196
                    }
2197
                    next;
2198
                }
217 by Vadim Tkachenko
Bugfix #597384
2199
	    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2200
               
2201
            if ($print_each_file) {
108.1.1 by Aleksandr Kuzminsky
Fixed number of issues in innobackupex-1.5.1 on windows platform
2202
                print STDERR "$prefix Backing up file '$source_dir/$database/$file'\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2203
            }
242.25.4 by Alexey Kopytov
Implementation of
2204
2205
	    if ($option_rsync) {
2206
		print RSYNC "$database/$file\n";
2207
		if (!$prep_mode) {
2208
		    $rsync_files_hash{"$database/$file"} = 1;
2209
		}
2210
            } elsif (!$option_remote_host && !$option_stream) {
108.1.4 by Aleksandr Kuzminsky
escape_path() function is added.
2211
                $src_name = escape_path("$source_dir/$database/$file");
2212
                $dst_name = escape_path("$backup_dir/$database");
242.26.20 by Alexey Kopytov
Fix for bug #924026: innobackupex fails during backup if table is
2213
                # Copy the file - If we get an error and the file actually exists, die with error msg
2214
                copy_if_exists("$src_name", "$dst_name")
2215
                  or Die "Failed to copy file '$file': $!";
22 by kinoyasu
"innobackup --stream=tar" is supported
2216
            } elsif ($option_remote_host) {
83 by Aleksandr Kuzminsky
Fixed bug394464
2217
                # Queue up files for one single scp per database.
2218
                push(@scp_files, "'$file'");
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
2219
            } elsif($option_stream) {
36 by kinoyasu
some small fixes of innobackupex: bug 355214, bug 356776, etc
2220
                my $ret = 0;
22 by kinoyasu
"innobackup --stream=tar" is supported
2221
                my $file_name = substr($file, rindex($file, '/') + 1);
86.1.1 by akuzminsky
Fixed bug#417178
2222
                $file_name=~s/([\$\\\" ])/\\$1/g;
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
2223
                $ret = system("cd $source_dir; $stream_cmd $database/$file_name") >> 8;
2224
                if ($ret == 1 && $option_stream eq 'tar') {
36 by kinoyasu
some small fixes of innobackupex: bug 355214, bug 356776, etc
2225
                    print STDERR "$prefix If you use GNU tar, this warning can be ignored.\n";
242.21.2 by Lachlan Mulcahy
Changed handling of non-existant files to use that same style as other places in innobackupex
2226
                # Check for non-zero exit code
2227
                } elsif ($ret != 0) {
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
2228
                    print STDERR "$prefix $stream_cmd returned with exit code $ret.\n";
242.21.2 by Lachlan Mulcahy
Changed handling of non-existant files to use that same style as other places in innobackupex
2229
                    # Only treat as fatal cases where the file exists
2230
                    if ( -e "$database/$file_name" ) {
2231
                        Die "Failed to stream '$database/$file_name': $!";
2232
                    } else {
2233
                        print STDERR "$prefix Ignoring nonexistent file '$database/$file_name'.\n";
2234
                    }
2235
36 by kinoyasu
some small fixes of innobackupex: bug 355214, bug 356776, etc
2236
                }
14 by kinoyasu
using rsync for incremental backup
2237
            }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2238
        }
131 by Vadim Tkachenko
bugfix 552111
2239
        if ($option_remote_host and @scp_files) {
114.1.1 by Daniel Nichter
Fix bug 510960: innobackupex --remote-host scp doesn't copy MyISAM files
2240
          my $scp_file_list = join(" ", map { "$source_dir/$database/$_" } @scp_files);
83 by Aleksandr Kuzminsky
Fixed bug394464
2241
          system("scp $option_scp_opt $scp_file_list '$option_remote_host:$backup_dir/$database/'")
102 by kinoyasu
change error message of scp .frm files
2242
              and Die "Failed to execute \"scp $option_scp_opt $scp_file_list '$option_remote_host:$backup_dir/$database/'\": $!";
83 by Aleksandr Kuzminsky
Fixed bug394464
2243
        }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2244
    }
2245
    closedir(DIR);
2246
242.25.4 by Alexey Kopytov
Implementation of
2247
    if ($option_rsync) {
380.2.1 by Sergei Glushchenko
Bug 543134.
2248
        if (-e "$source_dir/ib_lru_dump") {
2249
            print RSYNC "ib_lru_dump\n";
2250
            if (!$prep_mode) {
2251
                $rsync_files_hash{"ib_lru_dump"} = 1;
2252
            }
2253
        }
242.25.4 by Alexey Kopytov
Implementation of
2254
	close(RSYNC);
2255
2256
	# do the actual rsync now
2257
	$now = current_time();
2258
	my $rsync_cmd = "rsync -t \"$source_dir\" --files-from=\"$rsync_file_list\" \"$backup_dir\"";
2259
	print STDERR "$now Starting rsync as: $rsync_cmd\n";
2260
2261
	# ignore errors in the prep mode, since we are running without lock,
2262
	# so some files may have disappeared.
2263
	if (system("$rsync_cmd") && !$prep_mode) {
2264
	    Die "rsync failed: $!\n";
2265
	}
2266
2267
	$now = current_time();
2268
	print STDERR "$now rsync finished successfully.\n";
2269
2270
	# Remove from $backup_dir files that have been removed between first and
2271
	# second passes. Cannot use "rsync --delete" because it does not work
2272
	# with --files-from.
500.2.1 by Sergei Glushchenko
Bug 1123335
2273
	if (!$prep_mode && !$option_no_lock) {
242.25.4 by Alexey Kopytov
Implementation of
2274
	    open(RSYNC, "<$rsync_tmpfile_pass1")
2275
		|| Die "Can't open $rsync_tmpfile_pass1 for reading: $!\n";
2276
2277
	    while (<RSYNC>) {
2278
		chomp;
2279
		if (!exists $rsync_files_hash{$_}) {
2280
		    print STDERR "Removing '$backup_dir/$_'\n";
2281
		    unlink "$backup_dir/$_";
2282
		}
2283
	    }
2284
2285
	    close(RSYNC);
2286
	    unlink "$rsync_tmpfile_pass1" || \
2287
		Die "Failed to delete $rsync_tmpfile_pass1: $!";
2288
	    unlink "$rsync_tmpfile_pass2" || \
2289
		Die "Failed to delete $rsync_tmpfile_pass2: $!";
2290
	}
2291
    }
2292
2293
    if ($prep_mode) {
2294
	$operation = "a prep copy of";
2295
    } else {
2296
	$operation = "backing up";
2297
    }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2298
    $now = current_time();
471.6.1 by Alexey Kopytov
Bug #733665: innobackupex not supporting Maria 5.2
2299
    print STDERR "$now  $prefix Finished $operation non-InnoDB tables and files\n\n";
242.25.4 by Alexey Kopytov
Implementation of
2300
 }
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2301
2302
2303
#
2304
# file_to_array subroutine reads the given text file into an array and
2305
# stores each line as an element of the array. The end-of-line
2306
# character(s) are removed from the lines stored in the array.
2307
#    Parameters:
2308
#       filename   name of a text file
2309
#       lines_ref  a reference to an array
2310
#
2311
sub file_to_array {
2312
    my $filename = shift;
2313
    my $lines_ref = shift;
2314
    
2315
    open(FILE, $filename) || Die "can't open file '$filename': $!";
2316
    @{$lines_ref} = <FILE>;
2317
    close(FILE) || Die "can't close file '$filename': $!";
2318
2319
    foreach my $a (@{$lines_ref}) {
2320
        chomp($a);
2321
    }
2322
}
2323
2324
2325
#
2326
# unescape_string subroutine expands escape sequences found in the string and
2327
# returns the expanded string. It also removes possible single or double quotes
2328
# around the value.
2329
#    Parameters:
2330
#       value   a string
2331
#    Return value:
2332
#       a string with expanded escape sequences
2333
# 
2334
sub unescape_string {
2335
    my $value = shift;
2336
    my $result = '';
2337
    my $offset = 0;
2338
2339
    # remove quotes around the value if they exist
2340
    if (length($value) >= 2) {
2341
        if ((substr($value, 0, 1) eq "'" && substr($value, -1, 1) eq "'")
2342
            || (substr($value, 0, 1) eq '"' && substr($value, -1, 1) eq '"')) {
2343
            $value = substr($value, 1, -1);
2344
        }
2345
    }
2346
    
2347
    # expand escape sequences
2348
    while ($offset < length($value)) {
2349
        my $pos = index($value, "\\", $offset);
2350
        if ($pos < 0) {
2351
            $pos = length($value);
2352
            $result = $result . substr($value, $offset, $pos - $offset);
2353
            $offset = $pos;
2354
        } else {
2355
            my $replacement = substr($value, $pos, 2);
2356
            my $escape_code = substr($value, $pos + 1, 1);
2357
            if (exists $option_value_escapes{$escape_code}) {
2358
                $replacement = $option_value_escapes{$escape_code};
2359
            }
2360
            $result = $result 
2361
                . substr($value, $offset, $pos - $offset)
2362
                . $replacement;
2363
            $offset = $pos + 2;
2364
        }
2365
    }
2366
2367
    return $result;
2368
}
2369
2370
2371
#
2372
# read_config_file subroutine reads MySQL options file and
2373
# returns the options in a hash containing one hash per group.
2374
#    Parameters:
2375
#       filename    name of a MySQL options file
2376
#       groups_ref  a reference to hash variable where the read
2377
#                   options are returned
2378
#
2379
sub read_config_file {
2380
    #my $filename = shift;
2381
    my $groups_ref = shift;
2382
    my @lines ;
2383
    my $i;
2384
    my $group;
2385
    my $group_hash_ref;
2386
2387
    my $cmdline = '';
43 by kinoyasu
fix bug 358266, bug 359341
2388
    my $options = '';
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2389
242.47.10 by Sergei Glushchenko
Bug 996493: innobackupex --apply-log doesn't read config from backup-my.cnf
2390
36 by kinoyasu
some small fixes of innobackupex: bug 355214, bug 356776, etc
2391
    if ($option_defaults_file) {
108.1.5 by Aleksandr Kuzminsky
Fixed issue in quoting defaults-file when specified
2392
        $options = $options . " --defaults-file=\"$option_defaults_file\" ";
242.47.10 by Sergei Glushchenko
Bug 996493: innobackupex --apply-log doesn't read config from backup-my.cnf
2393
    } elsif ($option_apply_log) {
2394
        $options = $options . " --defaults-file=\"${backup_dir}/backup-my.cnf\" ";
36 by kinoyasu
some small fixes of innobackupex: bug 355214, bug 356776, etc
2395
    }
2396
487.3.1 by George O. Lorch III
Incorporated patch for Bug #740489 : Add --defaults-extra-file param to innobackupex
2397
    if ($option_defaults_extra_file) {
2398
        $options = $options . " --defaults-extra-file=\"$option_defaults_extra_file\" ";
2399
    }
2400
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
2401
    if ($option_defaults_group) {
2402
        $options = $options . " --defaults-group=\"$option_defaults_group\" ";
2403
    }
2404
43 by kinoyasu
fix bug 358266, bug 359341
2405
    $options = $options . "--print-param";
2406
108.1.5 by Aleksandr Kuzminsky
Fixed issue in quoting defaults-file when specified
2407
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2408
    # read file to an array, one line per element
2409
    #file_to_array($filename, \@lines);
2410
    $cmdline = "$option_ibbackup_binary $options";
2411
    @lines = `$cmdline`;
2412
2413
    # classify lines and save option values
2414
    $group = 'default';
2415
    $group_hash_ref = {}; 
2416
    ${$groups_ref}{$group} = $group_hash_ref;
2417
    # this pattern described an option value which may be
2418
    # quoted with single or double quotes. This pattern
2419
    # does not work by its own. It assumes that the first
2420
    # opening parenthesis in this string is the second opening
2421
    # parenthesis in the full pattern. 
108.1.1 by Aleksandr Kuzminsky
Fixed number of issues in innobackupex-1.5.1 on windows platform
2422
    my $value_pattern = q/((["'])([^\\\4]|(\\[^\4]))*\4)|([^\s]+)/;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2423
    for ($i = 0; $i < @lines; $i++) {
2424
      SWITCH: for ($lines[$i]) {
2425
          # comment
2426
          /^\s*(#|;)/
2427
             && do { last; };
2428
2429
          # group      
2430
          /^\s*\[(.*)\]/ 
2431
                && do { 
2432
                    $group = $1; 
2433
                    if (!exists ${$groups_ref}{$group}) {
2434
                        $group_hash_ref = {}; 
2435
                        ${$groups_ref}{$group} = $group_hash_ref;
2436
                    } else {
2437
                        $group_hash_ref = ${$groups_ref}{$group};
2438
                    }
2439
                    last; 
2440
                };
2441
2442
          # option
2443
          /^\s*([^\s=]+)\s*(#.*)?$/
2444
              && do { 
2445
                  ${$group_hash_ref}{$1} = '';
2446
                  last; 
2447
              };
2448
2449
          # set-variable = option = value
2450
          /^\s*set-variable\s*=\s*([^\s=]+)\s*=\s*($value_pattern)\s*(#.*)?$/
2451
              && do { ${$group_hash_ref}{$1} = unescape_string($2); last; };
2452
2453
          # option = value
2454
          /^\s*([^\s=]+)\s*=\s*($value_pattern)\s*(#.*)?$/
2455
              && do { ${$group_hash_ref}{$1} = unescape_string($2); last; };
2456
2457
          # empty line
2458
          /^\s*$/
2459
              && do { last; };
2460
2461
          # unknown
2462
          print("$prefix: Warning: Ignored unrecognized line ",
2463
                $i + 1,
2464
                " in options : '${lines[$i]}'\n"
2465
                );
2466
      }
2467
   }
2468
}
2469
    
2470
242.44.1 by Sergei Glushchenko
Bug #733651
2471
# has_option return whether the config has an option with the given name
2472
#    Parameters:
2473
#       config_ref   a reference to a config data
2474
#       group        option group name
2475
#       option_name  name of the option
2476
#    Return value:
2477
#       true if option exists, otherwise false
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2478
#
242.44.1 by Sergei Glushchenko
Bug #733651
2479
sub has_option {
2480
    my $config_ref = shift;
2481
    my $group = shift;
2482
    my $option_name = shift;
2483
    my $group_hash_ref;
2484
2485
    if (!exists ${$config_ref}{$group}) {
2486
        # no group
2487
        print STDERR "$prefix fatal error: no '$group' group in MySQL options\n";
2488
        exit(1);
2489
    }
2490
2491
    $group_hash_ref = ${$config_ref}{$group};
2492
    
2493
    return exists ${$group_hash_ref}{$option_name};
2494
}
2495
    
2496
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2497
# get_option subroutine returns the value of given option in the config
2498
# structure. If option is missing, this subroutine calls exit.
2499
#    Parameters:
2500
#       config_ref   a reference to a config data
2501
#       group        option group name
2502
#       option_name  name of the option
2503
#    Return value:
2504
#       option value as a string
2505
#
2506
sub get_option {
2507
    my $config_ref = shift;
2508
    my $group = shift;
2509
    my $option_name = shift;
2510
    my $group_hash_ref;
2511
2512
    if (!exists $config{$group}) {
2513
        # no group
22 by kinoyasu
"innobackup --stream=tar" is supported
2514
        print STDERR "$prefix fatal error: no '$group' group in MySQL options\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2515
        exit(1);
2516
    }
2517
    
2518
    $group_hash_ref = ${$config_ref}{$group};
2519
    if (!exists ${$group_hash_ref}{$option_name}) {
2520
        # no option
22 by kinoyasu
"innobackup --stream=tar" is supported
2521
        print STDERR "$prefix fatal error: no '$option_name' option in group '$group' in MySQL options\n";
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2522
        exit(1);
2523
    }
2524
2525
    return ${$group_hash_ref}{$option_name};
2526
}
2527
480.2.1 by Sergei Glushchenko
Bug 711166
2528
# get_table_name subroutine returns table name of specified file.
2529
#    Parameters:
2530
#       $_[0]        table path
2531
#    Return value:
2532
#       1 table name
2533
#
2534
sub get_table_name {
504.6.1 by Alexey Kopytov
Bug #1130627: Can't backup individual partitions
2535
   my $table;
2536
2537
   $table = get_table_name_with_part_suffix($_[0]);
2538
   # trim partition suffix
2539
   $table = (split('#P#', $table))[0];
2540
2541
   return $table;
2542
}
2543
2544
# Like get_table_name(), but keeps the partition suffix if present
2545
sub get_table_name_with_part_suffix {
480.2.1 by Sergei Glushchenko
Bug 711166
2546
   my $table_path = shift;
2547
   my $filename;
2548
   my $table;
2549
2550
   # get the last component in the table pathname 
2551
   $filename = (reverse(split(/\//, $table_path)))[0];
2552
   # get name of the table by removing file suffix
2553
   $table = (split(/\./, $filename))[0];
2554
2555
   return $table;
2556
}
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
2557
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2558
# check_if_required subroutine returns 1 if the specified database and
2559
# table needs to be backed up.
2560
#    Parameters:
2561
#       $_[0]        name of database to be checked 
2562
#       $_[1]        full path of table file (This argument is optional)
2563
#    Return value:
2564
#       1 if backup should be done and 0 if not
2565
#
2566
sub check_if_required {
171 by Daniel Nichter
Filter files copied according to --tables-file.
2567
   my ( $db, $table_path ) = @_;
2568
   my $db_count  = scalar keys %databases_list;
2569
   my $tbl_count = scalar keys %table_list;
2570
   my $table;
504.6.1 by Alexey Kopytov
Bug #1130627: Can't backup individual partitions
2571
   my $table_part;
171 by Daniel Nichter
Filter files copied according to --tables-file.
2572
2573
   if ( $db_count == 0 && $tbl_count == 0 ) {
2574
      # No databases defined with --databases option, include all databases,
2575
      # and no tables defined with --tables-file option, include all tables.
504.6.1 by Alexey Kopytov
Bug #1130627: Can't backup individual partitions
2576
       return 1;
171 by Daniel Nichter
Filter files copied according to --tables-file.
2577
   }
2578
   else {
2579
      if ( $table_path ) {
504.6.1 by Alexey Kopytov
Bug #1130627: Can't backup individual partitions
2580
         $table_part = get_table_name_with_part_suffix($table_path);
480.2.1 by Sergei Glushchenko
Bug 711166
2581
         $table = get_table_name($table_path);
171 by Daniel Nichter
Filter files copied according to --tables-file.
2582
      }
2583
   }
2584
2585
   # Filter for --databases.
2586
   if ( $db_count ) {
2587
      if (defined $databases_list{$db}) {
2588
         if (defined $table_path) {
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2589
            my $db_hash = $databases_list{$db};
2590
            $db_count = keys %$db_hash;
504.6.1 by Alexey Kopytov
Bug #1130627: Can't backup individual partitions
2591
            if ($db_count > 0 &&
2592
                !defined $databases_list{$db}->{$table_part} &&
2593
                !defined $databases_list{$db}->{$table}) {
171 by Daniel Nichter
Filter files copied according to --tables-file.
2594
               # --databases option specified, but table is not included
2595
               return 0;
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2596
            }
171 by Daniel Nichter
Filter files copied according to --tables-file.
2597
         }
2598
         # include this database and table
2599
         return 1;
2600
      }
2601
      else {
2602
         # --databases option given, but database is not included
2603
         return 0;
2604
      }
2605
   }
2606
2607
   # Filter for --tables-file.
2608
   if ( $tbl_count ) {
2609
      return 0 unless exists $table_list{$db};
504.6.1 by Alexey Kopytov
Bug #1130627: Can't backup individual partitions
2610
      return 0 if $table && !$table_list{$db}->{$table_part} &&
2611
          !$table_list{$db}->{$table};
171 by Daniel Nichter
Filter files copied according to --tables-file.
2612
   }
2613
2614
   return 1;  # backup the table
7 by Vadim Tkachenko
patche innobackup-1.5.1 added
2615
}
2616
2617
2618
# parse_databases_option_value subroutine parses the value of 
2619
# --databases option. If the option value begins with a slash
2620
# it is considered a pathname and the option value is read
2621
# from the file.
2622
# 
2623
# This subroutine sets the global "databases_list" variable.
2624
#
2625
sub parse_databases_option_value {
2626
    my $item;
2627
2628
    if ($option_databases =~ /^\//) {
2629
        # the value of the --databases option begins with a slash,
2630
        # the option value is pathname of the file containing
2631
        # list of databases
2632
        if (! -f $option_databases) {
2633
            Die "can't find file '$option_databases'";
2634
        }
2635
2636
        # read from file the value of --databases option
2637
        my @lines;
2638
    	file_to_array($option_databases, \@lines);
2639
	$option_databases = join(" ", @lines);
2640
    }
2641
2642
    # mark each database or database.table definition in the
2643
    # global databases_list.
2644
    foreach $item (split(/\s/, $option_databases)) {
2645
        my $db = "";
2646
        my $table = "";
2647
        my %hash;
2648
2649
        if ($item eq "") {
2650
            # ignore empty strings
2651
            next;
2652
        }
2653
2654
        # get database and table names
2655
        if ($item =~ /(\S*)\.(\S*)/) {
2656
            # item is of the form DATABASE.TABLE
2657
            $db = $1;
2658
            $table = $2;
2659
        } else {
2660
            # item is database name, table is undefined
2661
            $db = $item;
2662
        }
2663
2664
        if (! defined $databases_list{$db}) {
2665
            # create empty hash for the database
2666
            $databases_list{$db} = \%hash;
2667
        }
2668
        if ($table ne "") {
2669
            # add mapping table --> 1 to the database hash
2670
            my $h = $databases_list{$db};
2671
            $h->{$table} = 1;
2672
        }
2673
    }
2674
}
108.1.4 by Aleksandr Kuzminsky
escape_path() function is added.
2675
171 by Daniel Nichter
Filter files copied according to --tables-file.
2676
# Parse the --tables-file file to determine which InnoDB tables
2677
# are backedup up.  Only backedup tables have their .frm, etc.
2678
# files copied.
2679
sub parse_tables_file_option_value {
2680
   my ( $filename ) = @_;
2681
2682
   return unless $filename;
2683
2684
   open my $fh, '<', $filename;
2685
   if ( $fh ) {
2686
      while ( my $line = <$fh> ) {
172 by Daniel Nichter
Parse tables file as simple list of databases.tables.
2687
         chomp $line;
2688
         my ( $db, $tbl ) = $line =~ m/\s*([^\.]+)\.([^\.]+)\s*/;
171 by Daniel Nichter
Filter files copied according to --tables-file.
2689
         if ( $db && $tbl ) {
2690
            $table_list{$db}->{$tbl} = 1;
2691
         }
2692
         else {
2693
            warn "$prefix Invalid line in $filename: $line";
2694
         }
2695
      }
2696
   }
2697
   else {
2698
      warn "$prefix Cannot read --tables-file $filename: $OS_ERROR";
2699
   }
2700
2701
   return;
2702
}
2703
108.1.4 by Aleksandr Kuzminsky
escape_path() function is added.
2704
sub escape_path {
2705
  my $str = shift;
2706
  if ($win eq 1) {
2707
    $str =~ s/\//\\/g;
2708
    $str =~ s/\\\\/\\/g;
2709
    }
2710
  else{
2711
    $str =~ s/\/\//\//g;
2712
    }
2713
  return $str;
2714
2715
}
136.1.2 by Aleksandr Kuzminsky
innobackupex checks MySQL version.
2716
2717
sub set_xtrabackup_version {
2718
# Based on MySQL version choose correct binary
178 by root
support for 5.5 in scripts
2719
#  MySQL 5.0.* - xtrabackup_51
2720
#  MySQL 5.1.* - xtrabackup_51
152 by Aleksandr Kuzminsky
1. innobackupex saves the xtrabackup binary name in a file xtrabackup_binary.
2721
#  MySQL 5.1.* with InnoDB plugin - xtrabackup
471.6.1 by Alexey Kopytov
Bug #733665: innobackupex not supporting Maria 5.2
2722
#  MariaDB 5.1.* - xtrabackup
2723
#  MariaDB 5.2.* - xtrabackup
2724
#  MariaDB 5.3.* - xtrabackup
499.1.1 by Hrvoje Matijakovic
- Bug fixes for: Bug #1100008, Bug #1095925, Bug #1092235, Bug #1088967,
2725
#  Percona Server 5.0 - xtrabackup_51
2726
#  Percona Server 5.1 - xtrabackup
2727
#  Percona Server 5.5 - xtrabackup_55
504.10.3 by Alexey Kopytov
Basic 5.6 support:
2728
#  Percona Server 5.6 - xtrabackup_56
471.6.1 by Alexey Kopytov
Bug #733665: innobackupex not supporting Maria 5.2
2729
#  MySQL 5.5.* - xtrabackup_55
504.10.3 by Alexey Kopytov
Basic 5.6 support:
2730
#  MySQL 5.6.* - xtrabackup_56
471.6.1 by Alexey Kopytov
Bug #733665: innobackupex not supporting Maria 5.2
2731
#  MariaDB 5.5.* - xtrabackup_55
504.10.3 by Alexey Kopytov
Basic 5.6 support:
2732
#  MariaDB 10.0.* - xtrabackup_56
178 by root
support for 5.5 in scripts
2733
136.1.2 by Aleksandr Kuzminsky
innobackupex checks MySQL version.
2734
my @lines;
2735
my $var_version = '';
2736
my $var_innodb_version = '';
152 by Aleksandr Kuzminsky
1. innobackupex saves the xtrabackup binary name in a file xtrabackup_binary.
2737
my $ibbackup_binary;
136.1.2 by Aleksandr Kuzminsky
innobackupex checks MySQL version.
2738
mysql_open();
2739
mysql_send "SHOW VARIABLES LIKE 'version'\\G";
2740
file_to_array($mysql_stdout, \@lines);
2741
for (@lines) {
2742
	$var_version = $1 if /Value:\s+(\S+)/;
2743
	}
2744
mysql_send "SHOW VARIABLES LIKE 'innodb_version'\\G";
2745
file_to_array($mysql_stdout, \@lines);
2746
for (@lines) {
2747
	$var_innodb_version = $1 if /Value:\s+(\S+)/;
2748
	}
2749
if($var_version =~ m/5\.0\.\d/){
160 by Aleksandr Kuzminsky
Use new patch for MySQL 5.1
2750
	$ibbackup_binary = ($win eq 1 ? 'xtrabackup.exe' : 'xtrabackup_51');
136.1.2 by Aleksandr Kuzminsky
innobackupex checks MySQL version.
2751
}
373 by Alexey Kopytov
Cherrypick of innodb version detection failure fix.
2752
if($var_version =~ m/5\.1\.\d/ and $var_innodb_version =~ m/.*/){
160 by Aleksandr Kuzminsky
Use new patch for MySQL 5.1
2753
	$ibbackup_binary = ($win eq 1 ? 'xtrabackup.exe' : 'xtrabackup_51');
136.1.2 by Aleksandr Kuzminsky
innobackupex checks MySQL version.
2754
}
2755
if($var_version =~ m/5\.1\.\d/ and $var_innodb_version =~ m/1\.0\.\d+$/){
152 by Aleksandr Kuzminsky
1. innobackupex saves the xtrabackup binary name in a file xtrabackup_binary.
2756
	$ibbackup_binary = ($win eq 1 ? 'xtrabackup.exe' : 'xtrabackup');
136.1.2 by Aleksandr Kuzminsky
innobackupex checks MySQL version.
2757
}
373 by Alexey Kopytov
Cherrypick of innodb version detection failure fix.
2758
if($var_version =~ m/5\.1\.\d/ and $var_innodb_version =~ m/1\.0\.\d+-(rel)?\d/){
152 by Aleksandr Kuzminsky
1. innobackupex saves the xtrabackup binary name in a file xtrabackup_binary.
2759
	$ibbackup_binary = ($win eq 1 ? 'xtrabackup.exe' : 'xtrabackup');
136.1.2 by Aleksandr Kuzminsky
innobackupex checks MySQL version.
2760
}
471.6.1 by Alexey Kopytov
Bug #733665: innobackupex not supporting Maria 5.2
2761
if($var_version =~ m/5\.2\.\d/){
2762
    $ibbackup_binary = ($win eq 1 ? 'xtrabackup.exe' : 'xtrabackup');
2763
}
2764
if($var_version =~ m/5\.3\.\d/){
2765
    $ibbackup_binary = ($win eq 1 ? 'xtrabackup.exe' : 'xtrabackup');
2766
}
178 by root
support for 5.5 in scripts
2767
if($var_version =~ m/5\.5\.\d/){
2768
	$ibbackup_binary = ($win eq 1 ? 'xtrabackup.exe' : 'xtrabackup_55');
2769
}
504.10.3 by Alexey Kopytov
Basic 5.6 support:
2770
if($var_version =~ m/5\.6\.\d/ or $var_version =~ m/10\.0\.\d/){
2771
    $ibbackup_binary = ($win eq 1 ? 'xtrabackup.exe' : 'xtrabackup_56');
2772
}
136.1.2 by Aleksandr Kuzminsky
innobackupex checks MySQL version.
2773
mysql_close();
504.5.1 by Alexey Kopytov
Bug #1087219: innobackupex should have better error reporting for
2774
2775
if (!$ibbackup_binary) {
2776
    Die "Unsupported server version: '$var_version' " .
2777
        "(InnoDB version: '$var_innodb_version'). " .
2778
         "Please report a bug at ".
2779
         "https://bugs.launchpad.net/percona-xtrabackup\n";
2780
}
2781
152 by Aleksandr Kuzminsky
1. innobackupex saves the xtrabackup binary name in a file xtrabackup_binary.
2782
return $ibbackup_binary;
136.1.2 by Aleksandr Kuzminsky
innobackupex checks MySQL version.
2783
}
211 by Alexey Kopytov
Manual merge from lp:~percona-dev/percona-xtrabackup/safe-slave-backup
2784
127.1.6 by Daniel Nichter
Add and implement --safe-slave-backup and --safe-slave-backup-timeout.
2785
# Wait until it's safe to backup a slave.  Returns immediately if
2786
# the host isn't a slave.  Currently there's only one check:
2787
# Slave_open_temp_tables has to be zero.  Dies on timeout.
2788
sub wait_for_safe_slave {
2789
   my @lines;
471.1.1 by Alexey Kopytov
Bug #1037379: SQL_THREAD left in stopped state of
2790
   # whether host is detected as slave in safe slave backup mode
2791
   my $host_is_slave = 0;
2792
2793
   $sql_thread_started = 0;
2794
127.1.6 by Daniel Nichter
Add and implement --safe-slave-backup and --safe-slave-backup-timeout.
2795
   mysql_send 'SHOW SLAVE STATUS\G;';
2796
   file_to_array($mysql_stdout, \@lines);
2797
   foreach my $line ( @lines ) {
2798
      if ( $line =~ m/Read_Master_Log_Pos/ ) {
2799
         $host_is_slave = 1;
471.1.1 by Alexey Kopytov
Bug #1037379: SQL_THREAD left in stopped state of
2800
     } elsif ( $line =~ m/Slave_SQL_Running:.*Yes/ ) {
2801
         $sql_thread_started = 1;
2802
     }
127.1.6 by Daniel Nichter
Add and implement --safe-slave-backup and --safe-slave-backup-timeout.
2803
   }
2804
   if ( !$host_is_slave ) {
2805
      print STDERR "$prefix: Not checking slave open temp tables for --safe-slave-backup because host is not a slave\n";
2806
      return;
2807
   }
2808
471.1.1 by Alexey Kopytov
Bug #1037379: SQL_THREAD left in stopped state of
2809
   if ($sql_thread_started) {
2810
       mysql_send 'STOP SLAVE SQL_THREAD;';
2811
   }
127.1.6 by Daniel Nichter
Add and implement --safe-slave-backup and --safe-slave-backup-timeout.
2812
2813
   my $open_temp_tables = get_slave_open_temp_tables();
2814
   print STDERR "$prefix: Slave open temp tables: $open_temp_tables\n";
2815
2816
   return if $open_temp_tables == 0;
2817
2818
   my $sleep_time = 3;
2819
   my $n_attempts = int($option_safe_slave_backup_timeout / $sleep_time) || 1;
2820
   while ( $n_attempts-- ) {
2821
      print STDERR "$prefix: Starting slave SQL thread, waiting $sleep_time seconds, then checking Slave_open_temp_tables again ($n_attempts attempts remaining)...\n";
2822
      
2823
      mysql_send 'START SLAVE SQL_THREAD;';
2824
      sleep $sleep_time;
2825
      mysql_send 'STOP SLAVE SQL_THREAD;';
2826
2827
      $open_temp_tables = get_slave_open_temp_tables();
2828
      print STDERR "$prefix: Slave open temp tables: $open_temp_tables\n";
2829
      if ( !$open_temp_tables ) {
2830
         print STDERR "$prefix: Slave is safe to backup\n";
2831
         return;
2832
      }
2833
   } 
2834
471.1.1 by Alexey Kopytov
Bug #1037379: SQL_THREAD left in stopped state of
2835
   # Restart the slave if it was running at start
2836
   if ($sql_thread_started) {
2837
       print STDERR "Restarting slave SQL thread.\n";
2838
       mysql_send 'START SLAVE SQL_THREAD;';
2839
   }
2840
127.1.6 by Daniel Nichter
Add and implement --safe-slave-backup and --safe-slave-backup-timeout.
2841
   Die "Slave_open_temp_tables did not become zero after waiting $option_safe_slave_backup_timeout seconds";
2842
}
2843
2844
sub get_slave_open_temp_tables {
2845
   my @lines;
516.5.1 by Alexey Kopytov
Bug #945161: innobackupex fails if SQL_MODE=ANSI_QUOTES
2846
   mysql_send "SHOW STATUS LIKE 'slave_open_temp_tables'\\G";
127.1.6 by Daniel Nichter
Add and implement --safe-slave-backup and --safe-slave-backup-timeout.
2847
   file_to_array($mysql_stdout, \@lines);
2848
   my $last_value;
2849
   for my $i ( 0..$#lines ) {
2850
      $last_value = $i + 1
2851
         if $lines[$i] =~ m/Variable_name: Slave_open_temp_tables/i;
2852
   }
2853
   Die "SHOW STATUS LIKE 'slave_open_temp_tables' did not return anything"
2854
      unless $last_value;
2855
2856
   Die "Failed to get Slave_open_temp_tables from SHOW STATUS"
2857
      unless defined $lines[$last_value];
2858
2859
   my ($n) = $lines[$last_value] =~ m/(\d+)/;
2860
   return $n;
2861
}
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
2862
2863
=pod
2864
2865
=head1 NAME
2866
2867
innobackupex - Non-blocking backup tool for InnoDB, XtraDB and HailDB databases
2868
2869
=head1 SYNOPOSIS
2870
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
2871
innobackupex [--compress] [--compress-threads=NUMBER-OF-THREADS]
2872
             [--include=REGEXP] [--user=NAME]
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
2873
             [--password=WORD] [--port=PORT] [--socket=SOCKET]
242.17.19 by Alexey Kopytov
Bug #809073: ibbackup-binary option in innobackupex does not work
2874
             [--no-timestamp] [--ibbackup=IBBACKUP-BINARY]
450.1.1 by Hrvoje Matijakovic
* bugfix for Bug #1032090
2875
             [--slave-info] [--galera-info] [--stream=tar|xbstream]
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
2876
             [--scpopt=OPTIONS-FOR-SCP]  [--sshopt=OPTIONS-FOR-SSH]
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
2877
             [--defaults-file=MY.CNF] [--defaults-group=GROUP-NAME]
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
2878
             [--databases=LIST] [--remote-host=HOSTNAME] [--no-lock] 
2879
             [--tmpdir=DIRECTORY] [--tables-file=FILE]
2880
             [--incremental] [--incremental-basedir]
2881
             [--incremental-dir] [--incremental-lsn]
2882
             BACKUP-ROOT-DIR
2883
254.3.1 by Rodrigo Gadea
Fix Bug #764936: Documentation's unit in ''--use-memory'' option is not correct.
2884
innobackupex --apply-log [--use-memory=B] [--uncompress]
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
2885
             [--defaults-file=MY.CNF]
2886
             [--export] [--redo-only] [--ibbackup=IBBACKUP-BINARY]
2887
             BACKUP-DIR
2888
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
2889
innobackupex --copy-back [--defaults-file=MY.CNF] [--defaults-group=GROUP-NAME] BACKUP-DIR
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
2890
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
2891
innobackupex --move-back [--defaults-file=MY.CNF] [--defaults-group=GROUP-NAME] BACKUP-DIR
2892
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
2893
=head1 DESCRIPTION
2894
2895
The first command line above makes a hot backup of a MySQL database.
2896
By default it creates a backup directory (named by the current date
2897
and time) in the given backup root directory.  With the --no-timestamp
2898
option it does not create a time-stamped backup directory, but it puts
2899
the backup in the given directory (which must not exist).  This
2900
command makes a complete backup of all MyISAM and InnoDB tables and
2901
indexes in all databases or in all of the databases specified with the
2902
--databases option.  The created backup contains .frm, .MRG, .MYD,
471.6.1 by Alexey Kopytov
Bug #733665: innobackupex not supporting Maria 5.2
2903
.MYI, .MAD, .MAI, .TRG, .TRN, .ARM, .ARZ, .CSM, CSV, .opt, .par, and
2904
InnoDB data and log files.  The MY.CNF options file defines the
2905
location of the database.  This command connects to the MySQL server
2906
using the mysql client program, and runs xtrabackup as a child
2907
process.
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
2908
2909
The --apply-log command prepares a backup for starting a MySQL
2910
server on the backup. This command recovers InnoDB data files as specified
2911
in BACKUP-DIR/backup-my.cnf using BACKUP-DIR/xtrabackup_logfile,
2912
and creates new InnoDB log files as specified in BACKUP-DIR/backup-my.cnf.
2913
The BACKUP-DIR should be the path to a backup directory created by
2914
xtrabackup. This command runs xtrabackup as a child process, but it does not 
2915
connect to the database server.
2916
2917
The --copy-back command copies data, index, and log files
2918
from the backup directory back to their original locations.
2919
The MY.CNF options file defines the original location of the database.
2920
The BACKUP-DIR is the path to a backup directory created by xtrabackup.
2921
465 by Alexey Kopytov
Bug #803636: "moves files" option needed with --copy-back
2922
The --move-back command is similar to --copy-back with the only difference that
2923
it moves files to their original locations rather than copies them. As this
2924
option removes backup files, it must be used with caution. It may be useful in
2925
cases when there is not enough free disk space to copy files.
2926
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
2927
On success the exit code innobackupex is 0. A non-zero exit code 
2928
indicates an error.
2929
2930
2931
=head1 OPTIONS
2932
2933
=over
2934
2935
=item --apply-log
2936
2937
Prepare a backup in BACKUP-DIR by applying the transaction log file named "xtrabackup_logfile" located in the same directory. Also, create new transaction logs. The InnoDB configuration is read from the file "backup-my.cnf".
2938
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
2939
=item --compress
2940
2941
This option instructs xtrabackup to compress backup copies of InnoDB
2942
data files. It is passed directly to the xtrabackup child process. Try
2943
'xtrabackup --help' for more details.
2944
2945
=item --compress-threads
2946
2947
This option specifies the number of worker threads that will be used
2948
for parallel compression. It is passed directly to the xtrabackup
2949
child process. Try 'xtrabackup --help' for more details.
2950
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
2951
=item --copy-back
2952
2953
Copy all the files in a previously made backup from the backup directory to their original locations.
2954
2955
=item --databases=LIST
2956
466.1.1 by Hrvoje Matijakovic
* updated the supported releases in apt_repo
2957
This option specifies the list of databases that innobackupex should back up. The option accepts a string argument or path to file that contains the list of databases to back up. The list is of the form "databasename1[.table_name1] databasename2[.table_name2] . . .". If this option is not specified, all databases containing MyISAM and InnoDB tables will be backed up.  Please make sure that --databases contains all of the InnoDB databases and tables, so that all of the innodb.frm files are also backed up. In case the list is very long, this can be specified in a file, and the full path of the file can be specified instead of the list. (See option --tables-file.)
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
2958
2959
=item --defaults-file=[MY.CNF]
2960
2961
This option specifies what file to read the default MySQL options from.  The option accepts a string argument. It is also passed directly to xtrabackup's --defaults-file option. See the xtrabackup documentation for details.
2962
487.3.1 by George O. Lorch III
Incorporated patch for Bug #740489 : Add --defaults-extra-file param to innobackupex
2963
=item --defaults-extra-file=[MY.CNF]
2964
2965
This option specifies what extra file to read the default MySQL options from before the standard defaults-file.  The option accepts a string argument. It is also passed directly to xtrabackup's --defaults-extra-file option. See the xtrabackup documentation for details.
2966
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
2967
=item --export
2968
2969
This option is passed directly to xtrabackup's --export option. It enables exporting individual tables for import into another server. See the xtrabackup documentation for details.
2970
2971
=item --extra-lsndir=DIRECTORY
2972
2973
This option specifies the directory in which to save an extra copy of the "xtrabackup_checkpoints" file.  The option accepts a string argument. It is passed directly to xtrabackup's --extra-lsndir option. See the xtrabackup documentation for details.
2974
450.1.1 by Hrvoje Matijakovic
* bugfix for Bug #1032090
2975
=item --galera-info
2976
2977
This options creates the xtrabackup_galera_info file which contians the local node state at the time of the backup. Option should be used when performing the backup of Percona-XtraDB-Cluster.
2978
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
2979
=item --help
2980
2981
This option displays a help screen and exits.
2982
2983
=item --host=HOST
2984
2985
This option specifies the host to use when connecting to the database server with TCP/IP.  The option accepts a string argument. It is passed to the mysql child process without alteration. See mysql --help for details.
2986
242.17.19 by Alexey Kopytov
Bug #809073: ibbackup-binary option in innobackupex does not work
2987
=item --ibbackup=IBBACKUP-BINARY
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
2988
2989
This option specifies which xtrabackup binary should be used.  The option accepts a string argument. IBBACKUP-BINARY should be the command used to run XtraBackup. The option can be useful if the xtrabackup binary is not in your search path or working directory. If this option is not specified, innobackupex attempts to determine the binary to use automatically. By default, "xtrabackup" is the command used. However, when option --copy-back is specified, "xtrabackup_51" is the command used. And when option --apply-log is specified, the binary is used whose name is in the file "xtrabackup_binary" in the backup directory, if that file exists.
2990
2991
=item --include=REGEXP
2992
2993
This option is a regular expression to be matched against table names in databasename.tablename format. It is passed directly to xtrabackup's --tables option. See the xtrabackup documentation for details.
2994
2995
=item --incremental
2996
2997
This option tells xtrabackup to create an incremental backup, rather than a full one. It is passed to the xtrabackup child process. When this option is specified, either --incremental-lsn or --incremental-basedir can also be given. If neither option is given, option --incremental-basedir is passed to xtrabackup by default, set to the first timestamped backup directory in the backup base directory.
2998
2999
=item --incremental-basedir=DIRECTORY
3000
3001
This option specifies the directory containing the full backup that is the base dataset for the incremental backup.  The option accepts a string argument. It is used with the --incremental option.
3002
3003
=item --incremental-dir=DIRECTORY
3004
3005
This option specifies the directory where the incremental backup will be combined with the full backup to make a new full backup.  The option accepts a string argument. It is used with the --incremental option.
3006
3007
=item --incremental-lsn
3008
3009
This option specifies the log sequence number (LSN) to use for the incremental backup.  The option accepts a string argument. It is used with the --incremental option. It is used instead of specifying --incremental-basedir. For databases created by MySQL and Percona Server 5.0-series versions, specify the LSN as two 32-bit integers in high:low format. For databases created in 5.1 and later, specify the LSN as a single 64-bit integer.
3010
470.1.1 by Hrvoje Matijakovic
* release notes for 2.0.3
3011
=item --move-back
3012
3013
Move all the files in a previously made backup from the backup directory to the actual datadir location. Use with caution, as it removes backup files.
3014
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
3015
=item --no-lock
3016
499.1.1 by Hrvoje Matijakovic
- Bug fixes for: Bug #1100008, Bug #1095925, Bug #1092235, Bug #1088967,
3017
Use this option to disable table lock with "FLUSH TABLES WITH READ LOCK". Use it only if ALL your tables are InnoDB and you DO NOT CARE about the binary log position of the backup. This option shouldn't be used if there are any DDL statements being executed or if any updates are happening on non-InnoDB tables (this includes the system MyISAM tables in the mysql database), otherwise it could lead to an inconsistent backup. If you are considering to use --no-lock because your backups are failing to acquire the lock, this could be because of incoming replication events preventing the lock from succeeding. Please try using --safe-slave-backup to momentarily stop the replication slave thread, this may help the backup to succeed and you then don't need to resort to using this option.
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
3018
3019
=item --no-timestamp
3020
3021
This option prevents creation of a time-stamped subdirectory of the BACKUP-ROOT-DIR given on the command line. When it is specified, the backup is done in BACKUP-ROOT-DIR instead.
3022
3023
=item --parallel=NUMBER-OF-THREADS
3024
3025
This option specifies the number of threads the xtrabackup child process should use to back up files concurrently.  The option accepts an integer argument. It is passed directly to xtrabackup's --parallel option. See the xtrabackup documentation for details.
3026
3027
3028
=item --password=WORD
3029
3030
This option specifies the password to use when connecting to the database. It accepts a string argument.  It is passed to the mysql child process without alteration. See mysql --help for details.
3031
3032
=item --port=PORT
3033
3034
This option specifies the port to use when connecting to the database server with TCP/IP.  The option accepts a string argument. It is passed to the mysql child process. It is passed to the mysql child process without alteration. See mysql --help for details.
3035
3036
=item --redo-only
3037
499.1.1 by Hrvoje Matijakovic
- Bug fixes for: Bug #1100008, Bug #1095925, Bug #1092235, Bug #1088967,
3038
This option should be used when preparing the base full backup and when merging all incrementals except the last one. This option is passed directly to xtrabackup's --apply-log-only option. This forces xtrabackup to skip the "rollback" phase and do a "redo" only. This is necessary if the backup will have incremental changes applied to it later. See the xtrabackup documentation for details. 
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
3039
3040
=item --remote-host=HOSTNAME 
3041
242.47.3 by Stewart Smith
merge deprecation warning for --remote-host, updating version it to be removed in to 2.1
3042
This option is DEPRECATED and will be removed in Percona XtraBackup 2.1. In Percona XtraBackup 2.0 and later, you should use streaming backups instead. This option specifies the remote host on which the backup files will be created, by using an ssh connection.  The option accepts a string argument.
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
3043
477.2.1 by Hrvoje Matijakovic
Bug fixes for bug: Bug #1073502, Bug #1075269 and Bug #1066978
3044
=item --rsync
3045
3046
Uses the rsync utility to optimize local file transfers. When this option is specified, innobackupex uses rsync to copy all non-InnoDB files instead of spawning a separate cp for each file, which can be much faster for servers with a large number of databases or tables.  This option cannot be used together with --remote-host or --stream.
3047
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
3048
=item --safe-slave-backup
3049
3050
Stop slave SQL thread and wait to start backup until Slave_open_temp_tables in "SHOW STATUS" is zero. If there are no open temporary tables, the backup will take place, otherwise the SQL thread will be started and stopped until there are no open temporary tables. The backup will fail if Slave_open_temp_tables does not become zero after --safe-slave-backup-timeout seconds. The slave SQL thread will be restarted when the backup finishes.
3051
3052
=item --safe-slave-backup-timeout
3053
3054
How many seconds --safe-slave-backup should wait for Slave_open_temp_tables to become zero. (default 300)
3055
3056
=item --scpopt=SCP-OPTIONS
3057
3058
This option specifies the command line options to pass to scp when the option --remost-host is specified.  The option accepts a string argument. If the option is not specified, the default options are "-Cp -c arcfour".
3059
371 by Alexey Kopytov
Cherrypick of fix for bug 733658: pass options to both ssh and scp.
3060
=item --sshopt=SSH-OPTIONS
3061
3062
This option specifies the command line options to pass to ssh when the option --remost-host is specified.  The option accepts a string argument.
3063
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
3064
=item --slave-info
3065
3066
This option is useful when backing up a replication slave server. It prints the binary log position and name of the master server. It also writes this information to the "xtrabackup_slave_info" file as a "CHANGE MASTER" command. A new slave for this master can be set up by starting a slave server on this backup and issuing a "CHANGE MASTER" command with the binary log position saved in the "xtrabackup_slave_info" file.
3067
3068
=item --socket=SOCKET
3069
3070
This option specifies the socket to use when connecting to the local database server with a UNIX domain socket.  The option accepts a string argument. It is passed to the mysql child process without alteration. See mysql --help for details.
3071
477.2.1 by Hrvoje Matijakovic
Bug fixes for bug: Bug #1073502, Bug #1075269 and Bug #1066978
3072
=item --stream=STREAMNAME
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
3073
385.1.1 by Alexey Kopytov
Rebase of the parallel compression patch on new trunk + post-review
3074
This option specifies the format in which to do the streamed backup.  The option accepts a string argument. The backup will be done to STDOUT in the specified format. Currently, the only supported formats are tar and xbstream. This option is passed directly to xtrabackup's --stream option.
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
3075
3076
=item --tables-file=FILE
3077
3078
This option specifies the file in which there are a list of names of the form database.  The option accepts a string argument.table, one per line. The option is passed directly to xtrabackup's --tables-file option.
3079
3080
=item --throttle=IOS
3081
3082
This option specifies a number of I/O operations (pairs of read+write) per second.  It accepts an integer argument.  It is passed directly to xtrabackup's --throttle option.
3083
3084
=item --tmpdir=DIRECTORY
3085
3086
This option specifies the location where a temporary file will be stored.  The option accepts a string argument. It should be used when --remote-host or --stream is specified. For these options, the transaction log will first be stored to a temporary file, before streaming or copying to a remote host. This option specifies the location where that temporary file will be stored. If the option is not specifed, the default is to use the value of tmpdir read from the server configuration.
3087
254.3.1 by Rodrigo Gadea
Fix Bug #764936: Documentation's unit in ''--use-memory'' option is not correct.
3088
=item --use-memory=B
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
3089
254.3.1 by Rodrigo Gadea
Fix Bug #764936: Documentation's unit in ''--use-memory'' option is not correct.
3090
This option accepts a string argument that specifies the amount of memory in bytes for xtrabackup to use for crash recovery while preparing a backup. Multiples are supported providing the unit (e.g. 1MB, 1GB). It is used only with the option --apply-log. It is passed directly to xtrabackup's --use-memory option. See the xtrabackup documentation for details.
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
3091
3092
=item --user=NAME
3093
3094
This option specifies the MySQL username used when connecting to the server, if that's not the current user. The option accepts a string argument.  It is passed to the mysql child process without alteration. See mysql --help for details.
3095
427.1.2 by Sergei Glushchenko
Bug #483827. Support for mysqld_multi.
3096
=item --defaults-group=GROUP-NAME
3097
3098
This option specifies the group name in my.cnf which should be used. This is needed for mysqld_multi deployments.
3099
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
3100
=item --version
3101
3102
This option displays the xtrabackup version and copyright notice and then exits.
3103
3104
=back
3105
3106
=head1 BUGS
3107
3108
Bugs can be reported on Launchpad: https://bugs.launchpad.net/percona-xtrabackup/+filebug
3109
3110
=head1 COPYRIGHT
3111
356 by Alexey Kopytov
Cherrypick of (C) string update due to 2012.
3112
InnoDB Backup Utility Copyright 2003, 2009 Innobase Oy and Percona, Inc 2009-2012. All Rights Reserved.
240 by Alexey Kopytov
Updates to built-in innobackupex usage docs.
3113
3114
This software is published under the GNU GENERAL PUBLIC LICENSE Version 2, June 1991.
3115
3116
=cut