This utility is deprecated in MySQL 5.6.20 and removed in MySQL 5.7
mysqlhotcopy is a Perl script that was
originally written and contributed by Tim Bunce. It uses
FLUSH TABLES,
LOCK TABLES, and
cp or scp to make a
database backup. It is a fast way to make a backup of the
database or single tables, but it can be run only on the same
machine where the database directories are located.
mysqlhotcopy works only for backing up
MyISAM and ARCHIVE tables.
It runs on Unix.
To use mysqlhotcopy, you must have read
access to the files for the tables that you are backing up, the
SELECT privilege for those
tables, the RELOAD privilege (to
be able to execute FLUSH
TABLES), and the LOCK
TABLES privilege (to be able to lock the tables).
shell> mysqlhotcopy db_name [/path/to/new_directory]
shell> mysqlhotcopy db_name_1 ... db_name_n /path/to/new_directory
Back up tables in the given database that match a regular expression:
shell> mysqlhotcopy db_name./regex/
The regular expression for the table name can be negated by
prefixing it with a tilde (~):
shell> mysqlhotcopy db_name./~regex/
mysqlhotcopy supports the following options,
which can be specified on the command line or in the
[mysqlhotcopy] and
[client] groups of an option file. For
information about option files used by MySQL programs, see
Section 4.2.6, “Using Option Files”.
Table 4.20 mysqlhotcopy Options
| Format | Description |
|---|---|
| --addtodest | Do not rename target directory (if it exists); merely add files to it |
| --allowold | Do not abort if a target exists; rename it by adding an _old suffix |
| --checkpoint | Insert checkpoint entries |
| --chroot | Base directory of the chroot jail in which mysqld operates |
| --debug | Write debugging log |
| --dryrun | Report actions without performing them |
| --flushlog | Flush logs after all tables are locked |
| --help | Display help message and exit |
| --host | Connect to MySQL server on given host |
| --keepold | Do not delete previous (renamed) target when done |
| --method | The method for copying files |
| --noindices | Do not include full index files in the backup |
| --old_server | Connect to server that does not support FLUSH TABLES tbl_list WITH READ LOCK |
| --password | Password to use when connecting to server |
| --port | TCP/IP port number to use for connection |
| --quiet | Be silent except for errors |
| --regexp | Copy all databases with names that match the given regular expression |
| --resetmaster | Reset the binary log after locking all the tables |
| --resetslave | Reset the master.info file after locking all the tables |
| --socket | For connections to localhost, the Unix socket file to use |
| --tmpdir | The temporary directory |
| --user | MySQL user name to use when connecting to server |
--help,-?Display a help message and exit.
Do not rename target directory (if it exists); merely add files to it.
Do not abort if a target exists; rename it by adding an
_oldsuffix.Insert checkpoint entries into the specified database
db_nameand tabletbl_name.Base directory of the chroot jail in which mysqld operates. The
dir_namevalue should match that of the--chrootoption given to mysqld.Enable debug output.
--dryrun,-nReport actions without performing them.
Flush logs after all tables are locked.
--host=,host_name-hhost_nameThe host name of the local host to use for making a TCP/IP connection to the local server. By default, the connection is made to
localhostusing a Unix socket file.Do not delete previous (renamed) target when done.
The method for copying files (
cporscp). The default iscp.Do not include full index files for
MyISAMtables in the backup. This makes the backup smaller and faster. The indexes for reloaded tables can be reconstructed later with myisamchk -rq.--password=,password-ppasswordThe password to use when connecting to the server. The password value is not optional for this option, unlike for other MySQL programs.
Specifying a password on the command line should be considered insecure. See Section 6.1.2.1, “End-User Guidelines for Password Security”. You can use an option file to avoid giving the password on the command line.
--port=,port_num-Pport_numThe TCP/IP port number to use when connecting to the local server.
In MySQL 5.6, mysqlhotcopy uses
FLUSH TABLESto flush and lock tables. Use thetbl_listWITH READ LOCK--old_serveroption if the server is older than 5.5.3, which is when that statement was introduced.--quiet,-qBe silent except for errors.
--record_log_pos=db_name.tbl_nameRecord master and slave status in the specified database
db_nameand tabletbl_name.Copy all databases with names that match the given regular expression.
Reset the binary log after locking all the tables.
Reset the master info repository file or table after locking all the tables.
--socket=,path-SpathThe Unix socket file to use for connections to
localhost.The suffix to use for names of copied databases.
The temporary directory. The default is
/tmp.--user=,user_name-uuser_nameThe MySQL user name to use when connecting to the server.
Use perldoc for additional
mysqlhotcopy documentation, including
information about the structure of the tables needed for the
--checkpoint and
--record_log_pos options:
shell> perldoc mysqlhotcopy
Here it is, use at own risk.
package au.com.infomedix.utility;
import java.io.*;
import java.sql.*;
import java.util.Calendar;
import org.apache.commons.io.FileUtils;
/**
*
* A java representation of the perl mysqlhotcopy script
* Ref: http://dev.mysql.com/doc/refman/5.0/en/mysqlhotcopy.html
* <p>
* Some statistics for 28 files totaling 640MB:<br>
* <br>Windows Native: 104375 msecs
* <br>UNIX Native: 95520 msecs
* <br>
* <br>UNIX commons-io: 94657 msecs (1.5 mins)
* <br>WINDOWS commons-io: 96360 msecs (1.5 mins)
* <br>
*
* @TODO: Add a debug/verbose flag
* @TODO: Add more options
*
* @author Andrew Bruno
*
*/
public class MySqlHotCopy
{
private String username = null;
private String password = null;
/*
* Should always be localhost as files are assumed to be on the same server
* that mysql is running on. On Unix use 127.0.0.1 and not localhost or else
* you'll get Socket Exceptions
*/
private final String host = "127.0.0.1";
private String database = null;
private String url = null;
private String dirSourceIndex = null;
private String dirBackup = null;
private String copymode = null;
private static boolean error = false;
public MySqlHotCopy()
{
super();
}
public MySqlHotCopy( String args[] )
{
super();
username = args[0];
password = args[1];
database = args[2];
dirSourceIndex = args[3];
dirBackup = args[4];
copymode = args[5];
url = "jdbc:mysql://" + host + "/" + database;
}
/**
* @param args
*/
public static void main(String[] args)
{
if (args.length <= 0)
{
showUsageAndExit("Parameters missing", args);
}
else
{
if (args.length != 6)
{
showUsageAndExit("6 Parameters required", args);
}
else
{
MySqlHotCopy mySqlHotCopy = new MySqlHotCopy(args);
Connection conn = null;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(mySqlHotCopy.url, mySqlHotCopy.username, mySqlHotCopy.password);
System.out.println("Database connection established");
Statement s = conn.createStatement();
s.executeQuery("SHOW TABLES");
ResultSet rs = s.getResultSet();
String lockSqlCommand = "LOCK TABLES ";
String flushSqlCommand = "FLUSH TABLES ";
while (rs.next())
{
String tableName = (String) rs.getObject(1);
lockSqlCommand = lockSqlCommand + tableName + " READ";
flushSqlCommand = flushSqlCommand + tableName;
if (rs.isLast())
{
lockSqlCommand = lockSqlCommand + ";";
flushSqlCommand = flushSqlCommand + ";";
}
else
{
lockSqlCommand = lockSqlCommand + ", ";
flushSqlCommand = flushSqlCommand + ", ";
}
}
rs.close();
System.out.println("Lock Sql Command is " + lockSqlCommand);
System.out.println("Flush Sql Command is " + flushSqlCommand);
s.executeUpdate(lockSqlCommand);
s.executeUpdate(flushSqlCommand);
s.executeUpdate("FLUSH LOGS");
// s.executeUpdate("RESET MASTER");
// s.executeUpdate("RESET SLAVE");
long time = Calendar.getInstance().getTimeInMillis();
if (mySqlHotCopy.copymode.equals("nativedos"))
{
System.out.println("Using Native Dos mode to copy files");
String copyCommand = "cmd /c COPY /Y \"" + mySqlHotCopy.dirSourceIndex + "\" \"" + mySqlHotCopy.dirBackup + "\"";
System.out.println("DOS Copy Command = '" + copyCommand + "'");
Process process = Runtime.getRuntime().exec(copyCommand);
DataInputStream p_in = new DataInputStream(process.getInputStream());
BufferedReader d = new BufferedReader(new InputStreamReader(p_in));
String p_str;
while ((p_str = d.readLine()) != null)
{
System.out.println(p_str);
}
if (process.exitValue() != 0)
{
System.out.println("Dos copy process exited with an error value of " + process.exitValue());
}
}
else if (mySqlHotCopy.copymode.equals("nativeunix"))
{
final String copyCommand = "/bin/cp -v " + mySqlHotCopy.dirSourceIndex + "*" + " " + mySqlHotCopy.dirBackup;
System.out.println("Using Native Unix mode to copy files");
String[] cmd = { "/bin/sh", "-c", copyCommand };
System.out.println("UNIX Copy Command = '" + copyCommand + "'");
// See
// http://www.mountainstorm.com/publications/javazine.html
Process process = Runtime.getRuntime().exec(cmd, null, null);
DataInputStream p_in = new DataInputStream(process.getInputStream());
BufferedReader d_in = new BufferedReader(new InputStreamReader(p_in));
String p_str;
while ((p_str = d_in.readLine()) != null)
{
System.out.println(p_str);
}
DataInputStream p_err = new DataInputStream(process.getErrorStream());
BufferedReader d_err = new BufferedReader(new InputStreamReader(p_err));
String p_err_str;
while ((p_err_str = d_err.readLine()) != null)
{
System.out.println(p_err_str);
}
// OutputStreamWriter osWriter = new
// OutputStreamWriter(process.getOutputStream());
// PrintWriter out = new PrintWriter(osWriter);
// if ((process != null) && (process.exitValue() != 0))
// {
// System.out.println("UNIX copy process exited with an
// error value of " + process.exitValue());
// }
}
else if (mySqlHotCopy.copymode.equals("commonsiojava"))
{
System.out.println("Using Commons IO mode to copy files");
FileUtils.copyDirectory(new File(mySqlHotCopy.dirSourceIndex), new File(mySqlHotCopy.dirBackup));
}
else
{
showUsageAndExit("copymode " + mySqlHotCopy.copymode + " not supported", args);
}
time = Calendar.getInstance().getTimeInMillis() - time;
System.out.println("Copying of files took " + time + " milleseconds");
/* I dont think this is really needed */
s.executeUpdate("UNLOCK TABLES");
s.close();
}
catch (Exception e)
{
System.err.println("Exception caught: " + e.getMessage());
e.printStackTrace();
error = true;
}
finally
{
if (conn != null)
{
try
{
conn.close();
// System.out.println("Database connection terminated");
}
catch (Exception e)
{ /* ignore close errors */
}
}
}
if (error)
System.exit(1);
else
System.exit(0);
}
}
}
private static void showUsageAndExit(String errorString, String[] args)
{
System.err.println();
if ((errorString != null) && (errorString.length() != 0))
{
System.err.println("Error Message: " + errorString);
}
if (args.length != 0)
{
System.err.print(MySqlHotCopy.class.getName() + " called with parameters ");
for (int i = 0; i < args.length; i++)
{
String string = args[i];
System.err.print(string + " ");
}
System.err.println();
}
System.out.println("Usage: au.com.infomedix.udr.utility.MySqlHotCopy username password database dbindexdir dbbackupindexdir <copymode>");
System.out.println("where <copymode> is one of: ");
System.out.println("\t nativedos");
System.out.println("\t nativeunix");
System.out.println("\t commonsiojava");
System.exit(1);
}
}
On the other hand, if there is a way to find the directory location of where the index files to the MYISAM are via an SQL query, then you could alter code, and remove the sourceIndexDir field. This would add safely, and make the code smarter.
A bug report with a potential fix has been submitted.
This is how I finally did it in one line in bash:
cd /tmp/mysqlhotcopies/ && mysqlhotcopy --flushlog --regexp '.*' . && for d in *; do { mysqlhotcopy --flushlog --addtodest $d /tmp/mysqlhotcopies; } done
Suggestions welcomed.
-Kevin
DBD::mysql::db do failed: Can't find file: '...'
To avoid this you should dump the databases separately, so instead of doing
mysqlhotcopy --regexp='.+'.'.+' <dumpdir>
do it in two or more steps, for instance
mysqlhotcopy --regexp='^[a-m].+'.'.+' <dumpdir>
mysqlhotcopy --regexp='^[n-z].+'.'.+' <dumpdir>
DBD::mysql::db do failed: File '_path_to_file_' not found (Errcode: 24) at /usr/bin/mysqlhotcopy line 466.
A similar work around using regexp to split up the number of tables to dump should work.
If there is a --all-databases option for this utility would be a more elegant solution.
#!/usr/bin/perl
opendir (D, "/var/lib/mysql");
@f = readdir (D);
closedir (D);
foreach $file (@f)
{
$filename = "/var/lib/mysql/" . $file;
if (-d $filename && $file ne '.' && $file ne '..')
{
system "/usr/bin/mysqlhotcopy --allowold -u root $file /backup/mysql/";
}
}
That way only tables in one database are locked when copying files. If you have some very large database and other smaller all are locked because it takes a long time to copy the big one although smaller could be copied instantly.
#!/bin/bash
BACKUP_DIR=/backup
for i in `/usr/bin/find /var/lib/mysql/* -type d -printf "%f\n"`;do /usr/bin/mysqlhotcopy --allowold -u root $i $BACKUP_DIR; done
http://groups.google.co.uk/group/mailing.database.myodbc/browse_frm/thread/6309388ee0b0b295/45c8077d82d240e1?hl=en&lnk=st&q=mysql+backup+noindices#45c8077d82d240e1
The manual page is at
http://dev.mysql.com/doc/refman/4.1/en/repair-table.html