mylvmbackup-0.13/0000755000175000001440000000000011250465474010774 500000000000000mylvmbackup-0.13/ChangeLog0000644000175000001440000004417111223221502012453 000000000000002009-07-02 Lenz Grimmer - Deleted sample precleanup.pm hook as it has potential to cause harm and is too specialized on a particular use case (BUG#394668) 2009-06-26 Lenz Grimmer - Added support for rsync via SSH (BUG#392462) - Fixed InnoDB recovery in case a relative path to the MySQL data directory is defined (BUG#38337), improved the documentation of relpath in the man page. 2009-06-18 Lenz Grimmer - Fixed allowed format strings for timestamped backupdir and mountdir directory names - Updated documentation: added information about hooks as Perl modules, added new logerr hook to the list of available hooks, use of format strings for the backupdir and mountdir. Documented the fact that these directories are now created automatically, if they don't exist. - Fixed Makefile and RPM spec file to install Perl hooks (and include them in the distribution) - Removed the absolute path names to external tools, as they tend to differ between Linux distributions - ensure to configure $PATH correctly instead - Added --log-err to the startup options of the InnoDB recovery instance to redirect logging output to $TMP/mylvmbackup_recoverserver.err (instead of using the primary instance's error log file, in case it has been defined in my.cnf) 2009-06-14 Lenz Grimmer - Merged contributions from Matthew Boehm: - Added support for date/time formatted file paths for the backupdir and mountdir. Example: $backupdir=/path/to/%Y/%m/%d will expand to /path/to/2008/10/02 and backups will go in there. - Added support to attempt to create $backupdir and $mountdir if they do not exist. - Added support for using Perl modules as hook scripts. Module must be named .pm and must be a package of type . Module must implement ->execute() which is called by mylvmbackup to initiate the hook. It must return boolean true/false (1 or 0) on success/failure. ->execute() will be passed 2 parameters. The first parameter is a clone() of the global $dbh. This will allow hook scripts to perform actions on the DB using the existing connection. The second parameter is a string containing any messages passed to the run_hook() function. Module must also implement ->errmsg() which will return a string error message to be sent to log_msg(). This will be called by mylvmbackup when ->execute() returns false/0. - Added new hook, 'logerr'. Called by log_msg() when log severity is LOG_ERR. Passes $msg to hook script. 2009-06-13 Lenz Grimmer - Removed the bind mount of the position file directory: copy the config files (position record and my.cnf) into the writable snapshot directly - Fixed the backup backends to honor this change, fixed the rsnap plugin to actually include the config files as well - Removed some hardcoded /tmp paths with a $TMP variable - Removed superflous $lvm_version variable 2009-06-07 Lenz Grimmer - Made Linux LVMv2 a requirement 2009-05-07 Lenz Grimmer - Applied patch by Tim Stoop: added option --keep_mount which keeps the snapshot mounted after the mylvmbackup run (which also implies --keep_snapshot) 2009-03-02 Lenz Grimmer - Updated all URL references to point to lenzg.net instead of lenzg.org - Applied small patch from Baron Schwartz to allow reading from ~/.my.cnf 2008-12-17 Lenz Grimmer - Added project home page URL to the --help output, added note about the existence of a sample config file to the man page - Add build date to the version string in the help output - Fixed check for backupdir to not require it when using rsync to a remote server or when not doing any backups with backuptype=none (Thanks to Ronald Bradford for these suggestions) 2008-11-23 Lenz Grimmer - Added new option "--quiet" that suppresses informal logging output (warnings and errors will still be printed/logged) - Small fixes to kjetilho's patch 2008-11-20 Lenz Grimmer - Applied patch from "kjetilho" that makes mylvmbackup more robust and paranoid when it comes to handling errors/failures (Bug #298175) Now the script aborts cleanly in case of any error. 2008-10-22 Lenz Grimmer - Fixed error handling in case of a failed DB connection (patch submitted by Matthew Boehm, Bug #280989) - Merged changes from Alexander Skwar: Fix for Bug #278478 and implemented Blueprint "Improve the tar backup backend of mylvmbackup" 2008-10-01 Lenz Grimmer - Fixed Bug #271671: "overloading parameters does not work" by removing the default values for host and port from the configuration file and removing the unnecessary check for passing both host and socket at the same time. Updated documentation and configuration file comments accordingly. - Applied patch suggested by "Jonas" to fix Bug #267944: "backup returns successfully when snapshot creation fails" - Code cleanup: moved flushing of tables in a separate subroutine flush_tables() - Code cleanup: moved log messages into the respective subroutines - Code cleanup: use return values of subroutines instead of updating global variables - Improved some log messages to explain what was DONE or FAILED - Code cleanup: build up long command strings in a $command variable before passing it to system() - Renamed subroutine create_snapshot() to create_lvm_snapshot() 2008-09-25 Lenz Grimmer - Merged patch from Matthew Boehm: Removed old asciidoc documentation in favor of POD style. This removes the dependency on the external program a2x for creating documentation and uses the 'built-in' pod2html and pod2man instead. Updated the Makefile to accommodate the change. 2008-09-24 Lenz Grimmer - Applied patch from Matthew Boehm to make the backup file name suffix configurable via a "--suffix" option. Updated the man page accordingly. 2008-09-23 Lenz Grimmer - Bumped up version number to 0.11 - Applied patch from Matt Lohier to support rsnap as a backup backend - Updated man page - Moved the list of contributors from the man page into a separate CREDITS file, added missing names - Updated the RPM spec file to include CREDITS 2008-09-03 Lenz Grimmer - Applied patch from Marc Haber: added option "--keep_snapshot" that will skip the removal of the backup snapshot before terminating the script. Providing the option "--backuptype=none" will now skip creating a backup using the builtin backup modules. Both options provide more flexibility when using hooks for performing the actual backup tasks. - Added two new hooks: "backupsuccess" and "backupfailure" which are called respectively upon success of failure of the backup operation (Bug #264089) - Updated documentation 2008-07-18 Lenz Grimmer - Make sure that binaries are being found ($PATH may not include /sbin when called from cron), added missing entry for "lvs" to mylvmbackup.conf (Bug #255703) 2008-07-10 Lenz Grimmer - Applied patch from Patrick Hahn: provide an option to call external scripts/applications (hooks) at various stages of the backup process. See the man page for instructions - Added options "--skip_hooks" to disable the execution of hooks and "--hooksdir" to define the location for these (default is /usr/share/mylvmbackup) - Updated documentation: added new options and instructions on how to use hooks - Updated TODO 2008-07-09 Lenz Grimmer - Applied patch from Robin H. Johnson: Full support for an rsync:// service as the backup destination. If you include any path fragments with the rsync module name, they must already exist! - Updated documentation to reflect this change 2008-06-25 Lenz Grimmer - The mylvmbackup source tree was moved from Subversion to Bazaar and is now hosted on Launchpad.net: 2008-04-10 Lenz Grimmer - Bumped up version number to 0.9 2008-04-09 Lenz Grimmer - Fixed a bug in the InnoDB recovery function: the second mysqld process clobbered the socket file of the primary MySQL instance (thanks to Alain Hoang for reporting this) - Updated the man page, noted some other limitations of the InnoDB recovery function 2008-04-04 Lenz Grimmer - Bumped up version number to 0.8 2008-03-03 Lenz Grimmer - Bug fix: use the correct mysqld parameter to provide an alternative PID file (--pid-file instead of --pidfile) - thanks to Guillaume Boddaert and Jim Wilson for reporting this! - Added option "--skip_mycnf" to skip including a copy of the MySQL configuration file in the backup, added a safety check that the file actually exists prior to backing it up. 2007-10-27 Lenz Grimmer - Bumped up version number to 0.7 2007-10-27 Lenz Grimmer - Use mktemp/mkdtemp to generate the random temporary file/directory names 2007-10-27 Robin H. Johnson - Add rsync backup type. This is very useful if you want to use mylvmbackup to create the initial state for your slave servers. - Shrink the --help output by only listing common options, and referring the user to the manpage for further information. 2007-10-20 Robin H. Johnson - Add support for a trailing argument to tar, can be used for excluding files. - Clean up variable ordering and manpage to ensure that all arguments/configopts are documented. - Do not start NDB or a replication slave when performing InnoDB recovery - Separate out the suffix of the tarball (Preparation for rsync and users that want to use bzip2 or no compression.) - Use a temporary suffix at the end of the tar backup file to indicate that it is incomplete. - Applied patch from Robin H. Johnson: Include the my.cnf file in the backup. (TODO: make this optional and check for the existence of the file before copying it) - Add the ability to run an extra FLUSH TABLES for busy databases where lvcreate might take a long time (and may overrun the interactivity timeout on the connection, losing the lock). 2007-09-13 Lenz Grimmer - Added option "--pidfile" to provide an alternative PID file location for the second server instance that is started to perform the InnoDB recovery on the snapshot prior to backing it up (Otherwise it may default to using the same pid file location that the running server uses and safe_mysqld will abort) - thanks to Kristian Köhntopp for making me aware of this problem - Before discarding the snapshot LV, the output of "lvs " is now printed out for diagnostics. It contains useful information like "how much percent of the backing store was used, which helps tuning the size of the snapshot LV. - Updated the man page, documented the new pidfile option and added a section with general hints 2007-07-03 Lenz Grimmer - Added option "--skip-flush-tables" that performs the snapshot without flushing the tables to disk beforehand (which is not supported by InnoDB tables anyway) - this would save time, as the flushing can take some time, depending on the buffer sizes. (Thanks to Peter Zaitsev for the suggestion) 2007-05-31 Lenz Grimmer - Bumped up version number to 0.6 - Updated man page and README to list all required Perl modules (thanks to Scott Kaminiski for pointing this out) - Replaced the call to the external /bin/date binary for creating the timestamp string with a builtin function (using Date::Format) 2007-05-07 Lenz Grimmer - Bumped up version number to 0.5 - Slightly reworked Eric's patch and performed some minor code cleanup - Documented the InnoDB recovery option in the man page 2007-04-12 Eric Bergen - Added Option "--innodb-recover", which provides an option to run InnoDB recovery on LVM2 snapshots (which provide write access to the device) prior to creating the backup archive. This speeds up resuming a MySQL instance from a restored backup. Also fixed a bug with the default value handling for command line options. In version 0.4 if a config file was specified default values in the script were all changed to blank. This means that the config file had to supply values for every variable instead of just the values that need to be changed from default. 2007-01-14 Lenz Grimmer - Bumped up version number to 0.4 - Fixed DSN string handling (thanks to Peter Zaitsev for spotting this) - removed a few unused configuration options from the config file (we can re-add them once they are really used) - Slightly cleaned up Robin's changes, updated the man page and help output - Fixed logging to the console (log levels were not printed) 2007-01-12 Robin H. Johnson - Clean up option handling to load the defaults, followed by the default configuration file, followed by an alternative configuration file (specified via CLI arguments), followed by the remainder of the CLI arguments. - Do cleanups on directory inputs for spaces and trailing slashes. - Enforce a non-empty prefix at all times. - Change the capture of the position file and tarball creation to not use absolute paths, and instead use them relative to $mountdir. - Utilize a bindmount to get the position directory near the $mountdir for the tarball creation. - 'use vars' has been deprecated by upstream way back in Perl-5.6.0 http://perldoc.perl.org/vars.html, use 'my' instead. 2006-11-24 Lenz Grimmer - Cleaned up Fred's patch a bit: added --help output and corrected the option handling. Provide sane default values when no option file is used. - Only require SyS::Syslog if we actually use syslog for logging (less Perl module dependencies) - Slightly beefed up the console logging by printing a time stamp in front of the message and display "Info/Warning/Error/" according to the log level. - Removed syslog_ident and syslog_args from the command line options and config file (these remain hardcoded) - added check for hostname, if remote logging is requested - Updated and reformatted the help output - Changed the name of the default logging from "standard" to "console" - Added descriptions of the new logging options to the man page - Released as version 0.3 2006-11-23 Fred Blaise - Added functionality to use syslog for logging activity. This requires the Sys::Syslog Perl module. - Bugfix: in GetOptions, tar and umount were pointing to the mount binary. - Do not append a '/' to $mountdir if $prefix is empty. - Bugfix: Corrected variable 'date_format' back to 'datefmt' - Bugfix: Removed tailing slash for backupdir and mountdir in config file to avoid resulting double slash with unused variable - Bugfix: Fixed wrong section assignation of $prefix (misc, instead of lvm), which resulted in uninitialized value. 2006-11-23 Lenz Grimmer - slightly cleaned up Fred's patch, reverted using the previous default values and match the variables used in the config file with the command line options - Updated TODO (supporting external config files is done, thanks) - bumped up version number to 0.3 - Added installing of the config file to the Makefile - Changed the default LVM snapshot size from 10M to 5G to match the defaults - Added the config file to the RPM file list - Changed the script to still work without the configfile, falling back to builtin defaults (to revert the previous behavior). - Started converting the man page to asciidoc for easier maintenance and more possibilities to convert to other formats like HTML or DocBook. - Renamed the man page input file, added man page building with a2x to the Makefile 2006-11-22 Fred Blaise - Added initial support for using an external /etc/mylvmbackup.conf configuration file (requiring the Config::IniFiles Perl module) 2006-11-21 Lenz Grimmer - Removed the START/STOP SLAVE calls (They cause problems where the box isn't a slave, and don't actually help anything where the box is a slave) - thanks to Robin H. Johnson for reporting this and Fred Blaise for verifying it. 2006-11-15 Lenz Grimmer - Added Makefile to perform various build and installation tasks - Renamed the mylvmbackup source file to mylvmbackup.pl.in, which is turned into the mylvmbackup executable by the Makefile - Added RPM spec file to build RPM packages - Updated Version to 0.2 (now defined in the Makefile) - Updated INSTALL file, now one can run "make install" instead of manually copying the files - Updated TODO list - Released as version 0.2 2006-11-14 Lenz Grimmer - Documented Robin's changes in the man page, cleaned up the man page in general - Added new option: 'datefmt' that allows one to define the format of the date time stamp in the backup file name 2006-11-12 Robin H. Johnson - General cleanup, intended to make mylvmbackup usable for distributions. - Add --xfs to help with using XFS snapshots (adds nouuid per LVM HOWTO) - Support for relative paths within the datadir LV. - Sane default locations for the snapshot mount point and the backup directory. Distributions should create /var/tmp/mylvmbackup/mnt/ and /var/tmp/mylvmbackup/backup/ on installation of mylvmbackup. - Add a prefix name for backups, to enable multiple parallel backups. - Add host/port/socket support for connecting to MySQL properly. - Give a little more output during the backup process. - Change the position file format to be a key/value pair style. - Capture the slave and master status during position capture. - Hidden option: 'tararg' to override the default 'cvzf' parameter to tar. - Hidden option: 'backuplv' to control the name of the snapshot LV. 2006-05-05 Lenz Grimmer - Initial version 0.1 - Moved out of the internal BK repository, added GPL license and additional info mylvmbackup-0.13/COPYING0000644000175000001440000004310611076405744011753 00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. mylvmbackup-0.13/CREDITS0000644000175000001440000000367511215454675011751 00000000000000Several people have contributed to the script since it has been released. See the ChangeLog for more details. Robin H. Johnson from the Gentoo project cleaned up the code and added several useful features, e.g. rsync backup support. Fred Blaise contributed the initial support to use an external configuration file and logging via syslog. Eric Bergen provided the code that performs the InnoDB recovery prior to performing the backup of LVM2 snapshot volumes. He also fixed the broken handling of default options. Kristian Köhntopp suggested the '--pidfile' option and to add the output of the LVM statistics for being able to better tune the snapshot size. Marc Haber provided a patch for keeping snapshots and using "none" as a backup type. Patrick Hahn provided an option to call external scripts/applications (hooks) at various stages of the backup process. Matt Lohier submitted the patch to support rsnap as a backup backend. Matthew Boehm contributed a patch to make the backup file name suffix configurable via a "--suffix" option and also converted the documentation from asciidoc to Perl POD. He also contributed a patch to improve the error handling in case of a failed database connection and support for using date/time format strings in the backupdir and mountdir path names. Matthew also provided patches that enabled the use hooks written as Perl modules. Alexander Skwar contributed a patch to support backups using different compression methods other than gzip for the tar backup as well as support for using a non-GNU tar for the archiving. "kjetilho" (https://launchpad.net/~kjetilho-ifi) contributed a patch to improve the robustness and error handling of the entire script. (Bug #298175) Tim Stoop provided a patch to enable the --keep-mount option. Baron Schwartz provided a patch to allow reading the username and password from ~/.my.cnf Ronald Bradford provided many helpful suggestions to improve the usability and robustness of the script. mylvmbackup-0.13/hooks/0000755000175000001440000000000011223221176012104 500000000000000mylvmbackup-0.13/hooks/backupfailure.pm0000644000175000001440000000047011215454675015215 00000000000000#!/usr/bin/perl -w package backupfailure; use strict; use Date::Format; use Sys::Hostname; sub execute() { my ($class, $dbh, $msg) = @_; my $hostname = hostname; my $today = time2str("%C", time); my $content = "Date: $today\nHost: $hostname\n"; # send an email here...or something.. return 1; } 1; mylvmbackup-0.13/hooks/logerr.pm0000644000175000001440000000023411215454675013670 00000000000000#!/usr/bin/perl -w package logerr; use strict; sub execute() { my ($class, $dbh, $msg) = @_; # send an email with $msg to admin.... return 1; } 1; mylvmbackup-0.13/hooks/preflush.pm0000644000175000001440000000041211215454675014224 00000000000000#!/usr/bin/perl -w package preflush; use strict; my $errstr; sub execute() { my ($class, $dbh, $msg) = @_; if(!$dbh->do("FLUSH LOGS")) { $errstr = "Unable to flush logs: " . $DBI::errstr; return 0; } return 1; } sub errmsg() { return $errstr; } 1; mylvmbackup-0.13/INSTALL0000644000175000001440000000102611114751007011731 00000000000000Installation of mylvmbackup is pretty straight-forward: Extract the tarball and enter the created directory: tar zxvf mylvmbackup-.tar.gz cd mylvmbackup- Install the program and man page: make install By default, the files will be installed in the /usr/local directory hierarchy. You can override this using the "prefix" variable, e.g.: make prefix=/usr install To remove the files, simply run: make uninstall That's it! See the README and manual page for more info on how to use mylvmbackup. mylvmbackup-0.13/Makefile0000644000175000001440000000517611217145772012364 00000000000000# # Simple Makefile for mylvmbackup # # required programs POD2MAN = /usr/bin/pod2man POD2HTML = /usr/bin/pod2html CHMOD = /bin/chmod CP = /bin/cp FIND = /usr/bin/find GZIP = /bin/gzip INSTALL = /usr/bin/install INSTALL_DATA = $(INSTALL) -m 644 INSTALL_PROGRAM = $(INSTALL) -m 755 INSTALL_CONF = $(INSTALL) -m 600 MV = /bin/mv RM = /bin/rm RPMBUILD = /usr/bin/rpmbuild RPMFLAGS = -ta --clean SED = /bin/sed SHELL = /bin/sh TAR = /bin/tar # define some variables NAME = mylvmbackup VERSION = 0.13 BUILDDATE = $(shell date +%Y-%m-%d) MAN1 = man/$(NAME).1 HOOKS := $(wildcard hooks/*.pm) DISTFILES = \ ChangeLog \ COPYING \ CREDITS \ hooks \ INSTALL \ Makefile \ man \ $(NAME) \ $(NAME).conf \ $(NAME).pl.in \ $(NAME).spec \ $(NAME).spec.in \ README \ TODO CLEANFILES = $(NAME).spec $(NAME) $(MAN1) $(MAN1).html prefix = /usr/local sysconfdir = /etc bindir = $(prefix)/bin datadir = $(prefix)/share/mylvmbackup distdir = $(NAME)-$(VERSION) mandir = $(prefix)/man man1dir = $(mandir)/man1 all: $(DISTFILES) $(MAN1) $(NAME).spec: $(NAME).spec.in $(SED) -e s/@VERSION@/$(VERSION)/ < $< > $@ $(NAME): $(NAME).pl.in $(SED) -e s/@BUILDDATE@/$(BUILDDATE)/ \ -e s/@VERSION@/$(VERSION)/ < $< > $@ $(CHMOD) 755 $@ $(MAN1): $(POD2MAN) man/$(NAME).pod > $(MAN1) htmlman: $(POD2HTML) man/$(NAME).pod > $(MAN1).html $(RM) -f pod2htmd.tmp pod2htmi.tmp install: all test -d $(DESTDIR)$(bindir) || $(INSTALL) -d $(DESTDIR)$(bindir) test -d $(DESTDIR)$(man1dir) || $(INSTALL) -d $(DESTDIR)$(man1dir) test -d $(DESTDIR)$(sysconfdir) || $(INSTALL) -d $(DESTDIR)$(sysconfdir) test -d $(DESTDIR)$(datadir) || $(INSTALL) -d $(DESTDIR)$(datadir) $(INSTALL_PROGRAM) $(NAME) $(DESTDIR)$(bindir) $(INSTALL_DATA) $(MAN1) $(DESTDIR)$(man1dir)/$(NAME).1 if test -f $(DESTDIR)$(sysconfdir)/$(NAME).conf ; then $(MV) $(DESTDIR)$(sysconfdir)/$(NAME).conf $(DESTDIR)$(sysconfdir)/$(NAME).conf.bak ; fi $(INSTALL_CONF) $(NAME).conf $(DESTDIR)$(sysconfdir) for HOOK in $(HOOKS) ; do if [ ! -f $(DESTDIR)$(datadir)/$$HOOK ] ; then $(INSTALL_DATA) -v $$HOOK $(DESTDIR)$(datadir) ; fi ; done uninstall: $(RM) -f $(DESTDIR)$(bindir)/$(NAME) $(RM) -f $(DESTDIR)$(man1dir)/$(NAME).1 $(RM) -f $(DESTDIR)$(sysconfdir)/$(NAME).conf for HOOK in $(notdir $(HOOKS)) ; do $(RM) -f $(DESTDIR)$(datadir)/$$HOOK ; done distdir: all if test -d $(distdir) ; then $(RM) -rf $(distdir) ; fi mkdir $(distdir) $(CP) -a $(DISTFILES) $(distdir) dist: distdir $(TAR) chof - $(distdir) | $(GZIP) -c > $(distdir).tar.gz $(RM) -rf $(distdir) rpm: dist $(RPMBUILD) $(RPMFLAGS) $(distdir).tar.gz .PHONY: clean clean: $(RM) -f $(CLEANFILES) maintainer-clean: clean $(RM) -f $(distdir).tar.gz mylvmbackup-0.13/man/0000755000175000001440000000000011250465467011551 500000000000000mylvmbackup-0.13/man/mylvmbackup.pod0000644000175000001440000004477611221166764014545 00000000000000=head1 NAME mylvmbackup - a utility for creating MySQL backups using LVM snapshots =head1 SYNOPSIS mylvmbackup [OPTIONS] =head1 DESCRIPTION mylvmbackup is a tool for quickly creating backups of MySQL server's data files. To perform a backup, mylvmbackup obtains a read lock on all tables and flushes all server caches to disk, makes an LVM snapshot of the volume containing the MySQL data directory, and unlocks the tables again. The snapshot process takes only a small amount of time. When it is done, the server can continue normal operations, while the actual file backup proceeds. The LVM snapshot is mounted to a temporary directory and all data is backed up using the I program. By default, the archive file is created using a name of the form I, where I, I, I
, I, I, and I represent the year, month, day, hour, minute, and second of the time at which the backup occurred. The default prefix I, date format and file suffix may be modified. The use of timestamped archive names allows you to run mylvmbackup many times without danger of overwriting old archives. Alternatively, instead of I, you may use I. This process is nearly identical, with the exception that the file suffix is not used. The rsync backup can perform both local backups as well as backing up to a remote server using rsyncd or rsync via SSH. mylvmbackup also supports creating backups by using I, which is a wrapper around I to automatically maintain and rotate a given number of last backups (7 by default). It utilizes hard links to link to unchanged files for saving disk space. Additionally, a backup type I is provided for cases where the user wants to use mylvmbackup only for creating the snapshots and intends to perform the actual backup by using the appropriate hooks. (Or for cases where the snapshot itself is considered to be the backup). =head1 GENERAL HINTS It is required to run mylvmbackup on the same host where the MySQL server runs. If your MySQL daemon is not listening on localhost or using the default socket location, you must specify I<--host> or I<--socket>. Even though mylvmbackup communicates with the server through a normal client connection to obtain the read lock and flush data, it performs the actual backup by accessing the file system directly. It is also a requirement that the MySQL server's data directory resides on an LVM volume. (It is, however, a good idea to do the LVM backup to a different partition than the one where the data directory resides. Otherwise, there is a good chance that LVM will run out of undo space for LVM snapshot maintenance and the backup will fail.) The user who invokes mylvmbackup must have sufficient filesystem permissions to create the LVM snapshot and mount it. This includes read/write access to the backup directory. If you plan to back up InnoDB tables using LVM snapshots, be advised that it is not sufficient to lock the tables and issue the I command to get the table files into a consistent state. When starting the MySQL server from these restored files, InnoDB will detect these tables as being in an inconsistent state and will perform a log recovery run before the tables can be accessed again. As this can potentially take some time (which you may not want to spend after restoring a server and trying to get it back on its feet as fast as possible), consider using the option I<--innodb_recover>, which will perform the recovery operation on the backup snapshot prior to archiving it. The recovery operation is performed by spawning a second mysqld instance that uses the snapshot volume as the data directory. Note that this functionality currently assumes the default InnoDB configuration - it does not work properly if you use options like I<--innodb-file-per-table>, I<--innodb-data-home-dir>, I<--innodb-data-file-path> or I<--innodb-log-group-home-dir> that modify the default file layout for InnoDB tables. If you use InnoDB tables exclusively, you may also want to consider to include the option I<--skip_flush_tables>, to avoid the probably time-consuming and in this case unnecessary flushing of buffers. But don't enable this option when MyISAM tables are involved! =head1 HOOKS It is possible to run arbitrary external programs or scripts (hooks) at various stages of the backup process, to perform additional actions as part of the backup process. These scripts or symbolic links to executables should be placed in the directory that the I configuration option points to (I by default). They should return zero upon successful completion, any non-zero return value will be considered a failure which will be logged. Hook scripts can also be implemented as Perl modules. The module must be named I and must be a package of type I. The module must implement I which is called by mylvmbackup to initiate the hook. It must return boolean true/false (1 or 0) on success/failure. I will be passed 2 parameters. The first parameter is a clone() of the global database handle $dbh. This will allow hook scripts to interact with the database using the established connection. The second parameter is a string containing any messages passed to the I function. The module must also implement I which will return a string error message to be sent to I. This will be called by I when I returns false/0. The names of the scripts or symbolic links reflect the stage in which the hook will be called. Currently, the following stages exist: =over 4 =item B before a connection to the database server is established =item B before calling FLUSH TABLES =item B before the file system snapshot is created =item B before the database tables are unlocked again =item B before the connection to the database server is released =item B before the snapshot volume is mounted =item B before the snapshot backup will be performed =item B after a successful backup =item B after a failed backup =item B when an error is logged =item B before the snapshot is unmounted and discarded =back These hooks are optional and will only be called if a file for the particular stage exists and is executable. Note that hooks implemented as Perl modules (I) have priority over "plain" hook scripts (I), if both exist, only the first one will be used. The execution of all hooks can be suppressed by passing the I<--skip_hooks> option or by setting the I configuration option to I<1>; =head1 OPTIONS mylvmbackup supports the following command line options. The same options can also be defined in the I configuration file (omitting the leading dashes, of course). A sample configuration file is included in the distribution. =over 4 =item B<--user=string> Specifies the username to use for connecting to the MySQL server. The default is I. =item B<--password=string> Specifies the password to use for connecting to the MySQL server. The default is the empty string (no password). =item B<--host=string> Specifies the host name to use for connecting to the MySQL server. Note that mylvmbackup needs to be run on the same system that the MySQL server to be backed up runs on - do not enter a remote host's host name or IP address here! A non-empty value for I other than I overrides any given I path value. The default is the empty string. =item B<--port=number> Specifies the TCP port number to use for connecting to the MySQL server. This value is only honoured, if I is provided as well and is not equal to I. The default is the empty string. =item B<--socket=string> Specifies the path to the local socket file, if it is not located at the default location. The default is the empty string. =item B<--quiet> Suppresses logging of informal messages. Warnings and errors will still be printed or logged (depending on the selected logging mechanism). The default is verbose logging. =item B<--innodb_recover> Run InnoDB recovery on the writable snapshot prior to performing the backup. =item B<--skip_flush_tables> Don't issue a I command before creating the snapshot. Only use this option when backing up InnoDB tables (as they don't support this function anyway and will require recovery in any case). This option skips the (probably time consuming) flushing of buffers. =item B<--extra_flush_tables> If your database performs a lot of writes, it may help to perform an extra initial I so that the I can finish within the interactivity timeout during the read-locked flush. =item B<--pidfile=string> Specifies the full path and file name to the PID file of the server instance that is spawned to perform the InnoDB recovery (see option I<--innodb_recover>). Must be different from the PID file that the actual running server uses. The default is I =item B<--lvcreate=string> Specifies the pathname for the I program. The default is I. =item B<--lvremove=string> Specifies the pathname for the I program. The default is I. =item B<--lvs=string> Specifies the pathname for the I program. The default is I. =item B<--mysqld_safe=string> Specifies the pathname for the I program. The default is I. Only used to perform InnoDB recovery. =item B<--mycnf=string> Specifies the name of the MySQL config file to include in the backup. The default is I. =item B<--skip_mycnf> Skip backing up the MySQL configuration file. The default is to include a copy of the configuration file in the backup. =item B<--hooksdir=string> The location of external scripts or executable to be called during various stages of the backup. See the HOOKS section in this manual page for more info. The default is I. =item B<--skip_hooks> Skip invoking any external hooks during the backup. =item B<--vgname=string> Specifies the volume group of the logical volume where the MySQL data directory is located. The default is I. =item B<--lvname=string> Specifies the name of the logical volume where the MySQL data directory is located. The default is I. =item B<--backuplv=string> Specifies the name of the logical volume for the snapshot volume. The default is appending B<_snapshot> to the lvname. =item B<--keep_snapshot> If this option is given, mylvmbackup will not remove the snapshot before terminating. Note that keeping multiple LVM snapshots open at the same time can reduce I/O performance and you will need to manually discard the snapshot before invoking mylvmbackup again. =item B<--keep_mount> If this option is given, mylvmbackup will not remove the mounted partition before terminating. This option also implies I, as it would not be useful if the snapshot is removed. You need to manually unmount this directory before invoking mylvmbackup again. =item B<--relpath=string> Relative path on the logical volume to the MySQL data directory (no leading or trailing slash). Example: the logical volume is mounted on I, but the MySQL data directory is /var/lib/mysql. In this case, I should be set to I. The default is the empty string. =item B<--lvsize=string> Specifies the size for the snapshot volume. The default is I<5G> (5 gigabytes). =item B<--backuptype=string> Specifies what type of backup to perform. The available options are I, I, I and I. =item B<--prefix=string> Prefix added to the backup file names. It is also appended to the name of the directory used to mount the snapshot volume. The default value is I. =item B<--suffix=string> Suffix added to the backup file names (after the time stamp). The default value is I<_mysql>. =item B<--datefmt=string> Format of the time stamp included in the backup file name. See the I perldoc page for a description of the format. The default value is I<%Y%m%d_%H%M%S>, which creates a time stamp like I, e.g. I<20070531_112549> =item B<--mountdir=string> Path for mounting the snapshot volume to. The default value is I. If the directory does not exist, it will be created. It is possible to use selected I formatting sequences to create directory names which contain a dynamic date value. Currently, the following format strings are supported: I<%Y> 4-digit year (e.g. 2009), I<%m> month (01..12), I<%d> day of month, leading zero I<%h> month abbreviation, I<%H> hour, 24 hour clock, leading zero I<%M> minute, leading zero I<%S> seconds, leading zero Example: I<$mountdir=/path/to/%Y-%m-%d> will expand to I =item B<--backupdir=string> Specifies the pathname of the directory where the archive files will be written to. The backup directory must not be on the same volume as the MySQL data directory. If the directory does not exist, it will be created. It is possible to use selected I formatting sequences to create directory names which contain a dynamic date value. Currently, the following format strings are supported: I<%Y> 4-digit year (e.g. 2009), I<%m> month (01..12), I<%d> day of month, leading zero I<%h> month abbreviation, I<%H> hour, 24 hour clock, leading zero I<%M> minute, leading zero I<%S> seconds, leading zero Example: I<$mountdir=/path/to/%Y-%m-%d> will expand to I Instead of a local directory, you can also provide a valid rsync URL here, e.g. I, I or I. This requires a properly configured remote rsync setup (e.g. pre-setup SSH keys or a working rsyncd configuration). The default is I =item B<--mount=string> Specifies the pathname for the I program. The default is I. =item B<--umount=string> Specifies the pathname for the I program. The default is I. =item B<--tar=string> Specifies the pathname for the I program. The default is I. =item B<--tararg=string> Specifies the initial arguments for the I program. The default is I. =item B<--tarsuffixarg=string> Specifies the suffix arguments for the I program. The default is the empty string. To exclude a database, you would pass I<--exclude dbname> here. =item B<--tarfilesuffix=string> Specifies the suffix for the tarball. The default is I<.tar.gz>. =item B<--compress=string> Specifies the name of the compression program. Only used if I is set to I. Some possibilities are I, I or I. The program must support reading the to be compressed data from I and writing to I, without requiring intermediate temporary files (for this reason, 7zip cannot be used). It's also possible to use I. In this case, no compression will be done. Make sure to update the I option accordingly. The default is I. Can be left empty. =item B<--compressarg=string> Specifies the command line options given to the I program. For I, that would be I<--stdout --verbose --best>, for I or I I<--stdout --verbose -7> and for I, it would be empty. The default is I<--stdout --verbose --best>. =item B<--rsnap=string> Specifies the pathname for the I program. The default is I. =item B<--rsnaparg=string> Specifies the arguments for the I program. The default is I<7>, which causes it to keep the last 7 snapshot (useful when running I once per day). =item B<--rsync=string> Specifies the pathname for the I program. The default is I. =item B<--rsyncarg=string> Specifies the arguments for the I program. The default is I<-avWP>. Should must ensure that the recursive option is included either implicitly by I<-a>, or explicitly. =item B<--xfs> Use the I mount option to safely mount snapshot partitions that use the XFS file system. =item B<--log_method=string> How to log output from this script. Valid options are I, I or I. The default value is I. =item B<--syslog_socktype=string> What type of socket to use for connecting to the syslog service. Valid options are I, I and I. The default value is I. =item B<--syslog_facility=string> Define a particular syslog facility Default value is the empty string. =item B<--syslog_remotehost=string> Host name of a remote syslog server. =item B<--configfile=string> Specify an alternative configuration file. The default is I. =item B<--help> Displays a help message showing the available options. =back =head1 FILES =over 4 =item B The I configuration file =item B The executable Perl script that performs the work. =back =head1 REQUIREMENTS For proper operation I requires Perl 5 with the I and I modules. It also needs the I to read the global configuration file of the program and I in case you want to enable the syslog log facility. I is required to create the time stamp used in the backup file names. In addition, it utilizes I, I and I, which usually are part of the default Perl distribution. It also requires several other external programs: GNU I and I to back up the data, LVM utilities (I, I and I) to create and remove the LVM snapshot, and the system utilities I and I. Please note that mylvmbackup requires Linux LVM Version 2 or higher. It does not work on LVMv1, as this version does not support writable snapshots. Optionally, I or I may be required instead of I and I, depending on which backup type you choose. =head1 SEE ALSO mount(8), tar(1), lvcreate(8), lvremove(8), lvs(8), umount(8), rsync(1) =head1 AUTHOR This program was initially written by Aleksey "Walrus" Kishkin from MySQL AB, with suggestions from Peter Zaitsev and Lenz Grimmer. It is currently maintained by Lenz Grimmer, =head1 RESOURCES Main web site: http://www.lenzg.net/mylvmbackup Mailing list: https://launchpad.net/~mylvmbackup-discuss Source code, bug tracker: https://launchpad.net/mylvmbackup =head1 CREDITS See the file CREDITS included in the distribution for a list of individual contributors. =head1 COPYING mylvmbackup is distributed under the GNU public license. See the file COPYING for details. mylvmbackup-0.13/man/mylvmbackup.10000644000175000001440000006322211250465467014112 00000000000000.\" Automatically generated by Pod::Man 2.16 (Pod::Simple 3.05) .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .ie \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .el \{\ . de IX .. .\} .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "MYLVMBACKUP 1" .TH MYLVMBACKUP 1 "2009-06-26" "perl v5.10.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" mylvmbackup \- a utility for creating MySQL backups using LVM snapshots .SH "SYNOPSIS" .IX Header "SYNOPSIS" mylvmbackup [\s-1OPTIONS\s0] .SH "DESCRIPTION" .IX Header "DESCRIPTION" mylvmbackup is a tool for quickly creating backups of MySQL server's data files. To perform a backup, mylvmbackup obtains a read lock on all tables and flushes all server caches to disk, makes an \s-1LVM\s0 snapshot of the volume containing the MySQL data directory, and unlocks the tables again. The snapshot process takes only a small amount of time. When it is done, the server can continue normal operations, while the actual file backup proceeds. .PP The \s-1LVM\s0 snapshot is mounted to a temporary directory and all data is backed up using the \fItar\fR program. By default, the archive file is created using a name of the form \fIbackup\-YYYYMMDD_hhmmss_mysql.tar.gz\fR, where \fI\s-1YYYY\s0\fR, \fI\s-1MM\s0\fR, \fI\s-1DD\s0\fR, \&\fIhh\fR, \fImm\fR, and \fIss\fR represent the year, month, day, hour, minute, and second of the time at which the backup occurred. The default prefix \fIbackup\fR, date format and file suffix may be modified. The use of timestamped archive names allows you to run mylvmbackup many times without danger of overwriting old archives. .PP Alternatively, instead of \fItar\fR, you may use \fIrsync\fR. This process is nearly identical, with the exception that the file suffix is not used. The rsync backup can perform both local backups as well as backing up to a remote server using rsyncd or rsync via \s-1SSH\s0. .PP mylvmbackup also supports creating backups by using \fIrsnap\fR, which is a wrapper around \fIrsync\fR to automatically maintain and rotate a given number of last backups (7 by default). It utilizes hard links to link to unchanged files for saving disk space. .PP Additionally, a backup type \fInone\fR is provided for cases where the user wants to use mylvmbackup only for creating the snapshots and intends to perform the actual backup by using the appropriate hooks. (Or for cases where the snapshot itself is considered to be the backup). .SH "GENERAL HINTS" .IX Header "GENERAL HINTS" It is required to run mylvmbackup on the same host where the MySQL server runs. If your MySQL daemon is not listening on localhost or using the default socket location, you must specify \fI\-\-host\fR or \fI\-\-socket\fR. Even though mylvmbackup communicates with the server through a normal client connection to obtain the read lock and flush data, it performs the actual backup by accessing the file system directly. It is also a requirement that the MySQL server's data directory resides on an \s-1LVM\s0 volume. (It is, however, a good idea to do the \s-1LVM\s0 backup to a different partition than the one where the data directory resides. Otherwise, there is a good chance that \s-1LVM\s0 will run out of undo space for \s-1LVM\s0 snapshot maintenance and the backup will fail.) .PP The user who invokes mylvmbackup must have sufficient filesystem permissions to create the \s-1LVM\s0 snapshot and mount it. This includes read/write access to the backup directory. .PP If you plan to back up InnoDB tables using \s-1LVM\s0 snapshots, be advised that it is not sufficient to lock the tables and issue the \fI\s-1FLUSH\s0 \s-1TABLES\s0\fR command to get the table files into a consistent state. When starting the MySQL server from these restored files, InnoDB will detect these tables as being in an inconsistent state and will perform a log recovery run before the tables can be accessed again. As this can potentially take some time (which you may not want to spend after restoring a server and trying to get it back on its feet as fast as possible), consider using the option \fI\-\-innodb_recover\fR, which will perform the recovery operation on the backup snapshot prior to archiving it. .PP The recovery operation is performed by spawning a second mysqld instance that uses the snapshot volume as the data directory. Note that this functionality currently assumes the default InnoDB configuration \- it does not work properly if you use options like \fI\-\-innodb\-file\-per\-table\fR, \fI\-\-innodb\-data\-home\-dir\fR, \&\fI\-\-innodb\-data\-file\-path\fR or \fI\-\-innodb\-log\-group\-home\-dir\fR that modify the default file layout for InnoDB tables. .PP If you use InnoDB tables exclusively, you may also want to consider to include the option \fI\-\-skip_flush_tables\fR, to avoid the probably time-consuming and in this case unnecessary flushing of buffers. But don't enable this option when MyISAM tables are involved! .SH "HOOKS" .IX Header "HOOKS" It is possible to run arbitrary external programs or scripts (hooks) at various stages of the backup process, to perform additional actions as part of the backup process. .PP These scripts or symbolic links to executables should be placed in the directory that the \fIhooksdir\fR configuration option points to (\fI/usr/share/mylvmbackup\fR by default). They should return zero upon successful completion, any non-zero return value will be considered a failure which will be logged. .PP Hook scripts can also be implemented as Perl modules. The module must be named \&\fIhookname.pm\fR and must be a package of type \fIhookname\fR. The module must implement \fI\fIexecute()\fI\fR which is called by mylvmbackup to initiate the hook. It must return boolean true/false (1 or 0) on success/failure. \fI\fIexecute()\fI\fR will be passed 2 parameters. The first parameter is a \fIclone()\fR of the global database handle \f(CW$dbh\fR. This will allow hook scripts to interact with the database using the established connection. The second parameter is a string containing any messages passed to the \fI\fIrun_hook()\fI\fR function. The module must also implement \&\fI\fIerrmsg()\fI\fR which will return a string error message to be sent to \&\fI\fIlog_msg()\fI\fR. This will be called by \fImylvmbackup\fR when \fI\fIexecute()\fI\fR returns false/0. .PP The names of the scripts or symbolic links reflect the stage in which the hook will be called. Currently, the following stages exist: .IP "\fBpreconnect\fR" 4 .IX Item "preconnect" before a connection to the database server is established .IP "\fBpreflush\fR" 4 .IX Item "preflush" before calling \s-1FLUSH\s0 \s-1TABLES\s0 .IP "\fBpresnapshot\fR" 4 .IX Item "presnapshot" before the file system snapshot is created .IP "\fBpreunlock\fR" 4 .IX Item "preunlock" before the database tables are unlocked again .IP "\fBpredisconnect\fR" 4 .IX Item "predisconnect" before the connection to the database server is released .IP "\fBpremount\fR" 4 .IX Item "premount" before the snapshot volume is mounted .IP "\fBprebackup\fR" 4 .IX Item "prebackup" before the snapshot backup will be performed .IP "\fBbackupsuccess\fR" 4 .IX Item "backupsuccess" after a successful backup .IP "\fBbackupfailure\fR" 4 .IX Item "backupfailure" after a failed backup .IP "\fBlogerr\fR" 4 .IX Item "logerr" when an error is logged .IP "\fBprecleanup\fR" 4 .IX Item "precleanup" before the snapshot is unmounted and discarded .PP These hooks are optional and will only be called if a file for the particular stage exists and is executable. Note that hooks implemented as Perl modules (\fIhookname.pm\fR) have priority over \*(L"plain\*(R" hook scripts (\fIhookname\fR), if both exist, only the first one will be used. The execution of all hooks can be suppressed by passing the \fI\-\-skip_hooks\fR option or by setting the \&\fIskip_hooks\fR configuration option to \fI1\fR; .SH "OPTIONS" .IX Header "OPTIONS" mylvmbackup supports the following command line options. The same options can also be defined in the \fI/etc/mylvmbackup.conf\fR configuration file (omitting the leading dashes, of course). A sample configuration file is included in the distribution. .IP "\fB\-\-user=string\fR" 4 .IX Item "--user=string" Specifies the username to use for connecting to the MySQL server. The default is \fIroot\fR. .IP "\fB\-\-password=string\fR" 4 .IX Item "--password=string" Specifies the password to use for connecting to the MySQL server. The default is the empty string (no password). .IP "\fB\-\-host=string\fR" 4 .IX Item "--host=string" Specifies the host name to use for connecting to the MySQL server. Note that mylvmbackup needs to be run on the same system that the MySQL server to be backed up runs on \- do not enter a remote host's host name or \s-1IP\s0 address here! A non-empty value for \fIhost\fR other than \fIlocalhost\fR overrides any given \&\fIsocket\fR path value. The default is the empty string. .IP "\fB\-\-port=number\fR" 4 .IX Item "--port=number" Specifies the \s-1TCP\s0 port number to use for connecting to the MySQL server. This value is only honoured, if \fIhost\fR is provided as well and is not equal to \fIlocalhost\fR. The default is the empty string. .IP "\fB\-\-socket=string\fR" 4 .IX Item "--socket=string" Specifies the path to the local socket file, if it is not located at the default location. The default is the empty string. .IP "\fB\-\-quiet\fR" 4 .IX Item "--quiet" Suppresses logging of informal messages. Warnings and errors will still be printed or logged (depending on the selected logging mechanism). The default is verbose logging. .IP "\fB\-\-innodb_recover\fR" 4 .IX Item "--innodb_recover" Run InnoDB recovery on the writable snapshot prior to performing the backup. .IP "\fB\-\-skip_flush_tables\fR" 4 .IX Item "--skip_flush_tables" Don't issue a \fI\s-1FLUSH\s0 \s-1TABLES\s0 \s-1WITH\s0 \s-1READ\s0 \s-1LOCK\s0\fR command before creating the snapshot. Only use this option when backing up InnoDB tables (as they don't support this function anyway and will require recovery in any case). This option skips the (probably time consuming) flushing of buffers. .IP "\fB\-\-extra_flush_tables\fR" 4 .IX Item "--extra_flush_tables" If your database performs a lot of writes, it may help to perform an extra initial \fI\s-1FLUSH\s0 \s-1TABLES\s0\fR so that the \fIlvcreate\fR can finish within the interactivity timeout during the read-locked flush. .IP "\fB\-\-pidfile=string\fR" 4 .IX Item "--pidfile=string" Specifies the full path and file name to the \s-1PID\s0 file of the server instance that is spawned to perform the InnoDB recovery (see option \&\fI\-\-innodb_recover\fR). Must be different from the \s-1PID\s0 file that the actual running server uses. The default is \fI/var/tmp/mylvmbackup_recoverserver.pid\fR .IP "\fB\-\-lvcreate=string\fR" 4 .IX Item "--lvcreate=string" Specifies the pathname for the \fIlvcreate\fR program. The default is \fIlvcreate\fR. .IP "\fB\-\-lvremove=string\fR" 4 .IX Item "--lvremove=string" Specifies the pathname for the \fIlvremove\fR program. The default is \fIlvremove\fR. .IP "\fB\-\-lvs=string\fR" 4 .IX Item "--lvs=string" Specifies the pathname for the \fIlvs\fR program. The default is \fIlvs\fR. .IP "\fB\-\-mysqld_safe=string\fR" 4 .IX Item "--mysqld_safe=string" Specifies the pathname for the \fImysqld_safe\fR program. The default is \fImysqld_safe\fR. Only used to perform InnoDB recovery. .IP "\fB\-\-mycnf=string\fR" 4 .IX Item "--mycnf=string" Specifies the name of the MySQL config file to include in the backup. The default is \fI/etc/my.cnf\fR. .IP "\fB\-\-skip_mycnf\fR" 4 .IX Item "--skip_mycnf" Skip backing up the MySQL configuration file. The default is to include a copy of the configuration file in the backup. .IP "\fB\-\-hooksdir=string\fR" 4 .IX Item "--hooksdir=string" The location of external scripts or executable to be called during various stages of the backup. See the \s-1HOOKS\s0 section in this manual page for more info. The default is \fI/usr/share/mylvmbackup\fR. .IP "\fB\-\-skip_hooks\fR" 4 .IX Item "--skip_hooks" Skip invoking any external hooks during the backup. .IP "\fB\-\-vgname=string\fR" 4 .IX Item "--vgname=string" Specifies the volume group of the logical volume where the MySQL data directory is located. The default is \fImysql\fR. .IP "\fB\-\-lvname=string\fR" 4 .IX Item "--lvname=string" Specifies the name of the logical volume where the MySQL data directory is located. The default is \fIdata\fR. .IP "\fB\-\-backuplv=string\fR" 4 .IX Item "--backuplv=string" Specifies the name of the logical volume for the snapshot volume. The default is appending \fB_snapshot\fR to the lvname. .IP "\fB\-\-keep_snapshot\fR" 4 .IX Item "--keep_snapshot" If this option is given, mylvmbackup will not remove the snapshot before terminating. Note that keeping multiple \s-1LVM\s0 snapshots open at the same time can reduce I/O performance and you will need to manually discard the snapshot before invoking mylvmbackup again. .IP "\fB\-\-keep_mount\fR" 4 .IX Item "--keep_mount" If this option is given, mylvmbackup will not remove the mounted partition before terminating. This option also implies \fIkeep_snapshot=1\fR, as it would not be useful if the snapshot is removed. You need to manually unmount this directory before invoking mylvmbackup again. .IP "\fB\-\-relpath=string\fR" 4 .IX Item "--relpath=string" Relative path on the logical volume to the MySQL data directory (no leading or trailing slash). Example: the logical volume is mounted on \fI/var/lib\fR, but the MySQL data directory is /var/lib/mysql. In this case, \fIrelpath\fR should be set to \fImysql\fR. The default is the empty string. .IP "\fB\-\-lvsize=string\fR" 4 .IX Item "--lvsize=string" Specifies the size for the snapshot volume. The default is \fI5G\fR (5 gigabytes). .IP "\fB\-\-backuptype=string\fR" 4 .IX Item "--backuptype=string" Specifies what type of backup to perform. The available options are \&\fItar\fR, \fIrsync\fR, \fIrsnap\fR and \fInone\fR. .IP "\fB\-\-prefix=string\fR" 4 .IX Item "--prefix=string" Prefix added to the backup file names. It is also appended to the name of the directory used to mount the snapshot volume. The default value is \fIbackup\fR. .IP "\fB\-\-suffix=string\fR" 4 .IX Item "--suffix=string" Suffix added to the backup file names (after the time stamp). The default value is \fI_mysql\fR. .IP "\fB\-\-datefmt=string\fR" 4 .IX Item "--datefmt=string" Format of the time stamp included in the backup file name. See the \fIDate::Format\fR perldoc page for a description of the format. The default value is \fI\f(CI%Y\fI%m%d_%H%M%S\fR, which creates a time stamp like \fI\s-1YYYYMMDD_HHMMSS\s0\fR, e.g. \fI20070531_112549\fR .IP "\fB\-\-mountdir=string\fR" 4 .IX Item "--mountdir=string" Path for mounting the snapshot volume to. The default value is \fI/var/tmp/mylvmbackup/mnt/\fR. If the directory does not exist, it will be created. .Sp It is possible to use selected \fI\fItimestr()\fI\fR formatting sequences to create directory names which contain a dynamic date value. Currently, the following format strings are supported: \&\fI\f(CI%Y\fI\fR 4\-digit year (e.g. 2009), \&\fI\f(CI%m\fI\fR month (01..12), \&\fI\f(CI%d\fI\fR day of month, leading zero \&\fI\f(CI%h\fI\fR month abbreviation, \&\fI\f(CI%H\fI\fR hour, 24 hour clock, leading zero \&\fI\f(CI%M\fI\fR minute, leading zero \&\fI\f(CI%S\fI\fR seconds, leading zero Example: \fI\f(CI$mountdir\fI=/path/to/%Y\-%m\-%d\fR will expand to \fI/path/to/2009\-06\-13\fR .IP "\fB\-\-backupdir=string\fR" 4 .IX Item "--backupdir=string" Specifies the pathname of the directory where the archive files will be written to. The backup directory must not be on the same volume as the MySQL data directory. If the directory does not exist, it will be created. .Sp It is possible to use selected \fI\fItimestr()\fI\fR formatting sequences to create directory names which contain a dynamic date value. Currently, the following format strings are supported: \&\fI\f(CI%Y\fI\fR 4\-digit year (e.g. 2009), \&\fI\f(CI%m\fI\fR month (01..12), \&\fI\f(CI%d\fI\fR day of month, leading zero \&\fI\f(CI%h\fI\fR month abbreviation, \&\fI\f(CI%H\fI\fR hour, 24 hour clock, leading zero \&\fI\f(CI%M\fI\fR minute, leading zero \&\fI\f(CI%S\fI\fR seconds, leading zero Example: \fI\f(CI$mountdir\fI=/path/to/%Y\-%m\-%d\fR will expand to \fI/path/to/2009\-06\-13\fR .Sp Instead of a local directory, you can also provide a valid rsync \s-1URL\s0 here, e.g. \&\fIusername@hostname:/path\fR, \fIhostname:path\fR or \fIhostname::rsync\-module/path\fR. This requires a properly configured remote rsync setup (e.g. pre-setup \s-1SSH\s0 keys or a working rsyncd configuration). .Sp The default is \fI/var/tmp/mylvmbackup/backup/\fR .IP "\fB\-\-mount=string\fR" 4 .IX Item "--mount=string" Specifies the pathname for the \fImount\fR program. The default is \fImount\fR. .IP "\fB\-\-umount=string\fR" 4 .IX Item "--umount=string" Specifies the pathname for the \fIumount\fR program. The default is \fIumount\fR. .IP "\fB\-\-tar=string\fR" 4 .IX Item "--tar=string" Specifies the pathname for the \fItar\fR program. The default is \fItar\fR. .IP "\fB\-\-tararg=string\fR" 4 .IX Item "--tararg=string" Specifies the initial arguments for the \fItar\fR program. The default is \fIcvf\fR. .IP "\fB\-\-tarsuffixarg=string\fR" 4 .IX Item "--tarsuffixarg=string" Specifies the suffix arguments for the \fItar\fR program. The default is the empty string. To exclude a database, you would pass \fI\-\-exclude dbname\fR here. .IP "\fB\-\-tarfilesuffix=string\fR" 4 .IX Item "--tarfilesuffix=string" Specifies the suffix for the tarball. The default is \fI.tar.gz\fR. .IP "\fB\-\-compress=string\fR" 4 .IX Item "--compress=string" Specifies the name of the compression program. Only used if \fIbackuptype\fR is set to \fItar\fR. Some possibilities are \fIgzip\fR, \fIbzip2\fR or \fIlzma\fR. The program must support reading the to be compressed data from \fIstdin\fR and writing to \fIstdout\fR, without requiring intermediate temporary files (for this reason, 7zip cannot be used). It's also possible to use \fIcat\fR. In this case, no compression will be done. Make sure to update the \fIcompressarg\fR option accordingly. The default is \fIgzip\fR. Can be left empty. .IP "\fB\-\-compressarg=string\fR" 4 .IX Item "--compressarg=string" Specifies the command line options given to the \fIcompress\fR program. For \fIgzip\fR, that would be \fI\-\-stdout \-\-verbose \-\-best\fR, for \fIlzma\fR or \fIbzip2\fR \fI\-\-stdout \-\-verbose \-7\fR and for \fIcat\fR, it would be empty. The default is \fI\-\-stdout \-\-verbose \-\-best\fR. .IP "\fB\-\-rsnap=string\fR" 4 .IX Item "--rsnap=string" Specifies the pathname for the \fIrsnap\fR program. The default is \fIrsnap\fR. .IP "\fB\-\-rsnaparg=string\fR" 4 .IX Item "--rsnaparg=string" Specifies the arguments for the \fIrsnap\fR program. The default is \fI7\fR, which causes it to keep the last 7 snapshot (useful when running \fImylvmbackup\fR once per day). .IP "\fB\-\-rsync=string\fR" 4 .IX Item "--rsync=string" Specifies the pathname for the \fIrsync\fR program. The default is \fIrsync\fR. .IP "\fB\-\-rsyncarg=string\fR" 4 .IX Item "--rsyncarg=string" Specifies the arguments for the \fIrsync\fR program. The default is \fI\-avWP\fR. Should must ensure that the recursive option is included either implicitly by \fI\-a\fR, or explicitly. .IP "\fB\-\-xfs\fR" 4 .IX Item "--xfs" Use the \fInouuid\fR mount option to safely mount snapshot partitions that use the \s-1XFS\s0 file system. .IP "\fB\-\-log_method=string\fR" 4 .IX Item "--log_method=string" How to log output from this script. Valid options are \fIconsole\fR, \fIsyslog\fR or \fIboth\fR. The default value is \fIconsole\fR. .IP "\fB\-\-syslog_socktype=string\fR" 4 .IX Item "--syslog_socktype=string" What type of socket to use for connecting to the syslog service. Valid options are \fInative\fR, \fItcp\fR and \fIudp\fR. The default value is \fInative\fR. .IP "\fB\-\-syslog_facility=string\fR" 4 .IX Item "--syslog_facility=string" Define a particular syslog facility Default value is the empty string. .IP "\fB\-\-syslog_remotehost=string\fR" 4 .IX Item "--syslog_remotehost=string" Host name of a remote syslog server. .IP "\fB\-\-configfile=string\fR" 4 .IX Item "--configfile=string" Specify an alternative configuration file. The default is \fI/etc/mylvmbackup.conf\fR. .IP "\fB\-\-help\fR" 4 .IX Item "--help" Displays a help message showing the available options. .SH "FILES" .IX Header "FILES" .IP "\fB/etc/mylvbackup.conf\fR" 4 .IX Item "/etc/mylvbackup.conf" The \fImylvmbackup\fR configuration file .IP "\fBmylvmbackup\fR" 4 .IX Item "mylvmbackup" The executable Perl script that performs the work. .SH "REQUIREMENTS" .IX Header "REQUIREMENTS" For proper operation \fImylvmbackup\fR requires Perl 5 with the \fI\s-1DBI\s0\fR and \&\fIDBD::mysql\fR modules. It also needs the \fIConfig::IniFiles\fR to read the global configuration file of the program and \fISys::Syslog\fR in case you want to enable the syslog log facility. \fIDate::Format\fR is required to create the time stamp used in the backup file names. In addition, it utilizes \fIGetopt::Long\fR, \&\fIFile::Basename\fR and \fIFile::Temp\fR, which usually are part of the default Perl distribution. .PP It also requires several other external programs: \s-1GNU\s0 \fItar\fR and \fIgzip\fR to back up the data, \s-1LVM\s0 utilities (\fIlvcreate\fR, \fIlvremove\fR and \fIlvs\fR) to create and remove the \s-1LVM\s0 snapshot, and the system utilities \fImount\fR and \fIumount\fR. Please note that mylvmbackup requires Linux \s-1LVM\s0 Version 2 or higher. It does not work on LVMv1, as this version does not support writable snapshots. .PP Optionally, \fIrsync\fR or \fIrsnap\fR may be required instead of \fItar\fR and \fIgzip\fR, depending on which backup type you choose. .SH "SEE ALSO" .IX Header "SEE ALSO" \&\fImount\fR\|(8), \fItar\fR\|(1), \fIlvcreate\fR\|(8), \fIlvremove\fR\|(8), \fIlvs\fR\|(8), \fIumount\fR\|(8), \fIrsync\fR\|(1) .SH "AUTHOR" .IX Header "AUTHOR" This program was initially written by Aleksey \*(L"Walrus\*(R" Kishkin from MySQL \s-1AB\s0, with suggestions from Peter Zaitsev and Lenz Grimmer. .PP It is currently maintained by Lenz Grimmer, .SH "RESOURCES" .IX Header "RESOURCES" Main web site: http://www.lenzg.net/mylvmbackup .PP Mailing list: https://launchpad.net/~mylvmbackup\-discuss .PP Source code, bug tracker: https://launchpad.net/mylvmbackup .SH "CREDITS" .IX Header "CREDITS" See the file \s-1CREDITS\s0 included in the distribution for a list of individual contributors. .SH "COPYING" .IX Header "COPYING" mylvmbackup is distributed under the \s-1GNU\s0 public license. See the file \&\s-1COPYING\s0 for details. mylvmbackup-0.13/mylvmbackup0000755000175000001440000006174611250465467013214 00000000000000#!/usr/bin/perl -w # # mylvmbackup - utility for creating MySQL backups via LVM snapshots # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package mylvmbackup; use Config::IniFiles; use Date::Format; use DBI; use File::Basename; use File::Temp qw/ mkstemps mktemp /; use Getopt::Long; use diagnostics; use strict; # Version is set from the Makefile my $version='0.13'; my $build_date='2009-09-05'; # syslog-related options my $syslog_ident = 'mylvmbackup'; my $syslog_args = 'pid,ndelay'; my $configfile = "/etc/mylvmbackup.conf"; my $configfile2 = ""; my $TMP= ($ENV{TMPDIR} || "/tmp"); my $backupdir; my $backuplv; my $datefmt; my $hooksdir; my $host; my $innodb_recover; my $skip_flush_tables; my $skip_hooks; my $skip_mycnf; my $extra_flush_tables; my $keep_snapshot; my $keep_mount; my $lvcreate; my $lvname; my $lvremove; my $lvs; my $lvsize; my $mount; my $mysqld_safe; my $mycnf; my $mountdir; my $need_xfsworkaround; my $password; my $pidfile; my $port; my $quiet; my $backuptype; my $prefix; my $suffix; my $relpath; my $socket; my $rsync; my $rsnap; my $rsyncarg; my $rsnaparg; my $tar; my $tararg; my $tarsuffixarg; my $tarfilesuffix; my $compress; my $compressarg; my $umount; my $user; my $vgname; my $log_method; my $syslog_socktype; my $syslog_facility; my $syslog_remotehost; # Load defaults into variables load_defaults(); # Initialize variables from config file, if it exists if (-r $configfile) { load_config($configfile); } # Load the commandline arguments load_args(); # If they specified an alternative config file if ($configfile2 ne "") { die ("Unable to load specified config file: $!\n") unless (-r $configfile2); load_config($configfile2); # re-load the arguments, as they should override any config file settings load_args(); } if ("$log_method" eq "syslog") { use Sys::Syslog qw(:DEFAULT setlogsock :macros); if ($syslog_socktype ne "native") { die ("You need to provide syslog_remotehost!\n") unless ($syslog_remotehost); setlogsock ($syslog_socktype); $Sys::Syslog::host = $syslog_remotehost; } openlog ($syslog_ident, $syslog_args, $syslog_facility); log_msg ("Starting new backup...", LOG_INFO); } if (lvm_version() =~ /^1/) { log_msg("Linux LVM Version 2 or higher is required to run mylvmbackup.", LOG_ERR); exit(1); } # Clean up directory inputs $mountdir = clean_dirname($mountdir); $backupdir = clean_dirname($backupdir); # Validate the existence of a prefix die "You must specify a non-empty prefix to name your backup!\n" unless ($prefix ne ""); $backuplv = $lvname.'_snapshot' if length($backuplv) == 0; my $date = time2str($datefmt, time); my $fullprefix = $prefix.'-'.$date.$suffix; my $topmountdir = $mountdir; # No .tar.gz on the end! my $archivename = $backupdir.'/'.$fullprefix; my $mounted = 0; my $snapshot_created = 0; # Check for the backupdir, it must exist, and it must be readable/writable # Except when not doing any backups or using rsync to a remote server unless (($backuptype eq 'none') or ($backuptype eq 'rsync' and $backupdir =~ /^[^\/].*:.*/)) { check_dir($backupdir, 'backupdir'); } # Check the mountdir, it must exist, and be readable/writeable check_dir($mountdir, 'mountdir'); # Append the prefix to the mountdir, to allow multiple parallel backups. The # extra / is to ensure we go a level under it. An empty prefix is disallowed. $mountdir .= '/'.$prefix; my $posmountdir = $mountdir; $posmountdir .= '-pos'; # Notice that we do not add a slash. my $pos_filename = $posmountdir.'/'.$fullprefix.'.pos'; my $pos_tempfile_fh; my $pos_tempfile; ($pos_tempfile_fh, $pos_tempfile) = mkstemps($TMP.'/mylvmbackup-'.$fullprefix.'-XXXXXX', '.pos') or log_msg ("Cannot create temporary file $pos_tempfile: $!", LOG_ERR); my $mycnf_basename = File::Basename::basename($mycnf); my $mycnf_filename = $posmountdir.'/'.$fullprefix.'_'.$mycnf_basename; # Now create it mkdir $mountdir; mkdir $posmountdir; # Check it again for existence and read/write. check_dir($mountdir, 'mountdir'); # Now make sure it's empty my @mountdir_content = glob "$mountdir/*" ; unless ( scalar(@mountdir_content) eq 0) { log_msg ("Please make sure Temp dir ($mountdir) is empty.", LOG_ERR); exit(1); }; # Figure out our DSN string my $dsn = "DBI:mysql:database=mysql;mysql_read_default_group=client"; if(length($socket) > 0) { $dsn .= ";mysql_socket=".$socket; } if(length($host) > 0) { $dsn .= ";host=".$host; } if(length($port) > 0) { $dsn .= ";port=".$port; } run_hook ("preconnect"); log_msg ("Connecting to database...", LOG_INFO); my $dbh= DBI->connect($dsn,$user,$password); if (!$dbh) { log_msg ($DBI::errstr, LOG_ERR); die $DBI::errstr; } run_hook ("preflush"); flush_tables($dbh) unless ($skip_flush_tables == 1); create_posfile($dbh); run_hook ("presnapshot"); $snapshot_created= create_lvm_snapshot(); run_hook ("preunlock"); log_msg ("Unlocking tables...", LOG_INFO); $dbh->do("UNLOCK TABLES") or log_msg ($DBI::errstr, LOG_ERR) && die $DBI::errstr; run_hook ("predisconnect"); log_msg ("Disconnecting from database...", LOG_INFO); $dbh->disconnect; if ($snapshot_created) { run_hook("premount"); $mounted= mount_snapshot(); save_posfile(); if ($mounted) { if ($innodb_recover == 1) { do_innodb_recover(); } if (-f $mycnf && $skip_mycnf == 0) { create_mycnf_file(); } run_hook("prebackup"); my $backupsuccess=0; if ($backuptype eq 'tar') {$backupsuccess = do_backup_tar()} elsif ($backuptype eq 'rsync') {$backupsuccess = do_backup_rsync()} elsif ($backuptype eq 'rsnap') {$backupsuccess = do_backup_rsnap()} else {$backupsuccess = do_backup_none()}; if ($backupsuccess == 1) { run_hook("backupsuccess"); } else { run_hook("backupfailure"); } } } else { cleanup(); exit 1; } cleanup(); exit 0; # Please keep all 3 functions in the same order: load_config, load_args, load_defaults sub load_config { my $configfile = shift(@_); my $cfg = new Config::IniFiles( -file => $configfile ) or log_msg ("Couldn't read configuration file: " . $!, 'LOG_WARNING'); $user = $cfg->val( 'mysql', 'user', $user); $password = $cfg->val ('mysql', 'password', $password); $host = $cfg->val ('mysql', 'host', $host); $port = $cfg->val ('mysql', 'port', $port); $socket = $cfg->val ('mysql', 'socket', $socket); $mysqld_safe = $cfg->val ('mysql', 'mysqld_safe', $mysqld_safe); $mycnf = $cfg->val ('mysql', 'mycnf', $mycnf); $vgname=$cfg->val ('lvm', 'vgname', $vgname); $lvname=$cfg->val ('lvm', 'lvname', $lvname); $lvsize=$cfg->val ('lvm', 'lvsize', $lvsize); $backuplv = $cfg->val ('lvm', 'backuplv', $backuplv); $backuptype=$cfg->val ('misc', 'backuptype', $backuptype); $prefix=$cfg->val ('misc', 'prefix', $prefix); $suffix=$cfg->val ('misc', 'suffix', $suffix); $datefmt=$cfg->val ('misc', 'datefmt', $datefmt); $innodb_recover=$cfg->val ('misc', 'innodb_recover', $innodb_recover); $pidfile=$cfg->val ('misc', 'pidfile', $pidfile); $skip_flush_tables=$cfg->val ('misc', 'skip_flush_tables', $skip_flush_tables); $extra_flush_tables=$cfg->val ('misc', 'extra_flush_tables', $extra_flush_tables); $skip_mycnf=$cfg->val ('misc', 'skip_mycnf', $skip_mycnf); $rsyncarg=$cfg->val ('misc', 'rsyncarg', $rsyncarg); $rsnaparg=$cfg->val ('misc', 'rsnaparg', $rsnaparg); $tararg=$cfg->val ('misc', 'tararg', $tararg); $tarsuffixarg=$cfg->val ('misc', 'tarsuffixarg', $tarsuffixarg); $tarfilesuffix = $cfg->val ('misc', 'tarfilesuffix', $tarfilesuffix); $compressarg=$cfg->val ('misc', 'compressarg', $compressarg); $hooksdir = $cfg->val ('misc', 'hooksdir', $hooksdir); $skip_hooks=$cfg->val ('misc', 'skip_hooks', $skip_hooks); $keep_snapshot=$cfg->val ('misc', 'keep_snapshot', $keep_snapshot); $keep_mount=$cfg->val ('misc', 'keep_mount', $keep_mount); $quiet=$cfg->val ('misc', 'quiet', $quiet); $mountdir=$cfg->val ('fs', 'mountdir', $mountdir); $backupdir=$cfg->val ('fs', 'backupdir', $backupdir); $relpath=$cfg->val ('fs', 'relpath', $relpath); $need_xfsworkaround=$cfg->val ('fs', 'xfs', $need_xfsworkaround); $lvcreate=$cfg->val ('tools', 'lvcreate', $lvcreate); $lvremove=$cfg->val ('tools', 'lvremove', $lvremove); $lvs=$cfg->val ('tools', 'lvs', $lvs); $mount=$cfg->val ('tools', 'mount', $mount); $umount=$cfg->val ('tools', 'umount', $umount); $tar=$cfg->val ('tools', 'tar', $tar); $compress=$cfg->val ('tools', 'compress', $compress); $rsync=$cfg->val ('tools', 'rsync', $rsync); $rsnap=$cfg->val ('tools', 'rsnap', $rsnap); $log_method = $cfg->val('logging', 'log_method', $log_method); $syslog_socktype = $cfg->val ('logging', 'syslog_socktype', $syslog_socktype); $syslog_facility = $cfg->val ('logging', 'syslog_facility', $syslog_facility); $syslog_remotehost = $cfg->val ('logging', 'syslog_remotehost', $syslog_remotehost); } # Please keep all 3 functions in the same order: load_config, load_args, load_defaults sub load_args { GetOptions( # stuff that doesn't go in the config file ;-) "help" => \&help, "configfile=s" => \$configfile2, # mysql "user=s" => \$user, "password=s" => \$password, "host=s" => \$host, "port=i" => \$port, "socket=s" => \$socket, "mysqld_safe=s" => \$mysqld_safe, "mycnf=s" => \$mycnf, # lvm "vgname=s" => \$vgname, "lvname=s" => \$lvname, "lvsize=s" => \$lvsize, "backuplv=s" => \$backuplv, # misc "backuptype=s" => \$backuptype, "prefix=s" => \$prefix, "suffix=s" => \$suffix, "datefmt=s" => \$datefmt, "innodb_recover" => \&innodb_recover, "pidfile=s" => \$pidfile, "skip_flush_tables" => \&skip_flush_tables, "extra_flush_tables" => \&extra_flush_tables, "skip_mycnf" => \&skip_mycnf, "tararg=s" => \$tararg, "tarsuffixarg=s" => \$tarsuffixarg, "tarfilesuffix=s" => \$tarfilesuffix, "compressarg=s" => \$compressarg, "rsyncarg=s" => \$rsyncarg, "rsnaparg=s" => \$rsnaparg, "hooksdir=s" => \$hooksdir, "skip_hooks" => \&skip_hooks, "keep_snapshot" => \&keep_snapshot, "keep_mount" => \&keep_mount, "quiet" => \&quiet, # fs "mountdir=s" => \$mountdir, "backupdir=s" => \$backupdir, "relpath=s" => \$relpath, "xfs" => \&need_xfsworkaround, # tools "lvcreate=s" => \$lvcreate, "lvremove=s" => \$lvremove, "lvs=s" => \$lvs, "mount=s" => \$mount, "umount=s" => \$umount, "tar=s" => \$tar, "compress=s" => \$compress, "rsync=s" => \$rsync, "rsnap=s" => \$rsnap, # logging "log_method=s" => \$log_method, "syslog_socktype=s" => \$syslog_socktype, "syslog_facility=s" => \$syslog_facility, "syslog_remotehost=s" => \$syslog_remotehost, ) or help(); # As this function is called last, append to @INC here. eval "use lib '$hooksdir'"; } # Please keep all 3 functions in the same order: load_config, load_args, load_defaults sub load_defaults { # mysql $user = 'root'; $password = ''; $host = ''; $port = ''; $socket = ''; $mysqld_safe='mysqld_safe'; $mycnf = '/etc/my.cnf'; # lvm $vgname='mysql'; $lvname='data'; $lvsize='5G'; $backuplv = ''; # misc $backuptype='tar'; $prefix='backup'; $suffix='_mysql'; $datefmt='%Y%m%d_%H%M%S'; $innodb_recover=0; $pidfile = '$TMP/mylvmbackup_recoverserver.pid'; $skip_flush_tables=0; $extra_flush_tables=0; $skip_mycnf=0; $tararg='cvf'; $tarsuffixarg=''; $tarfilesuffix='.tar.gz'; $compressarg='--stdout --verbose --best'; $rsyncarg='-avPW'; $rsnaparg='7'; $hooksdir='/usr/share/mylvmbackup'; $skip_hooks=0; $keep_snapshot=0; $keep_mount=0; $quiet=0; # fs $mountdir='/var/tmp/mylvmbackup/mnt/'; $backupdir='/var/tmp/mylvmbackup/backup/'; $relpath=''; $need_xfsworkaround=0; # External tools - make sure that these are in $PATH or provide absolute names $lvcreate='lvcreate'; $lvremove='lvremove'; $lvs='lvs'; $mount='mount'; $umount='umount'; $tar='tar'; $compress='gzip'; $rsync='rsync'; $rsnap='rsnap'; # logging $log_method = 'console'; $syslog_socktype = 'native'; $syslog_facility = ''; $syslog_remotehost = ''; } sub flush_tables { my $dbh = shift; if($extra_flush_tables == 1) { log_msg ("Flushing tables (initial)...", LOG_INFO); $dbh->do("FLUSH TABLES") or log_msg ($DBI::errstr, LOG_ERR); } log_msg ("Flushing tables with read lock...", LOG_INFO); $dbh->do("FLUSH TABLES WITH READ LOCK") or log_msg ($DBI::errstr, LOG_ERR); } sub create_posfile { log_msg ("Taking position record into $pos_tempfile...", LOG_INFO); my $dbh = shift; _create_posfile_single($dbh, 'SHOW MASTER STATUS', $pos_tempfile_fh, 'Master'); _create_posfile_single($dbh, 'SHOW SLAVE STATUS', $pos_tempfile_fh, 'Slave'); close $pos_tempfile_fh or log_msg ("Closing $pos_tempfile failed: $!", LOG_ERR); } sub _create_posfile_single { my $dbh = shift; my $query = shift; my $fh = shift; my $pos_prefix = shift; my $sth = $dbh->prepare($query) or log_msg ($DBI::errstr, LOG_ERR); $sth->execute or log_msg ($DBI::errstr, LOG_ERR); while (my $r = $sth->fetchrow_hashref) { foreach my $f (@{$sth->{NAME}}) { my $v = $r->{$f}; $v = '' if (!defined($v)); my $line = "$pos_prefix:$f=$v\n"; print $fh $line or log_msg ("Writing position record failed: $!", LOG_ERR); } } $sth->finish; } sub create_mycnf_file { log_msg ("Copying $mycnf to $mycnf_filename...", LOG_INFO); use File::Copy; copy($mycnf, $mycnf_filename) or log_msg ("Could not copy $mycnf to $mycnf_filename: $!", LOG_ERR); } sub do_backup_tar { my $tarball = $archivename.$tarfilesuffix; my $tarballtmp = mktemp("$tarball.INCOMPLETE-XXXXXXX"); log_msg ("Taking actual backup...", LOG_INFO); log_msg ("Creating tar archive $tarball", LOG_INFO); my $mountdir_rel = $mountdir; $mountdir_rel =~ s/^$topmountdir//g; $mountdir_rel =~ s/^\/+//g; my $pos_filename_rel = $pos_filename; $pos_filename_rel =~ s/^$topmountdir//g; $pos_filename_rel =~ s/^\/+//g; my $mycnf_filename_rel = $mycnf_filename; $mycnf_filename_rel =~ s/^$topmountdir//g; $mycnf_filename_rel =~ s/^\/+//g; # To be portable, do a "cd" before calling tar (ie. don't do "tar ... -C ...") my $command= "cd '$topmountdir' ;"; # Check if a compress program has been set. # If NOT, then make tar write directly to $tarballtmp. # Otherwise make tar pipe to stdout and pipe stdin to compress program. # Build the primary tar command. $command.= sprintf("'%s' %s %s %s %s", $tar, $tararg, # If the user does not want compression, directly write the tar # file. Else write to "-", ie. stdout. ($compress eq "") ? $tarballtmp : "-", "$mountdir_rel/$relpath", $tarsuffixarg); # Maybe some additional files are to be added $command .= " $pos_filename_rel"; $command .= " $mycnf_filename_rel" if ($skip_mycnf==0); # If the stuff should be compressed (ie. a compress program has been set), # then the stream has to be piped to the $compress program. $command .= "| $compress $compressarg -> $tarballtmp" unless ($compress eq ""); if (run_command("create tar archive", $command)) { rename $tarballtmp, $tarball; return 1; } else { return 0; } } sub do_backup_none { log_msg ("Backuptype none selected, not doing backup... DONE", LOG_INFO); return 1; } sub do_backup_rsnap { my $destdir = $backupdir; log_msg ("Archiving with rsnap to $destdir", LOG_INFO); # Trailing slash is bad my $relpath_noslash = $relpath; $relpath_noslash =~ s/\/+$//g; my $command = "$rsnap $rsnaparg $mountdir/$relpath_noslash"; $command .= " $pos_filename"; $command .= " $mycnf_filename" if ($skip_mycnf==0); $command .= " $destdir/"; return run_command("create rsnap archive", $command); } sub do_backup_rsync { my $destdir = $archivename; # Do not use a temporary directory for remote backups my $destdirtmp = $destdir; unless ($destdir =~ /^[^\/].*:.*/) { $destdirtmp = sprintf('%s.INCOMPLETE-%07d',$destdir,int(rand(2**16))); } log_msg ("Taking actual backup...", LOG_INFO); log_msg ("Archiving with rsync to $destdir", LOG_INFO); # Trailing slash is bad my $relpath_noslash = $relpath; $relpath_noslash =~ s/\/+$//g; my $command = "$rsync $rsyncarg $mountdir/$relpath_noslash"; $command .= " $pos_filename"; $command .= " $mycnf_filename" if ($skip_mycnf==0); $command .= " $destdirtmp/"; if (run_command("create rsync archive", $command)) { rename $destdirtmp, $destdir if($destdirtmp ne $destdir); return 1; } else { return 0; } } sub mount_snapshot { log_msg ("Mounting snapshot...", LOG_INFO); my $params= 'rw'; $params.= ',nouuid' if $need_xfsworkaround; my $command= "$mount -o $params /dev/$vgname/$backuplv $mountdir"; return run_command("mount snapshot", $command); } sub do_innodb_recover { log_msg ("Recovering InnoDB...", LOG_INFO); my $command="echo 'select 1;' | $mysqld_safe --socket=$TMP/mylvmbackup.sock --pid-file=$pidfile --log-error=$TMP/mylvmbackup_recoverserver.err --datadir=$mountdir/$relpath --skip-networking --skip-grant --bootstrap --skip-ndbcluster --skip-slave-start"; return run_command("InnoDB recovery on snapshot", $command); } sub save_posfile { log_msg ("Copying $pos_tempfile to $pos_filename...", LOG_INFO); copy($pos_tempfile, $pos_filename) or log_msg ("Could not copy $pos_tempfile to $pos_filename: $!", LOG_ERR); } sub create_lvm_snapshot { my $command= "$lvcreate -s --size=$lvsize --name=$backuplv /dev/$vgname/$lvname"; return run_command("taking LVM snapshot", $command); } sub log_msg { my $msg = shift; my $syslog_level = shift; # Only log errors and warnings if quiet option is set return if ($quiet) and ($syslog_level eq LOG_INFO); if ($log_method eq "console") { __print_it($syslog_level, $msg); } elsif ($log_method eq "syslog") { __log_it ($syslog_level, $msg); } elsif ($log_method eq "both") { __print_it ($syslog_level, $msg); __log_it ($syslog_level, $msg); } if ($syslog_level eq LOG_ERR) { run_hook ("logerr", $msg); } sub __print_it { my $syslog_level = shift; my $msg = shift; my $logmsg = ''; if ($syslog_level eq LOG_WARNING) { $logmsg = " Warning: "; } elsif ($syslog_level eq LOG_INFO) { $logmsg = " Info: "; } elsif ($syslog_level eq LOG_ERR) { $logmsg = " Error: "; } print timestamp() . $logmsg . $msg . "\n"; } sub __log_it { syslog ($_[0], $_[1]); } sub timestamp { return ymd() . " " . hms(); } sub hms { my ($sec,$min,$hour,$mday,$mon,$year) = localtime(); return sprintf("%02d:%02d:%02d", $hour, $min, $sec); } sub ymd { my ($sec,$min,$hour,$mday,$mon,$year) = localtime(); return sprintf("%04d%02d%02d", $year+1900, $mon+1, $mday); } } # # Unmount file systems, clean up temp files and discard the snapshot (if # required) # sub cleanup { run_hook("precleanup"); log_msg ("Cleaning up...", LOG_INFO); unless ($keep_mount) { run_command("Unmounting $mountdir","$umount $mountdir") if ($mounted); unlink $pos_filename if (-f $pos_filename); unlink $mycnf_filename if (-f $mycnf_filename); if ($posmountdir) { rmdir $mountdir; rmdir $posmountdir; } unlink $pos_tempfile if (-f $pos_tempfile); } else { log_msg("Not removing mount as requested by configuration", LOG_INFO); } if (-e "/dev/$vgname/$backuplv") { my @lvs_info = `$lvs /dev/$vgname/$backuplv`; chomp (@lvs_info); log_msg ("LVM Usage stats:", LOG_INFO); foreach my $lvs_info (@lvs_info) { log_msg ($lvs_info, LOG_INFO); } } if ($snapshot_created) { unless ($keep_snapshot || $keep_mount) { run_command("Removing snapshot", "$lvremove -f /dev/$vgname/$backuplv"); } else { log_msg("Not removing snapshot as requested by configuration", LOG_INFO); } } } sub innodb_recover { $innodb_recover = 1; } sub skip_flush_tables { $skip_flush_tables = 1; } sub extra_flush_tables { $extra_flush_tables = 1; } sub skip_hooks { $skip_hooks = 1; } sub keep_snapshot { $keep_snapshot = 1; } sub keep_mount { $keep_mount = 1; } sub quiet { $quiet = 1; } sub skip_mycnf { $skip_mycnf = 1; } sub need_xfsworkaround { $need_xfsworkaround = 1; } sub help { print < MySQL username (def: $user) --password= MySQL password --host= Hostname for MySQL --port= TCP port for MySQL --socket= UNIX socket for MySQL --quiet Suppress diagnostic output, print warnings and errors only --vgname= VG containing datadir (def: $vgname) --lvname= LV containing datadir (def: $lvname) --relpath= Relative path on LV to datadir (def: $relpath) --lvsize= Size for snapshot volume (def: $lvsize) --prefix= Prefix for naming the backup (def: $prefix) --suffix= Prefix for naming the backup (def: $suffix) --backupdir= Path for archives (def: $backupdir) --backuptype= Select backup type: none, rsnap, rsync or tar (def: $backuptype) --configfile= Specify an alternative configuration file (def: $configfile) --help Print this help If your MySQL daemon is not listening on localhost, or using the default socket location, you must specify --host or --socket. EOF exit 1; } # # Check if given directory exists and is writable # sub check_dir { my ($dirname,$optioname) = @_; if (!(-d $dirname)) { eval { File::Path::mkpath($dirname) }; if($@) { log_msg ("The directory $dirname does not exist and I was unable to create it.", LOG_ERR); help(); } } unless ( (-d $dirname) and (-w $dirname) and (-r $dirname) and (-x $dirname)) { print < DIRERROR log_msg ("The directory $dirname does not exist or I don't have sufficient privileges to read/write/access it.", LOG_ERR); } } # # Sanitize directory names: # # 1. Remove any whitespace padding first # 2. Remove trailing slashes # sub clean_dirname { my ($d) = @_; $d = time2str($d, time) if($d =~ /(%[YmdhHMS])+/); $d =~ s/^\s*//g; $d =~ s/\s$//g; return File::Basename::dirname($d.'/foo') } # # Run system command # sub run_command { my ($message) = shift; log_msg("Running: " . join(" ", @_), LOG_INFO); if (system(@_) == 0 && $? == 0) { log_msg("DONE: $message", LOG_INFO); return 1; } else { my $err; if ($? & 0xff) { $err = "received signal " . ($? & 0xff); } elsif ($? >> 8) { $err = "exit status " . ($? >> 8); } else { $err = $!; } log_msg("FAILED: $message ($err)", LOG_ERR); } return 0; } # # Script hooks # sub run_hook { return if $skip_hooks; my ($hookname, $hookarg) = @_; my $hookfile = $hooksdir."/".$hookname; $hookarg="" unless ($hookarg); eval "use $hookname"; if($@) { # couldn't find hook as perl module. see if it's a shell script. if (-x $hookfile) { my $message="Running hook '$hookname'"; $message.=" with argument '$hookarg'" unless ($hookarg eq ""); log_msg ($message, LOG_INFO); system($hookfile $hookarg); if ( $? >> 8 != 0) { log_msg (sprintf("Hook $hookname failed with nonzero exit value %d", $? >> 8), $hookname eq "precleanup" ? LOG_WARNING : LOG_ERR); } } } else { log_msg ("Running hook '$hookname' as perl module.", LOG_INFO); my $ret = $hookname->execute(($dbh ? $dbh->clone() : undef), $hookarg); if(!$ret) { log_msg ("Perl module '$hookname' did not return a true result: " . $hookname->errmsg(), LOG_ERR); } } } sub lvm_version { my $lv = `$lvs --version`; log_msg("$lvs: $!", LOG_ERR) if $? != 0; $lv =~ s/LVM version: //; $lv =~ s/^\s*//; $lv =~ s/\s.+//g; return $lv; } # vim: ts=2 sw=2 expandtab ft=perl: mylvmbackup-0.13/mylvmbackup.conf0000644000175000001440000000420311250465451014107 00000000000000# # mylvmbackup configuration file # # Every line beginning with a pound sign (#) will be treated as a comment. # Values should be put right after the equals sign, without whitespace. # Please refer to the mylvmbackup(1) manual page for more information # # These values define how mylvmbackup should connect to the local MySQL server # Usually host, port and socket path don't need to be provided, if the # DBD::MySQL Perl module has been compiled with the same values that the local # MySQL server uses. If a non-empty host name other than "localhost" is # provided, the socket path is ignored. # [mysql] user=root password= host= port= socket= mycnf=/etc/my.cnf # # LVM-specific options # [lvm] vgname=mysql lvname=data backuplv= lvsize=5G # # File system specific options # [fs] xfs=0 mountdir=/var/tmp/mylvmbackup/mnt/ backupdir=/var/tmp/mylvmbackup/backup/ relpath= # # Names of required external utilities # Make sure the $PATH is set accordingly, especially for cron jobs! # [tools] lvcreate=lvcreate lvremove=lvremove lvs=lvs mount=mount tar=tar compress=gzip # alternative tar backup compression tools #compress=lzma #compress=bzip2 # or (for no compression): #compress=cat # rsync=rsync rsnap=rsnap umount=umount # # Other configuration options # [misc] backuptype=tar prefix=backup suffix=_mysql tararg=cvf tarsuffixarg= tarfilesuffix=.tar.gz compressarg=--stdout --verbose --best # for LZMA: #compressarg=--stdout --verbose -7 # for bzip2: #compressarg=--stdout --verbose -7 # for cat: #compressarg= # ie. nothing rsyncarg=-avWP rsnaparg=7 datefmt=%Y%m%d_%H%M%S innodb_recover=0 pidfile=/var/tmp/mylvmbackup_recoverserver.pid skip_flush_tables=0 extra_flush_tables=0 skip_mycnf=0 hooksdir=/usr/share/mylvmbackup skip_hooks=0 keep_snapshot=0 keep_mount=0 quiet=0 # # Logging options. The Sys::Syslog module is required for syslog option # See "perldoc Sys::Syslog" for more information. # [logging] # 'console' (STDOUT, STDERR) or 'syslog' or 'both'. log_method=console # 'native', 'tcp', 'udp'. Default is 'native' syslog_socktype=native syslog_facility= # If using remote syslog, don't forget to change the socket type to tcp or udp. syslog_remotehost= mylvmbackup-0.13/mylvmbackup.pl.in0000644000175000001440000006175411250465451014220 00000000000000#!/usr/bin/perl -w # # mylvmbackup - utility for creating MySQL backups via LVM snapshots # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package mylvmbackup; use Config::IniFiles; use Date::Format; use DBI; use File::Basename; use File::Temp qw/ mkstemps mktemp /; use Getopt::Long; use diagnostics; use strict; # Version is set from the Makefile my $version='@VERSION@'; my $build_date='@BUILDDATE@'; # syslog-related options my $syslog_ident = 'mylvmbackup'; my $syslog_args = 'pid,ndelay'; my $configfile = "/etc/mylvmbackup.conf"; my $configfile2 = ""; my $TMP= ($ENV{TMPDIR} || "/tmp"); my $backupdir; my $backuplv; my $datefmt; my $hooksdir; my $host; my $innodb_recover; my $skip_flush_tables; my $skip_hooks; my $skip_mycnf; my $extra_flush_tables; my $keep_snapshot; my $keep_mount; my $lvcreate; my $lvname; my $lvremove; my $lvs; my $lvsize; my $mount; my $mysqld_safe; my $mycnf; my $mountdir; my $need_xfsworkaround; my $password; my $pidfile; my $port; my $quiet; my $backuptype; my $prefix; my $suffix; my $relpath; my $socket; my $rsync; my $rsnap; my $rsyncarg; my $rsnaparg; my $tar; my $tararg; my $tarsuffixarg; my $tarfilesuffix; my $compress; my $compressarg; my $umount; my $user; my $vgname; my $log_method; my $syslog_socktype; my $syslog_facility; my $syslog_remotehost; # Load defaults into variables load_defaults(); # Initialize variables from config file, if it exists if (-r $configfile) { load_config($configfile); } # Load the commandline arguments load_args(); # If they specified an alternative config file if ($configfile2 ne "") { die ("Unable to load specified config file: $!\n") unless (-r $configfile2); load_config($configfile2); # re-load the arguments, as they should override any config file settings load_args(); } if ("$log_method" eq "syslog") { use Sys::Syslog qw(:DEFAULT setlogsock :macros); if ($syslog_socktype ne "native") { die ("You need to provide syslog_remotehost!\n") unless ($syslog_remotehost); setlogsock ($syslog_socktype); $Sys::Syslog::host = $syslog_remotehost; } openlog ($syslog_ident, $syslog_args, $syslog_facility); log_msg ("Starting new backup...", LOG_INFO); } if (lvm_version() =~ /^1/) { log_msg("Linux LVM Version 2 or higher is required to run mylvmbackup.", LOG_ERR); exit(1); } # Clean up directory inputs $mountdir = clean_dirname($mountdir); $backupdir = clean_dirname($backupdir); # Validate the existence of a prefix die "You must specify a non-empty prefix to name your backup!\n" unless ($prefix ne ""); $backuplv = $lvname.'_snapshot' if length($backuplv) == 0; my $date = time2str($datefmt, time); my $fullprefix = $prefix.'-'.$date.$suffix; my $topmountdir = $mountdir; # No .tar.gz on the end! my $archivename = $backupdir.'/'.$fullprefix; my $mounted = 0; my $snapshot_created = 0; # Check for the backupdir, it must exist, and it must be readable/writable # Except when not doing any backups or using rsync to a remote server unless (($backuptype eq 'none') or ($backuptype eq 'rsync' and $backupdir =~ /^[^\/].*:.*/)) { check_dir($backupdir, 'backupdir'); } # Check the mountdir, it must exist, and be readable/writeable check_dir($mountdir, 'mountdir'); # Append the prefix to the mountdir, to allow multiple parallel backups. The # extra / is to ensure we go a level under it. An empty prefix is disallowed. $mountdir .= '/'.$prefix; my $posmountdir = $mountdir; $posmountdir .= '-pos'; # Notice that we do not add a slash. my $pos_filename = $posmountdir.'/'.$fullprefix.'.pos'; my $pos_tempfile_fh; my $pos_tempfile; ($pos_tempfile_fh, $pos_tempfile) = mkstemps($TMP.'/mylvmbackup-'.$fullprefix.'-XXXXXX', '.pos') or log_msg ("Cannot create temporary file $pos_tempfile: $!", LOG_ERR); my $mycnf_basename = File::Basename::basename($mycnf); my $mycnf_filename = $posmountdir.'/'.$fullprefix.'_'.$mycnf_basename; # Now create it mkdir $mountdir; mkdir $posmountdir; # Check it again for existence and read/write. check_dir($mountdir, 'mountdir'); # Now make sure it's empty my @mountdir_content = glob "$mountdir/*" ; unless ( scalar(@mountdir_content) eq 0) { log_msg ("Please make sure Temp dir ($mountdir) is empty.", LOG_ERR); exit(1); }; # Figure out our DSN string my $dsn = "DBI:mysql:database=mysql;mysql_read_default_group=client"; if(length($socket) > 0) { $dsn .= ";mysql_socket=".$socket; } if(length($host) > 0) { $dsn .= ";host=".$host; } if(length($port) > 0) { $dsn .= ";port=".$port; } run_hook ("preconnect"); log_msg ("Connecting to database...", LOG_INFO); my $dbh= DBI->connect($dsn,$user,$password); if (!$dbh) { log_msg ($DBI::errstr, LOG_ERR); die $DBI::errstr; } run_hook ("preflush"); flush_tables($dbh) unless ($skip_flush_tables == 1); create_posfile($dbh); run_hook ("presnapshot"); $snapshot_created= create_lvm_snapshot(); run_hook ("preunlock"); log_msg ("Unlocking tables...", LOG_INFO); $dbh->do("UNLOCK TABLES") or log_msg ($DBI::errstr, LOG_ERR) && die $DBI::errstr; run_hook ("predisconnect"); log_msg ("Disconnecting from database...", LOG_INFO); $dbh->disconnect; if ($snapshot_created) { run_hook("premount"); $mounted= mount_snapshot(); save_posfile(); if ($mounted) { if ($innodb_recover == 1) { do_innodb_recover(); } if (-f $mycnf && $skip_mycnf == 0) { create_mycnf_file(); } run_hook("prebackup"); my $backupsuccess=0; if ($backuptype eq 'tar') {$backupsuccess = do_backup_tar()} elsif ($backuptype eq 'rsync') {$backupsuccess = do_backup_rsync()} elsif ($backuptype eq 'rsnap') {$backupsuccess = do_backup_rsnap()} else {$backupsuccess = do_backup_none()}; if ($backupsuccess == 1) { run_hook("backupsuccess"); } else { run_hook("backupfailure"); } } } else { cleanup(); exit 1; } cleanup(); exit 0; # Please keep all 3 functions in the same order: load_config, load_args, load_defaults sub load_config { my $configfile = shift(@_); my $cfg = new Config::IniFiles( -file => $configfile ) or log_msg ("Couldn't read configuration file: " . $!, 'LOG_WARNING'); $user = $cfg->val( 'mysql', 'user', $user); $password = $cfg->val ('mysql', 'password', $password); $host = $cfg->val ('mysql', 'host', $host); $port = $cfg->val ('mysql', 'port', $port); $socket = $cfg->val ('mysql', 'socket', $socket); $mysqld_safe = $cfg->val ('mysql', 'mysqld_safe', $mysqld_safe); $mycnf = $cfg->val ('mysql', 'mycnf', $mycnf); $vgname=$cfg->val ('lvm', 'vgname', $vgname); $lvname=$cfg->val ('lvm', 'lvname', $lvname); $lvsize=$cfg->val ('lvm', 'lvsize', $lvsize); $backuplv = $cfg->val ('lvm', 'backuplv', $backuplv); $backuptype=$cfg->val ('misc', 'backuptype', $backuptype); $prefix=$cfg->val ('misc', 'prefix', $prefix); $suffix=$cfg->val ('misc', 'suffix', $suffix); $datefmt=$cfg->val ('misc', 'datefmt', $datefmt); $innodb_recover=$cfg->val ('misc', 'innodb_recover', $innodb_recover); $pidfile=$cfg->val ('misc', 'pidfile', $pidfile); $skip_flush_tables=$cfg->val ('misc', 'skip_flush_tables', $skip_flush_tables); $extra_flush_tables=$cfg->val ('misc', 'extra_flush_tables', $extra_flush_tables); $skip_mycnf=$cfg->val ('misc', 'skip_mycnf', $skip_mycnf); $rsyncarg=$cfg->val ('misc', 'rsyncarg', $rsyncarg); $rsnaparg=$cfg->val ('misc', 'rsnaparg', $rsnaparg); $tararg=$cfg->val ('misc', 'tararg', $tararg); $tarsuffixarg=$cfg->val ('misc', 'tarsuffixarg', $tarsuffixarg); $tarfilesuffix = $cfg->val ('misc', 'tarfilesuffix', $tarfilesuffix); $compressarg=$cfg->val ('misc', 'compressarg', $compressarg); $hooksdir = $cfg->val ('misc', 'hooksdir', $hooksdir); $skip_hooks=$cfg->val ('misc', 'skip_hooks', $skip_hooks); $keep_snapshot=$cfg->val ('misc', 'keep_snapshot', $keep_snapshot); $keep_mount=$cfg->val ('misc', 'keep_mount', $keep_mount); $quiet=$cfg->val ('misc', 'quiet', $quiet); $mountdir=$cfg->val ('fs', 'mountdir', $mountdir); $backupdir=$cfg->val ('fs', 'backupdir', $backupdir); $relpath=$cfg->val ('fs', 'relpath', $relpath); $need_xfsworkaround=$cfg->val ('fs', 'xfs', $need_xfsworkaround); $lvcreate=$cfg->val ('tools', 'lvcreate', $lvcreate); $lvremove=$cfg->val ('tools', 'lvremove', $lvremove); $lvs=$cfg->val ('tools', 'lvs', $lvs); $mount=$cfg->val ('tools', 'mount', $mount); $umount=$cfg->val ('tools', 'umount', $umount); $tar=$cfg->val ('tools', 'tar', $tar); $compress=$cfg->val ('tools', 'compress', $compress); $rsync=$cfg->val ('tools', 'rsync', $rsync); $rsnap=$cfg->val ('tools', 'rsnap', $rsnap); $log_method = $cfg->val('logging', 'log_method', $log_method); $syslog_socktype = $cfg->val ('logging', 'syslog_socktype', $syslog_socktype); $syslog_facility = $cfg->val ('logging', 'syslog_facility', $syslog_facility); $syslog_remotehost = $cfg->val ('logging', 'syslog_remotehost', $syslog_remotehost); } # Please keep all 3 functions in the same order: load_config, load_args, load_defaults sub load_args { GetOptions( # stuff that doesn't go in the config file ;-) "help" => \&help, "configfile=s" => \$configfile2, # mysql "user=s" => \$user, "password=s" => \$password, "host=s" => \$host, "port=i" => \$port, "socket=s" => \$socket, "mysqld_safe=s" => \$mysqld_safe, "mycnf=s" => \$mycnf, # lvm "vgname=s" => \$vgname, "lvname=s" => \$lvname, "lvsize=s" => \$lvsize, "backuplv=s" => \$backuplv, # misc "backuptype=s" => \$backuptype, "prefix=s" => \$prefix, "suffix=s" => \$suffix, "datefmt=s" => \$datefmt, "innodb_recover" => \&innodb_recover, "pidfile=s" => \$pidfile, "skip_flush_tables" => \&skip_flush_tables, "extra_flush_tables" => \&extra_flush_tables, "skip_mycnf" => \&skip_mycnf, "tararg=s" => \$tararg, "tarsuffixarg=s" => \$tarsuffixarg, "tarfilesuffix=s" => \$tarfilesuffix, "compressarg=s" => \$compressarg, "rsyncarg=s" => \$rsyncarg, "rsnaparg=s" => \$rsnaparg, "hooksdir=s" => \$hooksdir, "skip_hooks" => \&skip_hooks, "keep_snapshot" => \&keep_snapshot, "keep_mount" => \&keep_mount, "quiet" => \&quiet, # fs "mountdir=s" => \$mountdir, "backupdir=s" => \$backupdir, "relpath=s" => \$relpath, "xfs" => \&need_xfsworkaround, # tools "lvcreate=s" => \$lvcreate, "lvremove=s" => \$lvremove, "lvs=s" => \$lvs, "mount=s" => \$mount, "umount=s" => \$umount, "tar=s" => \$tar, "compress=s" => \$compress, "rsync=s" => \$rsync, "rsnap=s" => \$rsnap, # logging "log_method=s" => \$log_method, "syslog_socktype=s" => \$syslog_socktype, "syslog_facility=s" => \$syslog_facility, "syslog_remotehost=s" => \$syslog_remotehost, ) or help(); # As this function is called last, append to @INC here. eval "use lib '$hooksdir'"; } # Please keep all 3 functions in the same order: load_config, load_args, load_defaults sub load_defaults { # mysql $user = 'root'; $password = ''; $host = ''; $port = ''; $socket = ''; $mysqld_safe='mysqld_safe'; $mycnf = '/etc/my.cnf'; # lvm $vgname='mysql'; $lvname='data'; $lvsize='5G'; $backuplv = ''; # misc $backuptype='tar'; $prefix='backup'; $suffix='_mysql'; $datefmt='%Y%m%d_%H%M%S'; $innodb_recover=0; $pidfile = '$TMP/mylvmbackup_recoverserver.pid'; $skip_flush_tables=0; $extra_flush_tables=0; $skip_mycnf=0; $tararg='cvf'; $tarsuffixarg=''; $tarfilesuffix='.tar.gz'; $compressarg='--stdout --verbose --best'; $rsyncarg='-avPW'; $rsnaparg='7'; $hooksdir='/usr/share/mylvmbackup'; $skip_hooks=0; $keep_snapshot=0; $keep_mount=0; $quiet=0; # fs $mountdir='/var/tmp/mylvmbackup/mnt/'; $backupdir='/var/tmp/mylvmbackup/backup/'; $relpath=''; $need_xfsworkaround=0; # External tools - make sure that these are in $PATH or provide absolute names $lvcreate='lvcreate'; $lvremove='lvremove'; $lvs='lvs'; $mount='mount'; $umount='umount'; $tar='tar'; $compress='gzip'; $rsync='rsync'; $rsnap='rsnap'; # logging $log_method = 'console'; $syslog_socktype = 'native'; $syslog_facility = ''; $syslog_remotehost = ''; } sub flush_tables { my $dbh = shift; if($extra_flush_tables == 1) { log_msg ("Flushing tables (initial)...", LOG_INFO); $dbh->do("FLUSH TABLES") or log_msg ($DBI::errstr, LOG_ERR); } log_msg ("Flushing tables with read lock...", LOG_INFO); $dbh->do("FLUSH TABLES WITH READ LOCK") or log_msg ($DBI::errstr, LOG_ERR); } sub create_posfile { log_msg ("Taking position record into $pos_tempfile...", LOG_INFO); my $dbh = shift; _create_posfile_single($dbh, 'SHOW MASTER STATUS', $pos_tempfile_fh, 'Master'); _create_posfile_single($dbh, 'SHOW SLAVE STATUS', $pos_tempfile_fh, 'Slave'); close $pos_tempfile_fh or log_msg ("Closing $pos_tempfile failed: $!", LOG_ERR); } sub _create_posfile_single { my $dbh = shift; my $query = shift; my $fh = shift; my $pos_prefix = shift; my $sth = $dbh->prepare($query) or log_msg ($DBI::errstr, LOG_ERR); $sth->execute or log_msg ($DBI::errstr, LOG_ERR); while (my $r = $sth->fetchrow_hashref) { foreach my $f (@{$sth->{NAME}}) { my $v = $r->{$f}; $v = '' if (!defined($v)); my $line = "$pos_prefix:$f=$v\n"; print $fh $line or log_msg ("Writing position record failed: $!", LOG_ERR); } } $sth->finish; } sub create_mycnf_file { log_msg ("Copying $mycnf to $mycnf_filename...", LOG_INFO); use File::Copy; copy($mycnf, $mycnf_filename) or log_msg ("Could not copy $mycnf to $mycnf_filename: $!", LOG_ERR); } sub do_backup_tar { my $tarball = $archivename.$tarfilesuffix; my $tarballtmp = mktemp("$tarball.INCOMPLETE-XXXXXXX"); log_msg ("Taking actual backup...", LOG_INFO); log_msg ("Creating tar archive $tarball", LOG_INFO); my $mountdir_rel = $mountdir; $mountdir_rel =~ s/^$topmountdir//g; $mountdir_rel =~ s/^\/+//g; my $pos_filename_rel = $pos_filename; $pos_filename_rel =~ s/^$topmountdir//g; $pos_filename_rel =~ s/^\/+//g; my $mycnf_filename_rel = $mycnf_filename; $mycnf_filename_rel =~ s/^$topmountdir//g; $mycnf_filename_rel =~ s/^\/+//g; # To be portable, do a "cd" before calling tar (ie. don't do "tar ... -C ...") my $command= "cd '$topmountdir' ;"; # Check if a compress program has been set. # If NOT, then make tar write directly to $tarballtmp. # Otherwise make tar pipe to stdout and pipe stdin to compress program. # Build the primary tar command. $command.= sprintf("'%s' %s %s %s %s", $tar, $tararg, # If the user does not want compression, directly write the tar # file. Else write to "-", ie. stdout. ($compress eq "") ? $tarballtmp : "-", "$mountdir_rel/$relpath", $tarsuffixarg); # Maybe some additional files are to be added $command .= " $pos_filename_rel"; $command .= " $mycnf_filename_rel" if ($skip_mycnf==0); # If the stuff should be compressed (ie. a compress program has been set), # then the stream has to be piped to the $compress program. $command .= "| $compress $compressarg -> $tarballtmp" unless ($compress eq ""); if (run_command("create tar archive", $command)) { rename $tarballtmp, $tarball; return 1; } else { return 0; } } sub do_backup_none { log_msg ("Backuptype none selected, not doing backup... DONE", LOG_INFO); return 1; } sub do_backup_rsnap { my $destdir = $backupdir; log_msg ("Archiving with rsnap to $destdir", LOG_INFO); # Trailing slash is bad my $relpath_noslash = $relpath; $relpath_noslash =~ s/\/+$//g; my $command = "$rsnap $rsnaparg $mountdir/$relpath_noslash"; $command .= " $pos_filename"; $command .= " $mycnf_filename" if ($skip_mycnf==0); $command .= " $destdir/"; return run_command("create rsnap archive", $command); } sub do_backup_rsync { my $destdir = $archivename; # Do not use a temporary directory for remote backups my $destdirtmp = $destdir; unless ($destdir =~ /^[^\/].*:.*/) { $destdirtmp = sprintf('%s.INCOMPLETE-%07d',$destdir,int(rand(2**16))); } log_msg ("Taking actual backup...", LOG_INFO); log_msg ("Archiving with rsync to $destdir", LOG_INFO); # Trailing slash is bad my $relpath_noslash = $relpath; $relpath_noslash =~ s/\/+$//g; my $command = "$rsync $rsyncarg $mountdir/$relpath_noslash"; $command .= " $pos_filename"; $command .= " $mycnf_filename" if ($skip_mycnf==0); $command .= " $destdirtmp/"; if (run_command("create rsync archive", $command)) { rename $destdirtmp, $destdir if($destdirtmp ne $destdir); return 1; } else { return 0; } } sub mount_snapshot { log_msg ("Mounting snapshot...", LOG_INFO); my $params= 'rw'; $params.= ',nouuid' if $need_xfsworkaround; my $command= "$mount -o $params /dev/$vgname/$backuplv $mountdir"; return run_command("mount snapshot", $command); } sub do_innodb_recover { log_msg ("Recovering InnoDB...", LOG_INFO); my $command="echo 'select 1;' | $mysqld_safe --socket=$TMP/mylvmbackup.sock --pid-file=$pidfile --log-error=$TMP/mylvmbackup_recoverserver.err --datadir=$mountdir/$relpath --skip-networking --skip-grant --bootstrap --skip-ndbcluster --skip-slave-start"; return run_command("InnoDB recovery on snapshot", $command); } sub save_posfile { log_msg ("Copying $pos_tempfile to $pos_filename...", LOG_INFO); copy($pos_tempfile, $pos_filename) or log_msg ("Could not copy $pos_tempfile to $pos_filename: $!", LOG_ERR); } sub create_lvm_snapshot { my $command= "$lvcreate -s --size=$lvsize --name=$backuplv /dev/$vgname/$lvname"; return run_command("taking LVM snapshot", $command); } sub log_msg { my $msg = shift; my $syslog_level = shift; # Only log errors and warnings if quiet option is set return if ($quiet) and ($syslog_level eq LOG_INFO); if ($log_method eq "console") { __print_it($syslog_level, $msg); } elsif ($log_method eq "syslog") { __log_it ($syslog_level, $msg); } elsif ($log_method eq "both") { __print_it ($syslog_level, $msg); __log_it ($syslog_level, $msg); } if ($syslog_level eq LOG_ERR) { run_hook ("logerr", $msg); } sub __print_it { my $syslog_level = shift; my $msg = shift; my $logmsg = ''; if ($syslog_level eq LOG_WARNING) { $logmsg = " Warning: "; } elsif ($syslog_level eq LOG_INFO) { $logmsg = " Info: "; } elsif ($syslog_level eq LOG_ERR) { $logmsg = " Error: "; } print timestamp() . $logmsg . $msg . "\n"; } sub __log_it { syslog ($_[0], $_[1]); } sub timestamp { return ymd() . " " . hms(); } sub hms { my ($sec,$min,$hour,$mday,$mon,$year) = localtime(); return sprintf("%02d:%02d:%02d", $hour, $min, $sec); } sub ymd { my ($sec,$min,$hour,$mday,$mon,$year) = localtime(); return sprintf("%04d%02d%02d", $year+1900, $mon+1, $mday); } } # # Unmount file systems, clean up temp files and discard the snapshot (if # required) # sub cleanup { run_hook("precleanup"); log_msg ("Cleaning up...", LOG_INFO); unless ($keep_mount) { run_command("Unmounting $mountdir","$umount $mountdir") if ($mounted); unlink $pos_filename if (-f $pos_filename); unlink $mycnf_filename if (-f $mycnf_filename); if ($posmountdir) { rmdir $mountdir; rmdir $posmountdir; } unlink $pos_tempfile if (-f $pos_tempfile); } else { log_msg("Not removing mount as requested by configuration", LOG_INFO); } if (-e "/dev/$vgname/$backuplv") { my @lvs_info = `$lvs /dev/$vgname/$backuplv`; chomp (@lvs_info); log_msg ("LVM Usage stats:", LOG_INFO); foreach my $lvs_info (@lvs_info) { log_msg ($lvs_info, LOG_INFO); } } if ($snapshot_created) { unless ($keep_snapshot || $keep_mount) { run_command("Removing snapshot", "$lvremove -f /dev/$vgname/$backuplv"); } else { log_msg("Not removing snapshot as requested by configuration", LOG_INFO); } } } sub innodb_recover { $innodb_recover = 1; } sub skip_flush_tables { $skip_flush_tables = 1; } sub extra_flush_tables { $extra_flush_tables = 1; } sub skip_hooks { $skip_hooks = 1; } sub keep_snapshot { $keep_snapshot = 1; } sub keep_mount { $keep_mount = 1; } sub quiet { $quiet = 1; } sub skip_mycnf { $skip_mycnf = 1; } sub need_xfsworkaround { $need_xfsworkaround = 1; } sub help { print < MySQL username (def: $user) --password= MySQL password --host= Hostname for MySQL --port= TCP port for MySQL --socket= UNIX socket for MySQL --quiet Suppress diagnostic output, print warnings and errors only --vgname= VG containing datadir (def: $vgname) --lvname= LV containing datadir (def: $lvname) --relpath= Relative path on LV to datadir (def: $relpath) --lvsize= Size for snapshot volume (def: $lvsize) --prefix= Prefix for naming the backup (def: $prefix) --suffix= Prefix for naming the backup (def: $suffix) --backupdir= Path for archives (def: $backupdir) --backuptype= Select backup type: none, rsnap, rsync or tar (def: $backuptype) --configfile= Specify an alternative configuration file (def: $configfile) --help Print this help If your MySQL daemon is not listening on localhost, or using the default socket location, you must specify --host or --socket. EOF exit 1; } # # Check if given directory exists and is writable # sub check_dir { my ($dirname,$optioname) = @_; if (!(-d $dirname)) { eval { File::Path::mkpath($dirname) }; if($@) { log_msg ("The directory $dirname does not exist and I was unable to create it.", LOG_ERR); help(); } } unless ( (-d $dirname) and (-w $dirname) and (-r $dirname) and (-x $dirname)) { print < DIRERROR log_msg ("The directory $dirname does not exist or I don't have sufficient privileges to read/write/access it.", LOG_ERR); } } # # Sanitize directory names: # # 1. Remove any whitespace padding first # 2. Remove trailing slashes # sub clean_dirname { my ($d) = @_; $d = time2str($d, time) if($d =~ /(%[YmdhHMS])+/); $d =~ s/^\s*//g; $d =~ s/\s$//g; return File::Basename::dirname($d.'/foo') } # # Run system command # sub run_command { my ($message) = shift; log_msg("Running: " . join(" ", @_), LOG_INFO); if (system(@_) == 0 && $? == 0) { log_msg("DONE: $message", LOG_INFO); return 1; } else { my $err; if ($? & 0xff) { $err = "received signal " . ($? & 0xff); } elsif ($? >> 8) { $err = "exit status " . ($? >> 8); } else { $err = $!; } log_msg("FAILED: $message ($err)", LOG_ERR); } return 0; } # # Script hooks # sub run_hook { return if $skip_hooks; my ($hookname, $hookarg) = @_; my $hookfile = $hooksdir."/".$hookname; $hookarg="" unless ($hookarg); eval "use $hookname"; if($@) { # couldn't find hook as perl module. see if it's a shell script. if (-x $hookfile) { my $message="Running hook '$hookname'"; $message.=" with argument '$hookarg'" unless ($hookarg eq ""); log_msg ($message, LOG_INFO); system($hookfile $hookarg); if ( $? >> 8 != 0) { log_msg (sprintf("Hook $hookname failed with nonzero exit value %d", $? >> 8), $hookname eq "precleanup" ? LOG_WARNING : LOG_ERR); } } } else { log_msg ("Running hook '$hookname' as perl module.", LOG_INFO); my $ret = $hookname->execute(($dbh ? $dbh->clone() : undef), $hookarg); if(!$ret) { log_msg ("Perl module '$hookname' did not return a true result: " . $hookname->errmsg(), LOG_ERR); } } } sub lvm_version { my $lv = `$lvs --version`; log_msg("$lvs: $!", LOG_ERR) if $? != 0; $lv =~ s/LVM version: //; $lv =~ s/^\s*//; $lv =~ s/\s.+//g; return $lv; } # vim: ts=2 sw=2 expandtab ft=perl: mylvmbackup-0.13/mylvmbackup.spec0000644000175000001440000000402711250465467014127 00000000000000# # spec file for package mylvmbackup (Version 0.13) # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation; either version 2 of the License, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., 59 # Temple Place, Suite 330, Boston, MA 02111-1307 USA Name: mylvmbackup Summary: Utility for creating MySQL backups via LVM snapshots Version: 0.13 Release: 0 License: GPL Group: Productivity/Archiving/Backup Source: %{name}-%{version}.tar.gz URL: http://www.lenzg.net/mylvmbackup/ BuildRoot: %{_tmppath}/%{name}-%{version}-build BuildArch: noarch %description mylvmbackup is a script for quickly creating backups of MySQL server's data files. To perform a backup, mylvmbackup obtains a read lock on all tables and flushes all server caches to disk, makes an LVM snapshot of the volume containing the MySQL data directory, and unlocks the tables again. The snapshot process takes only a small amount of time. When it is done, the server can continue normal operations, while the actual file backup proceeds. %prep %setup %install [ "$RPM_BUILD_ROOT" != "/" ] && [ -d $RPM_BUILD_ROOT ] && rm -rf $RPM_BUILD_ROOT; make DESTDIR=$RPM_BUILD_ROOT prefix=%{_prefix} mandir=%{_mandir} install %clean [ "$RPM_BUILD_ROOT" != "/" ] && [ -d $RPM_BUILD_ROOT ] && rm -rf $RPM_BUILD_ROOT; %files %defattr(-, root, root) %config(noreplace,missingok) %attr(600, root, root) %{_sysconfdir}/mylvmbackup.conf %config(noreplace) %{_datadir}/%{name}/*.pm %doc ChangeLog COPYING CREDITS INSTALL README TODO %doc %{_mandir}/man1/%{name}.1* %dir %{_datadir}/%{name} %{_bindir}/%{name} mylvmbackup-0.13/mylvmbackup.spec.in0000644000175000001440000000404111215457522014522 00000000000000# # spec file for package mylvmbackup (Version @VERSION@) # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation; either version 2 of the License, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., 59 # Temple Place, Suite 330, Boston, MA 02111-1307 USA Name: mylvmbackup Summary: Utility for creating MySQL backups via LVM snapshots Version: @VERSION@ Release: 0 License: GPL Group: Productivity/Archiving/Backup Source: %{name}-%{version}.tar.gz URL: http://www.lenzg.net/mylvmbackup/ BuildRoot: %{_tmppath}/%{name}-%{version}-build BuildArch: noarch %description mylvmbackup is a script for quickly creating backups of MySQL server's data files. To perform a backup, mylvmbackup obtains a read lock on all tables and flushes all server caches to disk, makes an LVM snapshot of the volume containing the MySQL data directory, and unlocks the tables again. The snapshot process takes only a small amount of time. When it is done, the server can continue normal operations, while the actual file backup proceeds. %prep %setup %install [ "$RPM_BUILD_ROOT" != "/" ] && [ -d $RPM_BUILD_ROOT ] && rm -rf $RPM_BUILD_ROOT; make DESTDIR=$RPM_BUILD_ROOT prefix=%{_prefix} mandir=%{_mandir} install %clean [ "$RPM_BUILD_ROOT" != "/" ] && [ -d $RPM_BUILD_ROOT ] && rm -rf $RPM_BUILD_ROOT; %files %defattr(-, root, root) %config(noreplace,missingok) %attr(600, root, root) %{_sysconfdir}/mylvmbackup.conf %config(noreplace) %{_datadir}/%{name}/*.pm %doc ChangeLog COPYING CREDITS INSTALL README TODO %doc %{_mandir}/man1/%{name}.1* %dir %{_datadir}/%{name} %{_bindir}/%{name} mylvmbackup-0.13/README0000644000175000001440000000624211152775034011575 00000000000000mylvmbackup - utility for creating MySQL backups via LVM snapshots Home page: http://www.lenzg.net/mylvmbackup/ Source code, Bug Reports: https://launchpad.net/mylvmbackup Maintainer: Lenz Grimmer mylvmbackup is a Perl script for quickly creating backups of MySQL server's data files. To perform a backup, mylvmbackup obtains a read lock on all tables and flushes all server caches to disk, makes an LVM snapshot of the volume containing the MySQL data directory, and unlocks the tables again. The snapshot process takes only a small amount of time. When it is done, the server can continue normal operations, while the actual file backup proceeds. The LVM snapshot is mounted to a temporary directory and all data is backed up using the tar program. By default, the archive file is created using a name of the form backup-YYYYMMDD_hhmmss_mysql.tar.gz, where YYYY, MM, DD, hh, mm, and ss represent the year, month, day, hour, minute, and second of the time at which the backup occurred. The prefix backup and the date format can be modified. The use of timestamped archive names allows you to run mylvmbackup many times without danger of overwriting old archives. It is necessary to run mylvmbackup on the same host where the MySQL server runs. If your MySQL daemon is not listening on localhost, or using the default socket location, you must specify --host or --socket. Even though mylvmbackup communicates with the server through a normal client connection to obtain the read lock and flush data, it makes the backup by accessing the file system directly. It is also necessary that the MySQL server data directory resides on an LVM volume. (It is, however, a good idea to do the LVM backup to a different partition than the one where the data directory resides. Otherwise, there is a good chance that LVM will run out of undo space for LVM snapshot maintenance and the backup will fail.) The user who invokes mylvmbackup must have sufficient filesystem permissions to create the LVM snapshot and mount it. This includes read/write access to the backup directory. Requirements For proper operation mylvmbackup requires Perl 5 with the 'DBI' and 'DBD::mysql' modules. It also needs the 'Config::IniFiles' to read the global configuration file of the program and 'Sys::Syslog' in case you want to enable the syslog log facility. 'Date::Format' is required to create the time stamp used in the backup file names. In addition, it utilizes 'Getopt::Long' and 'File::Basename' which usually are part of the default Perl distribution. It also requires several other external programs: GNU 'tar' and 'gzip' to back up and compress the data, LVM utilities ('lvcreate', 'lvremove' and 'lvs') to create and remove the LVM snapshot, and the system utilities 'mount' and 'umount'. Mailing list If you want to discuss the usage of mylvmbackup, propose patches or ask for help, there now is a mailinglist, hosted on FreeLists.org. To subscribe, either enter your email address on the mylvmbackup list information page at http://www.freelists.org/list/mylvmbackup or send an email with the subject "subscribe" to mylvmbackup-request@freelists.org. The list is archived at http://www.freelists.org/archives/mylvmbackup/ mylvmbackup-0.13/TODO0000644000175000001440000000066011076405744011406 00000000000000The mylvmbackup TODO list is now maintained as "Blueprints" on Launchpad: https://blueprints.launchpad.net/mylvmbackup - Ability to exclude the binlog/relay log - Providing an option to shut down the server instead of using FLUSH TABLES WITH READ LOCK before taking the snapshot, for consistent InnoDB snapshots (e.g. on a replication slave) - RPM packaging: fix Requires for distributions (e.g. perl-Config-IniFiles)